Minor updates/cleaning. New option -b to dump BER
[yaz-moved-to-github.git] / client / client.c
1 /* 
2  * Copyright (c) 1995-2003, Index Data
3  * See the file LICENSE for details.
4  *
5  * $Id: client.c,v 1.185 2003-03-11 11:07:47 adam Exp $
6  */
7
8 #include <stdio.h>
9 #include <stdlib.h>
10 #if HAVE_LOCALE_H
11 #include <locale.h>
12 #endif
13
14 #if HAVE_LANGINFO_H
15 #include <langinfo.h>
16 #endif
17
18 #include <time.h>
19 #include <ctype.h>
20
21 #ifdef WIN32
22 #include <io.h>
23 #define S_ISREG(x) (x & _S_IFREG)
24 #define S_ISDIR(x) (x & _S_IFDIR)
25 #endif
26
27 #include <yaz/yaz-util.h>
28
29 #include <yaz/comstack.h>
30
31 #include <yaz/proto.h>
32 #include <yaz/marcdisp.h>
33 #include <yaz/diagbib1.h>
34 #include <yaz/otherinfo.h>
35 #include <yaz/charneg.h>
36
37 #include <yaz/pquery.h>
38 #include <yaz/sortspec.h>
39
40 #include <yaz/ill.h>
41
42 #include <yaz/yaz-ccl.h>
43
44 #if HAVE_READLINE_READLINE_H
45 #include <readline/readline.h>
46 #include <unistd.h>
47 #endif
48 #if HAVE_READLINE_HISTORY_H
49 #include <readline/history.h>
50 #endif
51
52 #include <sys/stat.h>
53
54 #include "admin.h"
55 #include "tabcomplete.h"
56
57 #define C_PROMPT "Z> "
58
59 static char *codeset = 0;               /* character set for output */
60
61 static ODR out, in, print;              /* encoding and decoding streams */
62 static FILE *apdu_file = 0;
63 static FILE *ber_file = 0;
64 static COMSTACK conn = 0;               /* our z-association */
65 static Z_IdAuthentication *auth = 0;    /* our current auth definition */
66 char *databaseNames[128];
67 int num_databaseNames = 0;
68 static Z_External *record_last = 0;
69 static int setnumber = -1;              /* current result set number */
70 static int smallSetUpperBound = 0;
71 static int largeSetLowerBound = 1;
72 static int mediumSetPresentNumber = 0;
73 static Z_ElementSetNames *elementSetNames = 0; 
74 static int setno = 1;                   /* current set offset */
75 static enum oid_proto protocol = PROTO_Z3950;      /* current app protocol */
76 static enum oid_value recordsyntax = VAL_USMARC;
77 static enum oid_value schema = VAL_NONE;
78 static int sent_close = 0;
79 static NMEM session_mem = NULL;         /* memory handle for init-response */
80 static Z_InitResponse *session = 0;     /* session parameters */
81 static char last_scan_line[512] = "0";
82 static char last_scan_query[512] = "0";
83 static char ccl_fields[512] = "default.bib";
84 static char* esPackageName = 0;
85 static char* yazProxy = 0;
86 static int kilobytes = 1024;
87 static char* yazCharset = 0;
88 static char* yazLang = 0;
89
90 static char last_cmd[32] = "?";
91 static FILE *marc_file = 0;
92 static char *refid = NULL;
93 static char *last_open_command = NULL;
94 static int auto_reconnect = 0;
95
96 typedef enum {
97     QueryType_Prefix,
98     QueryType_CCL,
99     QueryType_CCL2RPN,
100     QueryType_CQL
101 } QueryType;
102
103 static QueryType queryType = QueryType_Prefix;
104
105 static CCL_bibset bibset;               /* CCL bibset handle */
106
107 #if HAVE_READLINE_COMPLETION_OVER
108
109 #else
110 /* readline doesn't have this var. Define it ourselves. */
111 int rl_attempted_completion_over = 0;
112 #endif
113
114 /* set this one to 1, to avoid decode of unknown MARCs  */
115 #define AVOID_MARC_DECODE 1
116
117 #define maxOtherInfosSupported 10
118 struct {
119     int oidval;
120     char* value;
121 } extraOtherInfos[maxOtherInfosSupported];
122         
123
124 void process_cmd_line(char* line);
125 char ** readline_completer(char *text, int start, int end);
126 char *command_generator(const char *text, int state);
127 char** curret_global_list=NULL;
128 int cmd_register_tab(const char* arg);
129
130 static void close_session (void);
131
132 ODR getODROutputStream()
133 {
134     return out;
135 }
136
137 const char* query_type_as_string(QueryType q) 
138 {
139     switch (q) { 
140     case QueryType_Prefix: return "prefix (RPN sent to server)";
141     case QueryType_CCL: return "CCL (CCL sent to server) ";
142     case QueryType_CCL2RPN: return "CCL -> RPN (RPN sent to server)";
143     case QueryType_CQL: return "CQL (CQL sent to server)";
144     default: 
145         return "unknown Query type internal yaz-client error";
146     }
147 }
148
149
150 void do_hex_dump(char* buf,int len) 
151 {
152 #if 0 
153     int i,x;
154     for( i=0; i<len ; i=i+16 ) 
155     {                   
156         printf(" %4.4d ",i);
157         for(x=0 ; i+x<len && x<16; ++x) 
158         {
159             printf("%2.2X ",(unsigned int)((unsigned char)buf[i+x]));
160         }
161         printf("\n");
162     }
163 #endif
164 }
165
166 void add_otherInfos(Z_APDU *a) 
167 {
168     Z_OtherInformation **oi;
169     int i;
170                 
171     yaz_oi_APDU(a, &oi);
172     for(i=0; i<maxOtherInfosSupported; ++i) 
173     {
174         if(extraOtherInfos[i].oidval != -1) 
175             yaz_oi_set_string_oidval(oi, out, extraOtherInfos[i].oidval,
176                                      1, extraOtherInfos[i].value);
177     }   
178 }
179
180 void send_apdu(Z_APDU *a)
181 {
182     char *buf;
183     int len;
184     
185     add_otherInfos(a);
186     
187     if (apdu_file)
188     {
189         z_APDU(print, &a, 0, 0);
190         odr_reset(print);
191     }
192     if (!z_APDU(out, &a, 0, 0))
193     {
194         odr_perror(out, "Encoding APDU");
195         close_session();
196         return;
197     }
198     buf = odr_getbuf(out, &len, 0);
199     if (ber_file)
200         odr_dumpBER(ber_file, buf, len);
201     /* printf ("sending APDU of size %d\n", len); */
202     if (cs_put(conn, buf, len) < 0)
203     {
204         fprintf(stderr, "cs_put: %s", cs_errmsg(cs_errno(conn)));
205         close_session();
206         return;
207     }
208     do_hex_dump(buf,len);
209     odr_reset(out); /* release the APDU structure  */
210 }
211
212 static void print_stringn(const unsigned char *buf, size_t len)
213 {
214     size_t i;
215     for (i = 0; i<len; i++)
216         if ((buf[i] <= 126 && buf[i] >= 32) || strchr ("\n\r\t\f", buf[i]))
217             printf ("%c", buf[i]);
218         else
219             printf ("\\X%02X", buf[i]);
220 }
221
222 static void print_refid (Z_ReferenceId *id)
223 {
224     if (id)
225     {
226         printf ("Reference Id: ");
227         print_stringn (id->buf, id->len);
228         printf ("\n");
229     }
230 }
231
232 static Z_ReferenceId *set_refid (ODR out)
233 {
234     Z_ReferenceId *id;
235     if (!refid)
236         return 0;
237     id = (Z_ReferenceId *) odr_malloc (out, sizeof(*id));
238     id->size = id->len = strlen(refid);
239     id->buf = (unsigned char *) odr_malloc (out, id->len);
240     memcpy (id->buf, refid, id->len);
241     return id;
242 }   
243
244 /* INIT SERVICE ------------------------------- */
245
246 static void send_initRequest(const char* type_and_host)
247 {
248     Z_APDU *apdu = zget_APDU(out, Z_APDU_initRequest);
249     Z_InitRequest *req = apdu->u.initRequest;
250
251     ODR_MASK_SET(req->options, Z_Options_search);
252     ODR_MASK_SET(req->options, Z_Options_present);
253     ODR_MASK_SET(req->options, Z_Options_namedResultSets);
254     ODR_MASK_SET(req->options, Z_Options_triggerResourceCtrl);
255     ODR_MASK_SET(req->options, Z_Options_scan);
256     ODR_MASK_SET(req->options, Z_Options_sort);
257     ODR_MASK_SET(req->options, Z_Options_extendedServices);
258     ODR_MASK_SET(req->options, Z_Options_delSet);
259
260     ODR_MASK_SET(req->protocolVersion, Z_ProtocolVersion_1);
261     ODR_MASK_SET(req->protocolVersion, Z_ProtocolVersion_2);
262     ODR_MASK_SET(req->protocolVersion, Z_ProtocolVersion_3);
263
264     *req->maximumRecordSize = 1024*kilobytes;
265     *req->preferredMessageSize = 1024*kilobytes;
266
267     req->idAuthentication = auth;
268
269     req->referenceId = set_refid (out);
270
271     if (yazProxy) 
272         yaz_oi_set_string_oidval(&req->otherInfo, out, VAL_PROXY,
273         1, type_and_host);
274     
275     if (yazCharset || yazLang) {
276         Z_OtherInformation **p;
277         Z_OtherInformationUnit *p0;
278         
279         yaz_oi_APDU(apdu, &p);
280         
281         if ((p0=yaz_oi_update(p, out, NULL, 0, 0))) {
282                 ODR_MASK_SET(req->options, Z_Options_negotiationModel);
283                 
284                 p0->which = Z_OtherInfo_externallyDefinedInfo;
285                 p0->information.externallyDefinedInfo =
286                         yaz_set_proposal_charneg(out,
287                                 (const char**)&yazCharset, (yazCharset)?1:0,
288                                 (const char**)&yazLang, (yazLang)?1:0, 1);
289         }
290     }
291     
292     send_apdu(apdu);
293     printf("Sent initrequest.\n");
294 }
295
296 static int process_initResponse(Z_InitResponse *res)
297 {
298     int ver = 0;
299     /* save session parameters for later use */
300     session_mem = odr_extract_mem(in);
301     session = res;
302
303     for (ver = 0; ver<5; ver++)
304         if (!ODR_MASK_GET(res->protocolVersion, ver))
305             break;
306
307     if (!*res->result)
308         printf("Connection rejected by v%d target.\n", ver);
309     else
310         printf("Connection accepted by v%d target.\n", ver);
311     if (res->implementationId)
312         printf("ID     : %s\n", res->implementationId);
313     if (res->implementationName)
314         printf("Name   : %s\n", res->implementationName);
315     if (res->implementationVersion)
316         printf("Version: %s\n", res->implementationVersion);
317     if (res->userInformationField)
318     {
319         printf("UserInformationfield:\n");
320         if (!z_External(print, (Z_External**)&res-> userInformationField,
321             0, 0))
322         {
323             odr_perror(print, "Printing userinfo\n");
324             odr_reset(print);
325         }
326         if (res->userInformationField->which == Z_External_octet)
327         {
328             printf("Guessing visiblestring:\n");
329             printf("'%s'\n", res->userInformationField->u. octet_aligned->buf);
330         }
331         odr_reset (print);
332     }
333     printf ("Options:");
334     if (ODR_MASK_GET(res->options, Z_Options_search))
335         printf (" search");
336     if (ODR_MASK_GET(res->options, Z_Options_present))
337         printf (" present");
338     if (ODR_MASK_GET(res->options, Z_Options_delSet))
339         printf (" delSet");
340     if (ODR_MASK_GET(res->options, Z_Options_resourceReport))
341         printf (" resourceReport");
342     if (ODR_MASK_GET(res->options, Z_Options_resourceCtrl))
343         printf (" resourceCtrl");
344     if (ODR_MASK_GET(res->options, Z_Options_accessCtrl))
345         printf (" accessCtrl");
346     if (ODR_MASK_GET(res->options, Z_Options_scan))
347         printf (" scan");
348     if (ODR_MASK_GET(res->options, Z_Options_sort))
349         printf (" sort");
350     if (ODR_MASK_GET(res->options, Z_Options_extendedServices))
351         printf (" extendedServices");
352     if (ODR_MASK_GET(res->options, Z_Options_level_1Segmentation))
353         printf (" level1Segmentation");
354     if (ODR_MASK_GET(res->options, Z_Options_level_2Segmentation))
355         printf (" level2Segmentation");
356     if (ODR_MASK_GET(res->options, Z_Options_concurrentOperations))
357         printf (" concurrentOperations");
358     if (ODR_MASK_GET(res->options, Z_Options_namedResultSets))
359     {
360         printf (" namedResultSets");
361         setnumber = 0;
362     }
363     if (ODR_MASK_GET(res->options, Z_Options_encapsulation))
364         printf (" encapsulation");
365     if (ODR_MASK_GET(res->options, Z_Options_resultCount))
366         printf (" resultCount");
367     if (ODR_MASK_GET(res->options, Z_Options_negotiationModel))
368         printf (" negotiationModel");
369     if (ODR_MASK_GET(res->options, Z_Options_duplicateDetection))
370         printf (" duplicateDetection");
371     if (ODR_MASK_GET(res->options, Z_Options_queryType104))
372         printf (" queryType104");
373     printf ("\n");
374     
375     if (ODR_MASK_GET(res->options, Z_Options_negotiationModel)) {
376     
377         Z_CharSetandLanguageNegotiation *p =
378                 yaz_get_charneg_record(res->otherInfo);
379         
380         if (p) {
381             
382             char *charset=NULL, *lang=NULL;
383             int selected;
384             
385             yaz_get_response_charneg(session_mem, p, &charset, &lang,
386                                      &selected);
387             
388             printf("Accepted character set : %s\n", charset);
389             printf("Accepted code language : %s\n", lang ? lang : "none");
390             printf("Accepted records in ...: %d\n", selected );
391         }
392     }
393     fflush (stdout);
394     return 0;
395 }
396
397 static int cmd_base(const char *arg)
398 {
399     int i;
400     const char *cp;
401
402     if (!*arg)
403     {
404         printf("Usage: base <database> <database> ...\n");
405         return 0;
406     }
407     for (i = 0; i<num_databaseNames; i++)
408         xfree (databaseNames[i]);
409     num_databaseNames = 0;
410     while (1)
411     {
412         char *cp1;
413         if (!(cp = strchr(arg, ' ')))
414             cp = arg + strlen(arg);
415         if (cp - arg < 1)
416             break;
417         databaseNames[num_databaseNames] = (char *)xmalloc (1 + cp - arg);
418         memcpy (databaseNames[num_databaseNames], arg, cp - arg);
419         databaseNames[num_databaseNames][cp - arg] = '\0';
420
421         for (cp1 = databaseNames[num_databaseNames]; *cp1 ; cp1++)
422             if (*cp1 == '+')
423                 *cp1 = ' ';
424         num_databaseNames++;
425
426         if (!*cp)
427             break;
428         arg = cp+1;
429     }
430     return 1;
431 }
432
433 void cmd_open_remember_last_open_command(const char* arg, char* new_open_command)
434 {
435     if(last_open_command != arg) 
436     {
437         if(last_open_command) xfree(last_open_command);
438         last_open_command = xstrdup(new_open_command);
439     }
440 }
441
442 int cmd_open(const char *arg)
443 {
444     void *add;
445     char type_and_host[101];
446     const char *basep = 0;
447     if (conn)
448     {
449         printf("Already connected.\n");
450         
451         cs_close (conn);
452         conn = NULL;
453         if (session_mem)
454         {
455             nmem_destroy (session_mem);
456             session_mem = NULL;
457         }
458     }   
459     cs_get_host_args(arg, &basep);
460
461     cmd_open_remember_last_open_command(arg,type_and_host);
462
463     if (yazProxy)
464         conn = cs_create_host(yazProxy, 1, &add);
465     else
466         conn = cs_create_host(arg, 1, &add);
467     if (!conn)
468     {
469         printf ("Couldn't create comstack\n");
470         return 0;
471     }
472     if (conn->protocol == PROTO_HTTP)
473     {
474         printf("HTTP transport not supported\n");
475         cs_close(conn);
476         conn = 0;
477         return 0;
478     }
479     printf("Connecting...");
480     fflush(stdout);
481     if (cs_connect(conn, add) < 0)
482     {
483         printf ("error = %s\n", cs_strerror(conn));
484         if (conn->cerrno == CSYSERR)
485         {
486             char msg[256];
487             yaz_strerror(msg, sizeof(msg));
488             printf ("%s\n", msg);
489         }
490         cs_close(conn);
491         conn = 0;
492         return 0;
493     }
494     printf("OK.\n");
495     if (conn->protocol == PROTO_Z3950)
496         send_initRequest(type_and_host);
497     if (basep && *basep)
498         cmd_base (basep);
499     return 2;
500 }
501
502
503 void try_reconnect() 
504 {
505     char* open_command;
506         
507     if(!( auto_reconnect && last_open_command) ) return ;
508
509     open_command = (char *) xmalloc (strlen(last_open_command)+6);
510     strcpy (open_command, "open ");
511         
512     strcat (open_command, last_open_command);
513
514     process_cmd_line(open_command);
515         
516     xfree(open_command);                                
517 }
518
519 int cmd_authentication(const char *arg)
520 {
521     static Z_IdAuthentication au;
522     static char user[40], group[40], pass[40];
523     static Z_IdPass idPass;
524     int r;
525
526     if (!*arg)
527     {
528         printf("Auth field set to null\n");
529         auth = 0;
530         return 1;
531     }
532     r = sscanf (arg, "%39s %39s %39s", user, group, pass);
533     if (r == 0)
534     {
535         printf("Auth field set to null\n");
536         auth = 0;
537     }
538     if (r == 1)
539     {
540         auth = &au;
541         au.which = Z_IdAuthentication_open;
542         au.u.open = user;
543     }
544     if (r == 2)
545     {
546         auth = &au;
547         au.which = Z_IdAuthentication_idPass;
548         au.u.idPass = &idPass;
549         idPass.groupId = NULL;
550         idPass.userId = user;
551         idPass.password = group;
552     }
553     if (r == 3)
554     {
555         auth = &au;
556         au.which = Z_IdAuthentication_idPass;
557         au.u.idPass = &idPass;
558         idPass.groupId = group;
559         idPass.userId = user;
560         idPass.password = pass;
561     }
562     return 1;
563 }
564
565 /* SEARCH SERVICE ------------------------------ */
566 static void display_record(Z_External *r);
567
568 static void print_record(const unsigned char *buf, size_t len)
569 {
570     size_t i = len;
571     print_stringn (buf, len);
572     /* add newline if not already added ... */
573     if (i <= 0 || buf[i-1] != '\n')
574         printf ("\n");
575 }
576
577 static void display_record(Z_External *r)
578 {
579     oident *ent = oid_getentbyoid(r->direct_reference);
580
581     record_last = r;
582     /*
583      * Tell the user what we got.
584      */
585     if (r->direct_reference)
586     {
587         printf("Record type: ");
588         if (ent)
589             printf("%s\n", ent->desc);
590         else if (!odr_oid(print, &r->direct_reference, 0, 0))
591         {
592             odr_perror(print, "print oid");
593             odr_reset(print);
594         }
595     }
596     /* Check if this is a known, ASN.1 type tucked away in an octet string */
597     if (ent && r->which == Z_External_octet)
598     {
599         Z_ext_typeent *type = z_ext_getentbyref(ent->value);
600         void *rr;
601
602         if (type)
603         {
604             /*
605              * Call the given decoder to process the record.
606              */
607             odr_setbuf(in, (char*)r->u.octet_aligned->buf,
608                 r->u.octet_aligned->len, 0);
609             if (!(*type->fun)(in, (char **)&rr, 0, 0))
610             {
611                 odr_perror(in, "Decoding constructed record.");
612                 fprintf(stdout, "[Near %d]\n", odr_offset(in));
613                 fprintf(stdout, "Packet dump:\n---------\n");
614                 odr_dumpBER(stdout, (char*)r->u.octet_aligned->buf,
615                             r->u.octet_aligned->len);
616                 fprintf(stdout, "---------\n");
617                 
618                 /* note just ignores the error ant print the bytes form the octet_aligned later */
619             } else {
620                 /*
621                  * Note: we throw away the original, BER-encoded record here.
622                  * Do something else with it if you want to keep it.
623                  */
624                 r->u.sutrs = (Z_SUTRS *) rr; /* we don't actually check the type here. */
625                 r->which = type->what;
626             }
627         }
628     }
629     if (ent && ent->oclass != CLASS_RECSYN) 
630         return;
631     if (ent && ent->value == VAL_SOIF)
632         print_record((const unsigned char *) r->u.octet_aligned->buf,
633                      r->u.octet_aligned->len);
634     else if (r->which == Z_External_octet)
635     {
636         const char *octet_buf = (char*)r->u.octet_aligned->buf;
637         if (ent->value == VAL_TEXT_XML || ent->value == VAL_APPLICATION_XML ||
638             ent->value == VAL_HTML)
639         {
640             print_record((const unsigned char *) octet_buf,
641                          r->u.octet_aligned->len);
642         }
643         else if (ent->value == VAL_POSTSCRIPT)
644         {
645             int size = r->u.octet_aligned->len;
646             if (size > 100)
647                 size = 100;
648             print_record((const unsigned char *) octet_buf, size);
649         }
650         else
651         {
652             if ( 
653 #if AVOID_MARC_DECODE
654                 /* primitive check for a marc OID 5.1-29 except 16 */
655                 ent->oidsuffix[0] == 5 && ent->oidsuffix[1] < 30 &&
656                 ent->oidsuffix[1] != 16
657 #else
658                 1
659 #endif
660                 )
661             {
662                 char *result;
663                 int rlen;
664                 yaz_iconv_t cd = 0;
665                 yaz_marc_t mt = yaz_marc_create();
666                     
667                 if (yaz_marc_decode_buf(mt, octet_buf,r->u.octet_aligned->len,
668                                         &result, &rlen)> 0)
669                 {
670                     char *from = 0;
671                     if (ent->value == VAL_USMARC)
672                     {
673                         if (octet_buf[9] == 'a')
674                             from = "UTF-8";
675                         else
676                             from = "MARC8";
677                     }
678                     else
679                         from = "ISO-8859-1";
680
681                     if (codeset && from)
682                     {   
683                         printf ("convert from %s to %s\n", from, codeset);
684                         cd = yaz_iconv_open(codeset, from);
685                     }
686                     if (!cd)
687                         fwrite (result, 1, rlen, stdout);
688                     else
689                     {
690                         char outbuf[12];
691                         size_t inbytesleft = rlen;
692                         const char *inp = result;
693                         
694                         while (inbytesleft)
695                         {
696                             size_t outbytesleft = sizeof(outbuf);
697                             char *outp = outbuf;
698                             size_t r = yaz_iconv (cd, (char**) &inp,
699                                                   &inbytesleft, 
700                                                   &outp, &outbytesleft);
701                             if (r == (size_t) (-1))
702                             {
703                                 int e = yaz_iconv_error(cd);
704                                 if (e != YAZ_ICONV_E2BIG)
705                                     break;
706                             }
707                             fwrite (outbuf, outp - outbuf, 1, stdout);
708                         }
709                     }
710                 }
711                 else
712                 {
713                     printf ("bad MARC. Dumping as it is:\n");
714                     print_record((const unsigned char*) octet_buf,
715                                   r->u.octet_aligned->len);
716                 }       
717                 yaz_marc_destroy(mt);
718                 if (cd)
719                     yaz_iconv_close(cd);
720             }
721             else
722             {
723                 print_record((const unsigned char*) octet_buf,
724                              r->u.octet_aligned->len);
725             }
726         }
727         if (marc_file)
728             fwrite (octet_buf, 1, r->u.octet_aligned->len, marc_file);
729     }
730     else if (ent && ent->value == VAL_SUTRS)
731     {
732         if (r->which != Z_External_sutrs)
733         {
734             printf("Expecting single SUTRS type for SUTRS.\n");
735             return;
736         }
737         print_record(r->u.sutrs->buf, r->u.sutrs->len);
738     }
739     else if (ent && ent->value == VAL_GRS1)
740     {
741         WRBUF w;
742         if (r->which != Z_External_grs1)
743         {
744             printf("Expecting single GRS type for GRS.\n");
745             return;
746         }
747         w = wrbuf_alloc();
748         yaz_display_grs1(w, r->u.grs1, 0);
749         puts (wrbuf_buf(w));
750         wrbuf_free(w, 1);
751     }
752     else 
753     {
754         printf("Unknown record representation.\n");
755         if (!z_External(print, &r, 0, 0))
756         {
757             odr_perror(print, "Printing external");
758             odr_reset(print);
759         }
760     }
761 }
762
763 static void display_diagrecs(Z_DiagRec **pp, int num)
764 {
765     int i;
766     oident *ent;
767     Z_DefaultDiagFormat *r;
768
769     printf("Diagnostic message(s) from database:\n");
770     for (i = 0; i<num; i++)
771     {
772         Z_DiagRec *p = pp[i];
773         if (p->which != Z_DiagRec_defaultFormat)
774         {
775             printf("Diagnostic record not in default format.\n");
776             return;
777         }
778         else
779             r = p->u.defaultFormat;
780         if (!(ent = oid_getentbyoid(r->diagnosticSetId)) ||
781             ent->oclass != CLASS_DIAGSET || ent->value != VAL_BIB1)
782             printf("Missing or unknown diagset\n");
783         printf("    [%d] %s", *r->condition, diagbib1_str(*r->condition));
784         switch (r->which)
785         {
786         case Z_DefaultDiagFormat_v2Addinfo:
787             printf (" -- v2 addinfo '%s'\n", r->u.v2Addinfo);
788             break;
789         case Z_DefaultDiagFormat_v3Addinfo:
790             printf (" -- v3 addinfo '%s'\n", r->u.v3Addinfo);
791             break;
792         }
793     }
794 }
795
796
797 static void display_nameplusrecord(Z_NamePlusRecord *p)
798 {
799     if (p->databaseName)
800         printf("[%s]", p->databaseName);
801     if (p->which == Z_NamePlusRecord_surrogateDiagnostic)
802         display_diagrecs(&p->u.surrogateDiagnostic, 1);
803     else if (p->which == Z_NamePlusRecord_databaseRecord)
804         display_record(p->u.databaseRecord);
805 }
806
807 static void display_records(Z_Records *p)
808 {
809     int i;
810
811     if (p->which == Z_Records_NSD)
812     {
813         Z_DiagRec dr, *dr_p = &dr;
814         dr.which = Z_DiagRec_defaultFormat;
815         dr.u.defaultFormat = p->u.nonSurrogateDiagnostic;
816         display_diagrecs (&dr_p, 1);
817     }
818     else if (p->which == Z_Records_multipleNSD)
819         display_diagrecs (p->u.multipleNonSurDiagnostics->diagRecs,
820                           p->u.multipleNonSurDiagnostics->num_diagRecs);
821     else 
822     {
823         printf("Records: %d\n", p->u.databaseOrSurDiagnostics->num_records);
824         for (i = 0; i < p->u.databaseOrSurDiagnostics->num_records; i++)
825             display_nameplusrecord(p->u.databaseOrSurDiagnostics->records[i]);
826     }
827 }
828
829 static int send_deleteResultSetRequest(const char *arg)
830 {
831     char names[8][32];
832     int i;
833
834     Z_APDU *apdu = zget_APDU(out, Z_APDU_deleteResultSetRequest);
835     Z_DeleteResultSetRequest *req = apdu->u.deleteResultSetRequest;
836
837     req->referenceId = set_refid (out);
838
839     req->num_resultSetList =
840         sscanf (arg, "%30s %30s %30s %30s %30s %30s %30s %30s",
841                 names[0], names[1], names[2], names[3],
842                 names[4], names[5], names[6], names[7]);
843
844     req->deleteFunction = (int *)
845         odr_malloc (out, sizeof(*req->deleteFunction));
846     if (req->num_resultSetList > 0)
847     {
848         *req->deleteFunction = Z_DeleteRequest_list;
849         req->resultSetList = (char **)
850             odr_malloc (out, sizeof(*req->resultSetList)*
851                         req->num_resultSetList);
852         for (i = 0; i<req->num_resultSetList; i++)
853             req->resultSetList[i] = names[i];
854     }
855     else
856     {
857         *req->deleteFunction = Z_DeleteRequest_all;
858         req->resultSetList = 0;
859     }
860     
861     send_apdu(apdu);
862     printf("Sent deleteResultSetRequest.\n");
863     return 2;
864 }
865
866 static int send_searchRequest(const char *arg)
867 {
868     Z_APDU *apdu = zget_APDU(out, Z_APDU_searchRequest);
869     Z_SearchRequest *req = apdu->u.searchRequest;
870     Z_Query query;
871     int oid[OID_SIZE];
872     struct ccl_rpn_node *rpn = NULL;
873     int error, pos;
874     char setstring[100];
875     Z_RPNQuery *RPNquery;
876     Odr_oct ccl_query;
877     YAZ_PQF_Parser pqf_parser;
878     Z_External *ext;
879
880     if (queryType == QueryType_CCL2RPN)
881     {
882         rpn = ccl_find_str(bibset, arg, &error, &pos);
883         if (error)
884         {
885             printf("CCL ERROR: %s\n", ccl_err_msg(error));
886             return 0;
887         }
888     }
889     req->referenceId = set_refid (out);
890     if (!strcmp(arg, "@big")) /* strictly for troublemaking */
891     {
892         static unsigned char big[2100];
893         static Odr_oct bigo;
894
895         /* send a very big referenceid to test transport stack etc. */
896         memset(big, 'A', 2100);
897         bigo.len = bigo.size = 2100;
898         bigo.buf = big;
899         req->referenceId = &bigo;
900     }
901     
902     if (setnumber >= 0)
903     {
904         sprintf(setstring, "%d", ++setnumber);
905         req->resultSetName = setstring;
906     }
907     *req->smallSetUpperBound = smallSetUpperBound;
908     *req->largeSetLowerBound = largeSetLowerBound;
909     *req->mediumSetPresentNumber = mediumSetPresentNumber;
910     if (smallSetUpperBound > 0 || (largeSetLowerBound > 1 &&
911         mediumSetPresentNumber > 0))
912     {
913         oident prefsyn;
914
915         prefsyn.proto = protocol;
916         prefsyn.oclass = CLASS_RECSYN;
917         prefsyn.value = recordsyntax;
918         req->preferredRecordSyntax =
919             odr_oiddup(out, oid_ent_to_oid(&prefsyn, oid));
920         req->smallSetElementSetNames =
921             req->mediumSetElementSetNames = elementSetNames;
922     }
923     req->num_databaseNames = num_databaseNames;
924     req->databaseNames = databaseNames;
925
926     req->query = &query;
927
928     switch (queryType)
929     {
930     case QueryType_Prefix:
931         query.which = Z_Query_type_1;
932         pqf_parser = yaz_pqf_create ();
933         RPNquery = yaz_pqf_parse (pqf_parser, out, arg);
934         if (!RPNquery)
935         {
936             const char *pqf_msg;
937             size_t off;
938             int code = yaz_pqf_error (pqf_parser, &pqf_msg, &off);
939             printf("%*s^\n", off+4, "");
940             printf("Prefix query error: %s (code %d)\n", pqf_msg, code);
941             
942             yaz_pqf_destroy (pqf_parser);
943             return 0;
944         }
945         yaz_pqf_destroy (pqf_parser);
946         query.u.type_1 = RPNquery;
947         break;
948     case QueryType_CCL:
949         query.which = Z_Query_type_2;
950         query.u.type_2 = &ccl_query;
951         ccl_query.buf = (unsigned char*) arg;
952         ccl_query.len = strlen(arg);
953         break;
954     case QueryType_CCL2RPN:
955         query.which = Z_Query_type_1;
956         RPNquery = ccl_rpn_query(out, rpn);
957         if (!RPNquery)
958         {
959             printf ("Couldn't convert from CCL to RPN\n");
960             return 0;
961         }
962         query.u.type_1 = RPNquery;
963         ccl_rpn_delete (rpn);
964         break;
965     case QueryType_CQL:
966         query.which = Z_Query_type_104;
967         ext = (Z_External *) odr_malloc(out, sizeof(*ext));
968         ext->direct_reference = odr_getoidbystr(out, "1.2.840.10003.16.2");
969         ext->indirect_reference = 0;
970         ext->descriptor = 0;
971         ext->which = Z_External_CQL;
972         ext->u.cql = odr_strdup(out, arg);
973         query.u.type_104 =  ext;
974         break;
975     default:
976         printf ("Unsupported query type\n");
977         return 0;
978     }
979     send_apdu(apdu);
980     setno = 1;
981     printf("Sent searchRequest.\n");
982     return 2;
983 }
984
985 /* display Query Expression as part of searchResult-1 */
986 static void display_queryExpression (Z_QueryExpression *qe)
987 {
988     if (!qe)
989         return;
990     if (qe->which == Z_QueryExpression_term)
991     {
992         if (qe->u.term->queryTerm)
993         {
994             Z_Term *term = qe->u.term->queryTerm;
995             switch (term->which)
996             {
997             case Z_Term_general:
998                 printf (" %.*s", term->u.general->len, term->u.general->buf);
999                 break;
1000             case Z_Term_characterString:
1001                 printf (" %s", term->u.characterString);
1002                 break;
1003             case Z_Term_numeric:
1004                 printf (" %d", *term->u.numeric);
1005                 break;
1006             case Z_Term_null:
1007                 printf (" null");
1008                 break;
1009             }
1010         }
1011     }
1012 }
1013
1014 /* see if we can find USR:SearchResult-1 */
1015 static void display_searchResult (Z_OtherInformation *o)
1016 {
1017     int i;
1018     if (!o)
1019         return ;
1020     for (i = 0; i < o->num_elements; i++)
1021     {
1022         if (o->list[i]->which == Z_OtherInfo_externallyDefinedInfo)
1023         {
1024             Z_External *ext = o->list[i]->information.externallyDefinedInfo;
1025             
1026             if (ext->which == Z_External_searchResult1)
1027             {
1028                 int j;
1029                 Z_SearchInfoReport *sr = ext->u.searchResult1;
1030                 printf ("SearchResult-1:");
1031                 for (j = 0; j < sr->num; j++)
1032                 {
1033                     if (!sr->elements[j]->subqueryExpression)
1034                         printf (" %d", j);
1035                     display_queryExpression (
1036                         sr->elements[j]->subqueryExpression);
1037                     display_queryExpression (
1038                         sr->elements[j]->subqueryInterpretation);
1039                     display_queryExpression (
1040                         sr->elements[j]->subqueryRecommendation);
1041                     if (sr->elements[j]->subqueryCount)
1042                         printf ("(%d)", *sr->elements[j]->subqueryCount);
1043                 }
1044                 printf ("\n");
1045             }
1046         }
1047     }
1048 }
1049
1050 static int process_searchResponse(Z_SearchResponse *res)
1051 {
1052     printf ("Received SearchResponse.\n");
1053     print_refid (res->referenceId);
1054     if (*res->searchStatus)
1055         printf("Search was a success.\n");
1056     else
1057         printf("Search was a bloomin' failure.\n");
1058     printf("Number of hits: %d", *res->resultCount);
1059     if (setnumber >= 0)
1060         printf (", setno %d", setnumber);
1061     printf ("\n");
1062     display_searchResult (res->additionalSearchInfo);
1063     printf("records returned: %d\n",
1064            *res->numberOfRecordsReturned);
1065     setno += *res->numberOfRecordsReturned;
1066     if (res->records)
1067         display_records(res->records);
1068     return 0;
1069 }
1070
1071 static void print_level(int iLevel)
1072 {
1073     int i;
1074     for (i = 0; i < iLevel * 4; i++)
1075         printf(" ");
1076 }
1077
1078 static void print_int(int iLevel, const char *pTag, int *pInt)
1079 {
1080     if (pInt != NULL)
1081     {
1082         print_level(iLevel);
1083         printf("%s: %d\n", pTag, *pInt);
1084     }
1085 }
1086
1087 static void print_string(int iLevel, const char *pTag, const char *pString)
1088 {
1089     if (pString != NULL)
1090     {
1091         print_level(iLevel);
1092         printf("%s: %s\n", pTag, pString);
1093     }
1094 }
1095
1096 static void print_oid(int iLevel, const char *pTag, Odr_oid *pOid)
1097 {
1098     if (pOid != NULL)
1099     {
1100         int *pInt = pOid;
1101
1102         print_level(iLevel);
1103         printf("%s:", pTag);
1104         for (; *pInt != -1; pInt++)
1105             printf(" %d", *pInt);
1106         printf("\n");
1107     }
1108 }
1109
1110 static void print_referenceId(int iLevel, Z_ReferenceId *referenceId)
1111 {
1112     if (referenceId != NULL)
1113     {
1114         int i;
1115
1116         print_level(iLevel);
1117         printf("Ref Id (%d, %d): ", referenceId->len, referenceId->size);
1118         for (i = 0; i < referenceId->len; i++)
1119             printf("%c", referenceId->buf[i]);
1120         printf("\n");
1121     }
1122 }
1123
1124 static void print_string_or_numeric(int iLevel, const char *pTag, Z_StringOrNumeric *pStringNumeric)
1125 {
1126     if (pStringNumeric != NULL)
1127     {
1128         switch (pStringNumeric->which)
1129         {
1130         case Z_StringOrNumeric_string:
1131             print_string(iLevel, pTag, pStringNumeric->u.string);
1132             break;
1133             
1134         case Z_StringOrNumeric_numeric:
1135             print_int(iLevel, pTag, pStringNumeric->u.numeric);
1136             break;
1137             
1138         default:
1139             print_level(iLevel);
1140             printf("%s: valid type for Z_StringOrNumeric\n", pTag);
1141             break;
1142         }
1143     }
1144 }
1145
1146 static void print_universe_report_duplicate(
1147     int iLevel,
1148     Z_UniverseReportDuplicate *pUniverseReportDuplicate)
1149 {
1150     if (pUniverseReportDuplicate != NULL)
1151     {
1152         print_level(iLevel);
1153         printf("Universe Report Duplicate: \n");
1154         iLevel++;
1155         print_string_or_numeric(iLevel, "Hit No",
1156                                 pUniverseReportDuplicate->hitno);
1157     }
1158 }
1159
1160 static void print_universe_report_hits(
1161     int iLevel,
1162     Z_UniverseReportHits *pUniverseReportHits)
1163 {
1164     if (pUniverseReportHits != NULL)
1165     {
1166         print_level(iLevel);
1167         printf("Universe Report Hits: \n");
1168         iLevel++;
1169         print_string_or_numeric(iLevel, "Database",
1170                                 pUniverseReportHits->database);
1171         print_string_or_numeric(iLevel, "Hits", pUniverseReportHits->hits);
1172     }
1173 }
1174
1175 static void print_universe_report(int iLevel, Z_UniverseReport *pUniverseReport)
1176 {
1177     if (pUniverseReport != NULL)
1178     {
1179         print_level(iLevel);
1180         printf("Universe Report: \n");
1181         iLevel++;
1182         print_int(iLevel, "Total Hits", pUniverseReport->totalHits);
1183         switch (pUniverseReport->which)
1184         {
1185         case Z_UniverseReport_databaseHits:
1186             print_universe_report_hits(iLevel,
1187                                        pUniverseReport->u.databaseHits);
1188             break;
1189             
1190         case Z_UniverseReport_duplicate:
1191             print_universe_report_duplicate(iLevel,
1192                                             pUniverseReport->u.duplicate);
1193             break;
1194             
1195         default:
1196             print_level(iLevel);
1197             printf("Type: %d\n", pUniverseReport->which);
1198             break;
1199         }
1200     }
1201 }
1202
1203 static void print_external(int iLevel, Z_External *pExternal)
1204 {
1205     if (pExternal != NULL)
1206     {
1207         print_level(iLevel);
1208         printf("External: \n");
1209         iLevel++;
1210         print_oid(iLevel, "Direct Reference", pExternal->direct_reference);
1211         print_int(iLevel, "InDirect Reference", pExternal->indirect_reference);
1212         print_string(iLevel, "Descriptor", pExternal->descriptor);
1213         switch (pExternal->which)
1214         {
1215         case Z_External_universeReport:
1216             print_universe_report(iLevel, pExternal->u.universeReport);
1217             break;
1218             
1219         default:
1220             print_level(iLevel);
1221             printf("Type: %d\n", pExternal->which);
1222             break;
1223         }
1224     }
1225 }
1226
1227 static int process_resourceControlRequest (Z_ResourceControlRequest *req)
1228 {
1229     printf ("Received ResourceControlRequest.\n");
1230     print_referenceId(1, req->referenceId);
1231     print_int(1, "Suspended Flag", req->suspendedFlag);
1232     print_int(1, "Partial Results Available", req->partialResultsAvailable);
1233     print_int(1, "Response Required", req->responseRequired);
1234     print_int(1, "Triggered Request Flag", req->triggeredRequestFlag);
1235     print_external(1, req->resourceReport);
1236     return 0;
1237 }
1238
1239 void process_ESResponse(Z_ExtendedServicesResponse *res)
1240 {
1241     printf("Status: ");
1242     switch (*res->operationStatus)
1243     {
1244     case Z_ExtendedServicesResponse_done:
1245         printf ("done\n");
1246         break;
1247     case Z_ExtendedServicesResponse_accepted:
1248         printf ("accepted\n");
1249         break;
1250     case Z_ExtendedServicesResponse_failure:
1251         printf ("failure\n");
1252         display_diagrecs(res->diagnostics, res->num_diagnostics);
1253         break;
1254     default:
1255         printf ("unknown\n");
1256     }
1257     if ( (*res->operationStatus != Z_ExtendedServicesResponse_failure) &&
1258         (res->num_diagnostics != 0) ) {
1259         display_diagrecs(res->diagnostics, res->num_diagnostics);
1260     }
1261     print_refid (res->referenceId);
1262     if (res->taskPackage && 
1263         res->taskPackage->which == Z_External_extendedService)
1264     {
1265         Z_TaskPackage *taskPackage = res->taskPackage->u.extendedService;
1266         Odr_oct *id = taskPackage->targetReference;
1267         Z_External *ext = taskPackage->taskSpecificParameters;
1268         
1269         if (id)
1270         {
1271             printf ("Target Reference: ");
1272             print_stringn (id->buf, id->len);
1273             printf ("\n");
1274         }
1275         if (ext->which == Z_External_update)
1276         {
1277             Z_IUUpdateTaskPackage *utp = ext->u.update->u.taskPackage;
1278             if (utp && utp->targetPart)
1279             {
1280                 Z_IUTargetPart *targetPart = utp->targetPart;
1281                 int i;
1282
1283                 for (i = 0; i<targetPart->num_taskPackageRecords;  i++)
1284                 {
1285
1286                     Z_IUTaskPackageRecordStructure *tpr =
1287                         targetPart->taskPackageRecords[i];
1288                     printf ("task package record %d\n", i+1);
1289                     if (tpr->which == Z_IUTaskPackageRecordStructure_record)
1290                     {
1291                         display_record (tpr->u.record);
1292                     }
1293                     else
1294                     {
1295                         printf ("other type\n");
1296                     }
1297                 }
1298             }
1299         }
1300     }
1301 }
1302
1303 const char *get_ill_element (void *clientData, const char *element)
1304 {
1305     return 0;
1306 }
1307
1308 static Z_External *create_external_itemRequest()
1309 {
1310     struct ill_get_ctl ctl;
1311     ILL_ItemRequest *req;
1312     Z_External *r = 0;
1313     int item_request_size = 0;
1314     char *item_request_buf = 0;
1315
1316     ctl.odr = out;
1317     ctl.clientData = 0;
1318     ctl.f = get_ill_element;
1319     
1320     req = ill_get_ItemRequest(&ctl, "ill", 0);
1321     if (!req)
1322         printf ("ill_get_ItemRequest failed\n");
1323         
1324     if (!ill_ItemRequest (out, &req, 0, 0))
1325     {
1326         if (apdu_file)
1327         {
1328             ill_ItemRequest(print, &req, 0, 0);
1329             odr_reset(print);
1330         }
1331         item_request_buf = odr_getbuf (out, &item_request_size, 0);
1332         if (item_request_buf)
1333             odr_setbuf (out, item_request_buf, item_request_size, 1);
1334         printf ("Couldn't encode ItemRequest, size %d\n", item_request_size);
1335         return 0;
1336     }
1337     else
1338     {
1339         oident oid;
1340         
1341         item_request_buf = odr_getbuf (out, &item_request_size, 0);
1342         oid.proto = PROTO_GENERAL;
1343         oid.oclass = CLASS_GENERAL;
1344         oid.value = VAL_ISO_ILL_1;
1345         
1346         r = (Z_External *) odr_malloc (out, sizeof(*r));
1347         r->direct_reference = odr_oiddup(out,oid_getoidbyent(&oid)); 
1348         r->indirect_reference = 0;
1349         r->descriptor = 0;
1350         r->which = Z_External_single;
1351         
1352         r->u.single_ASN1_type = (Odr_oct *)
1353             odr_malloc (out, sizeof(*r->u.single_ASN1_type));
1354         r->u.single_ASN1_type->buf = (unsigned char *)
1355         odr_malloc (out, item_request_size);
1356         r->u.single_ASN1_type->len = item_request_size;
1357         r->u.single_ASN1_type->size = item_request_size;
1358         memcpy (r->u.single_ASN1_type->buf, item_request_buf,
1359                 item_request_size);
1360         
1361         do_hex_dump(item_request_buf,item_request_size);
1362     }
1363     return r;
1364 }
1365
1366 static Z_External *create_external_ILL_APDU(int which)
1367 {
1368     struct ill_get_ctl ctl;
1369     ILL_APDU *ill_apdu;
1370     Z_External *r = 0;
1371     int ill_request_size = 0;
1372     char *ill_request_buf = 0;
1373         
1374     ctl.odr = out;
1375     ctl.clientData = 0;
1376     ctl.f = get_ill_element;
1377
1378     ill_apdu = ill_get_APDU(&ctl, "ill", 0);
1379
1380     if (!ill_APDU (out, &ill_apdu, 0, 0))
1381     {
1382         if (apdu_file)
1383         {
1384             printf ("-------------------\n");
1385             ill_APDU(print, &ill_apdu, 0, 0);
1386             odr_reset(print);
1387             printf ("-------------------\n");
1388         }
1389         ill_request_buf = odr_getbuf (out, &ill_request_size, 0);
1390         if (ill_request_buf)
1391             odr_setbuf (out, ill_request_buf, ill_request_size, 1);
1392         printf ("Couldn't encode ILL-Request, size %d\n", ill_request_size);
1393         return 0;
1394     }
1395     else
1396     {
1397         oident oid;
1398         ill_request_buf = odr_getbuf (out, &ill_request_size, 0);
1399         
1400         oid.proto = PROTO_GENERAL;
1401         oid.oclass = CLASS_GENERAL;
1402         oid.value = VAL_ISO_ILL_1;
1403         
1404         r = (Z_External *) odr_malloc (out, sizeof(*r));
1405         r->direct_reference = odr_oiddup(out,oid_getoidbyent(&oid)); 
1406         r->indirect_reference = 0;
1407         r->descriptor = 0;
1408         r->which = Z_External_single;
1409         
1410         r->u.single_ASN1_type = (Odr_oct *)
1411             odr_malloc (out, sizeof(*r->u.single_ASN1_type));
1412         r->u.single_ASN1_type->buf = (unsigned char *)
1413         odr_malloc (out, ill_request_size);
1414         r->u.single_ASN1_type->len = ill_request_size;
1415         r->u.single_ASN1_type->size = ill_request_size;
1416         memcpy (r->u.single_ASN1_type->buf, ill_request_buf, ill_request_size);
1417 /*         printf ("len = %d\n", ill_request_size); */
1418 /*              do_hex_dump(ill_request_buf,ill_request_size); */
1419 /*              printf("--- end of extenal\n"); */
1420
1421     }
1422     return r;
1423 }
1424
1425
1426 static Z_External *create_ItemOrderExternal(const char *type, int itemno)
1427 {
1428     Z_External *r = (Z_External *) odr_malloc(out, sizeof(Z_External));
1429     oident ItemOrderRequest;
1430   
1431     ItemOrderRequest.proto = PROTO_Z3950;
1432     ItemOrderRequest.oclass = CLASS_EXTSERV;
1433     ItemOrderRequest.value = VAL_ITEMORDER;
1434  
1435     r->direct_reference = odr_oiddup(out,oid_getoidbyent(&ItemOrderRequest)); 
1436     r->indirect_reference = 0;
1437     r->descriptor = 0;
1438
1439     r->which = Z_External_itemOrder;
1440
1441     r->u.itemOrder = (Z_ItemOrder *) odr_malloc(out,sizeof(Z_ItemOrder));
1442     memset(r->u.itemOrder, 0, sizeof(Z_ItemOrder));
1443     r->u.itemOrder->which=Z_IOItemOrder_esRequest;
1444
1445     r->u.itemOrder->u.esRequest = (Z_IORequest *) 
1446         odr_malloc(out,sizeof(Z_IORequest));
1447     memset(r->u.itemOrder->u.esRequest, 0, sizeof(Z_IORequest));
1448
1449     r->u.itemOrder->u.esRequest->toKeep = (Z_IOOriginPartToKeep *)
1450         odr_malloc(out,sizeof(Z_IOOriginPartToKeep));
1451     memset(r->u.itemOrder->u.esRequest->toKeep, 0, sizeof(Z_IOOriginPartToKeep));
1452     r->u.itemOrder->u.esRequest->notToKeep = (Z_IOOriginPartNotToKeep *)
1453         odr_malloc(out,sizeof(Z_IOOriginPartNotToKeep));
1454     memset(r->u.itemOrder->u.esRequest->notToKeep, 0, sizeof(Z_IOOriginPartNotToKeep));
1455
1456     r->u.itemOrder->u.esRequest->toKeep->supplDescription = NULL;
1457     r->u.itemOrder->u.esRequest->toKeep->contact = NULL;
1458     r->u.itemOrder->u.esRequest->toKeep->addlBilling = NULL;
1459
1460     r->u.itemOrder->u.esRequest->notToKeep->resultSetItem =
1461         (Z_IOResultSetItem *) odr_malloc(out, sizeof(Z_IOResultSetItem));
1462     memset(r->u.itemOrder->u.esRequest->notToKeep->resultSetItem, 0, sizeof(Z_IOResultSetItem));
1463     r->u.itemOrder->u.esRequest->notToKeep->resultSetItem->resultSetId = "1";
1464
1465     r->u.itemOrder->u.esRequest->notToKeep->resultSetItem->item =
1466         (int *) odr_malloc(out, sizeof(int));
1467     *r->u.itemOrder->u.esRequest->notToKeep->resultSetItem->item = itemno;
1468
1469     if (!strcmp (type, "item") || !strcmp(type, "2"))
1470     {
1471         printf ("using item-request\n");
1472         r->u.itemOrder->u.esRequest->notToKeep->itemRequest = 
1473             create_external_itemRequest();
1474     }
1475     else if (!strcmp(type, "ill") || !strcmp(type, "1"))
1476     {
1477         printf ("using ILL-request\n");
1478         r->u.itemOrder->u.esRequest->notToKeep->itemRequest = 
1479             create_external_ILL_APDU(ILL_APDU_ILL_Request);
1480     }
1481     else if (!strcmp(type, "xml") || !strcmp(type, "3"))
1482     {
1483     const char *xml_buf =
1484         "<itemorder>\n"
1485         "  <type>request</type>\n"
1486         "  <libraryNo>000200</libraryNo>\n"
1487         "  <borrowerTicketNo> 1212 </borrowerTicketNo>\n"
1488         "</itemorder>";
1489         r->u.itemOrder->u.esRequest->notToKeep->itemRequest =
1490             z_ext_record (out, VAL_TEXT_XML, xml_buf, strlen(xml_buf));
1491     }
1492     else
1493         r->u.itemOrder->u.esRequest->notToKeep->itemRequest = 0;
1494
1495     return r;
1496 }
1497
1498 static int send_itemorder(const char *type, int itemno)
1499 {
1500     Z_APDU *apdu = zget_APDU(out, Z_APDU_extendedServicesRequest);
1501     Z_ExtendedServicesRequest *req = apdu->u.extendedServicesRequest;
1502     oident ItemOrderRequest;
1503
1504     ItemOrderRequest.proto = PROTO_Z3950;
1505     ItemOrderRequest.oclass = CLASS_EXTSERV;
1506     ItemOrderRequest.value = VAL_ITEMORDER;
1507     req->packageType = odr_oiddup(out,oid_getoidbyent(&ItemOrderRequest));
1508     req->packageName = esPackageName;
1509
1510     req->taskSpecificParameters = create_ItemOrderExternal(type, itemno);
1511
1512     send_apdu(apdu);
1513     return 0;
1514 }
1515
1516 static int cmd_update(const char *arg)
1517 {
1518     Z_APDU *apdu = zget_APDU(out, Z_APDU_extendedServicesRequest );
1519     Z_ExtendedServicesRequest *req = apdu->u.extendedServicesRequest;
1520     Z_External *r;
1521     int oid[OID_SIZE];
1522     Z_IUOriginPartToKeep *toKeep;
1523     Z_IUSuppliedRecords *notToKeep;
1524     oident update_oid;
1525     char action[20], recid[20], fname[80];
1526     int action_no;
1527     Z_External *record_this = 0;
1528
1529     *action = 0;
1530     *recid = 0;
1531     *fname = 0;
1532     sscanf (arg, "%19s %19s %79s", action, recid, fname);
1533
1534     if (!strcmp (action, "insert"))
1535         action_no = Z_IUOriginPartToKeep_recordInsert;
1536     else if (!strcmp (action, "replace"))
1537         action_no = Z_IUOriginPartToKeep_recordReplace;
1538     else if (!strcmp (action, "delete"))
1539         action_no = Z_IUOriginPartToKeep_recordDelete;
1540     else if (!strcmp (action, "update"))
1541         action_no = Z_IUOriginPartToKeep_specialUpdate;
1542     else 
1543     {
1544         printf ("Bad action: %s\n", action);
1545         printf ("Possible values: insert, replace, delete, update\n");
1546         return 0;
1547     }
1548
1549     if (*fname)
1550     {
1551         FILE *inf;
1552         struct stat status;
1553         stat (fname, &status);
1554         if (S_ISREG(status.st_mode) && (inf = fopen(fname, "r")))
1555         {
1556             size_t len = status.st_size;
1557             char *buf = (char *) xmalloc (len);
1558
1559             fread (buf, 1, len, inf);
1560
1561             fclose (inf);
1562             
1563             record_this = z_ext_record (out, VAL_TEXT_XML, buf, len);
1564             
1565             xfree (buf);
1566         }
1567         else
1568         {
1569             printf ("File %s doesn't exist\n", fname);
1570             return 0;
1571         }
1572     }
1573     else
1574     {
1575         if (!record_last)
1576         {
1577             printf ("No last record (update ignored)\n");
1578             return 0;
1579         }
1580         record_this = record_last;
1581     }
1582
1583     update_oid.proto = PROTO_Z3950;
1584     update_oid.oclass = CLASS_EXTSERV;
1585     update_oid.value = VAL_DBUPDATE;
1586     oid_ent_to_oid (&update_oid, oid);
1587     req->packageType = odr_oiddup(out,oid);
1588     req->packageName = esPackageName;
1589     
1590     req->referenceId = set_refid (out);
1591
1592     r = req->taskSpecificParameters = (Z_External *)
1593         odr_malloc (out, sizeof(*r));
1594     r->direct_reference = odr_oiddup(out,oid);
1595     r->indirect_reference = 0;
1596     r->descriptor = 0;
1597     r->which = Z_External_update;
1598     r->u.update = (Z_IUUpdate *) odr_malloc(out, sizeof(*r->u.update));
1599     r->u.update->which = Z_IUUpdate_esRequest;
1600     r->u.update->u.esRequest = (Z_IUUpdateEsRequest *)
1601         odr_malloc(out, sizeof(*r->u.update->u.esRequest));
1602     toKeep = r->u.update->u.esRequest->toKeep = (Z_IUOriginPartToKeep *)
1603         odr_malloc(out, sizeof(*r->u.update->u.esRequest->toKeep));
1604     toKeep->databaseName = databaseNames[0];
1605     toKeep->schema = 0;
1606     toKeep->elementSetName = 0;
1607     toKeep->actionQualifier = 0;
1608     toKeep->action = (int *) odr_malloc(out, sizeof(*toKeep->action));
1609     *toKeep->action = action_no;
1610
1611     notToKeep = r->u.update->u.esRequest->notToKeep = (Z_IUSuppliedRecords *)
1612         odr_malloc(out, sizeof(*r->u.update->u.esRequest->notToKeep));
1613     notToKeep->num = 1;
1614     notToKeep->elements = (Z_IUSuppliedRecords_elem **)
1615         odr_malloc(out, sizeof(*notToKeep->elements));
1616     notToKeep->elements[0] = (Z_IUSuppliedRecords_elem *)
1617         odr_malloc(out, sizeof(**notToKeep->elements));
1618     notToKeep->elements[0]->which = Z_IUSuppliedRecords_elem_opaque;
1619     if (*recid)
1620     {
1621         notToKeep->elements[0]->u.opaque = (Odr_oct *)
1622             odr_malloc (out, sizeof(Odr_oct));
1623         notToKeep->elements[0]->u.opaque->buf = (unsigned char *) recid;
1624         notToKeep->elements[0]->u.opaque->size = strlen(recid);
1625         notToKeep->elements[0]->u.opaque->len = strlen(recid);
1626     }
1627     else
1628         notToKeep->elements[0]->u.opaque = 0;
1629     notToKeep->elements[0]->supplementalId = 0;
1630     notToKeep->elements[0]->correlationInfo = 0;
1631     notToKeep->elements[0]->record = record_this;
1632     
1633     send_apdu(apdu);
1634
1635     return 2;
1636 }
1637
1638 static int cmd_itemorder(const char *arg)
1639 {
1640     char type[12];
1641     int itemno;
1642     
1643     if (sscanf (arg, "%10s %d", type, &itemno) != 2)
1644         return 0;
1645
1646     printf("Item order request\n");
1647     fflush(stdout);
1648     send_itemorder(type, itemno);
1649     return 2;
1650 }
1651
1652 static int cmd_find(const char *arg)
1653 {
1654     if (!*arg)
1655     {
1656         printf("Find what?\n");
1657         return 0;
1658     }
1659     if (!conn)
1660     {
1661         try_reconnect(); 
1662         
1663         if (!conn) {                                    
1664             printf("Not connected yet\n");
1665             return 0;
1666         }
1667     }
1668     if (!send_searchRequest(arg))
1669         return 0;
1670     return 2;
1671 }
1672
1673 static int cmd_delete(const char *arg)
1674 {
1675     if (!conn)
1676     {
1677         printf("Not connected yet\n");
1678         return 0;
1679     }
1680     if (!send_deleteResultSetRequest(arg))
1681         return 0;
1682     return 2;
1683 }
1684
1685 static int cmd_ssub(const char *arg)
1686 {
1687     if (!(smallSetUpperBound = atoi(arg)))
1688         return 0;
1689     return 1;
1690 }
1691
1692 static int cmd_lslb(const char *arg)
1693 {
1694     if (!(largeSetLowerBound = atoi(arg)))
1695         return 0;
1696     return 1;
1697 }
1698
1699 static int cmd_mspn(const char *arg)
1700 {
1701     if (!(mediumSetPresentNumber = atoi(arg)))
1702         return 0;
1703     return 1;
1704 }
1705
1706 static int cmd_status(const char *arg)
1707 {
1708     printf("smallSetUpperBound: %d\n", smallSetUpperBound);
1709     printf("largeSetLowerBound: %d\n", largeSetLowerBound);
1710     printf("mediumSetPresentNumber: %d\n", mediumSetPresentNumber);
1711     return 1;
1712 }
1713
1714 static int cmd_setnames(const char *arg)
1715 {
1716     if (*arg == '1')         /* enable ? */
1717         setnumber = 0;
1718     else if (*arg == '0')    /* disable ? */
1719         setnumber = -1;
1720     else if (setnumber < 0)  /* no args, toggle .. */
1721         setnumber = 0;
1722     else
1723         setnumber = -1;
1724    
1725     if (setnumber >= 0)
1726         printf("Set numbering enabled.\n");
1727     else
1728         printf("Set numbering disabled.\n");
1729     return 1;
1730 }
1731
1732 /* PRESENT SERVICE ----------------------------- */
1733
1734 static int send_presentRequest(const char *arg)
1735 {
1736     Z_APDU *apdu = zget_APDU(out, Z_APDU_presentRequest);
1737     Z_PresentRequest *req = apdu->u.presentRequest;
1738     Z_RecordComposition compo;
1739     oident prefsyn;
1740     int nos = 1;
1741     int oid[OID_SIZE];
1742     char *p;
1743     char setstring[100];
1744
1745     req->referenceId = set_refid (out);
1746     if ((p = strchr(arg, '+')))
1747     {
1748         nos = atoi(p + 1);
1749         *p = 0;
1750     }
1751     if (*arg)
1752         setno = atoi(arg);
1753     if (p && (p=strchr(p+1, '+')))
1754     {
1755         strcpy (setstring, p+1);
1756         req->resultSetId = setstring;
1757     }
1758     else if (setnumber >= 0)
1759     {
1760         sprintf(setstring, "%d", setnumber);
1761         req->resultSetId = setstring;
1762     }
1763     req->resultSetStartPoint = &setno;
1764     req->numberOfRecordsRequested = &nos;
1765     prefsyn.proto = protocol;
1766     prefsyn.oclass = CLASS_RECSYN;
1767     prefsyn.value = recordsyntax;
1768     req->preferredRecordSyntax =
1769         odr_oiddup (out, oid_ent_to_oid(&prefsyn, oid));
1770
1771     if (schema != VAL_NONE)
1772     {
1773         oident prefschema;
1774
1775         prefschema.proto = protocol;
1776         prefschema.oclass = CLASS_SCHEMA;
1777         prefschema.value = schema;
1778
1779         req->recordComposition = &compo;
1780         compo.which = Z_RecordComp_complex;
1781         compo.u.complex = (Z_CompSpec *)
1782             odr_malloc(out, sizeof(*compo.u.complex));
1783         compo.u.complex->selectAlternativeSyntax = (bool_t *) 
1784             odr_malloc(out, sizeof(bool_t));
1785         *compo.u.complex->selectAlternativeSyntax = 0;
1786
1787         compo.u.complex->generic = (Z_Specification *)
1788             odr_malloc(out, sizeof(*compo.u.complex->generic));
1789         compo.u.complex->generic->which = Z_Schema_oid;
1790         compo.u.complex->generic->schema.oid = (Odr_oid *)
1791             odr_oiddup(out, oid_ent_to_oid(&prefschema, oid));
1792         if (!compo.u.complex->generic->schema.oid)
1793         {
1794             /* OID wasn't a schema! Try record syntax instead. */
1795             prefschema.oclass = CLASS_RECSYN;
1796             compo.u.complex->generic->schema.oid = (Odr_oid *)
1797                 odr_oiddup(out, oid_ent_to_oid(&prefschema, oid));
1798         }
1799         if (!elementSetNames)
1800             compo.u.complex->generic->elementSpec = 0;
1801         else
1802         {
1803             compo.u.complex->generic->elementSpec = (Z_ElementSpec *)
1804                 odr_malloc(out, sizeof(Z_ElementSpec));
1805             compo.u.complex->generic->elementSpec->which =
1806                 Z_ElementSpec_elementSetName;
1807             compo.u.complex->generic->elementSpec->u.elementSetName =
1808                 elementSetNames->u.generic;
1809         }
1810         compo.u.complex->num_dbSpecific = 0;
1811         compo.u.complex->dbSpecific = 0;
1812         compo.u.complex->num_recordSyntax = 0;
1813         compo.u.complex->recordSyntax = 0;
1814     }
1815     else if (elementSetNames)
1816     {
1817         req->recordComposition = &compo;
1818         compo.which = Z_RecordComp_simple;
1819         compo.u.simple = elementSetNames;
1820     }
1821     send_apdu(apdu);
1822     printf("Sent presentRequest (%d+%d).\n", setno, nos);
1823     return 2;
1824 }
1825     
1826 static void close_session (void)
1827 {
1828     cs_close (conn);
1829     conn = 0;
1830     if (session_mem)
1831     {
1832         nmem_destroy (session_mem);
1833         session_mem = NULL;
1834     }
1835     sent_close = 0;
1836     odr_reset(out);
1837     odr_reset(in);
1838     odr_reset(print);
1839 }
1840
1841 void process_close(Z_Close *req)
1842 {
1843     Z_APDU *apdu = zget_APDU(out, Z_APDU_close);
1844     Z_Close *res = apdu->u.close;
1845
1846     static char *reasons[] =
1847     {
1848         "finished",
1849         "shutdown",
1850         "system problem",
1851         "cost limit reached",
1852         "resources",
1853         "security violation",
1854         "protocolError",
1855         "lack of activity",
1856         "peer abort",
1857         "unspecified"
1858     };
1859
1860     printf("Reason: %s, message: %s\n", reasons[*req->closeReason],
1861         req->diagnosticInformation ? req->diagnosticInformation : "NULL");
1862     if (sent_close)
1863         close_session ();
1864     else
1865     {
1866         *res->closeReason = Z_Close_finished;
1867         send_apdu(apdu);
1868         printf("Sent response.\n");
1869         sent_close = 1;
1870     }
1871 }
1872
1873 static int cmd_show(const char *arg)
1874 {
1875     if (!conn)
1876     {
1877         printf("Not connected yet\n");
1878         return 0;
1879     }
1880     if (!send_presentRequest(arg))
1881         return 0;
1882     return 2;
1883 }
1884
1885 int cmd_quit(const char *arg)
1886 {
1887     printf("See you later, alligator.\n");
1888     xmalloc_trav ("");
1889     exit(0);
1890     return 0;
1891 }
1892
1893 int cmd_cancel(const char *arg)
1894 {
1895     Z_APDU *apdu = zget_APDU(out, Z_APDU_triggerResourceControlRequest);
1896     Z_TriggerResourceControlRequest *req =
1897         apdu->u.triggerResourceControlRequest;
1898     bool_t rfalse = 0;
1899     
1900     if (!conn)
1901     {
1902         printf("Session not initialized yet\n");
1903         return 0;
1904     }
1905     if (!ODR_MASK_GET(session->options, Z_Options_triggerResourceCtrl))
1906     {
1907         printf("Target doesn't support cancel (trigger resource ctrl)\n");
1908         return 0;
1909     }
1910     *req->requestedAction = Z_TriggerResourceCtrl_cancel;
1911     req->resultSetWanted = &rfalse;
1912
1913     send_apdu(apdu);
1914     printf("Sent cancel request\n");
1915     return 2;
1916 }
1917
1918 int send_scanrequest(const char *query, int pp, int num, const char *term)
1919 {
1920     Z_APDU *apdu = zget_APDU(out, Z_APDU_scanRequest);
1921     Z_ScanRequest *req = apdu->u.scanRequest;
1922     int oid[OID_SIZE];
1923     
1924     if (queryType == QueryType_CCL2RPN)
1925     {
1926         oident bib1;
1927         int error, pos;
1928         struct ccl_rpn_node *rpn;
1929
1930         rpn = ccl_find_str (bibset,  query, &error, &pos);
1931         if (error)
1932         {
1933             printf("CCL ERROR: %s\n", ccl_err_msg(error));
1934             return -1;
1935         }
1936         bib1.proto = PROTO_Z3950;
1937         bib1.oclass = CLASS_ATTSET;
1938         bib1.value = VAL_BIB1;
1939         req->attributeSet = oid_ent_to_oid (&bib1, oid);
1940         if (!(req->termListAndStartPoint = ccl_scan_query (out, rpn)))
1941         {
1942             printf("Couldn't convert CCL to Scan term\n");
1943             return -1;
1944         }
1945         ccl_rpn_delete (rpn);
1946     }
1947     else
1948     {
1949         YAZ_PQF_Parser pqf_parser = yaz_pqf_create ();
1950
1951         if (!(req->termListAndStartPoint =
1952               yaz_pqf_scan(pqf_parser, out, &req->attributeSet, query)))
1953         {
1954             const char *pqf_msg;
1955             size_t off;
1956             int code = yaz_pqf_error (pqf_parser, &pqf_msg, &off);
1957             printf("%*s^\n", off+7, "");
1958             printf("Prefix query error: %s (code %d)\n", pqf_msg, code);
1959             yaz_pqf_destroy (pqf_parser);
1960             return -1;
1961         }
1962         yaz_pqf_destroy (pqf_parser);
1963     }
1964     if (term && *term)
1965     {
1966         if (req->termListAndStartPoint->term &&
1967             req->termListAndStartPoint->term->which == Z_Term_general &&
1968             req->termListAndStartPoint->term->u.general)
1969         {
1970             req->termListAndStartPoint->term->u.general->buf =
1971                 (unsigned char *) odr_strdup(out, term);
1972             req->termListAndStartPoint->term->u.general->len =
1973                 req->termListAndStartPoint->term->u.general->size =
1974                 strlen(term);
1975         }
1976     }
1977     req->referenceId = set_refid (out);
1978     req->num_databaseNames = num_databaseNames;
1979     req->databaseNames = databaseNames;
1980     req->numberOfTermsRequested = &num;
1981     req->preferredPositionInResponse = &pp;
1982     send_apdu(apdu);
1983     return 2;
1984 }
1985
1986 int send_sortrequest(const char *arg, int newset)
1987 {
1988     Z_APDU *apdu = zget_APDU(out, Z_APDU_sortRequest);
1989     Z_SortRequest *req = apdu->u.sortRequest;
1990     Z_SortKeySpecList *sksl = (Z_SortKeySpecList *)
1991         odr_malloc (out, sizeof(*sksl));
1992     char setstring[32];
1993
1994     if (setnumber >= 0)
1995         sprintf (setstring, "%d", setnumber);
1996     else
1997         sprintf (setstring, "default");
1998
1999     req->referenceId = set_refid (out);
2000
2001     req->num_inputResultSetNames = 1;
2002     req->inputResultSetNames = (Z_InternationalString **)
2003         odr_malloc (out, sizeof(*req->inputResultSetNames));
2004     req->inputResultSetNames[0] = odr_strdup (out, setstring);
2005
2006     if (newset && setnumber >= 0)
2007         sprintf (setstring, "%d", ++setnumber);
2008
2009     req->sortedResultSetName = odr_strdup (out, setstring);
2010
2011     req->sortSequence = yaz_sort_spec (out, arg);
2012     if (!req->sortSequence)
2013     {
2014         printf ("Missing sort specifications\n");
2015         return -1;
2016     }
2017     send_apdu(apdu);
2018     return 2;
2019 }
2020
2021 void display_term(Z_TermInfo *t)
2022 {
2023     if (t->term->which == Z_Term_general)
2024     {
2025         printf("%.*s", t->term->u.general->len, t->term->u.general->buf);
2026         sprintf(last_scan_line, "%.*s", t->term->u.general->len,
2027             t->term->u.general->buf);
2028     }
2029     else
2030         printf("Term (not general)");
2031     if (t->globalOccurrences)
2032         printf (" (%d)\n", *t->globalOccurrences);
2033     else
2034         printf ("\n");
2035 }
2036
2037 void process_scanResponse(Z_ScanResponse *res)
2038 {
2039     int i;
2040     Z_Entry **entries = NULL;
2041     int num_entries = 0;
2042    
2043     printf("Received ScanResponse\n"); 
2044     print_refid (res->referenceId);
2045     printf("%d entries", *res->numberOfEntriesReturned);
2046     if (res->positionOfTerm)
2047         printf (", position=%d", *res->positionOfTerm); 
2048     printf ("\n");
2049     if (*res->scanStatus != Z_Scan_success)
2050         printf("Scan returned code %d\n", *res->scanStatus);
2051     if (!res->entries)
2052         return;
2053     if ((entries = res->entries->entries))
2054         num_entries = res->entries->num_entries;
2055     for (i = 0; i < num_entries; i++)
2056     {
2057         int pos_term = res->positionOfTerm ? *res->positionOfTerm : -1;
2058         if (entries[i]->which == Z_Entry_termInfo)
2059         {
2060             printf("%c ", i + 1 == pos_term ? '*' : ' ');
2061             display_term(entries[i]->u.termInfo);
2062         }
2063         else
2064             display_diagrecs(&entries[i]->u.surrogateDiagnostic, 1);
2065     }
2066     if (res->entries->nonsurrogateDiagnostics)
2067         display_diagrecs (res->entries->nonsurrogateDiagnostics,
2068                           res->entries->num_nonsurrogateDiagnostics);
2069 }
2070
2071 void process_sortResponse(Z_SortResponse *res)
2072 {
2073     printf("Received SortResponse: status=");
2074     switch (*res->sortStatus)
2075     {
2076     case Z_SortStatus_success:
2077         printf ("success"); break;
2078     case Z_SortStatus_partial_1:
2079         printf ("partial"); break;
2080     case Z_SortStatus_failure:
2081         printf ("failure"); break;
2082     default:
2083         printf ("unknown (%d)", *res->sortStatus);
2084     }
2085     printf ("\n");
2086     print_refid (res->referenceId);
2087     if (res->diagnostics)
2088         display_diagrecs(res->diagnostics,
2089                          res->num_diagnostics);
2090 }
2091
2092 void process_deleteResultSetResponse (Z_DeleteResultSetResponse *res)
2093 {
2094     printf("Got deleteResultSetResponse status=%d\n",
2095            *res->deleteOperationStatus);
2096     if (res->deleteListStatuses)
2097     {
2098         int i;
2099         for (i = 0; i < res->deleteListStatuses->num; i++)
2100         {
2101             printf ("%s status=%d\n", res->deleteListStatuses->elements[i]->id,
2102                     *res->deleteListStatuses->elements[i]->status);
2103         }
2104     }
2105 }
2106
2107 int cmd_sort_generic(const char *arg, int newset)
2108 {
2109     if (!conn)
2110     {
2111         printf("Session not initialized yet\n");
2112         return 0;
2113     }
2114     if (!ODR_MASK_GET(session->options, Z_Options_sort))
2115     {
2116         printf("Target doesn't support sort\n");
2117         return 0;
2118     }
2119     if (*arg)
2120     {
2121         if (send_sortrequest(arg, newset) < 0)
2122             return 0;
2123         return 2;
2124     }
2125     return 0;
2126 }
2127
2128 int cmd_sort(const char *arg)
2129 {
2130     return cmd_sort_generic (arg, 0);
2131 }
2132
2133 int cmd_sort_newset (const char *arg)
2134 {
2135     return cmd_sort_generic (arg, 1);
2136 }
2137
2138 int cmd_scan(const char *arg)
2139 {
2140     if (!conn)
2141     {
2142         try_reconnect();
2143         
2144         if (!conn) {                                                            
2145             printf("Session not initialized yet\n");
2146             return 0;
2147         }
2148     }
2149     if (!ODR_MASK_GET(session->options, Z_Options_scan))
2150     {
2151         printf("Target doesn't support scan\n");
2152         return 0;
2153     }
2154     if (*arg)
2155     {
2156         strcpy (last_scan_query, arg);
2157         if (send_scanrequest(arg, 1, 20, 0) < 0)
2158             return 0;
2159     }
2160     else
2161     {
2162         if (send_scanrequest(last_scan_query, 1, 20, last_scan_line) < 0)
2163             return 0;
2164     }
2165     return 2;
2166 }
2167
2168 int cmd_schema(const char *arg)
2169 {
2170     if (!arg || !*arg)
2171     {
2172         schema = VAL_NONE;
2173         return 1;
2174     }
2175     schema = oid_getvalbyname (arg);
2176     if (schema == VAL_NONE)
2177     {
2178         printf ("unknown schema\n");
2179         return 0;
2180     }
2181     return 1;
2182 }
2183
2184 int cmd_format(const char *arg)
2185 {
2186     oid_value nsyntax;
2187     if (!arg || !*arg)
2188     {
2189         printf("Usage: format <recordsyntax>\n");
2190         return 0;
2191     }
2192     nsyntax = oid_getvalbyname (arg);
2193     if (strcmp(arg, "none") && nsyntax == VAL_NONE)
2194     {
2195         printf ("unknown record syntax\n");
2196         return 0;
2197     }
2198     recordsyntax = nsyntax;
2199     return 1;
2200 }
2201
2202 int cmd_elements(const char *arg)
2203 {
2204     static Z_ElementSetNames esn;
2205     static char what[100];
2206
2207     if (!arg || !*arg)
2208     {
2209         elementSetNames = 0;
2210         return 1;
2211     }
2212     strcpy(what, arg);
2213     esn.which = Z_ElementSetNames_generic;
2214     esn.u.generic = what;
2215     elementSetNames = &esn;
2216     return 1;
2217 }
2218
2219 int cmd_attributeset(const char *arg)
2220 {
2221     char what[100];
2222
2223     if (!arg || !*arg)
2224     {
2225         printf("Usage: attributeset <setname>\n");
2226         return 0;
2227     }
2228     sscanf(arg, "%s", what);
2229     if (p_query_attset (what))
2230     {
2231         printf("Unknown attribute set name\n");
2232         return 0;
2233     }
2234     return 1;
2235 }
2236
2237 int cmd_querytype (const char *arg)
2238 {
2239     if (!strcmp (arg, "ccl"))
2240         queryType = QueryType_CCL;
2241     else if (!strcmp (arg, "prefix") || !strcmp(arg, "rpn"))
2242         queryType = QueryType_Prefix;
2243     else if (!strcmp (arg, "ccl2rpn") || !strcmp (arg, "cclrpn"))
2244         queryType = QueryType_CCL2RPN;
2245     else if (!strcmp(arg, "cql"))
2246         queryType = QueryType_CQL;        
2247     else
2248     {
2249         printf ("Querytype must be one of:\n");
2250         printf (" prefix         - Prefix query\n");
2251         printf (" ccl            - CCL query\n");
2252         printf (" ccl2rpn        - CCL query converted to RPN\n");
2253         printf (" cql            - CQL\n");
2254         return 0;
2255     }
2256     return 1;
2257 }
2258
2259 int cmd_refid (const char *arg)
2260 {
2261     xfree (refid);
2262     refid = NULL;
2263     if (*arg)
2264     {
2265         refid = (char *) xmalloc (strlen(arg)+1);
2266         strcpy (refid, arg);
2267     }
2268     return 1;
2269 }
2270
2271 int cmd_close(const char *arg)
2272 {
2273     Z_APDU *apdu;
2274     Z_Close *req;
2275     if (!conn)
2276         return 0;
2277
2278     apdu = zget_APDU(out, Z_APDU_close);
2279     req = apdu->u.close;
2280     *req->closeReason = Z_Close_finished;
2281     send_apdu(apdu);
2282     printf("Sent close request.\n");
2283     sent_close = 1;
2284     return 2;
2285 }
2286
2287 int cmd_packagename(const char* arg)
2288 {
2289     xfree (esPackageName);
2290     esPackageName = NULL;
2291     if (*arg)
2292     {
2293         esPackageName = (char *) xmalloc (strlen(arg)+1);
2294         strcpy (esPackageName, arg);
2295     }
2296     return 1;
2297 }
2298
2299 int cmd_proxy(const char* arg)
2300 {
2301     if (*arg == '\0') {
2302                 xfree (yazProxy);
2303                 yazProxy = NULL;
2304         
2305     }
2306     xfree (yazProxy);
2307     yazProxy = NULL;
2308     if (*arg)
2309     {
2310         yazProxy = (char *) xmalloc (strlen(arg)+1);
2311         strcpy (yazProxy, arg);
2312     } 
2313     return 1;
2314 }
2315
2316 int cmd_charset(const char* arg)
2317 {
2318     char l1[30], l2[30];
2319
2320     *l1 = *l2 = 0;
2321     if (sscanf(arg, "%29s %29s", l1, l2) < 1)
2322     {
2323         printf("Current character set is `%s'\n", (yazCharset) ? yazCharset:NULL);
2324         return 1;
2325     }
2326     xfree (yazCharset);
2327     yazCharset = NULL;
2328     if (*l1)
2329         yazCharset = xstrdup(l1);
2330     if (*l2)
2331     {
2332         odr_set_charset (out, l1, l2);
2333         odr_set_charset (in, l2, l1);
2334     }
2335     return 1;
2336 }
2337
2338 int cmd_lang(const char* arg)
2339 {
2340     if (*arg == '\0') {
2341         printf("Current language is `%s'\n", (yazLang)?yazLang:NULL);
2342         return 1;
2343     }
2344     xfree (yazLang);
2345     yazLang = NULL;
2346     if (*arg)
2347     {
2348         yazLang = (char *) xmalloc (strlen(arg)+1);
2349         strcpy (yazLang, arg);
2350     } 
2351     return 1;
2352 }
2353
2354 int cmd_source(const char* arg) 
2355 {
2356     /* first should open the file and read one line at a time.. */
2357     FILE* includeFile;
2358     char line[1024], *cp;
2359
2360     if(strlen(arg)<1) {
2361         fprintf(stderr,"Error in source command use a filename\n");
2362         return -1;
2363     }
2364     
2365     includeFile = fopen (arg, "r");
2366     
2367     if(!includeFile) {
2368         fprintf(stderr,"Unable to open file %s for reading\n",arg);
2369         return -1;
2370     }
2371     
2372     while(!feof(includeFile)) {
2373         memset(line,0,sizeof(line));
2374         fgets(line,sizeof(line),includeFile);
2375         
2376         if(strlen(line) < 2) continue;
2377         if(line[0] == '#') continue;
2378         
2379         if ((cp = strrchr (line, '\n')))
2380             *cp = '\0';
2381         
2382         process_cmd_line(line);
2383     }
2384     
2385     if(fclose(includeFile)<0) {
2386         perror("unable to close include file");
2387         exit(1);
2388     }
2389     return 1;
2390 }
2391
2392 int cmd_subshell(const char* args)
2393 {
2394     if(strlen(args)) 
2395         system(args);
2396     else 
2397         system(getenv("SHELL"));
2398     
2399     printf("\n");
2400     return 1;
2401 }
2402
2403 int cmd_set_berfile(const char *arg)
2404 {
2405     if (ber_file && ber_file != stdout && ber_file != stderr)
2406         fclose(ber_file);
2407     if (!strcmp(arg, ""))
2408         ber_file = 0;
2409     else if (!strcmp(arg, "-"))
2410         ber_file = stdout;
2411     else
2412         ber_file = fopen(arg, "a");
2413     return 1;
2414 }
2415
2416 int cmd_set_apdufile(const char *arg)
2417 {
2418     if(apdu_file && apdu_file != stderr && apdu_file != stderr)
2419         fclose(apdu_file);
2420     if (!strcmp(arg, ""))
2421         apdu_file = 0;
2422     else if (!strcmp(arg, "-"))
2423         apdu_file = stderr;
2424     else
2425     {
2426         apdu_file = fopen(arg, "a");
2427         if (!apdu_file)
2428             perror("unable to open apdu log file");
2429     }
2430     return 1;
2431 }
2432
2433 int cmd_set_cclfile(const char* arg)
2434 {  
2435     FILE *inf;
2436
2437     bibset = ccl_qual_mk (); 
2438     inf = fopen (arg, "r");
2439     if (!inf)
2440         perror("unable to open CCL file");
2441     else
2442     {
2443         ccl_qual_file (bibset, inf);
2444         fclose (inf);
2445     }
2446     strcpy(ccl_fields,arg);
2447     return 0;
2448 }
2449
2450 int cmd_set_auto_reconnect(const char* arg)
2451 {  
2452     if(strlen(arg)==0) {
2453         auto_reconnect = ! auto_reconnect;
2454     } else if(strcmp(arg,"on")==0) {
2455         auto_reconnect = 1;
2456     } else if(strcmp(arg,"off")==0) {
2457         auto_reconnect = 0;             
2458     } else {
2459         printf("Error use on or off\n");
2460         return 1;
2461     }
2462     
2463     if (auto_reconnect)
2464         printf("Set auto reconnect enabled.\n");
2465     else
2466         printf("Set auto reconnect disabled.\n");
2467     
2468     return 0;
2469 }
2470
2471 int cmd_set_marcdump(const char* arg)
2472 {
2473     if(marc_file && marc_file != stderr) { /* don't close stdout*/
2474         fclose(marc_file);
2475     }
2476
2477     if (!strcmp(arg, ""))
2478         marc_file = 0;
2479     else if (!strcmp(arg, "-"))
2480         marc_file = stderr;
2481     else
2482     {
2483         marc_file = fopen(arg, "a");
2484         if (!marc_file)
2485             perror("unable to open marc log file");
2486     }
2487     return 1;
2488 }
2489
2490 int cmd_set_proxy(const char* arg)
2491 {
2492     if(yazProxy) free(yazProxy);
2493     yazProxy=NULL;
2494     
2495     if(strlen(arg) > 1) {
2496         yazProxy=strdup(arg);
2497     }
2498     return 1;
2499 }
2500
2501 /* 
2502    this command takes 3 arge {name class oid} 
2503 */
2504 int cmd_register_oid(const char* args) {
2505     static struct {
2506         char* className;
2507         oid_class oclass;
2508     } oid_classes[] = {
2509         {"appctx",CLASS_APPCTX},
2510         {"absyn",CLASS_ABSYN},
2511         {"attset",CLASS_ATTSET},
2512         {"transyn",CLASS_TRANSYN},
2513         {"diagset",CLASS_DIAGSET},
2514         {"recsyn",CLASS_RECSYN},
2515         {"resform",CLASS_RESFORM},
2516         {"accform",CLASS_ACCFORM},
2517         {"extserv",CLASS_EXTSERV},
2518         {"userinfo",CLASS_USERINFO},
2519         {"elemspec",CLASS_ELEMSPEC},
2520         {"varset",CLASS_VARSET},
2521         {"schema",CLASS_SCHEMA},
2522         {"tagset",CLASS_TAGSET},
2523         {"general",CLASS_GENERAL},
2524         {0,(enum oid_class) 0}
2525     };
2526     char oname_str[101], oclass_str[101], oid_str[101];  
2527     char* name;
2528     int i;
2529     oid_class oidclass = CLASS_GENERAL;
2530     int val = 0, oid[OID_SIZE];
2531     struct oident * new_oident=NULL;
2532     
2533     if (sscanf (args, "%100[^ ] %100[^ ] %100s",
2534                 oname_str,oclass_str, oid_str) < 1) {
2535         printf("Error in regristrate command \n");
2536         return 0;
2537     }
2538     
2539     for (i = 0; oid_classes[i].className; i++) {
2540         if (!strcmp(oid_classes[i].className, oclass_str))
2541         {
2542             oidclass=oid_classes[i].oclass;
2543             break;
2544         }
2545     }
2546     
2547     if(!(oid_classes[i].className)) {
2548         printf("Unknonwn oid class %s\n",oclass_str);
2549         return 0;
2550     }
2551     
2552     i = 0;
2553     name = oid_str;
2554     val = 0;
2555     
2556     while (isdigit (*name))
2557     {
2558         val = val*10 + (*name - '0');
2559         name++;
2560         if (*name == '.')
2561         {
2562             if (i < OID_SIZE-1)
2563                 oid[i++] = val;
2564             val = 0;
2565             name++;
2566         }
2567     }
2568     oid[i] = val;
2569     oid[i+1] = -1;
2570     
2571     new_oident=oid_addent (oid,PROTO_GENERAL,oidclass,oname_str,VAL_DYNAMIC);  
2572     if(strcmp(new_oident->desc,oname_str)) {
2573         fprintf(stderr,"oid is already named as %s, regristration faild\n",
2574                 new_oident->desc);
2575     }
2576     return 1;  
2577 }
2578
2579 int cmd_push_command(const char* arg) 
2580 {
2581 #if HAVE_READLINE_HISTORY_H
2582     if(strlen(arg)>1) 
2583         add_history(arg);
2584 #else 
2585     fprintf(stderr,"Not compiled with the readline/history module\n");
2586 #endif
2587     return 1;
2588 }
2589
2590 void source_rcfile() 
2591 {
2592     /*  Look for a $HOME/.yazclientrc and source it if it exists */
2593     struct stat statbuf;
2594     char buffer[1000];
2595     char* homedir=getenv("HOME");
2596     
2597     if(!homedir) return;
2598     
2599     sprintf(buffer,"%s/.yazclientrc",homedir);
2600     
2601     if(stat(buffer,&statbuf)==0) {
2602         cmd_source(buffer);
2603     }
2604     
2605     if(stat(".yazclientrc",&statbuf)==0) {
2606         cmd_source(".yazclientrc");
2607     }
2608 }
2609
2610
2611 static void initialize(void)
2612 {
2613     FILE *inf;
2614     int i;
2615     
2616     if (!(out = odr_createmem(ODR_ENCODE)) ||
2617         !(in = odr_createmem(ODR_DECODE)) ||
2618         !(print = odr_createmem(ODR_PRINT)))
2619     {
2620         fprintf(stderr, "failed to allocate ODR streams\n");
2621         exit(1);
2622     }
2623     oid_init();
2624     
2625     setvbuf(stdout, 0, _IONBF, 0);
2626     if (apdu_file)
2627         odr_setprint(print, apdu_file);
2628
2629     bibset = ccl_qual_mk (); 
2630     inf = fopen (ccl_fields, "r");
2631     if (inf)
2632     {
2633         ccl_qual_file (bibset, inf);
2634         fclose (inf);
2635     }
2636     cmd_base("Default");
2637
2638 #if HAVE_READLINE_READLINE_H
2639     rl_attempted_completion_function = (CPPFunction*)readline_completer;
2640 #endif
2641     
2642     
2643     for(i=0; i<maxOtherInfosSupported; ++i) {
2644         extraOtherInfos[i].oidval = -1;
2645     }
2646     
2647     source_rcfile();
2648 }
2649
2650
2651 #if HAVE_GETTIMEOFDAY
2652 struct timeval tv_start, tv_end;
2653 #endif
2654
2655 void wait_and_handle_responce() 
2656 {
2657     
2658     int res;
2659     char *netbuffer= 0;
2660     int netbufferlen = 0;
2661     Z_APDU *apdu;
2662     
2663     
2664     if (conn)
2665     {
2666         do
2667         {
2668             if ((res = cs_get(conn, &netbuffer, &netbufferlen)) < 0)
2669             {
2670                 printf("Target closed connection\n");
2671                 close_session ();
2672                 break;
2673             }
2674             if (!res)
2675             {
2676                 printf("Target closed connection.\n");
2677                 close_session ();
2678                 break;
2679             }
2680             odr_reset(in); /* release APDU from last round */
2681             record_last = 0;
2682             odr_setbuf(in, netbuffer, res, 0);
2683             if (!z_APDU(in, &apdu, 0, 0))
2684             {
2685                 FILE *f = ber_file ? ber_file : stdout;
2686                 odr_perror(in, "Decoding incoming APDU");
2687                 fprintf(f, "[Near %d]\n", odr_offset(in));
2688                 fprintf(f, "Packet dump:\n---------\n");
2689                 odr_dumpBER(f, netbuffer, res);
2690                 fprintf(f, "---------\n");
2691                 if (apdu_file)
2692                     z_APDU(print, &apdu, 0, 0);
2693                 close_session ();
2694                 break;
2695             }
2696             if (ber_file)
2697                 odr_dumpBER(ber_file, netbuffer, res);
2698             if (apdu_file && !z_APDU(print, &apdu, 0, 0))
2699             {
2700                 odr_perror(print, "Failed to print incoming APDU");
2701                 odr_reset(print);
2702                 continue;
2703             }
2704             switch(apdu->which)
2705             {
2706             case Z_APDU_initResponse:
2707                 process_initResponse(apdu->u.initResponse);
2708                 break;
2709             case Z_APDU_searchResponse:
2710                 process_searchResponse(apdu->u.searchResponse);
2711                 break;
2712             case Z_APDU_scanResponse:
2713                 process_scanResponse(apdu->u.scanResponse);
2714                 break;
2715             case Z_APDU_presentResponse:
2716                 print_refid (apdu->u.presentResponse->referenceId);
2717                 setno +=
2718                     *apdu->u.presentResponse->numberOfRecordsReturned;
2719                 if (apdu->u.presentResponse->records)
2720                     display_records(apdu->u.presentResponse->records);
2721                 else
2722                     printf("No records.\n");
2723                 printf ("nextResultSetPosition = %d\n",
2724                         *apdu->u.presentResponse->nextResultSetPosition);
2725                 break;
2726             case Z_APDU_sortResponse:
2727                 process_sortResponse(apdu->u.sortResponse);
2728                 break;
2729             case Z_APDU_extendedServicesResponse:
2730                 printf("Got extended services response\n");
2731                 process_ESResponse(apdu->u.extendedServicesResponse);
2732                 break;
2733             case Z_APDU_close:
2734                 printf("Target has closed the association.\n");
2735                 process_close(apdu->u.close);
2736                 break;
2737             case Z_APDU_resourceControlRequest:
2738                 process_resourceControlRequest
2739                     (apdu->u.resourceControlRequest);
2740                 break;
2741             case Z_APDU_deleteResultSetResponse:
2742                 process_deleteResultSetResponse(apdu->u.
2743                                                 deleteResultSetResponse);
2744                 break;
2745             default:
2746                 printf("Received unknown APDU type (%d).\n", 
2747                        apdu->which);
2748                 close_session ();
2749             }
2750         }
2751         while (conn && cs_more(conn));
2752 #if HAVE_GETTIMEOFDAY
2753         gettimeofday (&tv_end, 0);
2754 #if 0
2755         printf ("S/U S/U=%ld/%ld %ld/%ld",
2756                 (long) tv_start.tv_sec,
2757                 (long) tv_start.tv_usec,
2758                 (long) tv_end.tv_sec,
2759                 (long) tv_end.tv_usec);
2760 #endif
2761         printf ("Elapsed: %.6f\n",
2762                 (double) tv_end.tv_usec / 1e6 + tv_end.tv_sec -
2763                 ((double) tv_start.tv_usec / 1e6 + tv_start.tv_sec));
2764 #endif
2765     }
2766     xfree (netbuffer);
2767 }
2768
2769
2770 int cmd_cclparse(const char* arg) 
2771 {
2772     int error, pos;
2773     struct ccl_rpn_node *rpn=NULL;
2774     
2775     
2776     rpn = ccl_find_str (bibset, arg, &error, &pos);
2777     
2778     if (error) {
2779         printf ("%*s^ - ", 3+strlen(last_cmd)+1+pos, " ");
2780         printf ("%s\n", ccl_err_msg (error));
2781     }
2782     else
2783     {
2784         if (rpn)
2785         {       
2786             ccl_pr_tree(rpn, stdout); 
2787         }
2788     }
2789     if (rpn)
2790         ccl_rpn_delete(rpn);
2791     
2792     printf ("\n");
2793     
2794     return 0;
2795 }
2796
2797
2798 int cmd_set_otherinfo(const char* args)
2799 {
2800     char oid[101], otherinfoString[101];
2801     int otherinfoNo;
2802     int sscan_res;
2803     int oidval;
2804     
2805     sscan_res = sscanf (args, "%d %100[^ ] %100s", &otherinfoNo, oid, otherinfoString);
2806     if(sscan_res==1) {
2807         /* reset this otherinfo */
2808         if(otherinfoNo>=maxOtherInfosSupported) {
2809             printf("Error otherinfo index to large (%d>%d)\n",otherinfoNo,maxOtherInfosSupported);
2810         }
2811         extraOtherInfos[otherinfoNo].oidval = -1;
2812         if(extraOtherInfos[otherinfoNo].value) free(extraOtherInfos[otherinfoNo].value);                        
2813         return 0;
2814     }
2815     if (sscan_res<3) {
2816         printf("Error in set_otherinfo command \n");
2817         return 0;
2818     }
2819     
2820     if(otherinfoNo>=maxOtherInfosSupported) {
2821         printf("Error otherinfo index to large (%d>%d)\n",otherinfoNo,maxOtherInfosSupported);
2822     }
2823     
2824     
2825     oidval = oid_getvalbyname (oid);
2826     if(oidval == -1 ) {
2827         printf("Error in set_otherinfo command unknown oid %s \n",oid);
2828         return 0;
2829     }
2830     extraOtherInfos[otherinfoNo].oidval = oidval;
2831     if(extraOtherInfos[otherinfoNo].value) free(extraOtherInfos[otherinfoNo].value);
2832     extraOtherInfos[otherinfoNo].value = strdup(otherinfoString);
2833     
2834     return 0;
2835 }
2836
2837 int cmd_list_otherinfo(const char* args)
2838 {
2839     int i;         
2840     
2841     if(strlen(args)>0) {
2842         i = atoi(args);
2843         if( i >= maxOtherInfosSupported ) {
2844             printf("Error otherinfo index to large (%d>%d)\n",i,maxOtherInfosSupported);
2845             return 0;
2846         }
2847
2848         if(extraOtherInfos[i].oidval != -1) 
2849             printf("  otherinfo %d %s %s\n",
2850                    i,
2851                    yaz_z3950_oid_value_to_str(
2852                        (enum oid_value) extraOtherInfos[i].oidval,
2853                        CLASS_RECSYN),
2854                    extraOtherInfos[i].value);
2855         
2856     } else {            
2857         for(i=0; i<maxOtherInfosSupported; ++i) {
2858             if(extraOtherInfos[i].oidval != -1) 
2859                 printf("  otherinfo %d %s %s\n",
2860                        i,
2861                        yaz_z3950_oid_value_to_str(
2862                            (enum oid_value) extraOtherInfos[i].oidval,
2863                            CLASS_RECSYN),
2864                        extraOtherInfos[i].value);
2865         }
2866         
2867     }
2868     return 0;
2869 }
2870
2871
2872 int cmd_list_all(const char* args) {
2873     int i;
2874     
2875     /* connection options */
2876     if(conn) {
2877         printf("Connected to         : %s\n",last_open_command);
2878     } else {
2879         if(last_open_command) 
2880             printf("Not connected to     : %s\n",last_open_command);
2881         else 
2882             printf("Not connected        : \n");
2883         
2884     }
2885     if(yazProxy) printf("using proxy          : %s\n",yazProxy);                
2886     
2887     printf("auto_reconnect       : %s\n",auto_reconnect?"on":"off");
2888     
2889     if (!auth) {
2890         printf("Authentication       : none\n");
2891     } else {
2892         switch(auth->which) {
2893         case Z_IdAuthentication_idPass:
2894             printf("Authentication       : IdPass\n"); 
2895             printf("    Login User       : %s\n",auth->u.idPass->userId?auth->u.idPass->userId:"");
2896             printf("    Login Group      : %s\n",auth->u.idPass->groupId?auth->u.idPass->groupId:"");
2897             printf("    Password         : %s\n",auth->u.idPass->password?auth->u.idPass->password:"");
2898             break;
2899         case Z_IdAuthentication_open:
2900             printf("Authentication       : psOpen\n");                  
2901             printf("    Open string      : %s\n",auth->u.open); 
2902             break;
2903         default:
2904             printf("Authentication       : Unknown\n");
2905         }
2906     }
2907     if ( yazCharset ) printf("Character set        : `%s'\n", (yazCharset) ? yazCharset:NULL);
2908     
2909     /* bases */
2910     printf("Bases                : ");
2911     for (i = 0; i<num_databaseNames; i++) printf("%s ",databaseNames[i]);
2912     printf("\n");
2913     
2914     /* Query options */
2915     printf("CCL file             : %s\n",ccl_fields);
2916     printf("Query type           : %s\n",query_type_as_string(queryType));
2917     
2918     printf("Named Result Sets    : %s\n",setnumber==-1?"off":"on");
2919     
2920     /* piggy back options */
2921     printf("ssub/lslb/mspn       : %d/%d/%d\n",smallSetUpperBound,largeSetLowerBound,mediumSetPresentNumber);
2922     
2923     /* print present related options */
2924     printf("Format               : %s\n",yaz_z3950_oid_value_to_str(recordsyntax,CLASS_RECSYN));
2925     printf("Schema               : %s\n",yaz_z3950_oid_value_to_str(schema,CLASS_SCHEMA));
2926     printf("Elements             : %s\n",elementSetNames?elementSetNames->u.generic:"");
2927     
2928     /* loging options */
2929     printf("APDU log             : %s\n",apdu_file?"on":"off");
2930     printf("Record log           : %s\n",marc_file?"on":"off");
2931     
2932     /* other infos */
2933     printf("Other Info: \n");
2934     cmd_list_otherinfo("");
2935     
2936     return 0;
2937 }
2938
2939 int cmd_clear_otherinfo(const char* args) 
2940 {
2941     if(strlen(args)>0) {
2942         int otherinfoNo;
2943         otherinfoNo = atoi(args);
2944         if( otherinfoNo >= maxOtherInfosSupported ) {
2945             printf("Error otherinfo index to large (%d>%d)\n",otherinfoNo,maxOtherInfosSupported);
2946             return 0;
2947         }
2948         
2949         if(extraOtherInfos[otherinfoNo].oidval != -1) {                 
2950             /* only clear if set. */
2951             extraOtherInfos[otherinfoNo].oidval=-1;
2952             free(extraOtherInfos[otherinfoNo].value);
2953         }
2954     } else {
2955         int i;
2956         
2957         for(i=0; i<maxOtherInfosSupported; ++i) {
2958             if (extraOtherInfos[i].oidval!=-1 ) {                               
2959                 extraOtherInfos[i].oidval=-1;
2960                 free(extraOtherInfos[i].value);
2961             }
2962         }
2963     }
2964     return 0;
2965 }
2966
2967 static int cmd_help (const char *line);
2968
2969 typedef char *(*completerFunctionType)(const char *text, int state);
2970
2971 static struct {
2972     char *cmd;
2973     int (*fun)(const char *arg);
2974     char *ad;
2975         completerFunctionType rl_completerfunction;
2976     int complete_filenames;
2977     char **local_tabcompletes;
2978 } cmd_array[] = {
2979     {"open", cmd_open, "('tcp'|'ssl')':<host>[':'<port>][/<db>]",NULL,0,NULL},
2980     {"quit", cmd_quit, "",NULL,0,NULL},
2981     {"find", cmd_find, "<query>",NULL,0,NULL},
2982     {"delete", cmd_delete, "<setname>",NULL,0,NULL},
2983     {"base", cmd_base, "<base-name>",NULL,0,NULL},
2984     {"show", cmd_show, "<rec#>['+'<#recs>['+'<setname>]]",NULL,0,NULL},
2985     {"scan", cmd_scan, "<term>",NULL,0,NULL},
2986     {"sort", cmd_sort, "<sortkey> <flag> <sortkey> <flag> ...",NULL,0,NULL},
2987     {"sort+", cmd_sort_newset, "<sortkey> <flag> <sortkey> <flag> ...",NULL,0,NULL},
2988     {"authentication", cmd_authentication, "<acctstring>",NULL,0,NULL},
2989     {"lslb", cmd_lslb, "<largeSetLowerBound>",NULL,0,NULL},
2990     {"ssub", cmd_ssub, "<smallSetUpperBound>",NULL,0,NULL},
2991     {"mspn", cmd_mspn, "<mediumSetPresentNumber>",NULL,0,NULL},
2992     {"status", cmd_status, "",NULL,0,NULL},
2993     {"setnames", cmd_setnames, "",NULL,0,NULL},
2994     {"cancel", cmd_cancel, "",NULL,0,NULL},
2995     {"format", cmd_format, "<recordsyntax>",complete_format,0,NULL},
2996     {"schema", cmd_schema, "<schema>",complete_schema,0,NULL},
2997     {"elements", cmd_elements, "<elementSetName>",NULL,0,NULL},
2998     {"close", cmd_close, "",NULL,0,NULL},
2999     {"attributeset", cmd_attributeset, "<attrset>",complete_attributeset,0,NULL},
3000     {"querytype", cmd_querytype, "<type>",complete_querytype,0,NULL},
3001     {"refid", cmd_refid, "<id>",NULL,0,NULL},
3002     {"itemorder", cmd_itemorder, "ill|item <itemno>",NULL,0,NULL},
3003     {"update", cmd_update, "<action> <recid> [<file>]",NULL,0,NULL},
3004     {"packagename", cmd_packagename, "<packagename>",NULL,0,NULL},
3005     {"proxy", cmd_proxy, "[('tcp'|'ssl')]<host>[':'<port>]",NULL,0,NULL},
3006     {"charset", cmd_charset, "<charset_name>",NULL,0,NULL},
3007     {"lang", cmd_lang, "<language_code>",NULL,0,NULL},
3008     {".", cmd_source, "<filename>",NULL,1,NULL},
3009     {"!", cmd_subshell, "Subshell command",NULL,1,NULL},
3010     {"set_apdufile", cmd_set_apdufile, "<filename>",NULL,1,NULL},
3011     {"set_berfile", cmd_set_berfile, "<filename>",NULL,1,NULL},
3012     {"set_marcdump", cmd_set_marcdump," <filename>",NULL,1,NULL},
3013     {"set_cclfile", cmd_set_cclfile," <filename>",NULL,1,NULL},
3014     {"set_auto_reconnect", cmd_set_auto_reconnect," on|off",complete_auto_reconnect,1,NULL},
3015         {"set_otherinfo", cmd_set_otherinfo,"<otherinfoinddex> <oid> <string>",NULL,0,NULL},
3016     {"register_oid", cmd_register_oid,"<name> <class> <oid>",NULL,0,NULL},
3017     {"push_command", cmd_push_command,"<command>",command_generator,0,NULL},
3018     {"register_tab", cmd_register_tab,"<commandname> <tab>",command_generator,0,NULL},
3019     {"cclparse", cmd_cclparse,"<ccl find command>",NULL,0,NULL},
3020     {"list_otherinfo",cmd_list_otherinfo,"[otherinfoinddex]",NULL,0,NULL},
3021     {"list_all",cmd_list_all,"",NULL,0,NULL},
3022     {"clear_otherinfo",cmd_clear_otherinfo,"",NULL,0,NULL},
3023     /* Server Admin Functions */
3024     {"adm-reindex", cmd_adm_reindex, "<database-name>",NULL,0,NULL},
3025     {"adm-truncate", cmd_adm_truncate, "('database'|'index')<object-name>",NULL,0,NULL},
3026     {"adm-create", cmd_adm_create, "",NULL,0,NULL},
3027     {"adm-drop", cmd_adm_drop, "('database'|'index')<object-name>",NULL,0,NULL},
3028     {"adm-import", cmd_adm_import, "<record-type> <dir> <pattern>",NULL,0,NULL},
3029     {"adm-refresh", cmd_adm_refresh, "",NULL,0,NULL},
3030     {"adm-commit", cmd_adm_commit, "",NULL,0,NULL},
3031     {"adm-shutdown", cmd_adm_shutdown, "",NULL,0,NULL},
3032     {"adm-startup", cmd_adm_startup, "",NULL,0,NULL},
3033     {"help", cmd_help, "", NULL,0,NULL},
3034     {0,0,0,0,0,0}
3035 };
3036
3037 static int cmd_help (const char *line)
3038 {
3039     int i;
3040     char topic[21];
3041     
3042     *topic = 0;
3043     sscanf (line, "%20s", topic);
3044
3045     if (*topic == 0)
3046         printf("Commands:\n");
3047     for (i = 0; cmd_array[i].cmd; i++)
3048         if (*topic == 0 || strcmp (topic, cmd_array[i].cmd) == 0)
3049             printf("   %s %s\n", cmd_array[i].cmd, cmd_array[i].ad);
3050     if (strcmp (topic, "find") == 0)
3051     {
3052         printf ("RPN:\n");
3053         printf (" \"term\"                        Simple Term\n");
3054         printf (" @attr [attset] type=value op  Attribute\n");
3055         printf (" @and opl opr                  And\n");
3056         printf (" @or opl opr                   Or\n");
3057         printf (" @not opl opr                  And-Not\n");
3058         printf (" @set set                      Result set\n");
3059         printf ("\n");
3060         printf ("Bib-1 attribute types\n");
3061         printf ("1=Use:         ");
3062         printf ("4=Title 7=ISBN 8=ISSN 30=Date 62=Abstract 1003=Author 1016=Any\n");
3063         printf ("2=Relation:    ");
3064         printf ("1<   2<=  3=  4>=  5>  6!=  102=Relevance\n");
3065         printf ("3=Position:    ");
3066         printf ("1=First in Field  2=First in subfield  3=Any position\n");
3067         printf ("4=Structure:   ");
3068         printf ("1=Phrase  2=Word  3=Key  4=Year  5=Date  6=WordList\n");
3069         printf ("5=Truncation:  ");
3070         printf ("1=Right  2=Left  3=L&R  100=No  101=#  102=Re-1  103=Re-2\n");
3071         printf ("6=Completeness:");
3072         printf ("1=Incomplete subfield  2=Complete subfield  3=Complete field\n");
3073     }
3074     return 1;
3075 }
3076
3077 int cmd_register_tab(const char* arg) {
3078         
3079     char command[101], tabargument[101];
3080     int i;
3081     int num_of_tabs;
3082     char** tabslist;
3083     
3084     if (sscanf (arg, "%100s %100s", command, tabargument) < 1) {
3085         return 0;
3086     }
3087     
3088     /* locate the amdn in the list */
3089     for (i = 0; cmd_array[i].cmd; i++) {
3090         if (!strncmp(cmd_array[i].cmd, command, strlen(command))) {
3091             break;
3092         }
3093     }
3094     
3095     if(!cmd_array[i].cmd) { 
3096         fprintf(stderr,"Unknown command %s\n",command);
3097         return 1;
3098     }
3099     
3100         
3101     if(!cmd_array[i].local_tabcompletes)
3102         cmd_array[i].local_tabcompletes = (char **) calloc(1,sizeof(char**));
3103     
3104     num_of_tabs=0;              
3105     
3106     tabslist = cmd_array[i].local_tabcompletes;
3107     for(;tabslist && *tabslist;tabslist++) {
3108         num_of_tabs++;
3109     }
3110     
3111     cmd_array[i].local_tabcompletes =  (char **)
3112         realloc(cmd_array[i].local_tabcompletes,(num_of_tabs+2)*sizeof(char**));
3113     tabslist=cmd_array[i].local_tabcompletes;
3114     tabslist[num_of_tabs]=strdup(tabargument);
3115     tabslist[num_of_tabs+1]=NULL;
3116     return 1;
3117 }
3118
3119
3120 void process_cmd_line(char* line)
3121 {  
3122     int i,res;
3123     char word[32], arg[1024];
3124     
3125 #if HAVE_GETTIMEOFDAY
3126     gettimeofday (&tv_start, 0);
3127 #endif
3128     
3129     if ((res = sscanf(line, "%31s %1023[^;]", word, arg)) <= 0)
3130     {
3131         strcpy(word, last_cmd);
3132         *arg = '\0';
3133     }
3134     else if (res == 1)
3135         *arg = 0;
3136     strcpy(last_cmd, word);
3137     
3138     /* removed tailing spaces from the arg command */
3139     { 
3140         char* p = arg;
3141         char* lastnonspace=NULL;
3142         
3143         for(;*p; ++p) {
3144             if(!isspace(*p)) {
3145                 lastnonspace = p;
3146             }
3147         }
3148         if(lastnonspace) 
3149             *(++lastnonspace) = 0;
3150     }
3151     
3152     for (i = 0; cmd_array[i].cmd; i++)
3153         if (!strncmp(cmd_array[i].cmd, word, strlen(word)))
3154         {
3155             res = (*cmd_array[i].fun)(arg);
3156             break;
3157         }
3158     
3159     if (!cmd_array[i].cmd) /* dump our help-screen */
3160     {
3161         printf("Unknown command: %s.\n", word);
3162         printf("use help for list of commands\n");
3163         /* cmd_help (""); */
3164         res = 1;
3165     }
3166     
3167     if(apdu_file) fflush(apdu_file);
3168     
3169     if (res >= 2)
3170         wait_and_handle_responce();
3171     
3172     if(apdu_file)
3173         fflush(apdu_file);
3174     if(marc_file)
3175         fflush(marc_file);
3176 }
3177
3178
3179 char *command_generator(const char *text, int state) 
3180 {
3181     static int idx; 
3182     if (state==0) {
3183         idx = 0;
3184     }
3185     for( ; cmd_array[idx].cmd; ++idx) {
3186         if (!strncmp(cmd_array[idx].cmd,text,strlen(text))) {
3187             ++idx;  /* skip this entry on the next run */
3188             return strdup(cmd_array[idx-1].cmd);
3189         }
3190     }
3191     return NULL;
3192 }
3193
3194
3195 /* 
3196    This function only known how to complete on the first word
3197 */
3198 char ** readline_completer(char *text, int start, int end) {
3199 #if HAVE_READLINE_READLINE_H
3200
3201         completerFunctionType completerToUse;
3202         
3203     if(start == 0) {
3204 #if HAVE_READLINE_RL_COMPLETION_MATCHES
3205         char** res=rl_completion_matches(text,
3206                                       command_generator); 
3207 #else
3208         char** res=completion_matches(text,
3209                                       (CPFunction*)command_generator); 
3210 #endif
3211         rl_attempted_completion_over = 1;
3212         return res;
3213     } else {
3214         char arg[1024],word[32];
3215         int i=0 ,res;
3216         if ((res = sscanf(rl_line_buffer, "%31s %1023[^;]", word, arg)) <= 0) {     
3217             rl_attempted_completion_over = 1;
3218             return NULL;
3219         }
3220         
3221         for (i = 0; cmd_array[i].cmd; i++) {
3222             if (!strncmp(cmd_array[i].cmd, word, strlen(word))) {
3223                 break;
3224             }
3225         }
3226         
3227         if(!cmd_array[i].cmd) return NULL;
3228         
3229         curret_global_list = cmd_array[i].local_tabcompletes;
3230         
3231         completerToUse = cmd_array[i].rl_completerfunction;
3232         if(completerToUse==NULL)  /* if no pr. command completer is defined use the default completer */
3233             completerToUse = default_completer;
3234         
3235         if(completerToUse) {
3236 #ifdef HAVE_READLINE_RL_COMPLETION_MATCHES
3237             char** res=
3238                 rl_completion_matches(text,
3239                                       completerToUse);
3240 #else
3241             char** res=
3242                 completion_matches(text,
3243                                    (CPFunction*)completerToUse);
3244 #endif
3245             if(!cmd_array[i].complete_filenames) 
3246                 rl_attempted_completion_over = 1;
3247             return res;
3248         } else {
3249             if(!cmd_array[i].complete_filenames) 
3250                 rl_attempted_completion_over = 1;
3251             return 0;
3252         }
3253     }
3254 #else 
3255     return 0;
3256 #endif 
3257 }
3258
3259
3260 static void client(void)
3261 {
3262     char line[1024];
3263
3264     line[1023] = '\0';
3265
3266 #if HAVE_GETTIMEOFDAY
3267     gettimeofday (&tv_start, 0);
3268 #endif
3269
3270     while (1)
3271     {
3272         char *line_in = NULL;
3273 #if HAVE_READLINE_READLINE_H
3274         if (isatty(0))
3275         {
3276             line_in=readline(C_PROMPT);
3277             if (!line_in)
3278                 break;
3279 #if HAVE_READLINE_HISTORY_H
3280             if (*line_in)
3281                 add_history(line_in);
3282 #endif
3283             strncpy(line, line_in, 1023);
3284             free (line_in);
3285         }
3286 #endif 
3287         if (!line_in)
3288         {
3289             char *end_p;
3290             printf (C_PROMPT);
3291             fflush(stdout);
3292             if (!fgets(line, 1023, stdin))
3293                 break;
3294             if ((end_p = strchr (line, '\n')))
3295                 *end_p = '\0';
3296         }
3297         process_cmd_line(line);
3298     }
3299 }
3300
3301 int main(int argc, char **argv)
3302 {
3303     char *prog = *argv;
3304     char *open_command = 0;
3305     char *auth_command = 0;
3306     char *arg;
3307     int ret;
3308     
3309 #if HAVE_LOCALE_H
3310     if (!setlocale(LC_CTYPE, ""))
3311         fprintf (stderr, "setlocale failed\n");
3312 #endif
3313 #if HAVE_LANGINFO_H
3314 #ifdef CODESET
3315     codeset = nl_langinfo(CODESET);
3316 #endif
3317 #endif
3318
3319     while ((ret = options("k:c:a:b:m:v:p:u:t:", argv, argc, &arg)) != -2)
3320     {
3321         switch (ret)
3322         {
3323         case 0:
3324             if (!open_command)
3325             {
3326                 open_command = (char *) xmalloc (strlen(arg)+6);
3327                 strcpy (open_command, "open ");
3328                 strcat (open_command, arg);
3329             }
3330             break;
3331         case 'k':
3332             kilobytes = atoi(arg);
3333             break;
3334         case 'm':
3335             if (!(marc_file = fopen (arg, "a")))
3336             {
3337                 perror (arg);
3338                 exit (1);
3339             }
3340             break;
3341         case 't':
3342             codeset = arg;
3343             break;
3344         case 'c':
3345             strncpy (ccl_fields, arg, sizeof(ccl_fields)-1);
3346             ccl_fields[sizeof(ccl_fields)-1] = '\0';
3347             break;
3348         case 'b':
3349             if (!strcmp(arg, "-"))
3350                 ber_file=stderr;
3351             else
3352                 ber_file=fopen(arg, "a");
3353             break;
3354         case 'a':
3355             if (!strcmp(arg, "-"))
3356                 apdu_file=stderr;
3357             else
3358                 apdu_file=fopen(arg, "a");
3359             break;
3360         case 'p':
3361             yazProxy=strdup(arg);
3362             break;
3363         case 'u':
3364             if (!auth_command)
3365             {
3366                 auth_command = (char *) xmalloc (strlen(arg)+6);
3367                 strcpy (auth_command, "auth ");
3368                 strcat (auth_command, arg);
3369             }
3370             break;
3371         case 'v':
3372             yaz_log_init (yaz_log_mask_str(arg), "", NULL);
3373             break;
3374         default:
3375             fprintf (stderr, "Usage: %s [-m <marclog>] [ -a <apdulog>] "
3376                      "[-b berdump] [-c cclfields]\n      [-p <proxy-addr>] [-u <auth>] "
3377                      "[-k size] [<server-addr>]\n",
3378                      prog);
3379             exit (1);
3380         }      
3381     }
3382     initialize();
3383     if (auth_command)
3384     {
3385 #ifdef HAVE_GETTIMEOFDAY
3386         gettimeofday (&tv_start, 0);
3387 #endif
3388         process_cmd_line (auth_command);
3389 #if HAVE_READLINE_HISTORY_H
3390         add_history(auth_command);
3391 #endif
3392         xfree(auth_command);
3393     }
3394     if (open_command)
3395     {
3396 #ifdef HAVE_GETTIMEOFDAY
3397         gettimeofday (&tv_start, 0);
3398 #endif
3399         process_cmd_line (open_command);
3400 #if HAVE_READLINE_HISTORY_H
3401         add_history(open_command);
3402 #endif
3403         xfree(open_command);
3404     }
3405     client ();
3406     exit (0);
3407 }
3408
3409 /*
3410  * Local variables:
3411  * tab-width: 8
3412  * c-basic-offset: 4
3413  * End:
3414  * vim600: sw=4 ts=8 fdm=marker
3415  * vim<600: sw=4 ts=8
3416  */