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