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