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