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