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