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