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