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