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