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