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