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