Check for open connection and proper protocol for update and xmles
[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.293 2005-06-30 08:34:01 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 (!conn)
2136     {
2137         printf ("Not connected yet\n");
2138         return 1;
2139     }
2140     if (protocol == PROTO_HTTP)
2141     {
2142         printf ("Not supported by SRW\n");
2143         return 1;
2144     }
2145     return 0;
2146 }
2147
2148 static int cmd_update_common(const char *arg, int version);
2149
2150 static int cmd_update(const char *arg)
2151 {
2152     return cmd_update_common(arg, 1);
2153 }
2154
2155 static int cmd_update0(const char *arg)
2156 {
2157     return cmd_update_common(arg, 0);
2158 }
2159
2160 static int cmd_update_common(const char *arg, int version)
2161 {
2162     Z_APDU *apdu = zget_APDU(out, Z_APDU_extendedServicesRequest );
2163     Z_ExtendedServicesRequest *req = apdu->u.extendedServicesRequest;
2164     Z_External *r;
2165     char action[20], recid[20];
2166     char *rec_buf;
2167     int rec_len;
2168     int action_no;
2169     int noread = 0;
2170     Z_External *record_this = 0;
2171
2172     if (only_z3950())
2173         return 1;
2174     *action = 0;
2175     *recid = 0;
2176     sscanf (arg, "%19s %19s%n", action, recid, &noread);
2177     if (noread == 0)
2178     {
2179         printf("Update must be followed by action and recid\n");
2180         printf(" where action is one of insert,replace,delete.update\n");
2181         printf(" recid is some record ID (any string)\n");
2182         return 0;
2183     }
2184
2185     if (!strcmp (action, "insert"))
2186         action_no = Z_IUOriginPartToKeep_recordInsert;
2187     else if (!strcmp (action, "replace"))
2188         action_no = Z_IUOriginPartToKeep_recordReplace;
2189     else if (!strcmp (action, "delete"))
2190         action_no = Z_IUOriginPartToKeep_recordDelete;
2191     else if (!strcmp (action, "update"))
2192         action_no = Z_IUOriginPartToKeep_specialUpdate;
2193     else 
2194     {
2195         printf ("Bad action: %s\n", action);
2196         printf ("Possible values: insert, replace, delete, update\n");
2197         return 0;
2198     }
2199
2200     arg += noread;
2201     if (parse_cmd_doc(&arg, out, &rec_buf, &rec_len, 1) == 0)
2202         return 0;
2203
2204     if (rec_buf)
2205         record_this = z_ext_record (out, VAL_TEXT_XML, rec_buf, rec_len);
2206     else
2207     {
2208         if (!record_last)
2209         {
2210             printf ("No last record (update ignored)\n");
2211             return 0;
2212         }
2213         record_this = record_last;
2214     }
2215
2216     req->packageType =
2217         yaz_oidval_to_z3950oid(out, CLASS_EXTSERV,
2218                                version == 0 ? VAL_DBUPDATE0 : VAL_DBUPDATE);
2219
2220     req->packageName = esPackageName;
2221     
2222     req->referenceId = set_refid (out);
2223
2224     r = req->taskSpecificParameters = (Z_External *)
2225         odr_malloc (out, sizeof(*r));
2226     r->direct_reference = req->packageType;
2227     r->indirect_reference = 0;
2228     r->descriptor = 0;
2229     if (version == 0)
2230     {
2231         Z_IU0OriginPartToKeep *toKeep;
2232         Z_IU0SuppliedRecords *notToKeep;
2233
2234         r->which = Z_External_update0;
2235         r->u.update0 = (Z_IU0Update *) odr_malloc(out, sizeof(*r->u.update0));
2236         r->u.update0->which = Z_IUUpdate_esRequest;
2237         r->u.update0->u.esRequest = (Z_IU0UpdateEsRequest *)
2238             odr_malloc(out, sizeof(*r->u.update0->u.esRequest));
2239         toKeep = r->u.update0->u.esRequest->toKeep = (Z_IU0OriginPartToKeep *)
2240             odr_malloc(out, sizeof(*r->u.update0->u.esRequest->toKeep));
2241         
2242         toKeep->databaseName = databaseNames[0];
2243         toKeep->schema = 0;
2244         toKeep->elementSetName = 0;
2245
2246         toKeep->action = (int *) odr_malloc(out, sizeof(*toKeep->action));
2247         *toKeep->action = action_no;
2248         
2249         notToKeep = r->u.update0->u.esRequest->notToKeep = (Z_IU0SuppliedRecords *)
2250             odr_malloc(out, sizeof(*r->u.update0->u.esRequest->notToKeep));
2251         notToKeep->num = 1;
2252         notToKeep->elements = (Z_IU0SuppliedRecords_elem **)
2253             odr_malloc(out, sizeof(*notToKeep->elements));
2254         notToKeep->elements[0] = (Z_IU0SuppliedRecords_elem *)
2255             odr_malloc(out, sizeof(**notToKeep->elements));
2256         notToKeep->elements[0]->which = Z_IUSuppliedRecords_elem_opaque;
2257         if (*recid)
2258         {
2259             notToKeep->elements[0]->u.opaque = (Odr_oct *)
2260                 odr_malloc (out, sizeof(Odr_oct));
2261             notToKeep->elements[0]->u.opaque->buf = (unsigned char *) recid;
2262             notToKeep->elements[0]->u.opaque->size = strlen(recid);
2263             notToKeep->elements[0]->u.opaque->len = strlen(recid);
2264         }
2265         else
2266             notToKeep->elements[0]->u.opaque = 0;
2267         notToKeep->elements[0]->supplementalId = 0;
2268         notToKeep->elements[0]->correlationInfo = 0;
2269         notToKeep->elements[0]->record = record_this;
2270     }
2271     else
2272     {
2273         Z_IUOriginPartToKeep *toKeep;
2274         Z_IUSuppliedRecords *notToKeep;
2275
2276         r->which = Z_External_update;
2277         r->u.update = (Z_IUUpdate *) odr_malloc(out, sizeof(*r->u.update));
2278         r->u.update->which = Z_IUUpdate_esRequest;
2279         r->u.update->u.esRequest = (Z_IUUpdateEsRequest *)
2280             odr_malloc(out, sizeof(*r->u.update->u.esRequest));
2281         toKeep = r->u.update->u.esRequest->toKeep = (Z_IUOriginPartToKeep *)
2282             odr_malloc(out, sizeof(*r->u.update->u.esRequest->toKeep));
2283         
2284         toKeep->databaseName = databaseNames[0];
2285         toKeep->schema = 0;
2286         toKeep->elementSetName = 0;
2287         toKeep->actionQualifier = 0;
2288         toKeep->action = (int *) odr_malloc(out, sizeof(*toKeep->action));
2289         *toKeep->action = action_no;
2290
2291         notToKeep = r->u.update->u.esRequest->notToKeep = (Z_IUSuppliedRecords *)
2292             odr_malloc(out, sizeof(*r->u.update->u.esRequest->notToKeep));
2293         notToKeep->num = 1;
2294         notToKeep->elements = (Z_IUSuppliedRecords_elem **)
2295             odr_malloc(out, sizeof(*notToKeep->elements));
2296         notToKeep->elements[0] = (Z_IUSuppliedRecords_elem *)
2297             odr_malloc(out, sizeof(**notToKeep->elements));
2298         notToKeep->elements[0]->which = Z_IUSuppliedRecords_elem_opaque;
2299         if (*recid)
2300         {
2301             notToKeep->elements[0]->u.opaque = (Odr_oct *)
2302                 odr_malloc (out, sizeof(Odr_oct));
2303             notToKeep->elements[0]->u.opaque->buf = (unsigned char *) recid;
2304             notToKeep->elements[0]->u.opaque->size = strlen(recid);
2305             notToKeep->elements[0]->u.opaque->len = strlen(recid);
2306         }
2307         else
2308             notToKeep->elements[0]->u.opaque = 0;
2309         notToKeep->elements[0]->supplementalId = 0;
2310         notToKeep->elements[0]->correlationInfo = 0;
2311         notToKeep->elements[0]->record = record_this;
2312     }
2313     
2314     send_apdu(apdu);
2315
2316     return 2;
2317 }
2318
2319 static int cmd_xmles(const char *arg)
2320 {
2321     if (only_z3950())
2322         return 1;
2323     else
2324     {
2325         int noread = 0;
2326         char oid_str[51];
2327         int oid_value_xmles = VAL_XMLES;
2328         Z_APDU *apdu = zget_APDU(out, Z_APDU_extendedServicesRequest);
2329         Z_ExtendedServicesRequest *req = apdu->u.extendedServicesRequest;
2330         
2331         Z_External *ext = (Z_External *) odr_malloc(out, sizeof(*ext));
2332         
2333         req->taskSpecificParameters = ext;
2334         ext->indirect_reference = 0;
2335         ext->descriptor = 0;
2336         ext->which = Z_External_octet;
2337         ext->u.single_ASN1_type = (Odr_oct *) odr_malloc (out, sizeof(Odr_oct));        
2338         sscanf(arg, "%50s%n", oid_str, &noread);
2339         if (noread == 0)
2340         {
2341             printf("Missing OID for xmles\n");
2342             return 0;
2343         }
2344         arg += noread;
2345         oid_value_xmles  = oid_getvalbyname(oid_str);
2346         if (oid_value_xmles == VAL_NONE)
2347         {
2348             printf("Bad OID: %s\n", oid_str);
2349             return 0;
2350         }
2351         
2352         if (parse_cmd_doc(&arg, out, (char **) &ext->u.single_ASN1_type->buf,
2353                           &ext->u.single_ASN1_type->len, 0) == 0)
2354             return 0;
2355         req->packageType = yaz_oidval_to_z3950oid(out, CLASS_EXTSERV,
2356                                                   oid_value_xmles);
2357         
2358         ext->direct_reference = yaz_oidval_to_z3950oid(out, CLASS_EXTSERV,
2359                                                        oid_value_xmles);
2360         send_apdu(apdu);
2361         
2362         return 2;
2363     }
2364 }
2365
2366 static int cmd_itemorder(const char *arg)
2367 {
2368     char type[12];
2369     int itemno;
2370    
2371     if (only_z3950())
2372         return 1;
2373     if (sscanf (arg, "%10s %d", type, &itemno) != 2)
2374         return 0;
2375
2376     printf("Item order request\n");
2377     fflush(stdout);
2378     send_itemorder(type, itemno);
2379     return 2;
2380 }
2381
2382 static void show_opt(const char *arg, void *clientData)
2383 {
2384     printf ("%s ", arg);
2385 }
2386
2387 static int cmd_zversion(const char *arg)
2388 {
2389     if (*arg && arg)
2390         z3950_version = atoi(arg);
2391     else
2392         printf ("version is %d\n", z3950_version);
2393     return 0;
2394 }
2395
2396 static int cmd_options(const char *arg)
2397 {
2398     if (*arg)
2399     {
2400         int r;
2401         int pos;
2402         r = yaz_init_opt_encode(&z3950_options, arg, &pos);
2403         if (r == -1)
2404             printf("Unknown option(s) near %s\n", arg+pos);
2405     }
2406     else
2407     {
2408         yaz_init_opt_decode(&z3950_options, show_opt, 0);
2409         printf ("\n");
2410     }
2411     return 0;
2412 }
2413
2414 static int cmd_explain(const char *arg)
2415 {
2416     if (protocol != PROTO_HTTP)
2417         return 0;
2418 #if HAVE_XML2
2419     if (!conn)
2420         cmd_open(0);
2421     if (conn)
2422     {
2423         Z_SRW_PDU *sr = 0;
2424         
2425         setno = 1;
2426         
2427         /* save this for later .. when fetching individual records */
2428         sr = yaz_srw_get(out, Z_SRW_explain_request);
2429         if (recordsyntax == VAL_TEXT_XML)
2430             sr->u.explain_request->recordPacking = "xml";
2431         send_srw(sr);
2432         return 2;
2433     }
2434 #endif
2435     return 0;
2436 }
2437
2438 static int cmd_init(const char *arg)
2439 {
2440     if (*arg)
2441     {
2442         strncpy (cur_host, arg, sizeof(cur_host)-1);
2443         cur_host[sizeof(cur_host)-1] = 0;
2444     }
2445     if (only_z3950())
2446         return 1;
2447     send_initRequest(cur_host);
2448     return 2;
2449 }
2450
2451 static int cmd_find(const char *arg)
2452 {
2453     if (!*arg)
2454     {
2455         printf("Find what?\n");
2456         return 0;
2457     }
2458     if (protocol == PROTO_HTTP)
2459     {
2460 #if HAVE_XML2
2461         if (!conn)
2462             cmd_open(0);
2463         if (!conn)
2464             return 0;
2465         if (!send_SRW_searchRequest(arg))
2466             return 0;
2467 #else
2468         return 0;
2469 #endif
2470     }
2471     else
2472     {
2473         if (!conn)
2474         {
2475             try_reconnect(); 
2476             
2477             if (!conn) {                                        
2478                 printf("Not connected yet\n");
2479                 return 0;
2480             }
2481         }
2482         if (!send_searchRequest(arg))
2483             return 0;
2484     }
2485     return 2;
2486 }
2487
2488 static int cmd_delete(const char *arg)
2489 {
2490     if (only_z3950())
2491         return 0;
2492     if (!send_deleteResultSetRequest(arg))
2493         return 0;
2494     return 2;
2495 }
2496
2497 static int cmd_ssub(const char *arg)
2498 {
2499     if (!(smallSetUpperBound = atoi(arg)))
2500         return 0;
2501     return 1;
2502 }
2503
2504 static int cmd_lslb(const char *arg)
2505 {
2506     if (!(largeSetLowerBound = atoi(arg)))
2507         return 0;
2508     return 1;
2509 }
2510
2511 static int cmd_mspn(const char *arg)
2512 {
2513     if (!(mediumSetPresentNumber = atoi(arg)))
2514         return 0;
2515     return 1;
2516 }
2517
2518 static int cmd_status(const char *arg)
2519 {
2520     printf("smallSetUpperBound: %d\n", smallSetUpperBound);
2521     printf("largeSetLowerBound: %d\n", largeSetLowerBound);
2522     printf("mediumSetPresentNumber: %d\n", mediumSetPresentNumber);
2523     return 1;
2524 }
2525
2526 static int cmd_setnames(const char *arg)
2527 {
2528     if (*arg == '1')         /* enable ? */
2529         setnumber = 0;
2530     else if (*arg == '0')    /* disable ? */
2531         setnumber = -1;
2532     else if (setnumber < 0)  /* no args, toggle .. */
2533         setnumber = 0;
2534     else
2535         setnumber = -1;
2536    
2537     if (setnumber >= 0)
2538         printf("Set numbering enabled.\n");
2539     else
2540         printf("Set numbering disabled.\n");
2541     return 1;
2542 }
2543
2544 /* PRESENT SERVICE ----------------------------- */
2545
2546 static void parse_show_args(const char *arg_c, char *setstring,
2547                             int *start, int *number)
2548 {
2549     char arg[40];
2550     char *p;
2551
2552     strncpy(arg, arg_c, sizeof(arg)-1);
2553     arg[sizeof(arg)-1] = '\0';
2554
2555     if ((p = strchr(arg, '+')))
2556     {
2557         *number = atoi(p + 1);
2558         *p = '\0';
2559     }
2560     if (*arg)
2561         *start = atoi(arg);
2562     if (p && (p=strchr(p+1, '+')))
2563         strcpy (setstring, p+1);
2564     else if (setnumber >= 0)
2565         sprintf(setstring, "%d", setnumber);
2566     else
2567         *setstring = '\0';
2568 }
2569
2570 static int send_presentRequest(const char *arg)
2571 {
2572     Z_APDU *apdu = zget_APDU(out, Z_APDU_presentRequest);
2573     Z_PresentRequest *req = apdu->u.presentRequest;
2574     Z_RecordComposition compo;
2575     int nos = 1;
2576     char setstring[100];
2577
2578     req->referenceId = set_refid (out);
2579
2580     parse_show_args(arg, setstring, &setno, &nos);
2581     if (*setstring)
2582         req->resultSetId = setstring;
2583
2584     req->resultSetStartPoint = &setno;
2585     req->numberOfRecordsRequested = &nos;
2586
2587     req->preferredRecordSyntax =
2588         yaz_oidval_to_z3950oid(out, CLASS_RECSYN, recordsyntax);
2589
2590     if (record_schema)
2591     {
2592         req->recordComposition = &compo;
2593         compo.which = Z_RecordComp_complex;
2594         compo.u.complex = (Z_CompSpec *)
2595             odr_malloc(out, sizeof(*compo.u.complex));
2596         compo.u.complex->selectAlternativeSyntax = (bool_t *) 
2597             odr_malloc(out, sizeof(bool_t));
2598         *compo.u.complex->selectAlternativeSyntax = 0;
2599
2600         compo.u.complex->generic = (Z_Specification *)
2601             odr_malloc(out, sizeof(*compo.u.complex->generic));
2602         compo.u.complex->generic->which = Z_Schema_oid;
2603
2604         compo.u.complex->generic->schema.oid =
2605             yaz_str_to_z3950oid(out, CLASS_SCHEMA, record_schema);
2606
2607         if (!compo.u.complex->generic->schema.oid)
2608         {
2609             /* OID wasn't a schema! Try record syntax instead. */
2610             compo.u.complex->generic->schema.oid = (Odr_oid *)
2611                 yaz_str_to_z3950oid(out, CLASS_RECSYN, record_schema);
2612         }
2613         if (!elementSetNames)
2614             compo.u.complex->generic->elementSpec = 0;
2615         else
2616         {
2617             compo.u.complex->generic->elementSpec = (Z_ElementSpec *)
2618                 odr_malloc(out, sizeof(Z_ElementSpec));
2619             compo.u.complex->generic->elementSpec->which =
2620                 Z_ElementSpec_elementSetName;
2621             compo.u.complex->generic->elementSpec->u.elementSetName =
2622                 elementSetNames->u.generic;
2623         }
2624         compo.u.complex->num_dbSpecific = 0;
2625         compo.u.complex->dbSpecific = 0;
2626         compo.u.complex->num_recordSyntax = 0;
2627         compo.u.complex->recordSyntax = 0;
2628     }
2629     else if (elementSetNames)
2630     {
2631         req->recordComposition = &compo;
2632         compo.which = Z_RecordComp_simple;
2633         compo.u.simple = elementSetNames;
2634     }
2635     send_apdu(apdu);
2636     printf("Sent presentRequest (%d+%d).\n", setno, nos);
2637     return 2;
2638 }
2639
2640 #if HAVE_XML2
2641 static int send_SRW_presentRequest(const char *arg)
2642 {
2643     char setstring[100];
2644     int nos = 1;
2645     Z_SRW_PDU *sr = srw_sr;
2646
2647     if (!sr)
2648         return 0;
2649     parse_show_args(arg, setstring, &setno, &nos);
2650     sr->u.request->startRecord = odr_intdup(out, setno);
2651     sr->u.request->maximumRecords = odr_intdup(out, nos);
2652     if (record_schema)
2653         sr->u.request->recordSchema = record_schema;
2654     if (recordsyntax == VAL_TEXT_XML)
2655         sr->u.request->recordPacking = "xml";
2656     return send_srw(sr);
2657 }
2658 #endif
2659
2660 static void close_session (void)
2661 {
2662     if (conn)
2663         cs_close (conn);
2664     conn = 0;
2665     sent_close = 0;
2666     odr_reset(out);
2667     odr_reset(in);
2668     odr_reset(print);
2669 }
2670
2671 void process_close(Z_Close *req)
2672 {
2673     Z_APDU *apdu = zget_APDU(out, Z_APDU_close);
2674     Z_Close *res = apdu->u.close;
2675
2676     static char *reasons[] =
2677     {
2678         "finished",
2679         "shutdown",
2680         "system problem",
2681         "cost limit reached",
2682         "resources",
2683         "security violation",
2684         "protocolError",
2685         "lack of activity",
2686         "peer abort",
2687         "unspecified"
2688     };
2689
2690     printf("Reason: %s, message: %s\n", reasons[*req->closeReason],
2691         req->diagnosticInformation ? req->diagnosticInformation : "NULL");
2692     if (sent_close)
2693         close_session ();
2694     else
2695     {
2696         *res->closeReason = Z_Close_finished;
2697         send_apdu(apdu);
2698         printf("Sent response.\n");
2699         sent_close = 1;
2700     }
2701 }
2702
2703 static int cmd_show(const char *arg)
2704 {
2705     if (protocol == PROTO_HTTP)
2706     {
2707 #if HAVE_XML2
2708         if (!conn)
2709             cmd_open(0);
2710         if (!conn)
2711             return 0;
2712         if (!send_SRW_presentRequest(arg))
2713             return 0;
2714 #else
2715         return 0;
2716 #endif
2717     }
2718     else
2719     {
2720         if (!conn)
2721         {
2722             printf("Not connected yet\n");
2723             return 0;
2724         }
2725         if (!send_presentRequest(arg))
2726             return 0;
2727     }
2728     return 2;
2729 }
2730
2731 int cmd_quit(const char *arg)
2732 {
2733     printf("See you later, alligator.\n");
2734     xmalloc_trav ("");
2735     exit(0);
2736     return 0;
2737 }
2738
2739 int cmd_cancel(const char *arg)
2740 {
2741     Z_APDU *apdu = zget_APDU(out, Z_APDU_triggerResourceControlRequest);
2742     Z_TriggerResourceControlRequest *req =
2743         apdu->u.triggerResourceControlRequest;
2744     bool_t rfalse = 0;
2745     
2746     if (only_z3950())
2747         return 0;
2748     if (session_initResponse &&
2749         !ODR_MASK_GET(session_initResponse->options,
2750                       Z_Options_triggerResourceCtrl))
2751     {
2752         printf("Target doesn't support cancel (trigger resource ctrl)\n");
2753         return 0;
2754     }
2755     *req->requestedAction = Z_TriggerResourceControlRequest_cancel;
2756     req->resultSetWanted = &rfalse;
2757     req->referenceId = set_refid (out);
2758
2759     send_apdu(apdu);
2760     printf("Sent cancel request\n");
2761     return 2;
2762 }
2763
2764
2765 int cmd_cancel_find(const char *arg) {
2766     int fres;
2767     fres=cmd_find(arg);
2768     if( fres > 0 ) {
2769         return cmd_cancel("");
2770     };
2771     return fres;
2772 }
2773
2774 int send_scanrequest(const char *query, int pp, int num, const char *term)
2775 {
2776     Z_APDU *apdu = zget_APDU(out, Z_APDU_scanRequest);
2777     Z_ScanRequest *req = apdu->u.scanRequest;
2778     
2779     if (only_z3950())
2780         return 0;
2781     if (queryType == QueryType_CCL2RPN)
2782     {
2783         int error, pos;
2784         struct ccl_rpn_node *rpn;
2785
2786         rpn = ccl_find_str (bibset,  query, &error, &pos);
2787         if (error)
2788         {
2789             printf("CCL ERROR: %s\n", ccl_err_msg(error));
2790             return -1;
2791         }
2792         req->attributeSet =
2793             yaz_oidval_to_z3950oid(out, CLASS_ATTSET, VAL_BIB1);
2794         if (!(req->termListAndStartPoint = ccl_scan_query (out, rpn)))
2795         {
2796             printf("Couldn't convert CCL to Scan term\n");
2797             return -1;
2798         }
2799         ccl_rpn_delete (rpn);
2800     }
2801     else
2802     {
2803         YAZ_PQF_Parser pqf_parser = yaz_pqf_create ();
2804
2805         if (!(req->termListAndStartPoint =
2806               yaz_pqf_scan(pqf_parser, out, &req->attributeSet, query)))
2807         {
2808             const char *pqf_msg;
2809             size_t off;
2810             int code = yaz_pqf_error (pqf_parser, &pqf_msg, &off);
2811             printf("%*s^\n", off+7, "");
2812             printf("Prefix query error: %s (code %d)\n", pqf_msg, code);
2813             yaz_pqf_destroy (pqf_parser);
2814             return -1;
2815         }
2816         yaz_pqf_destroy (pqf_parser);
2817     }
2818     if (term && *term)
2819     {
2820         if (req->termListAndStartPoint->term &&
2821             req->termListAndStartPoint->term->which == Z_Term_general &&
2822             req->termListAndStartPoint->term->u.general)
2823         {
2824             req->termListAndStartPoint->term->u.general->buf =
2825                 (unsigned char *) odr_strdup(out, term);
2826             req->termListAndStartPoint->term->u.general->len =
2827                 req->termListAndStartPoint->term->u.general->size =
2828                 strlen(term);
2829         }
2830     }
2831     req->referenceId = set_refid (out);
2832     req->num_databaseNames = num_databaseNames;
2833     req->databaseNames = databaseNames;
2834     req->numberOfTermsRequested = &num;
2835     req->preferredPositionInResponse = &pp;
2836     req->stepSize = odr_intdup(out, scan_stepSize);
2837     send_apdu(apdu);
2838     return 2;
2839 }
2840
2841 int send_sortrequest(const char *arg, int newset)
2842 {
2843     Z_APDU *apdu = zget_APDU(out, Z_APDU_sortRequest);
2844     Z_SortRequest *req = apdu->u.sortRequest;
2845     Z_SortKeySpecList *sksl = (Z_SortKeySpecList *)
2846         odr_malloc (out, sizeof(*sksl));
2847     char setstring[32];
2848
2849     if (only_z3950())
2850         return 0;
2851     if (setnumber >= 0)
2852         sprintf (setstring, "%d", setnumber);
2853     else
2854         sprintf (setstring, "default");
2855
2856     req->referenceId = set_refid (out);
2857
2858     req->num_inputResultSetNames = 1;
2859     req->inputResultSetNames = (Z_InternationalString **)
2860         odr_malloc (out, sizeof(*req->inputResultSetNames));
2861     req->inputResultSetNames[0] = odr_strdup (out, setstring);
2862
2863     if (newset && setnumber >= 0)
2864         sprintf (setstring, "%d", ++setnumber);
2865
2866     req->sortedResultSetName = odr_strdup (out, setstring);
2867
2868     req->sortSequence = yaz_sort_spec (out, arg);
2869     if (!req->sortSequence)
2870     {
2871         printf ("Missing sort specifications\n");
2872         return -1;
2873     }
2874     send_apdu(apdu);
2875     return 2;
2876 }
2877
2878 void display_term(Z_TermInfo *t)
2879 {
2880     if (t->displayTerm)
2881         printf("%s", t->displayTerm);
2882     else if (t->term->which == Z_Term_general)
2883     {
2884         printf("%.*s", t->term->u.general->len, t->term->u.general->buf);
2885         sprintf(last_scan_line, "%.*s", t->term->u.general->len,
2886             t->term->u.general->buf);
2887     }
2888     else
2889         printf("Term (not general)");
2890     if (t->globalOccurrences)
2891         printf (" (%d)\n", *t->globalOccurrences);
2892     else
2893         printf ("\n");
2894 }
2895
2896 void process_scanResponse(Z_ScanResponse *res)
2897 {
2898     int i;
2899     Z_Entry **entries = NULL;
2900     int num_entries = 0;
2901    
2902     printf("Received ScanResponse\n"); 
2903     print_refid (res->referenceId);
2904     printf("%d entries", *res->numberOfEntriesReturned);
2905     if (res->positionOfTerm)
2906         printf (", position=%d", *res->positionOfTerm); 
2907     printf ("\n");
2908     if (*res->scanStatus != Z_Scan_success)
2909         printf("Scan returned code %d\n", *res->scanStatus);
2910     if (!res->entries)
2911         return;
2912     if ((entries = res->entries->entries))
2913         num_entries = res->entries->num_entries;
2914     for (i = 0; i < num_entries; i++)
2915     {
2916         int pos_term = res->positionOfTerm ? *res->positionOfTerm : -1;
2917         if (entries[i]->which == Z_Entry_termInfo)
2918         {
2919             printf("%c ", i + 1 == pos_term ? '*' : ' ');
2920             display_term(entries[i]->u.termInfo);
2921         }
2922         else
2923             display_diagrecs(&entries[i]->u.surrogateDiagnostic, 1);
2924     }
2925     if (res->entries->nonsurrogateDiagnostics)
2926         display_diagrecs (res->entries->nonsurrogateDiagnostics,
2927                           res->entries->num_nonsurrogateDiagnostics);
2928 }
2929
2930 void process_sortResponse(Z_SortResponse *res)
2931 {
2932     printf("Received SortResponse: status=");
2933     switch (*res->sortStatus)
2934     {
2935     case Z_SortResponse_success:
2936         printf ("success"); break;
2937     case Z_SortResponse_partial_1:
2938         printf ("partial"); break;
2939     case Z_SortResponse_failure:
2940         printf ("failure"); break;
2941     default:
2942         printf ("unknown (%d)", *res->sortStatus);
2943     }
2944     printf ("\n");
2945     print_refid (res->referenceId);
2946     if (res->diagnostics)
2947         display_diagrecs(res->diagnostics,
2948                          res->num_diagnostics);
2949 }
2950
2951 void process_deleteResultSetResponse (Z_DeleteResultSetResponse *res)
2952 {
2953     printf("Got deleteResultSetResponse status=%d\n",
2954            *res->deleteOperationStatus);
2955     if (res->deleteListStatuses)
2956     {
2957         int i;
2958         for (i = 0; i < res->deleteListStatuses->num; i++)
2959         {
2960             printf ("%s status=%d\n", res->deleteListStatuses->elements[i]->id,
2961                     *res->deleteListStatuses->elements[i]->status);
2962         }
2963     }
2964 }
2965
2966 int cmd_sort_generic(const char *arg, int newset)
2967 {
2968     if (only_z3950())
2969         return 0;
2970     if (session_initResponse && 
2971         !ODR_MASK_GET(session_initResponse->options, Z_Options_sort))
2972     {
2973         printf("Target doesn't support sort\n");
2974         return 0;
2975     }
2976     if (*arg)
2977     {
2978         if (send_sortrequest(arg, newset) < 0)
2979             return 0;
2980         return 2;
2981     }
2982     return 0;
2983 }
2984
2985 int cmd_sort(const char *arg)
2986 {
2987     return cmd_sort_generic (arg, 0);
2988 }
2989
2990 int cmd_sort_newset (const char *arg)
2991 {
2992     return cmd_sort_generic (arg, 1);
2993 }
2994
2995 int cmd_scanstep(const char *arg)
2996 {
2997     scan_stepSize = atoi(arg);
2998     return 0;
2999 }
3000
3001 int cmd_scanpos(const char *arg)
3002 {
3003     int r = sscanf(arg, "%d", &scan_position);
3004     if (r == 0)
3005         scan_position = 1;
3006     return 0;
3007 }
3008
3009 int cmd_scansize(const char *arg)
3010 {
3011     int r = sscanf(arg, "%d", &scan_size);
3012     if (r == 0)
3013         scan_size = 20;
3014     return 0;
3015 }
3016
3017 int cmd_scan(const char *arg)
3018 {
3019     if (protocol == PROTO_HTTP)
3020     {
3021 #if HAVE_XML2
3022         if (!conn)
3023             cmd_open(0);
3024         if (!conn)
3025             return 0;
3026         if (*arg)
3027         {
3028             if (send_SRW_scanRequest(arg, scan_position, scan_size) < 0)
3029                 return 0;
3030         }
3031         else
3032         {
3033             if (send_SRW_scanRequest(last_scan_line, 1, scan_size) < 0)
3034                 return 0;
3035         }
3036         return 2;
3037 #else
3038         return 0;
3039 #endif
3040     }
3041     else
3042     {
3043         if (!conn)
3044         {
3045             try_reconnect();
3046             
3047             if (!conn) {                                                                
3048                 printf("Session not initialized yet\n");
3049                 return 0;
3050             }
3051         }
3052         if (session_initResponse && 
3053             !ODR_MASK_GET(session_initResponse->options, Z_Options_scan))
3054         {
3055             printf("Target doesn't support scan\n");
3056             return 0;
3057         }
3058         if (*arg)
3059         {
3060             strcpy (last_scan_query, arg);
3061             if (send_scanrequest(arg, scan_position, scan_size, 0) < 0)
3062                 return 0;
3063         }
3064         else
3065         {
3066             if (send_scanrequest(last_scan_query, 1, scan_size, last_scan_line) < 0)
3067                 return 0;
3068         }
3069         return 2;
3070     }
3071 }
3072
3073 int cmd_schema(const char *arg)
3074 {
3075     xfree(record_schema);
3076     record_schema = 0;
3077     if (arg && *arg)
3078         record_schema = xstrdup(arg);
3079     return 1;
3080 }
3081
3082 int cmd_format(const char *arg)
3083 {
3084     oid_value nsyntax;
3085     if (!arg || !*arg)
3086     {
3087         printf("Usage: format <recordsyntax>\n");
3088         return 0;
3089     }
3090     nsyntax = oid_getvalbyname (arg);
3091     if (strcmp(arg, "none") && nsyntax == VAL_NONE)
3092     {
3093         printf ("unknown record syntax\n");
3094         return 0;
3095     }
3096     recordsyntax = nsyntax;
3097     return 1;
3098 }
3099
3100 int cmd_elements(const char *arg)
3101 {
3102     static Z_ElementSetNames esn;
3103     static char what[100];
3104
3105     if (!arg || !*arg)
3106     {
3107         elementSetNames = 0;
3108         return 1;
3109     }
3110     strcpy(what, arg);
3111     esn.which = Z_ElementSetNames_generic;
3112     esn.u.generic = what;
3113     elementSetNames = &esn;
3114     return 1;
3115 }
3116
3117 int cmd_attributeset(const char *arg)
3118 {
3119     char what[100];
3120
3121     if (!arg || !*arg)
3122     {
3123         printf("Usage: attributeset <setname>\n");
3124         return 0;
3125     }
3126     sscanf(arg, "%s", what);
3127     if (p_query_attset (what))
3128     {
3129         printf("Unknown attribute set name\n");
3130         return 0;
3131     }
3132     return 1;
3133 }
3134
3135 int cmd_querytype (const char *arg)
3136 {
3137     if (!strcmp (arg, "ccl"))
3138         queryType = QueryType_CCL;
3139     else if (!strcmp (arg, "prefix") || !strcmp(arg, "rpn"))
3140         queryType = QueryType_Prefix;
3141     else if (!strcmp (arg, "ccl2rpn") || !strcmp (arg, "cclrpn"))
3142         queryType = QueryType_CCL2RPN;
3143     else if (!strcmp(arg, "cql"))
3144         queryType = QueryType_CQL;        
3145     else if (!strcmp (arg, "cql2rpn") || !strcmp (arg, "cqlrpn"))
3146         queryType = QueryType_CQL2RPN;
3147     else
3148     {
3149         printf ("Querytype must be one of:\n");
3150         printf (" prefix         - Prefix query\n");
3151         printf (" ccl            - CCL query\n");
3152         printf (" ccl2rpn        - CCL query converted to RPN\n");
3153         printf (" cql            - CQL\n");
3154         printf (" cql2rpn        - CQL query converted to RPN\n");
3155         return 0;
3156     }
3157     return 1;
3158 }
3159
3160 int cmd_refid (const char *arg)
3161 {
3162     xfree (refid);
3163     refid = NULL;
3164     if (*arg)
3165         refid = xstrdup (arg);
3166     return 1;
3167 }
3168
3169 int cmd_close(const char *arg)
3170 {
3171     Z_APDU *apdu;
3172     Z_Close *req;
3173     if (only_z3950())
3174         return 0;
3175     apdu = zget_APDU(out, Z_APDU_close);
3176     req = apdu->u.close;
3177     *req->closeReason = Z_Close_finished;
3178     send_apdu(apdu);
3179     printf("Sent close request.\n");
3180     sent_close = 1;
3181     return 2;
3182 }
3183
3184 int cmd_packagename(const char* arg)
3185 {
3186     xfree (esPackageName);
3187     esPackageName = NULL;
3188     if (*arg)
3189         esPackageName = xstrdup(arg);
3190     return 1;
3191 }
3192
3193 int cmd_proxy(const char* arg)
3194 {
3195     xfree (yazProxy);
3196     yazProxy = NULL;
3197     if (*arg)
3198         yazProxy = xstrdup (arg);
3199     return 1;
3200 }
3201
3202 int cmd_marccharset(const char *arg)
3203 {
3204     char l1[30];
3205
3206     *l1 = 0;
3207     if (sscanf(arg, "%29s", l1) < 1)
3208     {
3209         printf("MARC character set is `%s'\n", 
3210                marcCharset ? marcCharset: "none");
3211         return 1;
3212     }
3213     xfree (marcCharset);
3214     marcCharset = 0;
3215     if (strcmp(l1, "-"))
3216         marcCharset = xstrdup(l1);
3217     return 1;
3218 }
3219
3220 int cmd_displaycharset(const char *arg)
3221 {
3222     char l1[30];
3223
3224     *l1 = 0;
3225     if (sscanf(arg, "%29s", l1) < 1)
3226     {
3227         printf("Display character set is `%s'\n", 
3228                outputCharset ? outputCharset: "none");
3229     }
3230     else
3231     {
3232         xfree (outputCharset);
3233         outputCharset = 0;
3234         if (!strcmp(l1, "auto") && codeset)
3235         {
3236             if (codeset)
3237             {
3238                 printf ("Display character set: %s\n", codeset);
3239                 outputCharset = xstrdup(codeset);
3240             }
3241             else
3242                 printf ("No codeset found on this system\n");
3243         }
3244         else if (strcmp(l1, "-") && strcmp(l1, "none"))
3245             outputCharset = xstrdup(l1);
3246     } 
3247     return 1;
3248 }
3249
3250 int cmd_negcharset(const char *arg)
3251 {
3252     char l1[30];
3253
3254     *l1 = 0;
3255     if (sscanf(arg, "%29s %d %d", l1, &negotiationCharsetRecords,
3256                &negotiationCharsetVersion) < 1)
3257     {
3258         printf("Current negotiation character set is `%s'\n", 
3259                negotiationCharset ? negotiationCharset: "none");  
3260         printf("Records in charset %s\n", negotiationCharsetRecords ? 
3261                "yes" : "no");
3262         printf("Charneg version %d\n", negotiationCharsetVersion);
3263     }
3264     else
3265     {
3266         xfree (negotiationCharset);
3267         negotiationCharset = NULL;
3268         if (*l1 && strcmp(l1, "-") && strcmp(l1, "none"))
3269         {
3270             negotiationCharset = xstrdup(l1);
3271             printf ("Character set negotiation : %s\n", negotiationCharset);
3272         }
3273     }
3274     return 1;
3275 }
3276
3277 int cmd_charset(const char* arg)
3278 {
3279     char l1[30], l2[30], l3[30];
3280
3281     *l1 = *l2 = *l3 = 0;
3282     if (sscanf(arg, "%29s %29s %29s", l1, l2, l3) < 1)
3283     {
3284         cmd_negcharset("");
3285         cmd_displaycharset("");
3286         cmd_marccharset("");
3287     }
3288     else
3289     {
3290         cmd_negcharset(l1);
3291         if (*l2)
3292             cmd_displaycharset(l2);
3293         if (*l3)
3294             cmd_marccharset(l3);
3295     }
3296     return 1;
3297 }
3298
3299 int cmd_lang(const char* arg)
3300 {
3301     if (*arg == '\0') {
3302         printf("Current language is `%s'\n", (yazLang)?yazLang:NULL);
3303         return 1;
3304     }
3305     xfree (yazLang);
3306     yazLang = NULL;
3307     if (*arg)
3308         yazLang = xstrdup(arg);
3309     return 1;
3310 }
3311
3312 int cmd_source(const char* arg, int echo ) 
3313 {
3314     /* first should open the file and read one line at a time.. */
3315     FILE* includeFile;
3316     char line[102400], *cp;
3317
3318     if(strlen(arg)<1) {
3319         fprintf(stderr,"Error in source command use a filename\n");
3320         return -1;
3321     }
3322     
3323     includeFile = fopen (arg, "r");
3324     
3325     if(!includeFile) {
3326         fprintf(stderr,"Unable to open file %s for reading\n",arg);
3327         return -1;
3328     }
3329     
3330     while(!feof(includeFile)) {
3331         memset(line,0,sizeof(line));
3332         fgets(line,sizeof(line),includeFile);
3333         
3334         if(strlen(line) < 2) continue;
3335         if(line[0] == '#') continue;
3336         
3337         if ((cp = strrchr (line, '\n')))
3338             *cp = '\0';
3339         
3340         if( echo ) {
3341             printf( "processing line: %s\n",line );
3342         };
3343         process_cmd_line(line);
3344     }
3345     
3346     if(fclose(includeFile)<0) {
3347         perror("unable to close include file");
3348         exit(1);
3349     }
3350     return 1;
3351 }
3352
3353 int cmd_source_echo(const char* arg)
3354
3355     cmd_source(arg, 1);
3356     return 1;
3357 }
3358
3359 int cmd_source_noecho(const char* arg)
3360 {
3361     cmd_source(arg, 0);
3362     return 1;
3363 }
3364
3365
3366 int cmd_subshell(const char* args)
3367 {
3368     if(strlen(args)) 
3369         system(args);
3370     else 
3371         system(getenv("SHELL"));
3372     
3373     printf("\n");
3374     return 1;
3375 }
3376
3377 int cmd_set_berfile(const char *arg)
3378 {
3379     if (ber_file && ber_file != stdout && ber_file != stderr)
3380         fclose(ber_file);
3381     if (!strcmp(arg, ""))
3382         ber_file = 0;
3383     else if (!strcmp(arg, "-"))
3384         ber_file = stdout;
3385     else
3386         ber_file = fopen(arg, "a");
3387     return 1;
3388 }
3389
3390 int cmd_set_apdufile(const char *arg)
3391 {
3392     if(apdu_file && apdu_file != stderr && apdu_file != stderr)
3393         fclose(apdu_file);
3394     if (!strcmp(arg, ""))
3395         apdu_file = 0;
3396     else if (!strcmp(arg, "-"))
3397         apdu_file = stderr;
3398     else
3399     {
3400         apdu_file = fopen(arg, "a");
3401         if (!apdu_file)
3402             perror("unable to open apdu log file");
3403     }
3404     if (apdu_file)
3405         odr_setprint(print, apdu_file);
3406     return 1;
3407 }
3408
3409 int cmd_set_cclfile(const char* arg)
3410 {  
3411     FILE *inf;
3412
3413     bibset = ccl_qual_mk (); 
3414     inf = fopen (arg, "r");
3415     if (!inf)
3416         perror("unable to open CCL file");
3417     else
3418     {
3419         ccl_qual_file (bibset, inf);
3420         fclose (inf);
3421     }
3422     strcpy(ccl_fields,arg);
3423     return 0;
3424 }
3425
3426 int cmd_set_cqlfile(const char* arg)
3427 {
3428     cql_transform_t newcqltrans;
3429
3430     if ((newcqltrans = cql_transform_open_fname(arg)) == 0) {
3431         perror("unable to open CQL file");
3432         return 0;
3433     }
3434     if (cqltrans != 0)
3435         cql_transform_close(cqltrans);
3436
3437     cqltrans = newcqltrans;
3438     strcpy(cql_fields, arg);
3439     return 0;
3440 }
3441
3442 int cmd_set_auto_reconnect(const char* arg)
3443 {  
3444     if(strlen(arg)==0) {
3445         auto_reconnect = ! auto_reconnect;
3446     } else if(strcmp(arg,"on")==0) {
3447         auto_reconnect = 1;
3448     } else if(strcmp(arg,"off")==0) {
3449         auto_reconnect = 0;             
3450     } else {
3451         printf("Error use on or off\n");
3452         return 1;
3453     }
3454     
3455     if (auto_reconnect)
3456         printf("Set auto reconnect enabled.\n");
3457     else
3458         printf("Set auto reconnect disabled.\n");
3459     
3460     return 0;
3461 }
3462
3463
3464 int cmd_set_auto_wait(const char* arg)
3465 {  
3466     if(strlen(arg)==0) {
3467         auto_wait = ! auto_wait;
3468     } else if(strcmp(arg,"on")==0) {
3469         auto_wait = 1;
3470     } else if(strcmp(arg,"off")==0) {
3471         auto_wait = 0;          
3472     } else {
3473         printf("Error use on or off\n");
3474         return 1;
3475     }
3476     
3477     if (auto_wait)
3478         printf("Set auto wait enabled.\n");
3479     else
3480         printf("Set auto wait disabled.\n");
3481     
3482     return 0;
3483 }
3484
3485 int cmd_set_marcdump(const char* arg)
3486 {
3487     if(marc_file && marc_file != stderr) { /* don't close stdout*/
3488         fclose(marc_file);
3489     }
3490
3491     if (!strcmp(arg, ""))
3492         marc_file = 0;
3493     else if (!strcmp(arg, "-"))
3494         marc_file = stderr;
3495     else
3496     {
3497         marc_file = fopen(arg, "a");
3498         if (!marc_file)
3499             perror("unable to open marc log file");
3500     }
3501     return 1;
3502 }
3503
3504 /* 
3505    this command takes 3 arge {name class oid} 
3506 */
3507 int cmd_register_oid(const char* args) {
3508     static struct {
3509         char* className;
3510         oid_class oclass;
3511     } oid_classes[] = {
3512         {"appctx",CLASS_APPCTX},
3513         {"absyn",CLASS_ABSYN},
3514         {"attset",CLASS_ATTSET},
3515         {"transyn",CLASS_TRANSYN},
3516         {"diagset",CLASS_DIAGSET},
3517         {"recsyn",CLASS_RECSYN},
3518         {"resform",CLASS_RESFORM},
3519         {"accform",CLASS_ACCFORM},
3520         {"extserv",CLASS_EXTSERV},
3521         {"userinfo",CLASS_USERINFO},
3522         {"elemspec",CLASS_ELEMSPEC},
3523         {"varset",CLASS_VARSET},
3524         {"schema",CLASS_SCHEMA},
3525         {"tagset",CLASS_TAGSET},
3526         {"general",CLASS_GENERAL},
3527         {0,(enum oid_class) 0}
3528     };
3529     char oname_str[101], oclass_str[101], oid_str[101];  
3530     char* name;
3531     int i;
3532     oid_class oidclass = CLASS_GENERAL;
3533     int val = 0, oid[OID_SIZE];
3534     struct oident * new_oident=NULL;
3535     
3536     if (sscanf (args, "%100[^ ] %100[^ ] %100s",
3537                 oname_str,oclass_str, oid_str) < 1) {
3538         printf("Error in register command \n");
3539         return 0;
3540     }
3541     
3542     for (i = 0; oid_classes[i].className; i++) {
3543         if (!strcmp(oid_classes[i].className, oclass_str))
3544         {
3545             oidclass=oid_classes[i].oclass;
3546             break;
3547         }
3548     }
3549     
3550     if(!(oid_classes[i].className)) {
3551         printf("Unknown oid class %s\n",oclass_str);
3552         return 0;
3553     }
3554     
3555     i = 0;
3556     name = oid_str;
3557     val = 0;
3558     
3559     while (isdigit (*(unsigned char *) name))
3560     {
3561         val = val*10 + (*name - '0');
3562         name++;
3563         if (*name == '.')
3564         {
3565             if (i < OID_SIZE-1)
3566                 oid[i++] = val;
3567             val = 0;
3568             name++;
3569         }
3570     }
3571     oid[i] = val;
3572     oid[i+1] = -1;
3573     
3574     new_oident = oid_addent (oid, PROTO_GENERAL, oidclass, oname_str,
3575                              VAL_DYNAMIC);  
3576     if(strcmp(new_oident->desc,oname_str))
3577     {
3578         fprintf(stderr,"oid is already named as %s, registration failed\n",
3579                 new_oident->desc);
3580     }
3581     return 1;  
3582 }
3583
3584 int cmd_push_command(const char* arg) 
3585 {
3586 #if HAVE_READLINE_HISTORY_H
3587     if(strlen(arg)>1) 
3588         add_history(arg);
3589 #else 
3590     fprintf(stderr,"Not compiled with the readline/history module\n");
3591 #endif
3592     return 1;
3593 }
3594
3595 void source_rcfile() 
3596 {
3597     /*  Look for a $HOME/.yazclientrc and source it if it exists */
3598     struct stat statbuf;
3599     char buffer[1000];
3600     char* homedir=getenv("HOME");
3601
3602     if( homedir ) {
3603         
3604         sprintf(buffer,"%s/.yazclientrc",homedir);
3605
3606         if(stat(buffer,&statbuf)==0) {
3607             cmd_source(buffer, 0 );
3608         }
3609         
3610     };
3611     
3612     if(stat(".yazclientrc",&statbuf)==0) {
3613         cmd_source(".yazclientrc", 0 );
3614     }
3615 }
3616
3617
3618 static void initialize(void)
3619 {
3620     FILE *inf;
3621     int i;
3622     
3623     if (!(out = odr_createmem(ODR_ENCODE)) ||
3624         !(in = odr_createmem(ODR_DECODE)) ||
3625         !(print = odr_createmem(ODR_PRINT)))
3626     {
3627         fprintf(stderr, "failed to allocate ODR streams\n");
3628         exit(1);
3629     }
3630     oid_init();
3631     
3632     setvbuf(stdout, 0, _IONBF, 0);
3633     if (apdu_file)
3634         odr_setprint(print, apdu_file);
3635
3636     bibset = ccl_qual_mk (); 
3637     inf = fopen (ccl_fields, "r");
3638     if (inf)
3639     {
3640         ccl_qual_file (bibset, inf);
3641         fclose (inf);
3642     }
3643
3644     cqltrans = cql_transform_open_fname(cql_fields);
3645     /* If this fails, no problem: we detect cqltrans == 0 later */
3646
3647 #if HAVE_READLINE_READLINE_H
3648     rl_attempted_completion_function = (CPPFunction*)readline_completer;
3649 #endif
3650     
3651     
3652     for(i=0; i<maxOtherInfosSupported; ++i) {
3653         extraOtherInfos[i].oidval = -1;
3654     }
3655     
3656     source_rcfile();
3657 }
3658
3659
3660 #if HAVE_GETTIMEOFDAY
3661 struct timeval tv_start;
3662 #endif
3663
3664 #if HAVE_XML2
3665 static void handle_srw_record(Z_SRW_record *rec)
3666 {
3667     if (rec->recordPosition)
3668     {
3669         printf ("pos=%d", *rec->recordPosition);
3670         setno = *rec->recordPosition + 1;
3671     }
3672     if (rec->recordSchema)
3673         printf (" schema=%s", rec->recordSchema);
3674     printf ("\n");
3675     if (rec->recordData_buf && rec->recordData_len)
3676     {
3677         fwrite(rec->recordData_buf, 1, rec->recordData_len, stdout);
3678         if (marc_file)
3679             fwrite (rec->recordData_buf, 1, rec->recordData_len, marc_file);
3680     }
3681     else
3682         printf ("No data!");
3683     printf("\n");
3684 }
3685
3686 static void handle_srw_explain_response(Z_SRW_explainResponse *res)
3687 {
3688     handle_srw_record(&res->record);
3689 }
3690
3691 static void handle_srw_response(Z_SRW_searchRetrieveResponse *res)
3692 {
3693     int i;
3694
3695     printf ("Received SRW SearchRetrieve Response\n");
3696     
3697     for (i = 0; i<res->num_diagnostics; i++)
3698     {
3699         if (res->diagnostics[i].uri)
3700             printf ("SRW diagnostic %s\n",
3701                     res->diagnostics[i].uri);
3702         else
3703             printf ("SRW diagnostic missing or could not be decoded\n");
3704         if (res->diagnostics[i].message)
3705             printf ("Message: %s\n", res->diagnostics[i].message);
3706         if (res->diagnostics[i].details)
3707             printf ("Details: %s\n", res->diagnostics[i].details);
3708     }
3709     if (res->numberOfRecords)
3710         printf ("Number of hits: %d\n", *res->numberOfRecords);
3711     for (i = 0; i<res->num_records; i++)
3712         handle_srw_record(res->records + i);
3713 }
3714
3715 static void handle_srw_scan_term(Z_SRW_scanTerm *term)
3716 {
3717     if (term->displayTerm)
3718         printf("%s:", term->displayTerm);
3719     else if (term->value)
3720         printf("%s:", term->value);
3721     else
3722         printf("No value:");
3723     if (term->numberOfRecords)
3724         printf(" %d", *term->numberOfRecords);
3725     if (term->whereInList)
3726         printf(" %s", term->whereInList);
3727     if (term->value && term->displayTerm)
3728         printf(" %s", term->value);
3729
3730     strcpy(last_scan_line, term->value);
3731     printf("\n");
3732 }
3733
3734 static void handle_srw_scan_response(Z_SRW_scanResponse *res)
3735 {
3736     int i;
3737
3738     printf ("Received SRW Scan Response\n");
3739     
3740     for (i = 0; i<res->num_diagnostics; i++)
3741     {
3742         if (res->diagnostics[i].uri)
3743             printf ("SRW diagnostic %s\n",
3744                     res->diagnostics[i].uri);
3745         else
3746             printf ("SRW diagnostic missing or could not be decoded\n");
3747         if (res->diagnostics[i].message)
3748             printf ("Message: %s\n", res->diagnostics[i].message);
3749         if (res->diagnostics[i].details)
3750             printf ("Details: %s\n", res->diagnostics[i].details);
3751     }
3752     if (res->terms)
3753         for (i = 0; i<res->num_terms; i++)
3754             handle_srw_scan_term(res->terms + i);
3755 }
3756
3757 static void http_response(Z_HTTP_Response *hres)
3758 {
3759     int ret = -1;
3760     const char *content_type = z_HTTP_header_lookup(hres->headers,
3761                                                     "Content-Type");
3762     const char *connection_head = z_HTTP_header_lookup(hres->headers,
3763                                                        "Connection");
3764     if (content_type && !yaz_strcmp_del("text/xml", content_type, "; "))
3765     {
3766         Z_SOAP *soap_package = 0;
3767         ODR o = odr_createmem(ODR_DECODE);
3768         Z_SOAP_Handler soap_handlers[2] = {
3769             {"http://www.loc.gov/zing/srw/", 0,
3770              (Z_SOAP_fun) yaz_srw_codec},
3771             {0, 0, 0}
3772         };
3773         ret = z_soap_codec(o, &soap_package,
3774                            &hres->content_buf, &hres->content_len,
3775                            soap_handlers);
3776         if (!ret && soap_package->which == Z_SOAP_generic &&
3777             soap_package->u.generic->no == 0)
3778         {
3779             Z_SRW_PDU *sr = soap_package->u.generic->p;
3780             if (sr->which == Z_SRW_searchRetrieve_response)
3781                 handle_srw_response(sr->u.response);
3782             else if (sr->which == Z_SRW_explain_response)
3783                 handle_srw_explain_response(sr->u.explain_response);
3784             else if (sr->which == Z_SRW_scan_response)
3785                 handle_srw_scan_response(sr->u.scan_response);
3786             else
3787                 ret = -1;
3788         }
3789         else if (soap_package && (soap_package->which == Z_SOAP_fault
3790                           || soap_package->which == Z_SOAP_error))
3791         {
3792             printf ("HTTP Error Status=%d\n", hres->code);
3793             printf ("SOAP Fault code %s\n",
3794                     soap_package->u.fault->fault_code);
3795             printf ("SOAP Fault string %s\n", 
3796                     soap_package->u.fault->fault_string);
3797             if (soap_package->u.fault->details)
3798                 printf ("SOAP Details %s\n", 
3799                         soap_package->u.fault->details);
3800         }
3801         else
3802             ret = -1;
3803         odr_destroy(o);
3804     }
3805     if (ret)
3806     {
3807         if (hres->code != 200)
3808         {
3809             printf ("HTTP Error Status=%d\n", hres->code);
3810         }
3811         else
3812         {
3813             printf ("Decoding of SRW package failed\n");
3814         }
3815         close_session();
3816     }
3817     else
3818     {
3819         if (!strcmp(hres->version, "1.0"))
3820         {
3821             /* HTTP 1.0: only if Keep-Alive we stay alive.. */
3822             if (!connection_head || strcmp(connection_head, "Keep-Alive"))
3823                 close_session();
3824         }
3825         else 
3826         {
3827             /* HTTP 1.1: only if no close we stay alive .. */
3828             if (connection_head && !strcmp(connection_head, "close"))
3829                 close_session();
3830         }
3831     }
3832 }
3833 #endif
3834
3835 void wait_and_handle_response(int one_response_only) 
3836 {
3837     int reconnect_ok = 1;
3838     int res;
3839     char *netbuffer= 0;
3840     int netbufferlen = 0;
3841 #if HAVE_GETTIMEOFDAY
3842     int got_tv_end = 0;
3843     struct timeval tv_end;
3844 #endif
3845     Z_GDU *gdu;
3846     
3847     while(conn)
3848     {
3849         res = cs_get(conn, &netbuffer, &netbufferlen);
3850         if (reconnect_ok && res <= 0 && protocol == PROTO_HTTP)
3851         {
3852             cs_close(conn);
3853             conn = 0;
3854             cmd_open(0);
3855             reconnect_ok = 0;
3856             if (conn)
3857             {
3858                 char *buf_out;
3859                 int len_out;
3860                 
3861                 buf_out = odr_getbuf(out, &len_out, 0);
3862                 
3863                 do_hex_dump(buf_out, len_out);
3864
3865                 cs_put(conn, buf_out, len_out);
3866                 
3867                 odr_reset(out);
3868                 continue;
3869             }
3870         }
3871         else if (res <= 0)
3872         {
3873             printf("Target closed connection\n");
3874             close_session();
3875             break;
3876         }
3877 #if HAVE_GETTIMEOFDAY
3878         if (got_tv_end == 0)
3879             gettimeofday (&tv_end, 0); /* count first one only */
3880         got_tv_end++;
3881 #endif
3882         odr_reset(out);
3883         odr_reset(in); /* release APDU from last round */
3884         record_last = 0;
3885         do_hex_dump(netbuffer, res);
3886         odr_setbuf(in, netbuffer, res, 0);
3887         
3888         if (!z_GDU(in, &gdu, 0, 0))
3889         {
3890             FILE *f = ber_file ? ber_file : stdout;
3891             odr_perror(in, "Decoding incoming APDU");
3892             fprintf(f, "[Near %d]\n", odr_offset(in));
3893             fprintf(f, "Packet dump:\n---------\n");
3894             odr_dumpBER(f, netbuffer, res);
3895             fprintf(f, "---------\n");
3896             if (apdu_file)
3897             {
3898                 z_GDU(print, &gdu, 0, 0);
3899                 odr_reset(print);
3900             }
3901             if (conn && cs_more(conn))
3902                 continue;
3903             break;
3904         }
3905         if (ber_file)
3906             odr_dumpBER(ber_file, netbuffer, res);
3907         if (apdu_file && !z_GDU(print, &gdu, 0, 0))
3908         {
3909             odr_perror(print, "Failed to print incoming APDU");
3910             odr_reset(print);
3911                 continue;
3912         }
3913         if (gdu->which == Z_GDU_Z3950)
3914         {
3915             Z_APDU *apdu = gdu->u.z3950;
3916             switch(apdu->which)
3917             {
3918             case Z_APDU_initResponse:
3919                 process_initResponse(apdu->u.initResponse);
3920                 break;
3921             case Z_APDU_searchResponse:
3922                 process_searchResponse(apdu->u.searchResponse);
3923                 break;
3924             case Z_APDU_scanResponse:
3925                 process_scanResponse(apdu->u.scanResponse);
3926                 break;
3927             case Z_APDU_presentResponse:
3928                 print_refid (apdu->u.presentResponse->referenceId);
3929                 setno +=
3930                     *apdu->u.presentResponse->numberOfRecordsReturned;
3931                 if (apdu->u.presentResponse->records)
3932                     display_records(apdu->u.presentResponse->records);
3933                 else
3934                     printf("No records.\n");
3935                 printf ("nextResultSetPosition = %d\n",
3936                         *apdu->u.presentResponse->nextResultSetPosition);
3937                 break;
3938             case Z_APDU_sortResponse:
3939                 process_sortResponse(apdu->u.sortResponse);
3940                 break;
3941             case Z_APDU_extendedServicesResponse:
3942                 printf("Got extended services response\n");
3943                 process_ESResponse(apdu->u.extendedServicesResponse);
3944                 break;
3945             case Z_APDU_close:
3946                 printf("Target has closed the association.\n");
3947                 process_close(apdu->u.close);
3948                 break;
3949             case Z_APDU_resourceControlRequest:
3950                 process_resourceControlRequest
3951                     (apdu->u.resourceControlRequest);
3952                 break;
3953             case Z_APDU_deleteResultSetResponse:
3954                 process_deleteResultSetResponse(apdu->u.
3955                                                 deleteResultSetResponse);
3956                 break;
3957             default:
3958                 printf("Received unknown APDU type (%d).\n", 
3959                        apdu->which);
3960                 close_session ();
3961             }
3962         }
3963 #if HAVE_XML2
3964         else if (gdu->which == Z_GDU_HTTP_Response)
3965         {
3966             http_response(gdu->u.HTTP_Response);
3967         }
3968 #endif
3969         if (one_response_only)
3970             break;
3971         if (conn && !cs_more(conn))
3972             break;
3973     }
3974 #if HAVE_GETTIMEOFDAY
3975     if (got_tv_end)
3976     {
3977 #if 0
3978         printf ("S/U S/U=%ld/%ld %ld/%ld",
3979                 (long) tv_start.tv_sec,
3980                 (long) tv_start.tv_usec,
3981                 (long) tv_end.tv_sec,
3982                 (long) tv_end.tv_usec);
3983 #endif
3984         printf ("Elapsed: %.6f\n",
3985                 (double) tv_end.tv_usec / 1e6 + tv_end.tv_sec -
3986                 ((double) tv_start.tv_usec / 1e6 + tv_start.tv_sec));
3987     }
3988 #endif
3989     xfree (netbuffer);
3990 }
3991
3992
3993 int cmd_cclparse(const char* arg) 
3994 {
3995     int error, pos;
3996     struct ccl_rpn_node *rpn=NULL;
3997     
3998     
3999     rpn = ccl_find_str (bibset, arg, &error, &pos);
4000     
4001     if (error) {
4002         printf ("%*s^ - ", 3+strlen(last_cmd)+1+pos, " ");
4003         printf ("%s\n", ccl_err_msg (error));
4004     }
4005     else
4006     {
4007         if (rpn)
4008         {       
4009             ccl_pr_tree(rpn, stdout); 
4010         }
4011     }
4012     if (rpn)
4013         ccl_rpn_delete(rpn);
4014     
4015     printf ("\n");
4016     
4017     return 0;
4018 }
4019
4020
4021 int cmd_set_otherinfo(const char* args)
4022 {
4023     char oidstr[101], otherinfoString[101];
4024     int otherinfoNo;
4025     int sscan_res;
4026     int oidval;
4027     
4028     sscan_res = sscanf (args, "%d %100[^ ] %100s", &otherinfoNo, oidstr, otherinfoString);
4029     if (sscan_res==1) {
4030         /* reset this otherinfo */
4031         if(otherinfoNo>=maxOtherInfosSupported) {
4032             printf("Error otherinfo index to large (%d>%d)\n",
4033                    otherinfoNo,maxOtherInfosSupported);
4034         }
4035         extraOtherInfos[otherinfoNo].oidval = -1;
4036         if (extraOtherInfos[otherinfoNo].value)
4037             free(extraOtherInfos[otherinfoNo].value);                   
4038         return 0;
4039     }
4040     if (sscan_res<3) {
4041         printf("Error in set_otherinfo command \n");
4042         return 0;
4043     }
4044     
4045     if (otherinfoNo>=maxOtherInfosSupported) {
4046         printf("Error otherinfo index to large (%d>%d)\n",
4047                otherinfoNo,maxOtherInfosSupported);
4048     }
4049     
4050     oidval = oid_getvalbyname (oidstr);
4051     if (oidval == -1 ) {
4052         printf("Error in set_otherinfo command unknown oid %s \n",oidstr);
4053         return 0;
4054     }
4055     extraOtherInfos[otherinfoNo].oidval = oidval;
4056     if(extraOtherInfos[otherinfoNo].value) free(extraOtherInfos[otherinfoNo].value);
4057     extraOtherInfos[otherinfoNo].value = strdup(otherinfoString);
4058     
4059     return 0;
4060 }
4061
4062 int cmd_sleep(const char* args ) 
4063 {
4064     int sec=atoi(args);
4065     if( sec > 0 ) {
4066 #ifdef WIN32
4067         Sleep(sec*1000);
4068 #else
4069         sleep(sec);
4070 #endif
4071         printf("Done sleeping %d seconds\n", sec);      
4072     }
4073     return 1;    
4074 }
4075
4076 int cmd_list_otherinfo(const char* args)
4077 {
4078     int i;         
4079     
4080     if(strlen(args)>0) {
4081         i = atoi(args);
4082         if( i >= maxOtherInfosSupported ) {
4083             printf("Error otherinfo index to large (%d>%d)\n",i,maxOtherInfosSupported);
4084             return 0;
4085         }
4086
4087         if(extraOtherInfos[i].oidval != -1) 
4088             printf("  otherinfo %d %s %s\n",
4089                    i,
4090                    yaz_z3950_oid_value_to_str(
4091                        (enum oid_value) extraOtherInfos[i].oidval,
4092                        CLASS_RECSYN),
4093                    extraOtherInfos[i].value);
4094         
4095     } else {            
4096         for(i=0; i<maxOtherInfosSupported; ++i) {
4097             if(extraOtherInfos[i].oidval != -1) 
4098                 printf("  otherinfo %d %s %s\n",
4099                        i,
4100                        yaz_z3950_oid_value_to_str(
4101                            (enum oid_value) extraOtherInfos[i].oidval,
4102                            CLASS_RECSYN),
4103                        extraOtherInfos[i].value);
4104         }
4105         
4106     }
4107     return 0;
4108 }
4109
4110
4111 int cmd_list_all(const char* args) {
4112     int i;
4113     
4114     /* connection options */
4115     if(conn) {
4116         printf("Connected to         : %s\n",last_open_command);
4117     } else {
4118         if(last_open_command) 
4119             printf("Not connected to     : %s\n",last_open_command);
4120         else 
4121             printf("Not connected        : \n");
4122         
4123     }
4124     if(yazProxy) printf("using proxy          : %s\n",yazProxy);                
4125     
4126     printf("auto_reconnect       : %s\n",auto_reconnect?"on":"off");
4127     printf("auto_wait            : %s\n",auto_wait?"on":"off");
4128     
4129     if (!auth) {
4130         printf("Authentication       : none\n");
4131     } else {
4132         switch(auth->which) {
4133         case Z_IdAuthentication_idPass:
4134             printf("Authentication       : IdPass\n"); 
4135             printf("    Login User       : %s\n",auth->u.idPass->userId?auth->u.idPass->userId:"");
4136             printf("    Login Group      : %s\n",auth->u.idPass->groupId?auth->u.idPass->groupId:"");
4137             printf("    Password         : %s\n",auth->u.idPass->password?auth->u.idPass->password:"");
4138             break;
4139         case Z_IdAuthentication_open:
4140             printf("Authentication       : psOpen\n");                  
4141             printf("    Open string      : %s\n",auth->u.open); 
4142             break;
4143         default:
4144             printf("Authentication       : Unknown\n");
4145         }
4146     }
4147     if (negotiationCharset)
4148         printf("Neg. Character set   : `%s'\n", negotiationCharset);
4149     
4150     /* bases */
4151     printf("Bases                : ");
4152     for (i = 0; i<num_databaseNames; i++) printf("%s ",databaseNames[i]);
4153     printf("\n");
4154     
4155     /* Query options */
4156     printf("CCL file             : %s\n",ccl_fields);
4157     printf("CQL file             : %s\n",cql_fields);
4158     printf("Query type           : %s\n",query_type_as_string(queryType));
4159     
4160     printf("Named Result Sets    : %s\n",setnumber==-1?"off":"on");
4161     
4162     /* piggy back options */
4163     printf("ssub/lslb/mspn       : %d/%d/%d\n",smallSetUpperBound,largeSetLowerBound,mediumSetPresentNumber);
4164     
4165     /* print present related options */
4166     printf("Format               : %s\n",yaz_z3950_oid_value_to_str(recordsyntax,CLASS_RECSYN));
4167     printf("Schema               : %s\n",record_schema ? record_schema : "not set");
4168     printf("Elements             : %s\n",elementSetNames?elementSetNames->u.generic:"");
4169     
4170     /* loging options */
4171     printf("APDU log             : %s\n",apdu_file?"on":"off");
4172     printf("Record log           : %s\n",marc_file?"on":"off");
4173     
4174     /* other infos */
4175     printf("Other Info: \n");
4176     cmd_list_otherinfo("");
4177     
4178     return 0;
4179 }
4180
4181 int cmd_clear_otherinfo(const char* args) 
4182 {
4183     if(strlen(args)>0) {
4184         int otherinfoNo;
4185         otherinfoNo = atoi(args);
4186         if( otherinfoNo >= maxOtherInfosSupported ) {
4187             printf("Error otherinfo index to large (%d>%d)\n",otherinfoNo,maxOtherInfosSupported);
4188             return 0;
4189         }
4190         
4191         if(extraOtherInfos[otherinfoNo].oidval != -1) {                 
4192             /* only clear if set. */
4193             extraOtherInfos[otherinfoNo].oidval=-1;
4194             free(extraOtherInfos[otherinfoNo].value);
4195         }
4196     } else {
4197         int i;
4198         
4199         for(i=0; i<maxOtherInfosSupported; ++i) {
4200             if (extraOtherInfos[i].oidval!=-1 ) {                               
4201                 extraOtherInfos[i].oidval=-1;
4202                 free(extraOtherInfos[i].value);
4203             }
4204         }
4205     }
4206     return 0;
4207 }
4208
4209 int cmd_wait_response(const char *arg)
4210 {
4211     int wait_for = atoi(arg);
4212     int i=0;
4213     if( wait_for < 1 ) {
4214         wait_for = 1;
4215     };
4216     
4217     for( i=0 ; i < wait_for ; ++i ) {
4218         wait_and_handle_response(1);
4219     };
4220     return 0;
4221 }
4222
4223 static int cmd_help (const char *line);
4224
4225 typedef char *(*completerFunctionType)(const char *text, int state);
4226
4227 static struct {
4228     char *cmd;
4229     int (*fun)(const char *arg);
4230     char *ad;
4231         completerFunctionType rl_completerfunction;
4232     int complete_filenames;
4233     char **local_tabcompletes;
4234 } cmd_array[] = {
4235     {"open", cmd_open, "('tcp'|'ssl')':<host>[':'<port>][/<db>]",NULL,0,NULL},
4236     {"quit", cmd_quit, "",NULL,0,NULL},
4237     {"find", cmd_find, "<query>",NULL,0,NULL},
4238     {"delete", cmd_delete, "<setname>",NULL,0,NULL},
4239     {"base", cmd_base, "<base-name>",NULL,0,NULL},
4240     {"show", cmd_show, "<rec#>['+'<#recs>['+'<setname>]]",NULL,0,NULL},
4241     {"scan", cmd_scan, "<term>",NULL,0,NULL},
4242     {"scanstep", cmd_scanstep, "<size>",NULL,0,NULL},
4243     {"scanpos", cmd_scanpos, "<size>",NULL,0,NULL},
4244     {"scansize", cmd_scansize, "<size>",NULL,0,NULL},
4245     {"sort", cmd_sort, "<sortkey> <flag> <sortkey> <flag> ...",NULL,0,NULL},
4246     {"sort+", cmd_sort_newset, "<sortkey> <flag> <sortkey> <flag> ...",NULL,0,NULL},
4247     {"authentication", cmd_authentication, "<acctstring>",NULL,0,NULL},
4248     {"lslb", cmd_lslb, "<largeSetLowerBound>",NULL,0,NULL},
4249     {"ssub", cmd_ssub, "<smallSetUpperBound>",NULL,0,NULL},
4250     {"mspn", cmd_mspn, "<mediumSetPresentNumber>",NULL,0,NULL},
4251     {"status", cmd_status, "",NULL,0,NULL},
4252     {"setnames", cmd_setnames, "",NULL,0,NULL},
4253     {"cancel", cmd_cancel, "",NULL,0,NULL},
4254     {"cancel_find", cmd_cancel_find, "<query>",NULL,0,NULL},
4255     {"format", cmd_format, "<recordsyntax>",complete_format,0,NULL},
4256     {"schema", cmd_schema, "<schema>",complete_schema,0,NULL},
4257     {"elements", cmd_elements, "<elementSetName>",NULL,0,NULL},
4258     {"close", cmd_close, "",NULL,0,NULL},
4259     {"attributeset", cmd_attributeset, "<attrset>",complete_attributeset,0,NULL},
4260     {"querytype", cmd_querytype, "<type>",complete_querytype,0,NULL},
4261     {"refid", cmd_refid, "<id>",NULL,0,NULL},
4262     {"itemorder", cmd_itemorder, "ill|item <itemno>",NULL,0,NULL},
4263     {"update", cmd_update, "<action> <recid> [<doc>]",NULL,0,NULL},
4264     {"update0", cmd_update0, "<action> <recid> [<doc>]",NULL,0,NULL},
4265     {"xmles", cmd_xmles, "<OID> <doc>",NULL,0,NULL},
4266     {"packagename", cmd_packagename, "<packagename>",NULL,0,NULL},
4267     {"proxy", cmd_proxy, "[('tcp'|'ssl')]<host>[':'<port>]",NULL,0,NULL},
4268     {"charset", cmd_charset, "<nego_charset> <output_charset>",NULL,0,NULL},
4269     {"negcharset", cmd_negcharset, "<nego_charset>",NULL,0,NULL},
4270     {"displaycharset", cmd_displaycharset, "<output_charset>",NULL,0,NULL},
4271     {"marccharset", cmd_marccharset, "<charset_name>",NULL,0,NULL},
4272     {"lang", cmd_lang, "<language_code>",NULL,0,NULL},
4273     {".", cmd_source_echo, "<filename>",NULL,1,NULL},
4274     {"!", cmd_subshell, "Subshell command",NULL,1,NULL},
4275     {"set_apdufile", cmd_set_apdufile, "<filename>",NULL,1,NULL},
4276     {"set_berfile", cmd_set_berfile, "<filename>",NULL,1,NULL},
4277     {"set_marcdump", cmd_set_marcdump," <filename>",NULL,1,NULL},
4278     {"set_cclfile", cmd_set_cclfile," <filename>",NULL,1,NULL},
4279     {"set_cqlfile", cmd_set_cqlfile," <filename>",NULL,1,NULL},
4280     {"set_auto_reconnect", cmd_set_auto_reconnect," on|off",complete_auto_reconnect,1,NULL},
4281     {"set_auto_wait", cmd_set_auto_wait," on|off",complete_auto_reconnect,1,NULL},
4282     {"set_otherinfo", cmd_set_otherinfo,"<otherinfoinddex> <oid> <string>",NULL,0,NULL},
4283     {"sleep", cmd_sleep,"<seconds>",NULL,0,NULL},
4284     {"register_oid", cmd_register_oid,"<name> <class> <oid>",NULL,0,NULL},
4285     {"push_command", cmd_push_command,"<command>",command_generator,0,NULL},
4286     {"register_tab", cmd_register_tab,"<commandname> <tab>",command_generator,0,NULL},
4287     {"cclparse", cmd_cclparse,"<ccl find command>",NULL,0,NULL},
4288     {"list_otherinfo",cmd_list_otherinfo,"[otherinfoinddex]",NULL,0,NULL},
4289     {"list_all",cmd_list_all,"",NULL,0,NULL},
4290     {"clear_otherinfo",cmd_clear_otherinfo,"",NULL,0,NULL},
4291     {"wait_response",cmd_wait_response,"<number>",NULL,0,NULL},
4292     /* Server Admin Functions */
4293     {"adm-reindex", cmd_adm_reindex, "<database-name>",NULL,0,NULL},
4294     {"adm-truncate", cmd_adm_truncate, "('database'|'index')<object-name>",NULL,0,NULL},
4295     {"adm-create", cmd_adm_create, "",NULL,0,NULL},
4296     {"adm-drop", cmd_adm_drop, "('database'|'index')<object-name>",NULL,0,NULL},
4297     {"adm-import", cmd_adm_import, "<record-type> <dir> <pattern>",NULL,0,NULL},
4298     {"adm-refresh", cmd_adm_refresh, "",NULL,0,NULL},
4299     {"adm-commit", cmd_adm_commit, "",NULL,0,NULL},
4300     {"adm-shutdown", cmd_adm_shutdown, "",NULL,0,NULL},
4301     {"adm-startup", cmd_adm_startup, "",NULL,0,NULL},
4302     {"explain", cmd_explain, "", NULL, 0, NULL},
4303     {"options", cmd_options, "", NULL, 0, NULL},
4304     {"zversion", cmd_zversion, "", NULL, 0, NULL},
4305     {"help", cmd_help, "", NULL,0,NULL},
4306     {"init", cmd_init, "", NULL,0,NULL},
4307     {0,0,0,0,0,0}
4308 };
4309
4310 static int cmd_help (const char *line)
4311 {
4312     int i;
4313     char topic[21];
4314     
4315     *topic = 0;
4316     sscanf (line, "%20s", topic);
4317
4318     if (*topic == 0)
4319         printf("Commands:\n");
4320     for (i = 0; cmd_array[i].cmd; i++)
4321         if (*topic == 0 || strcmp (topic, cmd_array[i].cmd) == 0)
4322             printf("   %s %s\n", cmd_array[i].cmd, cmd_array[i].ad);
4323     if (!strcmp(topic, "find"))
4324     {
4325         printf("RPN:\n");
4326         printf(" \"term\"                        Simple Term\n");
4327         printf(" @attr [attset] type=value op  Attribute\n");
4328         printf(" @and opl opr                  And\n");
4329         printf(" @or opl opr                   Or\n");
4330         printf(" @not opl opr                  And-Not\n");
4331         printf(" @set set                      Result set\n");
4332         printf(" @prox exl dist ord rel uc ut  Proximity. Use help prox\n");
4333         printf("\n");
4334         printf("Bib-1 attribute types\n");
4335         printf("1=Use:         ");
4336         printf("4=Title 7=ISBN 8=ISSN 30=Date 62=Abstract 1003=Author 1016=Any\n");
4337         printf("2=Relation:    ");
4338         printf("1<   2<=  3=  4>=  5>  6!=  102=Relevance\n");
4339         printf("3=Position:    ");
4340         printf("1=First in Field  2=First in subfield  3=Any position\n");
4341         printf("4=Structure:   ");
4342         printf("1=Phrase  2=Word  3=Key  4=Year  5=Date  6=WordList\n");
4343         printf("5=Truncation:  ");
4344         printf("1=Right  2=Left  3=L&R  100=No  101=#  102=Re-1  103=Re-2\n");
4345         printf("6=Completeness:");
4346         printf("1=Incomplete subfield  2=Complete subfield  3=Complete field\n");
4347     }
4348     if (!strcmp(topic, "prox"))
4349     {
4350         printf("Proximity:\n");
4351         printf(" @prox exl dist ord rel uc ut\n");
4352         printf(" exl:  exclude flag . 0=include, 1=exclude.\n");
4353         printf(" dist: distance integer.\n");
4354         printf(" ord:  order flag. 0=unordered, 1=ordered.\n");
4355         printf(" rel:  relation integer. 1<  2<=  3= 4>=  5>  6!= .\n");
4356         printf(" uc:   unit class. k=known, p=private.\n");
4357         printf(" ut:   unit type. 1=character, 2=word, 3=sentence,\n");
4358         printf("        4=paragraph, 5=section, 6=chapter, 7=document,\n");
4359         printf("        8=element, 9=subelement, 10=elementType, 11=byte.\n");
4360         printf("\nExamples:\n");
4361         printf(" Search for a and b in-order at most 3 words apart:\n");
4362         printf("  @prox 0 3 1 2 k 2 a b\n");
4363         printf(" Search for any order of a and b next to each other:\n");
4364         printf("  @prox 0 1 0 3 k 2 a b\n");
4365     }
4366     return 1;
4367 }
4368
4369 int cmd_register_tab(const char* arg) {
4370         
4371     char command[101], tabargument[101];
4372     int i;
4373     int num_of_tabs;
4374     char** tabslist;
4375     
4376     if (sscanf (arg, "%100s %100s", command, tabargument) < 1) {
4377         return 0;
4378     }
4379     
4380     /* locate the amdn in the list */
4381     for (i = 0; cmd_array[i].cmd; i++) {
4382         if (!strncmp(cmd_array[i].cmd, command, strlen(command))) {
4383             break;
4384         }
4385     }
4386     
4387     if(!cmd_array[i].cmd) { 
4388         fprintf(stderr,"Unknown command %s\n",command);
4389         return 1;
4390     }
4391     
4392         
4393     if(!cmd_array[i].local_tabcompletes)
4394         cmd_array[i].local_tabcompletes = (char **) calloc(1,sizeof(char**));
4395     
4396     num_of_tabs=0;              
4397     
4398     tabslist = cmd_array[i].local_tabcompletes;
4399     for(;tabslist && *tabslist;tabslist++) {
4400         num_of_tabs++;
4401     }
4402     
4403     cmd_array[i].local_tabcompletes =  (char **)
4404         realloc(cmd_array[i].local_tabcompletes,(num_of_tabs+2)*sizeof(char**));
4405     tabslist=cmd_array[i].local_tabcompletes;
4406     tabslist[num_of_tabs]=strdup(tabargument);
4407     tabslist[num_of_tabs+1]=NULL;
4408     return 1;
4409 }
4410
4411
4412 void process_cmd_line(char* line)
4413 {  
4414     int i, res;
4415     char word[32], arg[10240];
4416     
4417 #if HAVE_GETTIMEOFDAY
4418     gettimeofday (&tv_start, 0);
4419 #endif
4420     
4421     if ((res = sscanf(line, "%31s %10239[^;]", word, arg)) <= 0)
4422     {
4423         strcpy(word, last_cmd);
4424         *arg = '\0';
4425     }
4426     else if (res == 1)
4427         *arg = 0;
4428     strcpy(last_cmd, word);
4429     
4430     /* removed tailing spaces from the arg command */
4431     { 
4432         char* p = arg;
4433         char* lastnonspace=NULL;
4434         
4435         for(;*p; ++p) {
4436             if(!isspace(*(unsigned char *) p)) {
4437                 lastnonspace = p;
4438             }
4439         }
4440         if(lastnonspace) 
4441             *(++lastnonspace) = 0;
4442     }
4443     
4444     for (i = 0; cmd_array[i].cmd; i++)
4445         if (!strncmp(cmd_array[i].cmd, word, strlen(word)))
4446         {
4447             res = (*cmd_array[i].fun)(arg);
4448             break;
4449         }
4450     
4451     if (!cmd_array[i].cmd) /* dump our help-screen */
4452     {
4453         printf("Unknown command: %s.\n", word);
4454         printf("Type 'help' for list of commands\n");
4455         res = 1;
4456     }
4457     
4458     if(apdu_file) fflush(apdu_file);
4459     
4460     if (res >= 2 && auto_wait)
4461         wait_and_handle_response(0);
4462     
4463     if(apdu_file)
4464         fflush(apdu_file);
4465     if(marc_file)
4466         fflush(marc_file);
4467 }
4468
4469
4470 char *command_generator(const char *text, int state) 
4471 {
4472     static int idx; 
4473     if (state==0) {
4474         idx = 0;
4475     }
4476     for( ; cmd_array[idx].cmd; ++idx) {
4477         if (!strncmp(cmd_array[idx].cmd,text,strlen(text))) {
4478             ++idx;  /* skip this entry on the next run */
4479             return strdup(cmd_array[idx-1].cmd);
4480         }
4481     }
4482     return NULL;
4483 }
4484
4485
4486 /* 
4487    This function only known how to complete on the first word
4488 */
4489 char ** readline_completer(char *text, int start, int end) {
4490 #if HAVE_READLINE_READLINE_H
4491
4492         completerFunctionType completerToUse;
4493         
4494     if(start == 0) {
4495 #if HAVE_READLINE_RL_COMPLETION_MATCHES
4496         char** res=rl_completion_matches(text,
4497                                       command_generator); 
4498 #else
4499         char** res=completion_matches(text,
4500                                       (CPFunction*)command_generator); 
4501 #endif
4502         rl_attempted_completion_over = 1;
4503         return res;
4504     } else {
4505         char arg[10240],word[32];
4506         int i=0 ,res;
4507         if ((res = sscanf(rl_line_buffer, "%31s %10239[^;]", word, arg)) <= 0) {     
4508             rl_attempted_completion_over = 1;
4509             return NULL;
4510         }
4511         
4512         for (i = 0; cmd_array[i].cmd; i++) {
4513             if (!strncmp(cmd_array[i].cmd, word, strlen(word))) {
4514                 break;
4515             }
4516         }
4517         
4518         if(!cmd_array[i].cmd) return NULL;
4519         
4520         curret_global_list = cmd_array[i].local_tabcompletes;
4521         
4522         completerToUse = cmd_array[i].rl_completerfunction;
4523         if(completerToUse==NULL)  /* if no pr. command completer is defined use the default completer */
4524             completerToUse = default_completer;
4525         
4526         if(completerToUse) {
4527 #ifdef HAVE_READLINE_RL_COMPLETION_MATCHES
4528             char** res=
4529                 rl_completion_matches(text,
4530                                       completerToUse);
4531 #else
4532             char** res=
4533                 completion_matches(text,
4534                                    (CPFunction*)completerToUse);
4535 #endif
4536             if(!cmd_array[i].complete_filenames) 
4537                 rl_attempted_completion_over = 1;
4538             return res;
4539         } else {
4540             if(!cmd_array[i].complete_filenames) 
4541                 rl_attempted_completion_over = 1;
4542             return 0;
4543         }
4544     }
4545 #else 
4546     return 0;
4547 #endif 
4548 }
4549
4550
4551 static void client(void)
4552 {
4553     char line[10240];
4554
4555     line[10239] = '\0';
4556
4557 #if HAVE_GETTIMEOFDAY
4558     gettimeofday (&tv_start, 0);
4559 #endif
4560
4561     while (1)
4562     {
4563         char *line_in = NULL;
4564 #if HAVE_READLINE_READLINE_H
4565         if (isatty(0))
4566         {
4567             line_in=readline(C_PROMPT);
4568             if (!line_in)
4569                 break;
4570 #if HAVE_READLINE_HISTORY_H
4571             if (*line_in)
4572                 add_history(line_in);
4573 #endif
4574             strncpy(line, line_in, 10239);
4575             free (line_in);
4576         }
4577 #endif 
4578         if (!line_in)
4579         {
4580             char *end_p;
4581             printf (C_PROMPT);
4582             fflush(stdout);
4583             if (!fgets(line, 10239, stdin))
4584                 break;
4585             if ((end_p = strchr (line, '\n')))
4586                 *end_p = '\0';
4587         }
4588         process_cmd_line(line);
4589     }
4590 }
4591
4592 static void show_version(void)
4593 {
4594     char vstr[20];
4595
4596     yaz_version(vstr, 0);
4597     printf ("YAZ version: %s\n", YAZ_VERSION);
4598     if (strcmp(vstr, YAZ_VERSION))
4599         printf ("YAZ DLL/SO: %s\n", vstr);
4600     exit(0);
4601 }
4602
4603 int main(int argc, char **argv)
4604 {
4605     char *prog = *argv;
4606     char *open_command = 0;
4607     char *auth_command = 0;
4608     char *arg;
4609     int ret;
4610     
4611 #if HAVE_LOCALE_H
4612     if (!setlocale(LC_CTYPE, ""))
4613         fprintf (stderr, "setlocale failed\n");
4614 #endif
4615 #if HAVE_LANGINFO_H
4616 #ifdef CODESET
4617     codeset = nl_langinfo(CODESET);
4618 #endif
4619 #endif
4620     if (codeset)
4621         outputCharset = xstrdup(codeset);
4622     
4623     ODR_MASK_SET(&z3950_options, Z_Options_search);
4624     ODR_MASK_SET(&z3950_options, Z_Options_present);
4625     ODR_MASK_SET(&z3950_options, Z_Options_namedResultSets);
4626     ODR_MASK_SET(&z3950_options, Z_Options_triggerResourceCtrl);
4627     ODR_MASK_SET(&z3950_options, Z_Options_scan);
4628     ODR_MASK_SET(&z3950_options, Z_Options_sort);
4629     ODR_MASK_SET(&z3950_options, Z_Options_extendedServices);
4630     ODR_MASK_SET(&z3950_options, Z_Options_delSet);
4631
4632     while ((ret = options("k:c:q:a:b:m:v:p:u:t:Vxd:", argv, argc, &arg)) != -2)
4633     {
4634         switch (ret)
4635         {
4636         case 0:
4637             if (!open_command)
4638             {
4639                 open_command = (char *) xmalloc (strlen(arg)+6);
4640                 strcpy (open_command, "open ");
4641                 strcat (open_command, arg);
4642             }
4643             else
4644             {
4645                 fprintf(stderr, "%s: Specify at most one server address\n",
4646                         prog);
4647                 exit(1);
4648             }
4649             break;
4650         case 'd':
4651             dump_file_prefix = arg;
4652             break;
4653         case 'k':
4654             kilobytes = atoi(arg);
4655             break;
4656         case 'm':
4657             if (!(marc_file = fopen (arg, "a")))
4658             {
4659                 perror (arg);
4660                 exit (1);
4661             }
4662             break;
4663         case 't':
4664             outputCharset = xstrdup(arg);
4665             break;
4666         case 'c':
4667             strncpy (ccl_fields, arg, sizeof(ccl_fields)-1);
4668             ccl_fields[sizeof(ccl_fields)-1] = '\0';
4669             break;
4670         case 'q':
4671             strncpy (cql_fields, arg, sizeof(cql_fields)-1);
4672             cql_fields[sizeof(cql_fields)-1] = '\0';
4673             break;
4674         case 'b':
4675             if (!strcmp(arg, "-"))
4676                 ber_file=stderr;
4677             else
4678                 ber_file=fopen(arg, "a");
4679             break;
4680         case 'a':
4681             if (!strcmp(arg, "-"))
4682                 apdu_file=stderr;
4683             else
4684                 apdu_file=fopen(arg, "a");
4685             break;
4686         case 'x':
4687             hex_dump = 1;
4688             break;
4689         case 'p':
4690             yazProxy=strdup(arg);
4691             break;
4692         case 'u':
4693             if (!auth_command)
4694             {
4695                 auth_command = (char *) xmalloc (strlen(arg)+6);
4696                 strcpy (auth_command, "auth ");
4697                 strcat (auth_command, arg);
4698             }
4699             break;
4700         case 'v':
4701             yaz_log_init(yaz_log_mask_str(arg), "", 0);
4702             break;
4703         case 'V':
4704             show_version();
4705             break;
4706         default:
4707             fprintf (stderr, "Usage: %s "
4708                      " [-a <apdulog>]"
4709                      " [-b berdump]"
4710                      " [-d dump]\n"
4711                      " [-c cclfields]"
4712                      " [-k size]"
4713                      " [-m <marclog>]\n" 
4714                      " [-p <proxy-addr>]"
4715                      " [-q cqlfields]"
4716                      " [-u <auth>]"
4717                      " [-V]"
4718                      " [<server-addr>]\n",
4719                      prog);
4720             exit (1);
4721         }      
4722     }
4723     initialize();
4724     if (auth_command)
4725     {
4726 #ifdef HAVE_GETTIMEOFDAY
4727         gettimeofday (&tv_start, 0);
4728 #endif
4729         process_cmd_line (auth_command);
4730 #if HAVE_READLINE_HISTORY_H
4731         add_history(auth_command);
4732 #endif
4733         xfree(auth_command);
4734     }
4735     if (open_command)
4736     {
4737 #ifdef HAVE_GETTIMEOFDAY
4738         gettimeofday (&tv_start, 0);
4739 #endif
4740         process_cmd_line (open_command);
4741 #if HAVE_READLINE_HISTORY_H
4742         add_history(open_command);
4743 #endif
4744         xfree(open_command);
4745     }
4746     client ();
4747     exit (0);
4748 }
4749 /*
4750  * Local variables:
4751  * c-basic-offset: 4
4752  * indent-tabs-mode: nil
4753  * End:
4754  * vim: shiftwidth=4 tabstop=8 expandtab
4755  */
4756