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