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