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