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