More type casts for char signed/unsigned and xmlChar. Using
[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.295 2005-08-22 20:34:21 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 static int last_hit_count = 0;
137
138 typedef enum {
139     QueryType_Prefix,
140     QueryType_CCL,
141     QueryType_CCL2RPN,
142     QueryType_CQL,
143     QueryType_CQL2RPN
144 } QueryType;
145
146 static QueryType queryType = QueryType_Prefix;
147
148 static CCL_bibset bibset;               /* CCL bibset handle */
149 static cql_transform_t cqltrans;        /* CQL context-set handle */
150
151 #if HAVE_READLINE_COMPLETION_OVER
152
153 #else
154 /* readline doesn't have this var. Define it ourselves. */
155 int rl_attempted_completion_over = 0;
156 #endif
157
158 /* set this one to 1, to avoid decode of unknown MARCs  */
159 #define AVOID_MARC_DECODE 1
160
161 #define maxOtherInfosSupported 10
162 struct {
163     int oidval;
164     char* value;
165 } extraOtherInfos[maxOtherInfosSupported];
166         
167
168 void process_cmd_line(char* line);
169 char ** readline_completer(char *text, int start, int end);
170 char *command_generator(const char *text, int state);
171 char** curret_global_list=NULL;
172 int cmd_register_tab(const char* arg);
173
174 static void close_session (void);
175
176 ODR getODROutputStream()
177 {
178     return out;
179 }
180
181 const char* query_type_as_string(QueryType q) 
182 {
183     switch (q) { 
184     case QueryType_Prefix: return "prefix (RPN sent to server)";
185     case QueryType_CCL: return "CCL (CCL sent to server) ";
186     case QueryType_CCL2RPN: return "CCL -> RPN (RPN sent to server)";
187     case QueryType_CQL: return "CQL (CQL sent to server)";
188     case QueryType_CQL2RPN: return "CQL -> RPN (RPN sent to server)";
189     default: 
190         return "unknown Query type internal yaz-client error";
191     }
192 }
193
194 static void do_hex_dump(const char* buf, int len) 
195 {
196     if (hex_dump)
197     {
198         int i,x;
199         for( i=0; i<len ; i=i+16 ) 
200         {                       
201             printf(" %4.4d ",i);
202             for(x=0 ; i+x<len && x<16; ++x) 
203             {
204                 printf("%2.2X ",(unsigned int)((unsigned char)buf[i+x]));
205             }
206             printf("\n");
207         }
208     }
209     if (dump_file_prefix)
210     {
211         static int no = 0;
212         if (++no < 1000 && strlen(dump_file_prefix) < 500)
213         {
214             char fname[1024];
215             FILE *of;
216             sprintf (fname, "%s.%03d.raw", dump_file_prefix, no);
217             of = fopen(fname, "wb");
218             
219             fwrite (buf, 1, len, of);
220             
221             fclose(of);
222         }
223     }
224 }
225
226 void add_otherInfos(Z_APDU *a) 
227 {
228     Z_OtherInformation **oi;
229     int i;
230                 
231     yaz_oi_APDU(a, &oi);
232     for(i=0; i<maxOtherInfosSupported; ++i) 
233     {
234         if(extraOtherInfos[i].oidval != -1) 
235             yaz_oi_set_string_oidval(oi, out, extraOtherInfos[i].oidval,
236                                      1, extraOtherInfos[i].value);
237     }   
238 }
239
240 int send_apdu(Z_APDU *a)
241 {
242     char *buf;
243     int len;
244     
245     add_otherInfos(a);
246     
247     if (apdu_file)
248     {
249         z_APDU(print, &a, 0, 0);
250         odr_reset(print);
251     }
252     if (!z_APDU(out, &a, 0, 0))
253     {
254         odr_perror(out, "Encoding APDU");
255         close_session();
256         return 0;
257     }
258     buf = odr_getbuf(out, &len, 0);
259     if (ber_file)
260         odr_dumpBER(ber_file, buf, len);
261     /* printf ("sending APDU of size %d\n", len); */
262     do_hex_dump(buf, len);
263     if (cs_put(conn, buf, len) < 0)
264     {
265         fprintf(stderr, "cs_put: %s", cs_errmsg(cs_errno(conn)));
266         close_session();
267         return 0;
268     }
269     odr_reset(out); /* release the APDU structure  */
270     return 1;
271 }
272
273 static void print_stringn(const unsigned char *buf, size_t len)
274 {
275     size_t i;
276     for (i = 0; i<len; i++)
277         if ((buf[i] <= 126 && buf[i] >= 32) || strchr ("\n\r\t\f", buf[i]))
278             printf ("%c", buf[i]);
279         else
280             printf ("\\X%02X", buf[i]);
281 }
282
283 static void print_refid (Z_ReferenceId *id)
284 {
285     if (id)
286     {
287         printf ("Reference Id: ");
288         print_stringn (id->buf, id->len);
289         printf ("\n");
290     }
291 }
292
293 static Z_ReferenceId *set_refid (ODR out)
294 {
295     Z_ReferenceId *id;
296     if (!refid)
297         return 0;
298     id = (Z_ReferenceId *) odr_malloc (out, sizeof(*id));
299     id->size = id->len = strlen(refid);
300     id->buf = (unsigned char *) odr_malloc (out, id->len);
301     memcpy (id->buf, refid, id->len);
302     return id;
303 }   
304
305 /* INIT SERVICE ------------------------------- */
306
307 static void send_initRequest(const char* type_and_host)
308 {
309     Z_APDU *apdu = zget_APDU(out, Z_APDU_initRequest);
310     Z_InitRequest *req = apdu->u.initRequest;
311     int i;
312
313     req->options = &z3950_options;
314
315     ODR_MASK_ZERO(req->protocolVersion);
316     for (i = 0; i<z3950_version; i++)
317         ODR_MASK_SET(req->protocolVersion, i);
318
319     *req->maximumRecordSize = 1024*kilobytes;
320     *req->preferredMessageSize = 1024*kilobytes;
321
322     req->idAuthentication = auth;
323
324     req->referenceId = set_refid (out);
325
326     if (yazProxy && type_and_host) 
327         yaz_oi_set_string_oidval(&req->otherInfo, out, VAL_PROXY,
328         1, type_and_host);
329     
330     if (negotiationCharset || yazLang) {
331         Z_OtherInformation **p;
332         Z_OtherInformationUnit *p0;
333         
334         yaz_oi_APDU(apdu, &p);
335         
336         if ((p0=yaz_oi_update(p, out, NULL, 0, 0))) {
337             ODR_MASK_SET(req->options, Z_Options_negotiationModel);
338             
339             p0->which = Z_OtherInfo_externallyDefinedInfo;
340             p0->information.externallyDefinedInfo =
341                 yaz_set_proposal_charneg(
342                     out,
343                     (const char**)&negotiationCharset, 
344                     negotiationCharset ? 1 : 0,
345                     (const char**)&yazLang, yazLang ? 1 : 0, 
346                     negotiationCharsetRecords);
347         }
348     }
349     
350     if (send_apdu(apdu))
351         printf("Sent initrequest.\n");
352 }
353
354
355 /* These two are used only from process_initResponse() */
356 static void render_initUserInfo(Z_OtherInformation *ui1);
357 static void render_diag(Z_DiagnosticFormat *diag);
358
359 static void pr_opt(const char *opt, void *clientData)
360 {
361     printf (" %s", opt);
362 }
363
364 static int process_initResponse(Z_InitResponse *res)
365 {
366     int ver = 0;
367     /* save session parameters for later use */
368     session_mem = odr_extract_mem(in);
369     session_initResponse = res;
370
371     for (ver = 0; ver < 8; ver++)
372         if (!ODR_MASK_GET(res->protocolVersion, ver))
373             break;
374
375     if (!*res->result)
376         printf("Connection rejected by v%d target.\n", ver);
377     else
378         printf("Connection accepted by v%d target.\n", ver);
379     if (res->implementationId)
380         printf("ID     : %s\n", res->implementationId);
381     if (res->implementationName)
382         printf("Name   : %s\n", res->implementationName);
383     if (res->implementationVersion)
384         printf("Version: %s\n", res->implementationVersion);
385     if (res->userInformationField)
386     {
387         Z_External *uif = res->userInformationField;
388         if (uif->which == Z_External_userInfo1) {
389             render_initUserInfo(uif->u.userInfo1);
390         } else {
391             printf("UserInformationfield:\n");
392             if (!z_External(print, (Z_External**)&uif, 0, 0))
393             {
394                 odr_perror(print, "Printing userinfo\n");
395                 odr_reset(print);
396             }
397             if (uif->which == Z_External_octet) {
398                 printf("Guessing visiblestring:\n");
399                 printf("'%.*s'\n", uif->u.octet_aligned->len,
400                        uif->u.octet_aligned->buf);
401             }
402             else if (uif->which == Z_External_single) 
403             {
404                 Odr_any *sat = uif->u.single_ASN1_type;
405                 oident *oid = oid_getentbyoid(uif->direct_reference);
406                 if (oid->value == VAL_OCLCUI) {
407                     Z_OCLC_UserInformation *oclc_ui;
408                     ODR decode = odr_createmem(ODR_DECODE);
409                     odr_setbuf(decode, (char *) sat->buf, sat->len, 0);
410                     if (!z_OCLC_UserInformation(decode, &oclc_ui, 0, 0))
411                         printf ("Bad OCLC UserInformation:\n");
412                     else
413                         printf ("OCLC UserInformation:\n");
414                     if (!z_OCLC_UserInformation(print, &oclc_ui, 0, 0))
415                         printf ("Bad OCLC UserInformation spec\n");
416                     odr_destroy(decode);
417                 }
418                 else
419                 {
420                     /* Peek at any private Init-diagnostic APDUs */
421                     printf("### NAUGHTY: External is '%.*s'\n",
422                            sat->len, sat->buf);
423                 }
424             }
425             odr_reset (print);
426         }
427     }
428     printf ("Options:");
429     yaz_init_opt_decode(res->options, pr_opt, 0);
430     printf ("\n");
431
432     if (ODR_MASK_GET(res->options, Z_Options_namedResultSets))
433         setnumber = 0;
434     
435     if (ODR_MASK_GET(res->options, Z_Options_negotiationModel)) {
436     
437         Z_CharSetandLanguageNegotiation *p =
438                 yaz_get_charneg_record(res->otherInfo);
439         
440         if (p) {
441             
442             char *charset=NULL, *lang=NULL;
443             int selected;
444             
445             yaz_get_response_charneg(session_mem, p, &charset, &lang,
446                                      &selected);
447
448             if (outputCharset && negotiationCharset) {
449                     odr_set_charset (out, charset, outputCharset);
450                     odr_set_charset (in, outputCharset, charset);
451             }
452             else {
453                     odr_set_charset (out, 0, 0);
454                     odr_set_charset (in, 0, 0);
455             }
456             
457             printf("Accepted character set : %s\n", charset);
458             printf("Accepted code language : %s\n", lang ? lang : "none");
459             printf("Accepted records in ...: %d\n", selected );
460         }
461     }
462     fflush (stdout);
463     return 0;
464 }
465
466
467 static void render_initUserInfo(Z_OtherInformation *ui1) {
468     int i;
469     printf("Init response contains %d otherInfo unit%s:\n",
470            ui1->num_elements, ui1->num_elements == 1 ? "" : "s");
471
472     for (i = 0; i < ui1->num_elements; i++) {
473         Z_OtherInformationUnit *unit = ui1->list[i];
474         printf("  %d: otherInfo unit contains ", i+1);
475         if (unit->which == Z_OtherInfo_externallyDefinedInfo &&
476             unit->information.externallyDefinedInfo &&
477             unit->information.externallyDefinedInfo->which ==
478             Z_External_diag1) {
479             render_diag(unit->information.externallyDefinedInfo->u.diag1);
480         } 
481         else if (unit->which != Z_OtherInfo_externallyDefinedInfo)
482         {
483             printf("unsupported otherInfo unit->which = %d\n", unit->which);
484         }
485         else 
486         {
487             printf("unsupported otherInfo unit external %d\n",
488                    unit->information.externallyDefinedInfo ? 
489                    unit->information.externallyDefinedInfo->which : -2);
490         }
491     }
492 }
493
494
495 /* ### should this share code with display_diagrecs()? */
496 static void render_diag(Z_DiagnosticFormat *diag) {
497     int i;
498
499     printf("%d diagnostic%s:\n", diag->num, diag->num == 1 ? "" : "s");
500     for (i = 0; i < diag->num; i++) {
501         Z_DiagnosticFormat_s *ds = diag->elements[i];
502         printf("    %d: ", i+1);
503         switch (ds->which) {
504         case Z_DiagnosticFormat_s_defaultDiagRec: {
505             Z_DefaultDiagFormat *dd = ds->u.defaultDiagRec;
506             /* ### should check `dd->diagnosticSetId' */
507             printf("code=%d (%s)", *dd->condition,
508                    diagbib1_str(*dd->condition));
509             /* Both types of addinfo are the same, so use type-pun */
510             if (dd->u.v2Addinfo != 0)
511                 printf(",\n\taddinfo='%s'", dd->u.v2Addinfo);
512             break;
513         }
514         case Z_DiagnosticFormat_s_explicitDiagnostic:
515             printf("Explicit diagnostic (not supported)");
516             break;
517         default:
518             printf("Unrecognised diagnostic type %d", ds->which);
519             break;
520         }
521
522         if (ds->message != 0)
523             printf(", message='%s'", ds->message);
524         printf("\n");
525     }
526 }
527
528
529 static int set_base(const char *arg)
530 {
531     int i;
532     const char *cp;
533
534     for (i = 0; i<num_databaseNames; i++)
535         xfree (databaseNames[i]);
536     num_databaseNames = 0;
537     while (1)
538     {
539         char *cp1;
540         if (!(cp = strchr(arg, ' ')))
541             cp = arg + strlen(arg);
542         if (cp - arg < 1)
543             break;
544         databaseNames[num_databaseNames] = (char *)xmalloc (1 + cp - arg);
545         memcpy (databaseNames[num_databaseNames], arg, cp - arg);
546         databaseNames[num_databaseNames][cp - arg] = '\0';
547
548         for (cp1 = databaseNames[num_databaseNames]; *cp1 ; cp1++)
549             if (*cp1 == '+')
550                 *cp1 = ' ';
551         num_databaseNames++;
552
553         if (!*cp)
554             break;
555         arg = cp+1;
556     }
557     if (num_databaseNames == 0)
558     {
559         num_databaseNames = 1;
560         databaseNames[0] = xstrdup("");
561     }
562     return 1;
563 }
564
565 static int parse_cmd_doc(const char **arg, ODR out, char **buf,
566                          int *len, int opt)
567 {
568     const char *sep;
569     while (**arg && strchr(" \t\n\r\f", **arg))
570         (*arg)++;
571     if ((*arg)[0] == '\"' && (sep=strchr(*arg+1, '"')))
572     {
573         (*arg)++;
574         *len = sep - *arg;
575         *buf = odr_strdupn(out, *arg, *len);
576         (*arg) = sep+1;
577         return 1;
578     }
579     else if ((*arg)[0] && (*arg)[0] != '\"')
580     {
581         long fsize;
582         FILE *inf;
583         const char *fname = *arg;
584         
585         while (**arg != '\0' && **arg != ' ')
586             (*arg)++;
587             
588         inf = fopen(fname, "rb");
589         if (!inf)
590         {
591             printf("Couldn't open %s\n", fname);
592             return 0;
593         }
594         if (fseek(inf, 0L, SEEK_END) == -1)
595         {
596             printf("Couldn't seek in %s\n", fname);
597             fclose(inf);
598             return 0;
599         }
600         fsize = ftell(inf);
601         if (fseek(inf, 0L, SEEK_SET) == -1)
602         {
603             printf("Couldn't seek in %s\n", fname);
604             fclose(inf);
605             return 0;
606         }
607         *len = fsize;
608         *buf = odr_malloc(out, fsize);
609         if (fread(*buf, 1, fsize, inf) != fsize)
610         {
611             printf("Unable to read %s\n", fname);
612             fclose(inf);
613             return 0;
614         }
615         fclose(inf);
616         return 1;
617     }
618     else if (**arg == '\0')
619     {
620         if (opt)
621         {
622             *len = 0;
623             *buf = 0;
624             return 1;
625         }
626         printf("Missing doc argument\n");
627     }
628     else
629         printf("Bad doc argument %s\n", *arg);
630     return 0;
631 }
632
633 static int cmd_base(const char *arg)
634 {
635     if (!*arg)
636     {
637         printf("Usage: base <database> <database> ...\n");
638         return 0;
639     }
640     return set_base(arg);
641 }
642
643 void cmd_open_remember_last_open_command(const char* arg, char* new_open_command)
644 {
645     if(last_open_command != arg) 
646     {
647         if(last_open_command) xfree(last_open_command);
648         last_open_command = xstrdup(new_open_command);
649     }
650 }
651
652 int session_connect(const char *arg)
653 {
654     void *add;
655     char type_and_host[101];
656     const char *basep = 0;
657 #if HAVE_OPENSSL_SSL_H
658     SSL *ssl;
659 #endif
660     if (conn)
661     {
662         cs_close (conn);
663         conn = 0;
664     }   
665     if (session_mem)
666     {
667         nmem_destroy (session_mem);
668         session_mem = NULL;
669         session_initResponse = 0;
670     }
671     cs_get_host_args(arg, &basep);
672
673     strncpy(type_and_host, arg, sizeof(type_and_host)-1);
674     type_and_host[sizeof(type_and_host)-1] = '\0';
675
676     cmd_open_remember_last_open_command(arg, type_and_host);
677
678     if (yazProxy)
679         conn = cs_create_host(yazProxy, 1, &add);
680     else
681         conn = cs_create_host(arg, 1, &add);
682     if (!conn)
683     {
684         printf ("Couldn't create comstack\n");
685         return 0;
686     }
687 #if HAVE_XML2
688     if (conn->protocol == PROTO_HTTP)
689         queryType = QueryType_CQL;
690 #else
691     if (conn->protocol == PROTO_HTTP)
692     {
693         printf ("SRW/HTTP not enabled in this YAZ\n");
694         cs_close(conn);
695         conn = 0;
696         return 0;
697     }
698 #endif
699     protocol = conn->protocol;
700     if (conn->protocol == PROTO_HTTP)
701         set_base("");
702     else
703         set_base("Default");
704     printf("Connecting...");
705     fflush(stdout);
706     if (cs_connect(conn, add) < 0)
707     {
708         printf ("error = %s\n", cs_strerror(conn));
709         if (conn->cerrno == CSYSERR)
710         {
711             char msg[256];
712             yaz_strerror(msg, sizeof(msg));
713             printf ("%s\n", msg);
714         }
715         cs_close(conn);
716         conn = 0;
717         return 0;
718     }
719     printf("OK.\n");
720 #if HAVE_OPENSSL_SSL_H
721     if ((ssl = (SSL *) cs_get_ssl(conn)))
722     {
723         X509 *server_cert = SSL_get_peer_certificate (ssl);
724
725         if (server_cert)
726         {
727             char *pem_buf;
728             int pem_len;
729             BIO *bio = BIO_new(BIO_s_mem());
730
731             /* get PEM buffer in memory */
732             PEM_write_bio_X509(bio, server_cert);
733             pem_len = BIO_get_mem_data(bio, &pem_buf);
734             fwrite(pem_buf, pem_len, 1, stdout);
735         
736             /* print all info on screen .. */
737             X509_print_fp(stdout, server_cert);
738             BIO_free(bio);
739
740             X509_free (server_cert);
741         }
742     }
743 #endif
744     if (basep && *basep)
745         set_base (basep);
746     if (protocol == PROTO_Z3950)
747     {
748         send_initRequest(type_and_host);
749         return 2;
750     }
751     return 0;
752 }
753
754 int cmd_open(const char *arg)
755 {
756     if (arg)
757     {
758         strncpy (cur_host, arg, sizeof(cur_host)-1);
759         cur_host[sizeof(cur_host)-1] = 0;
760     }
761     return session_connect(cur_host);
762 }
763
764 void try_reconnect() 
765 {
766     char* open_command;
767         
768     if(!( auto_reconnect && last_open_command) ) return ;
769
770     open_command = (char *) xmalloc (strlen(last_open_command)+6);
771     strcpy (open_command, "open ");
772         
773     strcat (open_command, last_open_command);
774
775     process_cmd_line(open_command);
776         
777     xfree(open_command);                                
778 }
779
780 int cmd_authentication(const char *arg)
781 {
782     static Z_IdAuthentication au;
783     static char user[40], group[40], pass[40];
784     static Z_IdPass idPass;
785     int r;
786
787     if (!*arg)
788     {
789         printf("Auth field set to null\n");
790         auth = 0;
791         return 1;
792     }
793     r = sscanf (arg, "%39s %39s %39s", user, group, pass);
794     if (r == 0)
795     {
796         printf("Authentication set to null\n");
797         auth = 0;
798     }
799     if (r == 1)
800     {
801         auth = &au;
802         if (!strcmp(user, "-")) {
803             au.which = Z_IdAuthentication_anonymous;
804             printf("Authentication set to Anonymous\n");
805         } else {
806             au.which = Z_IdAuthentication_open;
807             au.u.open = user;
808             printf("Authentication set to Open (%s)\n", user);
809         }
810     }
811     if (r == 2)
812     {
813         auth = &au;
814         au.which = Z_IdAuthentication_idPass;
815         au.u.idPass = &idPass;
816         idPass.groupId = NULL;
817         idPass.userId = user;
818         idPass.password = group;
819         printf("Authentication set to User (%s), Pass (%s)\n", user, group);
820     }
821     if (r == 3)
822     {
823         auth = &au;
824         au.which = Z_IdAuthentication_idPass;
825         au.u.idPass = &idPass;
826         idPass.groupId = group;
827         idPass.userId = user;
828         idPass.password = pass;
829         printf("Authentication set to User (%s), Group (%s), Pass (%s)\n",
830                user, group, pass);
831     }
832     return 1;
833 }
834
835 /* SEARCH SERVICE ------------------------------ */
836 static void display_record(Z_External *r);
837
838 static void print_record(const unsigned char *buf, size_t len)
839 {
840     size_t i = len;
841     print_stringn (buf, len);
842     /* add newline if not already added ... */
843     if (i <= 0 || buf[i-1] != '\n')
844         printf ("\n");
845 }
846
847 static void display_record(Z_External *r)
848 {
849     oident *ent = oid_getentbyoid(r->direct_reference);
850
851     record_last = r;
852     /*
853      * Tell the user what we got.
854      */
855     if (r->direct_reference)
856     {
857         printf("Record type: ");
858         if (ent)
859             printf("%s\n", ent->desc);
860         else if (!odr_oid(print, &r->direct_reference, 0, 0))
861         {
862             odr_perror(print, "print oid");
863             odr_reset(print);
864         }
865     }
866     /* Check if this is a known, ASN.1 type tucked away in an octet string */
867     if (ent && r->which == Z_External_octet)
868     {
869         Z_ext_typeent *type = z_ext_getentbyref(ent->value);
870         char *rr;
871
872         if (type)
873         {
874             /*
875              * Call the given decoder to process the record.
876              */
877             odr_setbuf(in, (char*)r->u.octet_aligned->buf,
878                 r->u.octet_aligned->len, 0);
879             if (!(*type->fun)(in, &rr, 0, 0))
880             {
881                 odr_perror(in, "Decoding constructed record.");
882                 fprintf(stdout, "[Near %d]\n", odr_offset(in));
883                 fprintf(stdout, "Packet dump:\n---------\n");
884                 odr_dumpBER(stdout, (char*)r->u.octet_aligned->buf,
885                             r->u.octet_aligned->len);
886                 fprintf(stdout, "---------\n");
887                 
888                 /* note just ignores the error ant print the bytes form the octet_aligned later */
889             } else {
890                 /*
891                  * Note: we throw away the original, BER-encoded record here.
892                  * Do something else with it if you want to keep it.
893                  */
894                 r->u.sutrs = (Z_SUTRS *) rr; /* we don't actually check the type here. */
895                 r->which = type->what;
896             }
897         }
898     }
899     if (ent && ent->value == VAL_SOIF)
900     {
901         print_record((const unsigned char *) r->u.octet_aligned->buf,
902                      r->u.octet_aligned->len);
903         if (marc_file)
904             fwrite (r->u.octet_aligned->buf, 1, r->u.octet_aligned->len, marc_file);
905     }
906     else if (r->which == Z_External_octet)
907     {
908         const char *octet_buf = (char*)r->u.octet_aligned->buf;
909         if (ent->oclass == CLASS_RECSYN && 
910                 (ent->value == VAL_TEXT_XML || 
911                  ent->value == VAL_APPLICATION_XML ||
912                  ent->value == VAL_HTML))
913         {
914             print_record((const unsigned char *) octet_buf,
915                          r->u.octet_aligned->len);
916         }
917         else if (ent->value == VAL_POSTSCRIPT)
918         {
919             int size = r->u.octet_aligned->len;
920             if (size > 100)
921                 size = 100;
922             print_record((const unsigned char *) octet_buf, size);
923         }
924         else
925         {
926             if ( 
927 #if AVOID_MARC_DECODE
928                 /* primitive check for a marc OID 5.1-29 except 16 */
929                 ent->oidsuffix[0] == 5 && ent->oidsuffix[1] < 30 &&
930                 ent->oidsuffix[1] != 16
931 #else
932                 1
933 #endif
934                 )
935             {
936                 char *result;
937                 int rlen;
938                 yaz_iconv_t cd = 0;
939                 yaz_marc_t mt = yaz_marc_create();
940                     
941                 if (yaz_marc_decode_buf(mt, octet_buf,r->u.octet_aligned->len,
942                                         &result, &rlen)> 0)
943                 {
944                     char *from = 0;
945                     if (marcCharset && !strcmp(marcCharset, "auto"))
946                     {
947                         if (ent->value == VAL_USMARC)
948                         {
949                             if (octet_buf[9] == 'a')
950                                 from = "UTF-8";
951                             else
952                                 from = "MARC-8";
953                         }
954                         else
955                             from = "ISO-8859-1";
956                     }
957                     else if (marcCharset)
958                         from = marcCharset;
959                     if (outputCharset && from)
960                     {   
961                         cd = yaz_iconv_open(outputCharset, from);
962                         printf ("convert from %s to %s", from, 
963                                 outputCharset);
964                         if (!cd)
965                             printf (" unsupported\n");
966                         else
967                             printf ("\n");
968                     }
969                     if (!cd)
970                         fwrite (result, 1, rlen, stdout);
971                     else
972                     {
973                         char outbuf[6];
974                         size_t inbytesleft = rlen;
975                         const char *inp = result;
976                         
977                         while (inbytesleft)
978                         {
979                             size_t outbytesleft = sizeof(outbuf);
980                             char *outp = outbuf;
981                             size_t r;
982
983                             r = yaz_iconv (cd, (char**) &inp,
984                                            &inbytesleft, 
985                                            &outp, &outbytesleft);
986                             if (r == (size_t) (-1))
987                             {
988                                 int e = yaz_iconv_error(cd);
989                                 if (e != YAZ_ICONV_E2BIG)
990                                     break;
991                             }
992                             fwrite (outbuf, outp - outbuf, 1, stdout);
993                         }
994                     }
995                 }
996                 else
997                 {
998                     printf ("bad MARC. Dumping as it is:\n");
999                     print_record((const unsigned char*) octet_buf,
1000                                   r->u.octet_aligned->len);
1001                 }       
1002                 yaz_marc_destroy(mt);
1003                 if (cd)
1004                     yaz_iconv_close(cd);
1005             }
1006             else
1007             {
1008                 print_record((const unsigned char*) octet_buf,
1009                              r->u.octet_aligned->len);
1010             }
1011         }
1012         if (marc_file)
1013             fwrite (octet_buf, 1, r->u.octet_aligned->len, marc_file);
1014     }
1015     else if (ent && ent->value == VAL_SUTRS)
1016     {
1017         if (r->which != Z_External_sutrs)
1018         {
1019             printf("Expecting single SUTRS type for SUTRS.\n");
1020             return;
1021         }
1022         print_record(r->u.sutrs->buf, r->u.sutrs->len);
1023         if (marc_file)
1024             fwrite (r->u.sutrs->buf, 1, r->u.sutrs->len, marc_file);
1025     }
1026     else if (ent && ent->value == VAL_GRS1)
1027     {
1028         WRBUF w;
1029         if (r->which != Z_External_grs1)
1030         {
1031             printf("Expecting single GRS type for GRS.\n");
1032             return;
1033         }
1034         w = wrbuf_alloc();
1035         yaz_display_grs1(w, r->u.grs1, 0);
1036         puts (wrbuf_buf(w));
1037         wrbuf_free(w, 1);
1038     }
1039     else if (ent && ent->value == VAL_OPAC)
1040     {
1041         int i;
1042         if (r->u.opac->bibliographicRecord)
1043             display_record(r->u.opac->bibliographicRecord);
1044         for (i = 0; i<r->u.opac->num_holdingsData; i++)
1045         {
1046             Z_HoldingsRecord *h = r->u.opac->holdingsData[i];
1047             if (h->which == Z_HoldingsRecord_marcHoldingsRecord)
1048             {
1049                 printf ("MARC holdings %d\n", i);
1050                 display_record(h->u.marcHoldingsRecord);
1051             }
1052             else if (h->which == Z_HoldingsRecord_holdingsAndCirc)
1053             {
1054                 int j;
1055
1056                 Z_HoldingsAndCircData *data = h->u.holdingsAndCirc;
1057
1058                 printf ("Data holdings %d\n", i);
1059                 if (data->typeOfRecord)
1060                     printf ("typeOfRecord: %s\n", data->typeOfRecord);
1061                 if (data->encodingLevel)
1062                     printf ("encodingLevel: %s\n", data->encodingLevel);
1063                 if (data->receiptAcqStatus)
1064                     printf ("receiptAcqStatus: %s\n", data->receiptAcqStatus);
1065                 if (data->generalRetention)
1066                     printf ("generalRetention: %s\n", data->generalRetention);
1067                 if (data->completeness)
1068                     printf ("completeness: %s\n", data->completeness);
1069                 if (data->dateOfReport)
1070                     printf ("dateOfReport: %s\n", data->dateOfReport);
1071                 if (data->nucCode)
1072                     printf ("nucCode: %s\n", data->nucCode);
1073                 if (data->localLocation)
1074                     printf ("localLocation: %s\n", data->localLocation);
1075                 if (data->shelvingLocation)
1076                     printf ("shelvingLocation: %s\n", data->shelvingLocation);
1077                 if (data->callNumber)
1078                     printf ("callNumber: %s\n", data->callNumber);
1079                 if (data->shelvingData)
1080                     printf ("shelvingData: %s\n", data->shelvingData);
1081                 if (data->copyNumber)
1082                     printf ("copyNumber: %s\n", data->copyNumber);
1083                 if (data->publicNote)
1084                     printf ("publicNote: %s\n", data->publicNote);
1085                 if (data->reproductionNote)
1086                     printf ("reproductionNote: %s\n", data->reproductionNote);
1087                 if (data->termsUseRepro)
1088                     printf ("termsUseRepro: %s\n", data->termsUseRepro);
1089                 if (data->enumAndChron)
1090                     printf ("enumAndChron: %s\n", data->enumAndChron);
1091                 for (j = 0; j<data->num_volumes; j++)
1092                 {
1093                     printf ("volume %d\n", j);
1094                     if (data->volumes[j]->enumeration)
1095                         printf (" enumeration: %s\n",
1096                                 data->volumes[j]->enumeration);
1097                     if (data->volumes[j]->chronology)
1098                         printf (" chronology: %s\n",
1099                                 data->volumes[j]->chronology);
1100                     if (data->volumes[j]->enumAndChron)
1101                         printf (" enumAndChron: %s\n",
1102                                 data->volumes[j]->enumAndChron);
1103                 }
1104                 for (j = 0; j<data->num_circulationData; j++)
1105                 {
1106                     printf ("circulation %d\n", j);
1107                     if (data->circulationData[j]->availableNow)
1108                         printf (" availableNow: %d\n",
1109                                 *data->circulationData[j]->availableNow);
1110                     if (data->circulationData[j]->availablityDate)
1111                         printf (" availabiltyDate: %s\n",
1112                                 data->circulationData[j]->availablityDate);
1113                     if (data->circulationData[j]->availableThru)
1114                         printf (" availableThru: %s\n",
1115                                 data->circulationData[j]->availableThru);
1116                     if (data->circulationData[j]->restrictions)
1117                         printf (" restrictions: %s\n",
1118                                 data->circulationData[j]->restrictions);
1119                     if (data->circulationData[j]->itemId)
1120                         printf (" itemId: %s\n",
1121                                 data->circulationData[j]->itemId);
1122                     if (data->circulationData[j]->renewable)
1123                         printf (" renewable: %d\n",
1124                                 *data->circulationData[j]->renewable);
1125                     if (data->circulationData[j]->onHold)
1126                         printf (" onHold: %d\n",
1127                                 *data->circulationData[j]->onHold);
1128                     if (data->circulationData[j]->enumAndChron)
1129                         printf (" enumAndChron: %s\n",
1130                                 data->circulationData[j]->enumAndChron);
1131                     if (data->circulationData[j]->midspine)
1132                         printf (" midspine: %s\n",
1133                                 data->circulationData[j]->midspine);
1134                     if (data->circulationData[j]->temporaryLocation)
1135                         printf (" temporaryLocation: %s\n",
1136                                 data->circulationData[j]->temporaryLocation);
1137                 }
1138             }
1139         }
1140     }
1141     else 
1142     {
1143         printf("Unknown record representation.\n");
1144         if (!z_External(print, &r, 0, 0))
1145         {
1146             odr_perror(print, "Printing external");
1147             odr_reset(print);
1148         }
1149     }
1150 }
1151
1152 static void display_diagrecs(Z_DiagRec **pp, int num)
1153 {
1154     int i;
1155     oident *ent;
1156     Z_DefaultDiagFormat *r;
1157
1158     printf("Diagnostic message(s) from database:\n");
1159     for (i = 0; i<num; i++)
1160     {
1161         Z_DiagRec *p = pp[i];
1162         if (p->which != Z_DiagRec_defaultFormat)
1163         {
1164             printf("Diagnostic record not in default format.\n");
1165             return;
1166         }
1167         else
1168             r = p->u.defaultFormat;
1169         if (!(ent = oid_getentbyoid(r->diagnosticSetId)) ||
1170             ent->oclass != CLASS_DIAGSET || ent->value != VAL_BIB1)
1171             printf("Missing or unknown diagset\n");
1172         printf("    [%d] %s", *r->condition, diagbib1_str(*r->condition));
1173         switch (r->which)
1174         {
1175         case Z_DefaultDiagFormat_v2Addinfo:
1176             printf (" -- v2 addinfo '%s'\n", r->u.v2Addinfo);
1177             break;
1178         case Z_DefaultDiagFormat_v3Addinfo:
1179             printf (" -- v3 addinfo '%s'\n", r->u.v3Addinfo);
1180             break;
1181         }
1182     }
1183 }
1184
1185
1186 static void display_nameplusrecord(Z_NamePlusRecord *p)
1187 {
1188     if (p->databaseName)
1189         printf("[%s]", p->databaseName);
1190     if (p->which == Z_NamePlusRecord_surrogateDiagnostic)
1191         display_diagrecs(&p->u.surrogateDiagnostic, 1);
1192     else if (p->which == Z_NamePlusRecord_databaseRecord)
1193         display_record(p->u.databaseRecord);
1194 }
1195
1196 static void display_records(Z_Records *p)
1197 {
1198     int i;
1199
1200     if (p->which == Z_Records_NSD)
1201     {
1202         Z_DiagRec dr, *dr_p = &dr;
1203         dr.which = Z_DiagRec_defaultFormat;
1204         dr.u.defaultFormat = p->u.nonSurrogateDiagnostic;
1205         display_diagrecs (&dr_p, 1);
1206     }
1207     else if (p->which == Z_Records_multipleNSD)
1208         display_diagrecs (p->u.multipleNonSurDiagnostics->diagRecs,
1209                           p->u.multipleNonSurDiagnostics->num_diagRecs);
1210     else 
1211     {
1212         printf("Records: %d\n", p->u.databaseOrSurDiagnostics->num_records);
1213         for (i = 0; i < p->u.databaseOrSurDiagnostics->num_records; i++)
1214             display_nameplusrecord(p->u.databaseOrSurDiagnostics->records[i]);
1215     }
1216 }
1217
1218 static int send_deleteResultSetRequest(const char *arg)
1219 {
1220     char names[8][32];
1221     int i;
1222
1223     Z_APDU *apdu = zget_APDU(out, Z_APDU_deleteResultSetRequest);
1224     Z_DeleteResultSetRequest *req = apdu->u.deleteResultSetRequest;
1225
1226     req->referenceId = set_refid (out);
1227
1228     req->num_resultSetList =
1229         sscanf (arg, "%30s %30s %30s %30s %30s %30s %30s %30s",
1230                 names[0], names[1], names[2], names[3],
1231                 names[4], names[5], names[6], names[7]);
1232
1233     req->deleteFunction = (int *)
1234         odr_malloc (out, sizeof(*req->deleteFunction));
1235     if (req->num_resultSetList > 0)
1236     {
1237         *req->deleteFunction = Z_DeleteResultSetRequest_list;
1238         req->resultSetList = (char **)
1239             odr_malloc (out, sizeof(*req->resultSetList)*
1240                         req->num_resultSetList);
1241         for (i = 0; i<req->num_resultSetList; i++)
1242             req->resultSetList[i] = names[i];
1243     }
1244     else
1245     {
1246         *req->deleteFunction = Z_DeleteResultSetRequest_all;
1247         req->resultSetList = 0;
1248     }
1249     
1250     send_apdu(apdu);
1251     printf("Sent deleteResultSetRequest.\n");
1252     return 2;
1253 }
1254
1255 #if HAVE_XML2
1256 static int send_srw(Z_SRW_PDU *sr)
1257 {
1258     const char *charset = negotiationCharset;
1259     const char *host_port = cur_host;
1260     char *path = 0;
1261     char ctype[50];
1262     Z_SOAP_Handler h[2] = {
1263         {"http://www.loc.gov/zing/srw/", 0, (Z_SOAP_fun) yaz_srw_codec},
1264         {0, 0, 0}
1265     };
1266     ODR o = odr_createmem(ODR_ENCODE);
1267     int ret;
1268     Z_SOAP *p = odr_malloc(o, sizeof(*p));
1269     Z_GDU *gdu;
1270
1271     path = odr_malloc(out, strlen(databaseNames[0])+2);
1272     *path = '/';
1273     strcpy(path+1, databaseNames[0]);
1274
1275     gdu = z_get_HTTP_Request(out);
1276     gdu->u.HTTP_Request->version = http_version;
1277     gdu->u.HTTP_Request->path = odr_strdup(out, path);
1278
1279     if (host_port)
1280     {
1281         const char *cp0 = strstr(host_port, "://");
1282         const char *cp1 = 0;
1283         if (cp0)
1284             cp0 = cp0+3;
1285         else
1286             cp0 = host_port;
1287
1288         cp1 = strchr(cp0, '/');
1289         if (!cp1)
1290             cp1 = cp0+strlen(cp0);
1291
1292         if (cp0 && cp1)
1293         {
1294             char *h = odr_malloc(out, cp1 - cp0 + 1);
1295             memcpy (h, cp0, cp1 - cp0);
1296             h[cp1-cp0] = '\0';
1297             z_HTTP_header_add(out, &gdu->u.HTTP_Request->headers,
1298                               "Host", h);
1299         }
1300     }
1301
1302     strcpy(ctype, "text/xml");
1303     if (charset && strlen(charset) < 20)
1304     {
1305         strcat(ctype, "; charset=");
1306         strcat(ctype, charset);
1307     }
1308     z_HTTP_header_add(out, &gdu->u.HTTP_Request->headers,
1309                       "Content-Type", ctype);
1310     z_HTTP_header_add(out, &gdu->u.HTTP_Request->headers,
1311                       "SOAPAction", "\"\"");
1312     p->which = Z_SOAP_generic;
1313     p->u.generic = odr_malloc(o, sizeof(*p->u.generic));
1314     p->u.generic->no = 0;
1315     p->u.generic->ns = 0;
1316     p->u.generic->p = sr;
1317     p->ns = "http://schemas.xmlsoap.org/soap/envelope/";
1318
1319     ret = z_soap_codec_enc(o, &p,
1320                            &gdu->u.HTTP_Request->content_buf,
1321                            &gdu->u.HTTP_Request->content_len, h,
1322                            charset);
1323
1324     if (z_GDU(out, &gdu, 0, 0))
1325     {
1326         /* encode OK */
1327         char *buf_out;
1328         int len_out;
1329         int r;
1330         if (apdu_file)
1331         {
1332             if (!z_GDU(print, &gdu, 0, 0))
1333                 printf ("Failed to print outgoing APDU\n");
1334             odr_reset(print);
1335         }
1336         buf_out = odr_getbuf(out, &len_out, 0);
1337         
1338         /* we don't odr_reset(out), since we may need the buffer again */
1339
1340         do_hex_dump(buf_out, len_out);
1341
1342         r = cs_put(conn, buf_out, len_out);
1343
1344         odr_destroy(o);
1345         
1346         if (r >= 0)
1347             return 2;
1348     }
1349     return 0;
1350 }
1351 #endif
1352
1353 #if HAVE_XML2
1354 static char *encode_SRW_term(ODR o, const char *q)
1355 {
1356     const char *in_charset = "ISO-8859-1";
1357     WRBUF w = wrbuf_alloc();
1358     yaz_iconv_t cd;
1359     char *res;
1360     if (outputCharset)
1361         in_charset = outputCharset;
1362     cd = yaz_iconv_open("UTF-8", in_charset);
1363     if (!cd)
1364     {
1365         wrbuf_free(w, 1);
1366         return odr_strdup(o, q);
1367     }
1368     wrbuf_iconv_write(w, cd, q, strlen(q));
1369     if (wrbuf_len(w))
1370     {
1371         int len = wrbuf_len(w);
1372         res = odr_strdupn(o, wrbuf_buf(w), len);
1373     }
1374     else
1375         res = odr_strdup(o, q);    
1376     yaz_iconv_close(cd);
1377     wrbuf_free(w, 1);
1378     return res;
1379 }
1380
1381
1382 static int send_SRW_scanRequest(const char *arg, int pos, int num)
1383 {
1384     Z_SRW_PDU *sr = 0;
1385     
1386     /* regular requestse .. */
1387     sr = yaz_srw_get(out, Z_SRW_scan_request);
1388
1389     switch(queryType)
1390     {
1391     case QueryType_CQL:
1392         sr->u.scan_request->query_type = Z_SRW_query_type_cql;
1393         sr->u.scan_request->scanClause.cql = encode_SRW_term(out, arg);
1394         break;
1395     case QueryType_Prefix:
1396         sr->u.scan_request->query_type = Z_SRW_query_type_pqf;
1397         sr->u.scan_request->scanClause.pqf = encode_SRW_term(out, arg);
1398         break;
1399     default:
1400         printf ("Only CQL and PQF supported in SRW\n");
1401         return 0;
1402     }
1403     sr->u.scan_request->responsePosition = odr_intdup(out, pos);
1404     sr->u.scan_request->maximumTerms = odr_intdup(out, num);
1405     return send_srw(sr);
1406 }
1407
1408 static int send_SRW_searchRequest(const char *arg)
1409 {
1410     Z_SRW_PDU *sr = 0;
1411     
1412     if (!srw_sr)
1413     {
1414         assert(srw_sr_odr_out == 0);
1415         srw_sr_odr_out = odr_createmem(ODR_ENCODE);
1416     }
1417     odr_reset(srw_sr_odr_out);
1418
1419     setno = 1;
1420
1421     /* save this for later .. when fetching individual records */
1422     srw_sr =  yaz_srw_get(srw_sr_odr_out, Z_SRW_searchRetrieve_request);
1423     
1424     /* regular request .. */
1425     sr = yaz_srw_get(out, Z_SRW_searchRetrieve_request);
1426
1427     switch(queryType)
1428     {
1429     case QueryType_CQL:
1430         srw_sr->u.request->query_type = Z_SRW_query_type_cql;
1431         srw_sr->u.request->query.cql = encode_SRW_term(srw_sr_odr_out, arg);
1432
1433         sr->u.request->query_type = Z_SRW_query_type_cql;
1434         sr->u.request->query.cql = encode_SRW_term(srw_sr_odr_out, arg);
1435         break;
1436     case QueryType_Prefix:
1437         srw_sr->u.request->query_type = Z_SRW_query_type_pqf;
1438         srw_sr->u.request->query.pqf = encode_SRW_term(srw_sr_odr_out, arg);
1439
1440         sr->u.request->query_type = Z_SRW_query_type_pqf;
1441         sr->u.request->query.pqf = encode_SRW_term(srw_sr_odr_out, arg);
1442         break;
1443     default:
1444         printf ("Only CQL and PQF supported in SRW\n");
1445         return 0;
1446     }
1447     sr->u.request->maximumRecords = odr_intdup(out, 0);
1448
1449     if (record_schema)
1450         sr->u.request->recordSchema = record_schema;
1451     if (recordsyntax == VAL_TEXT_XML)
1452         sr->u.explain_request->recordPacking = "xml";
1453     return send_srw(sr);
1454 }
1455 #endif
1456
1457 static int send_searchRequest(const char *arg)
1458 {
1459     Z_APDU *apdu = zget_APDU(out, Z_APDU_searchRequest);
1460     Z_SearchRequest *req = apdu->u.searchRequest;
1461     Z_Query query;
1462     struct ccl_rpn_node *rpn = NULL;
1463     int error, pos;
1464     char setstring[100];
1465     Z_RPNQuery *RPNquery;
1466     Odr_oct ccl_query;
1467     YAZ_PQF_Parser pqf_parser;
1468     Z_External *ext;
1469     QueryType myQueryType = queryType;
1470     char pqfbuf[512];
1471
1472     if (myQueryType == QueryType_CCL2RPN)
1473     {
1474         rpn = ccl_find_str(bibset, arg, &error, &pos);
1475         if (error)
1476         {
1477             printf("CCL ERROR: %s\n", ccl_err_msg(error));
1478             return 0;
1479         }
1480     } else if (myQueryType == QueryType_CQL2RPN) {
1481         /* ### All this code should be wrapped in a utility function */
1482         CQL_parser parser;
1483         struct cql_node *node;
1484         const char *addinfo;
1485         if (cqltrans == 0) {
1486             printf("Can't use CQL: no translation file.  Try set_cqlfile\n");
1487             return 0;
1488         }
1489         parser = cql_parser_create();
1490         if ((error = cql_parser_string(parser, arg)) != 0) {
1491             printf("Can't parse CQL: must be a syntax error\n");
1492             return 0;
1493         }
1494         node = cql_parser_result(parser);
1495         if ((error = cql_transform_buf(cqltrans, node, pqfbuf,
1496                                        sizeof pqfbuf)) != 0) {
1497             error = cql_transform_error(cqltrans, &addinfo);
1498             printf ("Can't convert CQL to PQF: %s (addinfo=%s)\n",
1499                     cql_strerror(error), addinfo);
1500             return 0;
1501         }
1502         arg = pqfbuf;
1503         myQueryType = QueryType_Prefix;
1504     }
1505
1506     req->referenceId = set_refid (out);
1507     if (!strcmp(arg, "@big")) /* strictly for troublemaking */
1508     {
1509         static unsigned char big[2100];
1510         static Odr_oct bigo;
1511
1512         /* send a very big referenceid to test transport stack etc. */
1513         memset(big, 'A', 2100);
1514         bigo.len = bigo.size = 2100;
1515         bigo.buf = big;
1516         req->referenceId = &bigo;
1517     }
1518     
1519     if (setnumber >= 0)
1520     {
1521         sprintf(setstring, "%d", ++setnumber);
1522         req->resultSetName = setstring;
1523     }
1524     *req->smallSetUpperBound = smallSetUpperBound;
1525     *req->largeSetLowerBound = largeSetLowerBound;
1526     *req->mediumSetPresentNumber = mediumSetPresentNumber;
1527     if (smallSetUpperBound > 0 || (largeSetLowerBound > 1 &&
1528         mediumSetPresentNumber > 0))
1529     {
1530         req->preferredRecordSyntax =
1531             yaz_oidval_to_z3950oid(out, CLASS_RECSYN, recordsyntax);
1532
1533         req->smallSetElementSetNames =
1534             req->mediumSetElementSetNames = elementSetNames;
1535     }
1536     req->num_databaseNames = num_databaseNames;
1537     req->databaseNames = databaseNames;
1538
1539     req->query = &query;
1540
1541     switch (myQueryType)
1542     {
1543     case QueryType_Prefix:
1544         query.which = Z_Query_type_1;
1545         pqf_parser = yaz_pqf_create ();
1546         RPNquery = yaz_pqf_parse (pqf_parser, out, arg);
1547         if (!RPNquery)
1548         {
1549             const char *pqf_msg;
1550             size_t off;
1551             int code = yaz_pqf_error (pqf_parser, &pqf_msg, &off);
1552             printf("%*s^\n", off+4, "");
1553             printf("Prefix query error: %s (code %d)\n", pqf_msg, code);
1554             
1555             yaz_pqf_destroy (pqf_parser);
1556             return 0;
1557         }
1558         yaz_pqf_destroy (pqf_parser);
1559         query.u.type_1 = RPNquery;
1560         break;
1561     case QueryType_CCL:
1562         query.which = Z_Query_type_2;
1563         query.u.type_2 = &ccl_query;
1564         ccl_query.buf = (unsigned char*) arg;
1565         ccl_query.len = strlen(arg);
1566         break;
1567     case QueryType_CCL2RPN:
1568         query.which = Z_Query_type_1;
1569         RPNquery = ccl_rpn_query(out, rpn);
1570         if (!RPNquery)
1571         {
1572             printf ("Couldn't convert from CCL to RPN\n");
1573             return 0;
1574         }
1575         query.u.type_1 = RPNquery;
1576         ccl_rpn_delete (rpn);
1577         break;
1578     case QueryType_CQL:
1579         query.which = Z_Query_type_104;
1580         ext = (Z_External *) odr_malloc(out, sizeof(*ext));
1581         ext->direct_reference = odr_getoidbystr(out, "1.2.840.10003.16.2");
1582         ext->indirect_reference = 0;
1583         ext->descriptor = 0;
1584         ext->which = Z_External_CQL;
1585         ext->u.cql = odr_strdup(out, arg);
1586         query.u.type_104 =  ext;
1587         break;
1588     default:
1589         printf ("Unsupported query type\n");
1590         return 0;
1591     }
1592     if (send_apdu(apdu))
1593         printf("Sent searchRequest.\n");
1594     setno = 1;
1595     return 2;
1596 }
1597
1598 /* display Query Expression as part of searchResult-1 */
1599 static void display_queryExpression (Z_QueryExpression *qe)
1600 {
1601     if (!qe)
1602         return;
1603     if (qe->which == Z_QueryExpression_term)
1604     {
1605         if (qe->u.term->queryTerm)
1606         {
1607             Z_Term *term = qe->u.term->queryTerm;
1608             switch (term->which)
1609             {
1610             case Z_Term_general:
1611                 printf (" %.*s", term->u.general->len, term->u.general->buf);
1612                 break;
1613             case Z_Term_characterString:
1614                 printf (" %s", term->u.characterString);
1615                 break;
1616             case Z_Term_numeric:
1617                 printf (" %d", *term->u.numeric);
1618                 break;
1619             case Z_Term_null:
1620                 printf (" null");
1621                 break;
1622             }
1623         }
1624     }
1625 }
1626
1627 /* see if we can find USR:SearchResult-1 */
1628 static void display_searchResult (Z_OtherInformation *o)
1629 {
1630     int i;
1631     if (!o)
1632         return ;
1633     for (i = 0; i < o->num_elements; i++)
1634     {
1635         if (o->list[i]->which == Z_OtherInfo_externallyDefinedInfo)
1636         {
1637             Z_External *ext = o->list[i]->information.externallyDefinedInfo;
1638             
1639             if (ext->which == Z_External_searchResult1)
1640             {
1641                 int j;
1642                 Z_SearchInfoReport *sr = ext->u.searchResult1;
1643                 printf ("SearchResult-1:");
1644                 for (j = 0; j < sr->num; j++)
1645                 {
1646                     if (!sr->elements[j]->subqueryExpression)
1647                         printf (" %d", j);
1648                     display_queryExpression (
1649                         sr->elements[j]->subqueryExpression);
1650                     display_queryExpression (
1651                         sr->elements[j]->subqueryInterpretation);
1652                     display_queryExpression (
1653                         sr->elements[j]->subqueryRecommendation);
1654                     if (sr->elements[j]->subqueryCount)
1655                         printf ("(%d)", *sr->elements[j]->subqueryCount);
1656                 }
1657                 printf ("\n");
1658             }
1659         }
1660     }
1661 }
1662
1663 static int process_searchResponse(Z_SearchResponse *res)
1664 {
1665     printf ("Received SearchResponse.\n");
1666     print_refid (res->referenceId);
1667     if (*res->searchStatus)
1668         printf("Search was a success.\n");
1669     else
1670         printf("Search was a bloomin' failure.\n");
1671     printf("Number of hits: %d", *res->resultCount);
1672     last_hit_count = *res->resultCount;
1673     if (setnumber >= 0)
1674         printf (", setno %d", setnumber);
1675     printf ("\n");
1676     display_searchResult (res->additionalSearchInfo);
1677     printf("records returned: %d\n",
1678            *res->numberOfRecordsReturned);
1679     setno += *res->numberOfRecordsReturned;
1680     if (res->records)
1681         display_records(res->records);
1682     return 0;
1683 }
1684
1685 static void print_level(int iLevel)
1686 {
1687     int i;
1688     for (i = 0; i < iLevel * 4; i++)
1689         printf(" ");
1690 }
1691
1692 static void print_int(int iLevel, const char *pTag, int *pInt)
1693 {
1694     if (pInt != NULL)
1695     {
1696         print_level(iLevel);
1697         printf("%s: %d\n", pTag, *pInt);
1698     }
1699 }
1700
1701 static void print_string(int iLevel, const char *pTag, const char *pString)
1702 {
1703     if (pString != NULL)
1704     {
1705         print_level(iLevel);
1706         printf("%s: %s\n", pTag, pString);
1707     }
1708 }
1709
1710 static void print_oid(int iLevel, const char *pTag, Odr_oid *pOid)
1711 {
1712     if (pOid != NULL)
1713     {
1714         int *pInt = pOid;
1715
1716         print_level(iLevel);
1717         printf("%s:", pTag);
1718         for (; *pInt != -1; pInt++)
1719             printf(" %d", *pInt);
1720         printf("\n");
1721     }
1722 }
1723
1724 static void print_referenceId(int iLevel, Z_ReferenceId *referenceId)
1725 {
1726     if (referenceId != NULL)
1727     {
1728         int i;
1729
1730         print_level(iLevel);
1731         printf("Ref Id (%d, %d): ", referenceId->len, referenceId->size);
1732         for (i = 0; i < referenceId->len; i++)
1733             printf("%c", referenceId->buf[i]);
1734         printf("\n");
1735     }
1736 }
1737
1738 static void print_string_or_numeric(int iLevel, const char *pTag, Z_StringOrNumeric *pStringNumeric)
1739 {
1740     if (pStringNumeric != NULL)
1741     {
1742         switch (pStringNumeric->which)
1743         {
1744         case Z_StringOrNumeric_string:
1745             print_string(iLevel, pTag, pStringNumeric->u.string);
1746             break;
1747             
1748         case Z_StringOrNumeric_numeric:
1749             print_int(iLevel, pTag, pStringNumeric->u.numeric);
1750             break;
1751             
1752         default:
1753             print_level(iLevel);
1754             printf("%s: valid type for Z_StringOrNumeric\n", pTag);
1755             break;
1756         }
1757     }
1758 }
1759
1760 static void print_universe_report_duplicate(
1761     int iLevel,
1762     Z_UniverseReportDuplicate *pUniverseReportDuplicate)
1763 {
1764     if (pUniverseReportDuplicate != NULL)
1765     {
1766         print_level(iLevel);
1767         printf("Universe Report Duplicate: \n");
1768         iLevel++;
1769         print_string_or_numeric(iLevel, "Hit No",
1770                                 pUniverseReportDuplicate->hitno);
1771     }
1772 }
1773
1774 static void print_universe_report_hits(
1775     int iLevel,
1776     Z_UniverseReportHits *pUniverseReportHits)
1777 {
1778     if (pUniverseReportHits != NULL)
1779     {
1780         print_level(iLevel);
1781         printf("Universe Report Hits: \n");
1782         iLevel++;
1783         print_string_or_numeric(iLevel, "Database",
1784                                 pUniverseReportHits->database);
1785         print_string_or_numeric(iLevel, "Hits", pUniverseReportHits->hits);
1786     }
1787 }
1788
1789 static void print_universe_report(int iLevel, Z_UniverseReport *pUniverseReport)
1790 {
1791     if (pUniverseReport != NULL)
1792     {
1793         print_level(iLevel);
1794         printf("Universe Report: \n");
1795         iLevel++;
1796         print_int(iLevel, "Total Hits", pUniverseReport->totalHits);
1797         switch (pUniverseReport->which)
1798         {
1799         case Z_UniverseReport_databaseHits:
1800             print_universe_report_hits(iLevel,
1801                                        pUniverseReport->u.databaseHits);
1802             break;
1803             
1804         case Z_UniverseReport_duplicate:
1805             print_universe_report_duplicate(iLevel,
1806                                             pUniverseReport->u.duplicate);
1807             break;
1808             
1809         default:
1810             print_level(iLevel);
1811             printf("Type: %d\n", pUniverseReport->which);
1812             break;
1813         }
1814     }
1815 }
1816
1817 static void print_external(int iLevel, Z_External *pExternal)
1818 {
1819     if (pExternal != NULL)
1820     {
1821         print_level(iLevel);
1822         printf("External: \n");
1823         iLevel++;
1824         print_oid(iLevel, "Direct Reference", pExternal->direct_reference);
1825         print_int(iLevel, "InDirect Reference", pExternal->indirect_reference);
1826         print_string(iLevel, "Descriptor", pExternal->descriptor);
1827         switch (pExternal->which)
1828         {
1829         case Z_External_universeReport:
1830             print_universe_report(iLevel, pExternal->u.universeReport);
1831             break;
1832             
1833         default:
1834             print_level(iLevel);
1835             printf("Type: %d\n", pExternal->which);
1836             break;
1837         }
1838     }
1839 }
1840
1841 static int process_resourceControlRequest (Z_ResourceControlRequest *req)
1842 {
1843     printf ("Received ResourceControlRequest.\n");
1844     print_referenceId(1, req->referenceId);
1845     print_int(1, "Suspended Flag", req->suspendedFlag);
1846     print_int(1, "Partial Results Available", req->partialResultsAvailable);
1847     print_int(1, "Response Required", req->responseRequired);
1848     print_int(1, "Triggered Request Flag", req->triggeredRequestFlag);
1849     print_external(1, req->resourceReport);
1850     return 0;
1851 }
1852
1853 void process_ESResponse(Z_ExtendedServicesResponse *res)
1854 {
1855     printf("Status: ");
1856     switch (*res->operationStatus)
1857     {
1858     case Z_ExtendedServicesResponse_done:
1859         printf ("done\n");
1860         break;
1861     case Z_ExtendedServicesResponse_accepted:
1862         printf ("accepted\n");
1863         break;
1864     case Z_ExtendedServicesResponse_failure:
1865         printf ("failure\n");
1866         display_diagrecs(res->diagnostics, res->num_diagnostics);
1867         break;
1868     default:
1869         printf ("unknown\n");
1870     }
1871     if ( (*res->operationStatus != Z_ExtendedServicesResponse_failure) &&
1872         (res->num_diagnostics != 0) ) {
1873         display_diagrecs(res->diagnostics, res->num_diagnostics);
1874     }
1875     print_refid (res->referenceId);
1876     if (res->taskPackage && 
1877         res->taskPackage->which == Z_External_extendedService)
1878     {
1879         Z_TaskPackage *taskPackage = res->taskPackage->u.extendedService;
1880         Odr_oct *id = taskPackage->targetReference;
1881         Z_External *ext = taskPackage->taskSpecificParameters;
1882         
1883         if (id)
1884         {
1885             printf ("Target Reference: ");
1886             print_stringn (id->buf, id->len);
1887             printf ("\n");
1888         }
1889         if (ext->which == Z_External_update)
1890         {
1891             Z_IUUpdateTaskPackage *utp = ext->u.update->u.taskPackage;
1892             if (utp && utp->targetPart)
1893             {
1894                 Z_IUTargetPart *targetPart = utp->targetPart;
1895                 int i;
1896
1897                 for (i = 0; i<targetPart->num_taskPackageRecords;  i++)
1898                 {
1899
1900                     Z_IUTaskPackageRecordStructure *tpr =
1901                         targetPart->taskPackageRecords[i];
1902                     printf ("task package record %d\n", i+1);
1903                     if (tpr->which == Z_IUTaskPackageRecordStructure_record)
1904                     {
1905                         display_record (tpr->u.record);
1906                     }
1907                     else
1908                     {
1909                         printf ("other type\n");
1910                     }
1911                 }
1912             }
1913         }
1914     }
1915     if (res->taskPackage && res->taskPackage->which == Z_External_octet)
1916     {
1917         Odr_oct *doc = res->taskPackage->u.octet_aligned;
1918         printf("%.*s\n", doc->len, doc->buf);
1919     }
1920 }
1921
1922 const char *get_ill_element (void *clientData, const char *element)
1923 {
1924     return 0;
1925 }
1926
1927 static Z_External *create_external_itemRequest()
1928 {
1929     struct ill_get_ctl ctl;
1930     ILL_ItemRequest *req;
1931     Z_External *r = 0;
1932     int item_request_size = 0;
1933     char *item_request_buf = 0;
1934
1935     ctl.odr = out;
1936     ctl.clientData = 0;
1937     ctl.f = get_ill_element;
1938     
1939     req = ill_get_ItemRequest(&ctl, "ill", 0);
1940     if (!req)
1941         printf ("ill_get_ItemRequest failed\n");
1942         
1943     if (!ill_ItemRequest (out, &req, 0, 0))
1944     {
1945         if (apdu_file)
1946         {
1947             ill_ItemRequest(print, &req, 0, 0);
1948             odr_reset(print);
1949         }
1950         item_request_buf = odr_getbuf (out, &item_request_size, 0);
1951         if (item_request_buf)
1952             odr_setbuf (out, item_request_buf, item_request_size, 1);
1953         printf ("Couldn't encode ItemRequest, size %d\n", item_request_size);
1954         return 0;
1955     }
1956     else
1957     {
1958         oident oid;
1959         
1960         item_request_buf = odr_getbuf (out, &item_request_size, 0);
1961         oid.proto = PROTO_GENERAL;
1962         oid.oclass = CLASS_GENERAL;
1963         oid.value = VAL_ISO_ILL_1;
1964         
1965         r = (Z_External *) odr_malloc (out, sizeof(*r));
1966         r->direct_reference = odr_oiddup(out,oid_getoidbyent(&oid)); 
1967         r->indirect_reference = 0;
1968         r->descriptor = 0;
1969         r->which = Z_External_single;
1970         
1971         r->u.single_ASN1_type = (Odr_oct *)
1972             odr_malloc (out, sizeof(*r->u.single_ASN1_type));
1973         r->u.single_ASN1_type->buf = (unsigned char *)
1974         odr_malloc (out, item_request_size);
1975         r->u.single_ASN1_type->len = item_request_size;
1976         r->u.single_ASN1_type->size = item_request_size;
1977         memcpy (r->u.single_ASN1_type->buf, item_request_buf,
1978                 item_request_size);
1979         
1980         do_hex_dump(item_request_buf,item_request_size);
1981     }
1982     return r;
1983 }
1984
1985 static Z_External *create_external_ILL_APDU(int which)
1986 {
1987     struct ill_get_ctl ctl;
1988     ILL_APDU *ill_apdu;
1989     Z_External *r = 0;
1990     int ill_request_size = 0;
1991     char *ill_request_buf = 0;
1992         
1993     ctl.odr = out;
1994     ctl.clientData = 0;
1995     ctl.f = get_ill_element;
1996
1997     ill_apdu = ill_get_APDU(&ctl, "ill", 0);
1998
1999     if (!ill_APDU (out, &ill_apdu, 0, 0))
2000     {
2001         if (apdu_file)
2002         {
2003             printf ("-------------------\n");
2004             ill_APDU(print, &ill_apdu, 0, 0);
2005             odr_reset(print);
2006             printf ("-------------------\n");
2007         }
2008         ill_request_buf = odr_getbuf (out, &ill_request_size, 0);
2009         if (ill_request_buf)
2010             odr_setbuf (out, ill_request_buf, ill_request_size, 1);
2011         printf ("Couldn't encode ILL-Request, size %d\n", ill_request_size);
2012         return 0;
2013     }
2014     else
2015     {
2016         oident oid;
2017         ill_request_buf = odr_getbuf (out, &ill_request_size, 0);
2018         
2019         oid.proto = PROTO_GENERAL;
2020         oid.oclass = CLASS_GENERAL;
2021         oid.value = VAL_ISO_ILL_1;
2022         
2023         r = (Z_External *) odr_malloc (out, sizeof(*r));
2024         r->direct_reference = odr_oiddup(out,oid_getoidbyent(&oid)); 
2025         r->indirect_reference = 0;
2026         r->descriptor = 0;
2027         r->which = Z_External_single;
2028         
2029         r->u.single_ASN1_type = (Odr_oct *)
2030             odr_malloc (out, sizeof(*r->u.single_ASN1_type));
2031         r->u.single_ASN1_type->buf = (unsigned char *)
2032         odr_malloc (out, ill_request_size);
2033         r->u.single_ASN1_type->len = ill_request_size;
2034         r->u.single_ASN1_type->size = ill_request_size;
2035         memcpy (r->u.single_ASN1_type->buf, ill_request_buf, ill_request_size);
2036 /*         printf ("len = %d\n", ill_request_size); */
2037 /*              do_hex_dump(ill_request_buf,ill_request_size); */
2038 /*              printf("--- end of extenal\n"); */
2039
2040     }
2041     return r;
2042 }
2043
2044
2045 static Z_External *create_ItemOrderExternal(const char *type, int itemno)
2046 {
2047     Z_External *r = (Z_External *) odr_malloc(out, sizeof(Z_External));
2048     oident ItemOrderRequest;
2049   
2050     ItemOrderRequest.proto = PROTO_Z3950;
2051     ItemOrderRequest.oclass = CLASS_EXTSERV;
2052     ItemOrderRequest.value = VAL_ITEMORDER;
2053  
2054     r->direct_reference = odr_oiddup(out,oid_getoidbyent(&ItemOrderRequest)); 
2055     r->indirect_reference = 0;
2056     r->descriptor = 0;
2057
2058     r->which = Z_External_itemOrder;
2059
2060     r->u.itemOrder = (Z_ItemOrder *) odr_malloc(out,sizeof(Z_ItemOrder));
2061     memset(r->u.itemOrder, 0, sizeof(Z_ItemOrder));
2062     r->u.itemOrder->which=Z_IOItemOrder_esRequest;
2063
2064     r->u.itemOrder->u.esRequest = (Z_IORequest *) 
2065         odr_malloc(out,sizeof(Z_IORequest));
2066     memset(r->u.itemOrder->u.esRequest, 0, sizeof(Z_IORequest));
2067
2068     r->u.itemOrder->u.esRequest->toKeep = (Z_IOOriginPartToKeep *)
2069         odr_malloc(out,sizeof(Z_IOOriginPartToKeep));
2070     memset(r->u.itemOrder->u.esRequest->toKeep, 0, sizeof(Z_IOOriginPartToKeep));
2071     r->u.itemOrder->u.esRequest->notToKeep = (Z_IOOriginPartNotToKeep *)
2072         odr_malloc(out,sizeof(Z_IOOriginPartNotToKeep));
2073     memset(r->u.itemOrder->u.esRequest->notToKeep, 0, sizeof(Z_IOOriginPartNotToKeep));
2074
2075     r->u.itemOrder->u.esRequest->toKeep->supplDescription = NULL;
2076     r->u.itemOrder->u.esRequest->toKeep->contact = NULL;
2077     r->u.itemOrder->u.esRequest->toKeep->addlBilling = NULL;
2078
2079     r->u.itemOrder->u.esRequest->notToKeep->resultSetItem =
2080         (Z_IOResultSetItem *) odr_malloc(out, sizeof(Z_IOResultSetItem));
2081     memset(r->u.itemOrder->u.esRequest->notToKeep->resultSetItem, 0, sizeof(Z_IOResultSetItem));
2082     r->u.itemOrder->u.esRequest->notToKeep->resultSetItem->resultSetId = "1";
2083
2084     r->u.itemOrder->u.esRequest->notToKeep->resultSetItem->item =
2085         (int *) odr_malloc(out, sizeof(int));
2086     *r->u.itemOrder->u.esRequest->notToKeep->resultSetItem->item = itemno;
2087
2088     if (!strcmp (type, "item") || !strcmp(type, "2"))
2089     {
2090         printf ("using item-request\n");
2091         r->u.itemOrder->u.esRequest->notToKeep->itemRequest = 
2092             create_external_itemRequest();
2093     }
2094     else if (!strcmp(type, "ill") || !strcmp(type, "1"))
2095     {
2096         printf ("using ILL-request\n");
2097         r->u.itemOrder->u.esRequest->notToKeep->itemRequest = 
2098             create_external_ILL_APDU(ILL_APDU_ILL_Request);
2099     }
2100     else if (!strcmp(type, "xml") || !strcmp(type, "3"))
2101     {
2102     const char *xml_buf =
2103         "<itemorder>\n"
2104         "  <type>request</type>\n"
2105         "  <libraryNo>000200</libraryNo>\n"
2106         "  <borrowerTicketNo> 1212 </borrowerTicketNo>\n"
2107         "</itemorder>";
2108         r->u.itemOrder->u.esRequest->notToKeep->itemRequest =
2109             z_ext_record (out, VAL_TEXT_XML, xml_buf, strlen(xml_buf));
2110     }
2111     else
2112         r->u.itemOrder->u.esRequest->notToKeep->itemRequest = 0;
2113
2114     return r;
2115 }
2116
2117 static int send_itemorder(const char *type, int itemno)
2118 {
2119     Z_APDU *apdu = zget_APDU(out, Z_APDU_extendedServicesRequest);
2120     Z_ExtendedServicesRequest *req = apdu->u.extendedServicesRequest;
2121     oident ItemOrderRequest;
2122
2123     ItemOrderRequest.proto = PROTO_Z3950;
2124     ItemOrderRequest.oclass = CLASS_EXTSERV;
2125     ItemOrderRequest.value = VAL_ITEMORDER;
2126     req->packageType = odr_oiddup(out,oid_getoidbyent(&ItemOrderRequest));
2127     req->packageName = esPackageName;
2128
2129     req->taskSpecificParameters = create_ItemOrderExternal(type, itemno);
2130
2131     send_apdu(apdu);
2132     return 0;
2133 }
2134
2135 static int only_z3950()
2136 {
2137     if (!conn)
2138     {
2139         printf ("Not connected yet\n");
2140         return 1;
2141     }
2142     if (protocol == PROTO_HTTP)
2143     {
2144         printf ("Not supported by SRW\n");
2145         return 1;
2146     }
2147     return 0;
2148 }
2149
2150 static int cmd_update_common(const char *arg, int version);
2151
2152 static int cmd_update(const char *arg)
2153 {
2154     return cmd_update_common(arg, 1);
2155 }
2156
2157 static int cmd_update0(const char *arg)
2158 {
2159     return cmd_update_common(arg, 0);
2160 }
2161
2162 static int cmd_update_common(const char *arg, int version)
2163 {
2164     Z_APDU *apdu = zget_APDU(out, Z_APDU_extendedServicesRequest );
2165     Z_ExtendedServicesRequest *req = apdu->u.extendedServicesRequest;
2166     Z_External *r;
2167     char action[20], recid[20];
2168     char *rec_buf;
2169     int rec_len;
2170     int action_no;
2171     int noread = 0;
2172     Z_External *record_this = 0;
2173
2174     if (only_z3950())
2175         return 1;
2176     *action = 0;
2177     *recid = 0;
2178     sscanf (arg, "%19s %19s%n", action, recid, &noread);
2179     if (noread == 0)
2180     {
2181         printf("Update must be followed by action and recid\n");
2182         printf(" where action is one of insert,replace,delete.update\n");
2183         printf(" recid is some record ID (any string)\n");
2184         return 0;
2185     }
2186
2187     if (!strcmp (action, "insert"))
2188         action_no = Z_IUOriginPartToKeep_recordInsert;
2189     else if (!strcmp (action, "replace"))
2190         action_no = Z_IUOriginPartToKeep_recordReplace;
2191     else if (!strcmp (action, "delete"))
2192         action_no = Z_IUOriginPartToKeep_recordDelete;
2193     else if (!strcmp (action, "update"))
2194         action_no = Z_IUOriginPartToKeep_specialUpdate;
2195     else 
2196     {
2197         printf ("Bad action: %s\n", action);
2198         printf ("Possible values: insert, replace, delete, update\n");
2199         return 0;
2200     }
2201
2202     arg += noread;
2203     if (parse_cmd_doc(&arg, out, &rec_buf, &rec_len, 1) == 0)
2204         return 0;
2205
2206     if (rec_buf)
2207         record_this = z_ext_record (out, VAL_TEXT_XML, rec_buf, rec_len);
2208     else
2209     {
2210         if (!record_last)
2211         {
2212             printf ("No last record (update ignored)\n");
2213             return 0;
2214         }
2215         record_this = record_last;
2216     }
2217
2218     req->packageType =
2219         yaz_oidval_to_z3950oid(out, CLASS_EXTSERV,
2220                                version == 0 ? VAL_DBUPDATE0 : VAL_DBUPDATE);
2221
2222     req->packageName = esPackageName;
2223     
2224     req->referenceId = set_refid (out);
2225
2226     r = req->taskSpecificParameters = (Z_External *)
2227         odr_malloc (out, sizeof(*r));
2228     r->direct_reference = req->packageType;
2229     r->indirect_reference = 0;
2230     r->descriptor = 0;
2231     if (version == 0)
2232     {
2233         Z_IU0OriginPartToKeep *toKeep;
2234         Z_IU0SuppliedRecords *notToKeep;
2235
2236         r->which = Z_External_update0;
2237         r->u.update0 = (Z_IU0Update *) odr_malloc(out, sizeof(*r->u.update0));
2238         r->u.update0->which = Z_IUUpdate_esRequest;
2239         r->u.update0->u.esRequest = (Z_IU0UpdateEsRequest *)
2240             odr_malloc(out, sizeof(*r->u.update0->u.esRequest));
2241         toKeep = r->u.update0->u.esRequest->toKeep = (Z_IU0OriginPartToKeep *)
2242             odr_malloc(out, sizeof(*r->u.update0->u.esRequest->toKeep));
2243         
2244         toKeep->databaseName = databaseNames[0];
2245         toKeep->schema = 0;
2246         toKeep->elementSetName = 0;
2247
2248         toKeep->action = (int *) odr_malloc(out, sizeof(*toKeep->action));
2249         *toKeep->action = action_no;
2250         
2251         notToKeep = r->u.update0->u.esRequest->notToKeep = (Z_IU0SuppliedRecords *)
2252             odr_malloc(out, sizeof(*r->u.update0->u.esRequest->notToKeep));
2253         notToKeep->num = 1;
2254         notToKeep->elements = (Z_IU0SuppliedRecords_elem **)
2255             odr_malloc(out, sizeof(*notToKeep->elements));
2256         notToKeep->elements[0] = (Z_IU0SuppliedRecords_elem *)
2257             odr_malloc(out, sizeof(**notToKeep->elements));
2258         notToKeep->elements[0]->which = Z_IUSuppliedRecords_elem_opaque;
2259         if (*recid)
2260         {
2261             notToKeep->elements[0]->u.opaque = (Odr_oct *)
2262                 odr_malloc (out, sizeof(Odr_oct));
2263             notToKeep->elements[0]->u.opaque->buf = (unsigned char *) recid;
2264             notToKeep->elements[0]->u.opaque->size = strlen(recid);
2265             notToKeep->elements[0]->u.opaque->len = strlen(recid);
2266         }
2267         else
2268             notToKeep->elements[0]->u.opaque = 0;
2269         notToKeep->elements[0]->supplementalId = 0;
2270         notToKeep->elements[0]->correlationInfo = 0;
2271         notToKeep->elements[0]->record = record_this;
2272     }
2273     else
2274     {
2275         Z_IUOriginPartToKeep *toKeep;
2276         Z_IUSuppliedRecords *notToKeep;
2277
2278         r->which = Z_External_update;
2279         r->u.update = (Z_IUUpdate *) odr_malloc(out, sizeof(*r->u.update));
2280         r->u.update->which = Z_IUUpdate_esRequest;
2281         r->u.update->u.esRequest = (Z_IUUpdateEsRequest *)
2282             odr_malloc(out, sizeof(*r->u.update->u.esRequest));
2283         toKeep = r->u.update->u.esRequest->toKeep = (Z_IUOriginPartToKeep *)
2284             odr_malloc(out, sizeof(*r->u.update->u.esRequest->toKeep));
2285         
2286         toKeep->databaseName = databaseNames[0];
2287         toKeep->schema = 0;
2288         toKeep->elementSetName = 0;
2289         toKeep->actionQualifier = 0;
2290         toKeep->action = (int *) odr_malloc(out, sizeof(*toKeep->action));
2291         *toKeep->action = action_no;
2292
2293         notToKeep = r->u.update->u.esRequest->notToKeep = (Z_IUSuppliedRecords *)
2294             odr_malloc(out, sizeof(*r->u.update->u.esRequest->notToKeep));
2295         notToKeep->num = 1;
2296         notToKeep->elements = (Z_IUSuppliedRecords_elem **)
2297             odr_malloc(out, sizeof(*notToKeep->elements));
2298         notToKeep->elements[0] = (Z_IUSuppliedRecords_elem *)
2299             odr_malloc(out, sizeof(**notToKeep->elements));
2300         notToKeep->elements[0]->which = Z_IUSuppliedRecords_elem_opaque;
2301         if (*recid)
2302         {
2303             notToKeep->elements[0]->u.opaque = (Odr_oct *)
2304                 odr_malloc (out, sizeof(Odr_oct));
2305             notToKeep->elements[0]->u.opaque->buf = (unsigned char *) recid;
2306             notToKeep->elements[0]->u.opaque->size = strlen(recid);
2307             notToKeep->elements[0]->u.opaque->len = strlen(recid);
2308         }
2309         else
2310             notToKeep->elements[0]->u.opaque = 0;
2311         notToKeep->elements[0]->supplementalId = 0;
2312         notToKeep->elements[0]->correlationInfo = 0;
2313         notToKeep->elements[0]->record = record_this;
2314     }
2315     
2316     send_apdu(apdu);
2317
2318     return 2;
2319 }
2320
2321 static int cmd_xmles(const char *arg)
2322 {
2323     if (only_z3950())
2324         return 1;
2325     else
2326     {
2327         int noread = 0;
2328         char oid_str[51];
2329         int oid_value_xmles = VAL_XMLES;
2330         Z_APDU *apdu = zget_APDU(out, Z_APDU_extendedServicesRequest);
2331         Z_ExtendedServicesRequest *req = apdu->u.extendedServicesRequest;
2332         
2333         Z_External *ext = (Z_External *) odr_malloc(out, sizeof(*ext));
2334         
2335         req->taskSpecificParameters = ext;
2336         ext->indirect_reference = 0;
2337         ext->descriptor = 0;
2338         ext->which = Z_External_octet;
2339         ext->u.single_ASN1_type = (Odr_oct *) odr_malloc (out, sizeof(Odr_oct));        
2340         sscanf(arg, "%50s%n", oid_str, &noread);
2341         if (noread == 0)
2342         {
2343             printf("Missing OID for xmles\n");
2344             return 0;
2345         }
2346         arg += noread;
2347         oid_value_xmles  = oid_getvalbyname(oid_str);
2348         if (oid_value_xmles == VAL_NONE)
2349         {
2350             printf("Bad OID: %s\n", oid_str);
2351             return 0;
2352         }
2353         
2354         if (parse_cmd_doc(&arg, out, (char **) &ext->u.single_ASN1_type->buf,
2355                           &ext->u.single_ASN1_type->len, 0) == 0)
2356             return 0;
2357         req->packageType = yaz_oidval_to_z3950oid(out, CLASS_EXTSERV,
2358                                                   oid_value_xmles);
2359         
2360         ext->direct_reference = yaz_oidval_to_z3950oid(out, CLASS_EXTSERV,
2361                                                        oid_value_xmles);
2362         send_apdu(apdu);
2363         
2364         return 2;
2365     }
2366 }
2367
2368 static int cmd_itemorder(const char *arg)
2369 {
2370     char type[12];
2371     int itemno;
2372    
2373     if (only_z3950())
2374         return 1;
2375     if (sscanf (arg, "%10s %d", type, &itemno) != 2)
2376         return 0;
2377
2378     printf("Item order request\n");
2379     fflush(stdout);
2380     send_itemorder(type, itemno);
2381     return 2;
2382 }
2383
2384 static void show_opt(const char *arg, void *clientData)
2385 {
2386     printf ("%s ", arg);
2387 }
2388
2389 static int cmd_zversion(const char *arg)
2390 {
2391     if (*arg && arg)
2392         z3950_version = atoi(arg);
2393     else
2394         printf ("version is %d\n", z3950_version);
2395     return 0;
2396 }
2397
2398 static int cmd_options(const char *arg)
2399 {
2400     if (*arg)
2401     {
2402         int r;
2403         int pos;
2404         r = yaz_init_opt_encode(&z3950_options, arg, &pos);
2405         if (r == -1)
2406             printf("Unknown option(s) near %s\n", arg+pos);
2407     }
2408     else
2409     {
2410         yaz_init_opt_decode(&z3950_options, show_opt, 0);
2411         printf ("\n");
2412     }
2413     return 0;
2414 }
2415
2416 static int cmd_explain(const char *arg)
2417 {
2418     if (protocol != PROTO_HTTP)
2419         return 0;
2420 #if HAVE_XML2
2421     if (!conn)
2422         cmd_open(0);
2423     if (conn)
2424     {
2425         Z_SRW_PDU *sr = 0;
2426         
2427         setno = 1;
2428         
2429         /* save this for later .. when fetching individual records */
2430         sr = yaz_srw_get(out, Z_SRW_explain_request);
2431         if (recordsyntax == VAL_TEXT_XML)
2432             sr->u.explain_request->recordPacking = "xml";
2433         send_srw(sr);
2434         return 2;
2435     }
2436 #endif
2437     return 0;
2438 }
2439
2440 static int cmd_init(const char *arg)
2441 {
2442     if (*arg)
2443     {
2444         strncpy (cur_host, arg, sizeof(cur_host)-1);
2445         cur_host[sizeof(cur_host)-1] = 0;
2446     }
2447     if (only_z3950())
2448         return 1;
2449     send_initRequest(cur_host);
2450     return 2;
2451 }
2452
2453 static int cmd_find(const char *arg)
2454 {
2455     if (!*arg)
2456     {
2457         printf("Find what?\n");
2458         return 0;
2459     }
2460     if (protocol == PROTO_HTTP)
2461     {
2462 #if HAVE_XML2
2463         if (!conn)
2464             cmd_open(0);
2465         if (!conn)
2466             return 0;
2467         if (!send_SRW_searchRequest(arg))
2468             return 0;
2469 #else
2470         return 0;
2471 #endif
2472     }
2473     else
2474     {
2475         if (!conn)
2476         {
2477             try_reconnect(); 
2478             
2479             if (!conn) {                                        
2480                 printf("Not connected yet\n");
2481                 return 0;
2482             }
2483         }
2484         if (!send_searchRequest(arg))
2485             return 0;
2486     }
2487     return 2;
2488 }
2489
2490 static int cmd_delete(const char *arg)
2491 {
2492     if (only_z3950())
2493         return 0;
2494     if (!send_deleteResultSetRequest(arg))
2495         return 0;
2496     return 2;
2497 }
2498
2499 static int cmd_ssub(const char *arg)
2500 {
2501     if (!(smallSetUpperBound = atoi(arg)))
2502         return 0;
2503     return 1;
2504 }
2505
2506 static int cmd_lslb(const char *arg)
2507 {
2508     if (!(largeSetLowerBound = atoi(arg)))
2509         return 0;
2510     return 1;
2511 }
2512
2513 static int cmd_mspn(const char *arg)
2514 {
2515     if (!(mediumSetPresentNumber = atoi(arg)))
2516         return 0;
2517     return 1;
2518 }
2519
2520 static int cmd_status(const char *arg)
2521 {
2522     printf("smallSetUpperBound: %d\n", smallSetUpperBound);
2523     printf("largeSetLowerBound: %d\n", largeSetLowerBound);
2524     printf("mediumSetPresentNumber: %d\n", mediumSetPresentNumber);
2525     return 1;
2526 }
2527
2528 static int cmd_setnames(const char *arg)
2529 {
2530     if (*arg == '1')         /* enable ? */
2531         setnumber = 0;
2532     else if (*arg == '0')    /* disable ? */
2533         setnumber = -1;
2534     else if (setnumber < 0)  /* no args, toggle .. */
2535         setnumber = 0;
2536     else
2537         setnumber = -1;
2538    
2539     if (setnumber >= 0)
2540         printf("Set numbering enabled.\n");
2541     else
2542         printf("Set numbering disabled.\n");
2543     return 1;
2544 }
2545
2546 /* PRESENT SERVICE ----------------------------- */
2547
2548 static void parse_show_args(const char *arg_c, char *setstring,
2549                             int *start, int *number)
2550 {
2551     char arg[40];
2552     char *p;
2553
2554     strncpy(arg, arg_c, sizeof(arg)-1);
2555     arg[sizeof(arg)-1] = '\0';
2556
2557     if ((p = strchr(arg, '+')))
2558     {
2559         *number = atoi(p + 1);
2560         *p = '\0';
2561     }
2562     if (*arg)
2563     {
2564         if (!strcmp(arg, "all"))
2565         {
2566             *number = last_hit_count;
2567             *start = 1;
2568         }
2569         else
2570             *start = atoi(arg);
2571     }
2572     if (p && (p=strchr(p+1, '+')))
2573         strcpy (setstring, p+1);
2574     else if (setnumber >= 0)
2575         sprintf(setstring, "%d", setnumber);
2576     else
2577         *setstring = '\0';
2578 }
2579
2580 static int send_presentRequest(const char *arg)
2581 {
2582     Z_APDU *apdu = zget_APDU(out, Z_APDU_presentRequest);
2583     Z_PresentRequest *req = apdu->u.presentRequest;
2584     Z_RecordComposition compo;
2585     int nos = 1;
2586     char setstring[100];
2587
2588     req->referenceId = set_refid (out);
2589
2590     parse_show_args(arg, setstring, &setno, &nos);
2591     if (*setstring)
2592         req->resultSetId = setstring;
2593
2594     req->resultSetStartPoint = &setno;
2595     req->numberOfRecordsRequested = &nos;
2596
2597     req->preferredRecordSyntax =
2598         yaz_oidval_to_z3950oid(out, CLASS_RECSYN, recordsyntax);
2599
2600     if (record_schema)
2601     {
2602         req->recordComposition = &compo;
2603         compo.which = Z_RecordComp_complex;
2604         compo.u.complex = (Z_CompSpec *)
2605             odr_malloc(out, sizeof(*compo.u.complex));
2606         compo.u.complex->selectAlternativeSyntax = (bool_t *) 
2607             odr_malloc(out, sizeof(bool_t));
2608         *compo.u.complex->selectAlternativeSyntax = 0;
2609
2610         compo.u.complex->generic = (Z_Specification *)
2611             odr_malloc(out, sizeof(*compo.u.complex->generic));
2612         compo.u.complex->generic->which = Z_Schema_oid;
2613
2614         compo.u.complex->generic->schema.oid =
2615             yaz_str_to_z3950oid(out, CLASS_SCHEMA, record_schema);
2616
2617         if (!compo.u.complex->generic->schema.oid)
2618         {
2619             /* OID wasn't a schema! Try record syntax instead. */
2620             compo.u.complex->generic->schema.oid = (Odr_oid *)
2621                 yaz_str_to_z3950oid(out, CLASS_RECSYN, record_schema);
2622         }
2623         if (!elementSetNames)
2624             compo.u.complex->generic->elementSpec = 0;
2625         else
2626         {
2627             compo.u.complex->generic->elementSpec = (Z_ElementSpec *)
2628                 odr_malloc(out, sizeof(Z_ElementSpec));
2629             compo.u.complex->generic->elementSpec->which =
2630                 Z_ElementSpec_elementSetName;
2631             compo.u.complex->generic->elementSpec->u.elementSetName =
2632                 elementSetNames->u.generic;
2633         }
2634         compo.u.complex->num_dbSpecific = 0;
2635         compo.u.complex->dbSpecific = 0;
2636         compo.u.complex->num_recordSyntax = 0;
2637         compo.u.complex->recordSyntax = 0;
2638     }
2639     else if (elementSetNames)
2640     {
2641         req->recordComposition = &compo;
2642         compo.which = Z_RecordComp_simple;
2643         compo.u.simple = elementSetNames;
2644     }
2645     send_apdu(apdu);
2646     printf("Sent presentRequest (%d+%d).\n", setno, nos);
2647     return 2;
2648 }
2649
2650 #if HAVE_XML2
2651 static int send_SRW_presentRequest(const char *arg)
2652 {
2653     char setstring[100];
2654     int nos = 1;
2655     Z_SRW_PDU *sr = srw_sr;
2656
2657     if (!sr)
2658         return 0;
2659     parse_show_args(arg, setstring, &setno, &nos);
2660     sr->u.request->startRecord = odr_intdup(out, setno);
2661     sr->u.request->maximumRecords = odr_intdup(out, nos);
2662     if (record_schema)
2663         sr->u.request->recordSchema = record_schema;
2664     if (recordsyntax == VAL_TEXT_XML)
2665         sr->u.request->recordPacking = "xml";
2666     return send_srw(sr);
2667 }
2668 #endif
2669
2670 static void close_session (void)
2671 {
2672     if (conn)
2673         cs_close (conn);
2674     conn = 0;
2675     sent_close = 0;
2676     odr_reset(out);
2677     odr_reset(in);
2678     odr_reset(print);
2679     last_hit_count = 0;
2680 }
2681
2682 void process_close(Z_Close *req)
2683 {
2684     Z_APDU *apdu = zget_APDU(out, Z_APDU_close);
2685     Z_Close *res = apdu->u.close;
2686
2687     static char *reasons[] =
2688     {
2689         "finished",
2690         "shutdown",
2691         "system problem",
2692         "cost limit reached",
2693         "resources",
2694         "security violation",
2695         "protocolError",
2696         "lack of activity",
2697         "peer abort",
2698         "unspecified"
2699     };
2700
2701     printf("Reason: %s, message: %s\n", reasons[*req->closeReason],
2702         req->diagnosticInformation ? req->diagnosticInformation : "NULL");
2703     if (sent_close)
2704         close_session ();
2705     else
2706     {
2707         *res->closeReason = Z_Close_finished;
2708         send_apdu(apdu);
2709         printf("Sent response.\n");
2710         sent_close = 1;
2711     }
2712 }
2713
2714 static int cmd_show(const char *arg)
2715 {
2716     if (protocol == PROTO_HTTP)
2717     {
2718 #if HAVE_XML2
2719         if (!conn)
2720             cmd_open(0);
2721         if (!conn)
2722             return 0;
2723         if (!send_SRW_presentRequest(arg))
2724             return 0;
2725 #else
2726         return 0;
2727 #endif
2728     }
2729     else
2730     {
2731         if (!conn)
2732         {
2733             printf("Not connected yet\n");
2734             return 0;
2735         }
2736         if (!send_presentRequest(arg))
2737             return 0;
2738     }
2739     return 2;
2740 }
2741
2742 int cmd_quit(const char *arg)
2743 {
2744     printf("See you later, alligator.\n");
2745     xmalloc_trav ("");
2746     exit(0);
2747     return 0;
2748 }
2749
2750 int cmd_cancel(const char *arg)
2751 {
2752     Z_APDU *apdu = zget_APDU(out, Z_APDU_triggerResourceControlRequest);
2753     Z_TriggerResourceControlRequest *req =
2754         apdu->u.triggerResourceControlRequest;
2755     bool_t rfalse = 0;
2756     
2757     if (only_z3950())
2758         return 0;
2759     if (session_initResponse &&
2760         !ODR_MASK_GET(session_initResponse->options,
2761                       Z_Options_triggerResourceCtrl))
2762     {
2763         printf("Target doesn't support cancel (trigger resource ctrl)\n");
2764         return 0;
2765     }
2766     *req->requestedAction = Z_TriggerResourceControlRequest_cancel;
2767     req->resultSetWanted = &rfalse;
2768     req->referenceId = set_refid (out);
2769
2770     send_apdu(apdu);
2771     printf("Sent cancel request\n");
2772     return 2;
2773 }
2774
2775
2776 int cmd_cancel_find(const char *arg) {
2777     int fres;
2778     fres=cmd_find(arg);
2779     if( fres > 0 ) {
2780         return cmd_cancel("");
2781     };
2782     return fres;
2783 }
2784
2785 int send_scanrequest(const char *query, int pp, int num, const char *term)
2786 {
2787     Z_APDU *apdu = zget_APDU(out, Z_APDU_scanRequest);
2788     Z_ScanRequest *req = apdu->u.scanRequest;
2789     
2790     if (only_z3950())
2791         return 0;
2792     if (queryType == QueryType_CCL2RPN)
2793     {
2794         int error, pos;
2795         struct ccl_rpn_node *rpn;
2796
2797         rpn = ccl_find_str (bibset,  query, &error, &pos);
2798         if (error)
2799         {
2800             printf("CCL ERROR: %s\n", ccl_err_msg(error));
2801             return -1;
2802         }
2803         req->attributeSet =
2804             yaz_oidval_to_z3950oid(out, CLASS_ATTSET, VAL_BIB1);
2805         if (!(req->termListAndStartPoint = ccl_scan_query (out, rpn)))
2806         {
2807             printf("Couldn't convert CCL to Scan term\n");
2808             return -1;
2809         }
2810         ccl_rpn_delete (rpn);
2811     }
2812     else
2813     {
2814         YAZ_PQF_Parser pqf_parser = yaz_pqf_create ();
2815
2816         if (!(req->termListAndStartPoint =
2817               yaz_pqf_scan(pqf_parser, out, &req->attributeSet, query)))
2818         {
2819             const char *pqf_msg;
2820             size_t off;
2821             int code = yaz_pqf_error (pqf_parser, &pqf_msg, &off);
2822             printf("%*s^\n", off+7, "");
2823             printf("Prefix query error: %s (code %d)\n", pqf_msg, code);
2824             yaz_pqf_destroy (pqf_parser);
2825             return -1;
2826         }
2827         yaz_pqf_destroy (pqf_parser);
2828     }
2829     if (term && *term)
2830     {
2831         if (req->termListAndStartPoint->term &&
2832             req->termListAndStartPoint->term->which == Z_Term_general &&
2833             req->termListAndStartPoint->term->u.general)
2834         {
2835             req->termListAndStartPoint->term->u.general->buf =
2836                 (unsigned char *) odr_strdup(out, term);
2837             req->termListAndStartPoint->term->u.general->len =
2838                 req->termListAndStartPoint->term->u.general->size =
2839                 strlen(term);
2840         }
2841     }
2842     req->referenceId = set_refid (out);
2843     req->num_databaseNames = num_databaseNames;
2844     req->databaseNames = databaseNames;
2845     req->numberOfTermsRequested = &num;
2846     req->preferredPositionInResponse = &pp;
2847     req->stepSize = odr_intdup(out, scan_stepSize);
2848     send_apdu(apdu);
2849     return 2;
2850 }
2851
2852 int send_sortrequest(const char *arg, int newset)
2853 {
2854     Z_APDU *apdu = zget_APDU(out, Z_APDU_sortRequest);
2855     Z_SortRequest *req = apdu->u.sortRequest;
2856     Z_SortKeySpecList *sksl = (Z_SortKeySpecList *)
2857         odr_malloc (out, sizeof(*sksl));
2858     char setstring[32];
2859
2860     if (only_z3950())
2861         return 0;
2862     if (setnumber >= 0)
2863         sprintf (setstring, "%d", setnumber);
2864     else
2865         sprintf (setstring, "default");
2866
2867     req->referenceId = set_refid (out);
2868
2869     req->num_inputResultSetNames = 1;
2870     req->inputResultSetNames = (Z_InternationalString **)
2871         odr_malloc (out, sizeof(*req->inputResultSetNames));
2872     req->inputResultSetNames[0] = odr_strdup (out, setstring);
2873
2874     if (newset && setnumber >= 0)
2875         sprintf (setstring, "%d", ++setnumber);
2876
2877     req->sortedResultSetName = odr_strdup (out, setstring);
2878
2879     req->sortSequence = yaz_sort_spec (out, arg);
2880     if (!req->sortSequence)
2881     {
2882         printf ("Missing sort specifications\n");
2883         return -1;
2884     }
2885     send_apdu(apdu);
2886     return 2;
2887 }
2888
2889 void display_term(Z_TermInfo *t)
2890 {
2891     if (t->displayTerm)
2892         printf("%s", t->displayTerm);
2893     else if (t->term->which == Z_Term_general)
2894     {
2895         printf("%.*s", t->term->u.general->len, t->term->u.general->buf);
2896         sprintf(last_scan_line, "%.*s", t->term->u.general->len,
2897             t->term->u.general->buf);
2898     }
2899     else
2900         printf("Term (not general)");
2901     if (t->globalOccurrences)
2902         printf (" (%d)\n", *t->globalOccurrences);
2903     else
2904         printf ("\n");
2905 }
2906
2907 void process_scanResponse(Z_ScanResponse *res)
2908 {
2909     int i;
2910     Z_Entry **entries = NULL;
2911     int num_entries = 0;
2912    
2913     printf("Received ScanResponse\n"); 
2914     print_refid (res->referenceId);
2915     printf("%d entries", *res->numberOfEntriesReturned);
2916     if (res->positionOfTerm)
2917         printf (", position=%d", *res->positionOfTerm); 
2918     printf ("\n");
2919     if (*res->scanStatus != Z_Scan_success)
2920         printf("Scan returned code %d\n", *res->scanStatus);
2921     if (!res->entries)
2922         return;
2923     if ((entries = res->entries->entries))
2924         num_entries = res->entries->num_entries;
2925     for (i = 0; i < num_entries; i++)
2926     {
2927         int pos_term = res->positionOfTerm ? *res->positionOfTerm : -1;
2928         if (entries[i]->which == Z_Entry_termInfo)
2929         {
2930             printf("%c ", i + 1 == pos_term ? '*' : ' ');
2931             display_term(entries[i]->u.termInfo);
2932         }
2933         else
2934             display_diagrecs(&entries[i]->u.surrogateDiagnostic, 1);
2935     }
2936     if (res->entries->nonsurrogateDiagnostics)
2937         display_diagrecs (res->entries->nonsurrogateDiagnostics,
2938                           res->entries->num_nonsurrogateDiagnostics);
2939 }
2940
2941 void process_sortResponse(Z_SortResponse *res)
2942 {
2943     printf("Received SortResponse: status=");
2944     switch (*res->sortStatus)
2945     {
2946     case Z_SortResponse_success:
2947         printf ("success"); break;
2948     case Z_SortResponse_partial_1:
2949         printf ("partial"); break;
2950     case Z_SortResponse_failure:
2951         printf ("failure"); break;
2952     default:
2953         printf ("unknown (%d)", *res->sortStatus);
2954     }
2955     printf ("\n");
2956     print_refid (res->referenceId);
2957     if (res->diagnostics)
2958         display_diagrecs(res->diagnostics,
2959                          res->num_diagnostics);
2960 }
2961
2962 void process_deleteResultSetResponse (Z_DeleteResultSetResponse *res)
2963 {
2964     printf("Got deleteResultSetResponse status=%d\n",
2965            *res->deleteOperationStatus);
2966     if (res->deleteListStatuses)
2967     {
2968         int i;
2969         for (i = 0; i < res->deleteListStatuses->num; i++)
2970         {
2971             printf ("%s status=%d\n", res->deleteListStatuses->elements[i]->id,
2972                     *res->deleteListStatuses->elements[i]->status);
2973         }
2974     }
2975 }
2976
2977 int cmd_sort_generic(const char *arg, int newset)
2978 {
2979     if (only_z3950())
2980         return 0;
2981     if (session_initResponse && 
2982         !ODR_MASK_GET(session_initResponse->options, Z_Options_sort))
2983     {
2984         printf("Target doesn't support sort\n");
2985         return 0;
2986     }
2987     if (*arg)
2988     {
2989         if (send_sortrequest(arg, newset) < 0)
2990             return 0;
2991         return 2;
2992     }
2993     return 0;
2994 }
2995
2996 int cmd_sort(const char *arg)
2997 {
2998     return cmd_sort_generic (arg, 0);
2999 }
3000
3001 int cmd_sort_newset (const char *arg)
3002 {
3003     return cmd_sort_generic (arg, 1);
3004 }
3005
3006 int cmd_scanstep(const char *arg)
3007 {
3008     scan_stepSize = atoi(arg);
3009     return 0;
3010 }
3011
3012 int cmd_scanpos(const char *arg)
3013 {
3014     int r = sscanf(arg, "%d", &scan_position);
3015     if (r == 0)
3016         scan_position = 1;
3017     return 0;
3018 }
3019
3020 int cmd_scansize(const char *arg)
3021 {
3022     int r = sscanf(arg, "%d", &scan_size);
3023     if (r == 0)
3024         scan_size = 20;
3025     return 0;
3026 }
3027
3028 int cmd_scan(const char *arg)
3029 {
3030     if (protocol == PROTO_HTTP)
3031     {
3032 #if HAVE_XML2
3033         if (!conn)
3034             cmd_open(0);
3035         if (!conn)
3036             return 0;
3037         if (*arg)
3038         {
3039             if (send_SRW_scanRequest(arg, scan_position, scan_size) < 0)
3040                 return 0;
3041         }
3042         else
3043         {
3044             if (send_SRW_scanRequest(last_scan_line, 1, scan_size) < 0)
3045                 return 0;
3046         }
3047         return 2;
3048 #else
3049         return 0;
3050 #endif
3051     }
3052     else
3053     {
3054         if (!conn)
3055         {
3056             try_reconnect();
3057             
3058             if (!conn) {                                                                
3059                 printf("Session not initialized yet\n");
3060                 return 0;
3061             }
3062         }
3063         if (session_initResponse && 
3064             !ODR_MASK_GET(session_initResponse->options, Z_Options_scan))
3065         {
3066             printf("Target doesn't support scan\n");
3067             return 0;
3068         }
3069         if (*arg)
3070         {
3071             strcpy (last_scan_query, arg);
3072             if (send_scanrequest(arg, scan_position, scan_size, 0) < 0)
3073                 return 0;
3074         }
3075         else
3076         {
3077             if (send_scanrequest(last_scan_query, 1, scan_size, last_scan_line) < 0)
3078                 return 0;
3079         }
3080         return 2;
3081     }
3082 }
3083
3084 int cmd_schema(const char *arg)
3085 {
3086     xfree(record_schema);
3087     record_schema = 0;
3088     if (arg && *arg)
3089         record_schema = xstrdup(arg);
3090     return 1;
3091 }
3092
3093 int cmd_format(const char *arg)
3094 {
3095     oid_value nsyntax;
3096     if (!arg || !*arg)
3097     {
3098         printf("Usage: format <recordsyntax>\n");
3099         return 0;
3100     }
3101     nsyntax = oid_getvalbyname (arg);
3102     if (strcmp(arg, "none") && nsyntax == VAL_NONE)
3103     {
3104         printf ("unknown record syntax\n");
3105         return 0;
3106     }
3107     recordsyntax = nsyntax;
3108     return 1;
3109 }
3110
3111 int cmd_elements(const char *arg)
3112 {
3113     static Z_ElementSetNames esn;
3114     static char what[100];
3115
3116     if (!arg || !*arg)
3117     {
3118         elementSetNames = 0;
3119         return 1;
3120     }
3121     strcpy(what, arg);
3122     esn.which = Z_ElementSetNames_generic;
3123     esn.u.generic = what;
3124     elementSetNames = &esn;
3125     return 1;
3126 }
3127
3128 int cmd_attributeset(const char *arg)
3129 {
3130     char what[100];
3131
3132     if (!arg || !*arg)
3133     {
3134         printf("Usage: attributeset <setname>\n");
3135         return 0;
3136     }
3137     sscanf(arg, "%s", what);
3138     if (p_query_attset (what))
3139     {
3140         printf("Unknown attribute set name\n");
3141         return 0;
3142     }
3143     return 1;
3144 }
3145
3146 int cmd_querytype (const char *arg)
3147 {
3148     if (!strcmp (arg, "ccl"))
3149         queryType = QueryType_CCL;
3150     else if (!strcmp (arg, "prefix") || !strcmp(arg, "rpn"))
3151         queryType = QueryType_Prefix;
3152     else if (!strcmp (arg, "ccl2rpn") || !strcmp (arg, "cclrpn"))
3153         queryType = QueryType_CCL2RPN;
3154     else if (!strcmp(arg, "cql"))
3155         queryType = QueryType_CQL;        
3156     else if (!strcmp (arg, "cql2rpn") || !strcmp (arg, "cqlrpn"))
3157         queryType = QueryType_CQL2RPN;
3158     else
3159     {
3160         printf ("Querytype must be one of:\n");
3161         printf (" prefix         - Prefix query\n");
3162         printf (" ccl            - CCL query\n");
3163         printf (" ccl2rpn        - CCL query converted to RPN\n");
3164         printf (" cql            - CQL\n");
3165         printf (" cql2rpn        - CQL query converted to RPN\n");
3166         return 0;
3167     }
3168     return 1;
3169 }
3170
3171 int cmd_refid (const char *arg)
3172 {
3173     xfree (refid);
3174     refid = NULL;
3175     if (*arg)
3176         refid = xstrdup (arg);
3177     return 1;
3178 }
3179
3180 int cmd_close(const char *arg)
3181 {
3182     Z_APDU *apdu;
3183     Z_Close *req;
3184     if (only_z3950())
3185         return 0;
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},
4300     {"list_all",cmd_list_all,"",NULL,0,NULL},
4301     {"clear_otherinfo",cmd_clear_otherinfo,"",NULL,0,NULL},
4302     {"wait_response",cmd_wait_response,"<number>",NULL,0,NULL},
4303     /* Server Admin Functions */
4304     {"adm-reindex", cmd_adm_reindex, "<database-name>",NULL,0,NULL},
4305     {"adm-truncate", cmd_adm_truncate, "('database'|'index')<object-name>",NULL,0,NULL},
4306     {"adm-create", cmd_adm_create, "",NULL,0,NULL},
4307     {"adm-drop", cmd_adm_drop, "('database'|'index')<object-name>",NULL,0,NULL},
4308     {"adm-import", cmd_adm_import, "<record-type> <dir> <pattern>",NULL,0,NULL},
4309     {"adm-refresh", cmd_adm_refresh, "",NULL,0,NULL},
4310     {"adm-commit", cmd_adm_commit, "",NULL,0,NULL},
4311     {"adm-shutdown", cmd_adm_shutdown, "",NULL,0,NULL},
4312     {"adm-startup", cmd_adm_startup, "",NULL,0,NULL},
4313     {"explain", cmd_explain, "", NULL, 0, NULL},
4314     {"options", cmd_options, "", NULL, 0, NULL},
4315     {"zversion", cmd_zversion, "", NULL, 0, NULL},
4316     {"help", cmd_help, "", NULL,0,NULL},
4317     {"init", cmd_init, "", NULL,0,NULL},
4318     {0,0,0,0,0,0}
4319 };
4320
4321 static int cmd_help (const char *line)
4322 {
4323     int i;
4324     char topic[21];
4325     
4326     *topic = 0;
4327     sscanf (line, "%20s", topic);
4328
4329     if (*topic == 0)
4330         printf("Commands:\n");
4331     for (i = 0; cmd_array[i].cmd; i++)
4332         if (*topic == 0 || strcmp (topic, cmd_array[i].cmd) == 0)
4333             printf("   %s %s\n", cmd_array[i].cmd, cmd_array[i].ad);
4334     if (!strcmp(topic, "find"))
4335     {
4336         printf("RPN:\n");
4337         printf(" \"term\"                        Simple Term\n");
4338         printf(" @attr [attset] type=value op  Attribute\n");
4339         printf(" @and opl opr                  And\n");
4340         printf(" @or opl opr                   Or\n");
4341         printf(" @not opl opr                  And-Not\n");
4342         printf(" @set set                      Result set\n");
4343         printf(" @prox exl dist ord rel uc ut  Proximity. Use help prox\n");
4344         printf("\n");
4345         printf("Bib-1 attribute types\n");
4346         printf("1=Use:         ");
4347         printf("4=Title 7=ISBN 8=ISSN 30=Date 62=Abstract 1003=Author 1016=Any\n");
4348         printf("2=Relation:    ");
4349         printf("1<   2<=  3=  4>=  5>  6!=  102=Relevance\n");
4350         printf("3=Position:    ");
4351         printf("1=First in Field  2=First in subfield  3=Any position\n");
4352         printf("4=Structure:   ");
4353         printf("1=Phrase  2=Word  3=Key  4=Year  5=Date  6=WordList\n");
4354         printf("5=Truncation:  ");
4355         printf("1=Right  2=Left  3=L&R  100=No  101=#  102=Re-1  103=Re-2\n");
4356         printf("6=Completeness:");
4357         printf("1=Incomplete subfield  2=Complete subfield  3=Complete field\n");
4358     }
4359     if (!strcmp(topic, "prox"))
4360     {
4361         printf("Proximity:\n");
4362         printf(" @prox exl dist ord rel uc ut\n");
4363         printf(" exl:  exclude flag . 0=include, 1=exclude.\n");
4364         printf(" dist: distance integer.\n");
4365         printf(" ord:  order flag. 0=unordered, 1=ordered.\n");
4366         printf(" rel:  relation integer. 1<  2<=  3= 4>=  5>  6!= .\n");
4367         printf(" uc:   unit class. k=known, p=private.\n");
4368         printf(" ut:   unit type. 1=character, 2=word, 3=sentence,\n");
4369         printf("        4=paragraph, 5=section, 6=chapter, 7=document,\n");
4370         printf("        8=element, 9=subelement, 10=elementType, 11=byte.\n");
4371         printf("\nExamples:\n");
4372         printf(" Search for a and b in-order at most 3 words apart:\n");
4373         printf("  @prox 0 3 1 2 k 2 a b\n");
4374         printf(" Search for any order of a and b next to each other:\n");
4375         printf("  @prox 0 1 0 3 k 2 a b\n");
4376     }
4377     return 1;
4378 }
4379
4380 int cmd_register_tab(const char* arg) {
4381         
4382     char command[101], tabargument[101];
4383     int i;
4384     int num_of_tabs;
4385     char** tabslist;
4386     
4387     if (sscanf (arg, "%100s %100s", command, tabargument) < 1) {
4388         return 0;
4389     }
4390     
4391     /* locate the amdn in the list */
4392     for (i = 0; cmd_array[i].cmd; i++) {
4393         if (!strncmp(cmd_array[i].cmd, command, strlen(command))) {
4394             break;
4395         }
4396     }
4397     
4398     if(!cmd_array[i].cmd) { 
4399         fprintf(stderr,"Unknown command %s\n",command);
4400         return 1;
4401     }
4402     
4403         
4404     if(!cmd_array[i].local_tabcompletes)
4405         cmd_array[i].local_tabcompletes = (char **) calloc(1,sizeof(char**));
4406     
4407     num_of_tabs=0;              
4408     
4409     tabslist = cmd_array[i].local_tabcompletes;
4410     for(;tabslist && *tabslist;tabslist++) {
4411         num_of_tabs++;
4412     }
4413     
4414     cmd_array[i].local_tabcompletes =  (char **)
4415         realloc(cmd_array[i].local_tabcompletes,(num_of_tabs+2)*sizeof(char**));
4416     tabslist=cmd_array[i].local_tabcompletes;
4417     tabslist[num_of_tabs]=strdup(tabargument);
4418     tabslist[num_of_tabs+1]=NULL;
4419     return 1;
4420 }
4421
4422
4423 void process_cmd_line(char* line)
4424 {  
4425     int i, res;
4426     char word[32], arg[10240];
4427     
4428 #if HAVE_GETTIMEOFDAY
4429     gettimeofday (&tv_start, 0);
4430 #endif
4431     
4432     if ((res = sscanf(line, "%31s %10239[^;]", word, arg)) <= 0)
4433     {
4434         strcpy(word, last_cmd);
4435         *arg = '\0';
4436     }
4437     else if (res == 1)
4438         *arg = 0;
4439     strcpy(last_cmd, word);
4440     
4441     /* removed tailing spaces from the arg command */
4442     { 
4443         char* p = arg;
4444         char* lastnonspace=NULL;
4445         
4446         for(;*p; ++p) {
4447             if(!isspace(*(unsigned char *) p)) {
4448                 lastnonspace = p;
4449             }
4450         }
4451         if(lastnonspace) 
4452             *(++lastnonspace) = 0;
4453     }
4454     
4455     for (i = 0; cmd_array[i].cmd; i++)
4456         if (!strncmp(cmd_array[i].cmd, word, strlen(word)))
4457         {
4458             res = (*cmd_array[i].fun)(arg);
4459             break;
4460         }
4461     
4462     if (!cmd_array[i].cmd) /* dump our help-screen */
4463     {
4464         printf("Unknown command: %s.\n", word);
4465         printf("Type 'help' for list of commands\n");
4466         res = 1;
4467     }
4468     
4469     if(apdu_file) fflush(apdu_file);
4470     
4471     if (res >= 2 && auto_wait)
4472         wait_and_handle_response(0);
4473     
4474     if(apdu_file)
4475         fflush(apdu_file);
4476     if(marc_file)
4477         fflush(marc_file);
4478 }
4479
4480
4481 char *command_generator(const char *text, int state) 
4482 {
4483     static int idx; 
4484     if (state==0) {
4485         idx = 0;
4486     }
4487     for( ; cmd_array[idx].cmd; ++idx) {
4488         if (!strncmp(cmd_array[idx].cmd,text,strlen(text))) {
4489             ++idx;  /* skip this entry on the next run */
4490             return strdup(cmd_array[idx-1].cmd);
4491         }
4492     }
4493     return NULL;
4494 }
4495
4496
4497 /* 
4498    This function only known how to complete on the first word
4499 */
4500 char ** readline_completer(char *text, int start, int end) {
4501 #if HAVE_READLINE_READLINE_H
4502
4503         completerFunctionType completerToUse;
4504         
4505     if(start == 0) {
4506 #if HAVE_READLINE_RL_COMPLETION_MATCHES
4507         char** res=rl_completion_matches(text,
4508                                       command_generator); 
4509 #else
4510         char** res=completion_matches(text,
4511                                       (CPFunction*)command_generator); 
4512 #endif
4513         rl_attempted_completion_over = 1;
4514         return res;
4515     } else {
4516         char arg[10240],word[32];
4517         int i=0 ,res;
4518         if ((res = sscanf(rl_line_buffer, "%31s %10239[^;]", word, arg)) <= 0) {     
4519             rl_attempted_completion_over = 1;
4520             return NULL;
4521         }
4522         
4523         for (i = 0; cmd_array[i].cmd; i++) {
4524             if (!strncmp(cmd_array[i].cmd, word, strlen(word))) {
4525                 break;
4526             }
4527         }
4528         
4529         if(!cmd_array[i].cmd) return NULL;
4530         
4531         curret_global_list = cmd_array[i].local_tabcompletes;
4532         
4533         completerToUse = cmd_array[i].rl_completerfunction;
4534         if(completerToUse==NULL)  /* if no pr. command completer is defined use the default completer */
4535             completerToUse = default_completer;
4536         
4537         if(completerToUse) {
4538 #ifdef HAVE_READLINE_RL_COMPLETION_MATCHES
4539             char** res=
4540                 rl_completion_matches(text,
4541                                       completerToUse);
4542 #else
4543             char** res=
4544                 completion_matches(text,
4545                                    (CPFunction*)completerToUse);
4546 #endif
4547             if(!cmd_array[i].complete_filenames) 
4548                 rl_attempted_completion_over = 1;
4549             return res;
4550         } else {
4551             if(!cmd_array[i].complete_filenames) 
4552                 rl_attempted_completion_over = 1;
4553             return 0;
4554         }
4555     }
4556 #else 
4557     return 0;
4558 #endif 
4559 }
4560
4561
4562 static void client(void)
4563 {
4564     char line[10240];
4565
4566     line[10239] = '\0';
4567
4568 #if HAVE_GETTIMEOFDAY
4569     gettimeofday (&tv_start, 0);
4570 #endif
4571
4572     while (1)
4573     {
4574         char *line_in = NULL;
4575 #if HAVE_READLINE_READLINE_H
4576         if (isatty(0))
4577         {
4578             line_in=readline(C_PROMPT);
4579             if (!line_in)
4580                 break;
4581 #if HAVE_READLINE_HISTORY_H
4582             if (*line_in)
4583                 add_history(line_in);
4584 #endif
4585             strncpy(line, line_in, 10239);
4586             free (line_in);
4587         }
4588 #endif 
4589         if (!line_in)
4590         {
4591             char *end_p;
4592             printf (C_PROMPT);
4593             fflush(stdout);
4594             if (!fgets(line, 10239, stdin))
4595                 break;
4596             if ((end_p = strchr (line, '\n')))
4597                 *end_p = '\0';
4598         }
4599         process_cmd_line(line);
4600     }
4601 }
4602
4603 static void show_version(void)
4604 {
4605     char vstr[20];
4606
4607     yaz_version(vstr, 0);
4608     printf ("YAZ version: %s\n", YAZ_VERSION);
4609     if (strcmp(vstr, YAZ_VERSION))
4610         printf ("YAZ DLL/SO: %s\n", vstr);
4611     exit(0);
4612 }
4613
4614 int main(int argc, char **argv)
4615 {
4616     char *prog = *argv;
4617     char *open_command = 0;
4618     char *auth_command = 0;
4619     char *arg;
4620     int ret;
4621     
4622 #if HAVE_LOCALE_H
4623     if (!setlocale(LC_CTYPE, ""))
4624         fprintf (stderr, "setlocale failed\n");
4625 #endif
4626 #if HAVE_LANGINFO_H
4627 #ifdef CODESET
4628     codeset = nl_langinfo(CODESET);
4629 #endif
4630 #endif
4631     if (codeset)
4632         outputCharset = xstrdup(codeset);
4633     
4634     ODR_MASK_SET(&z3950_options, Z_Options_search);
4635     ODR_MASK_SET(&z3950_options, Z_Options_present);
4636     ODR_MASK_SET(&z3950_options, Z_Options_namedResultSets);
4637     ODR_MASK_SET(&z3950_options, Z_Options_triggerResourceCtrl);
4638     ODR_MASK_SET(&z3950_options, Z_Options_scan);
4639     ODR_MASK_SET(&z3950_options, Z_Options_sort);
4640     ODR_MASK_SET(&z3950_options, Z_Options_extendedServices);
4641     ODR_MASK_SET(&z3950_options, Z_Options_delSet);
4642
4643     while ((ret = options("k:c:q:a:b:m:v:p:u:t:Vxd:", argv, argc, &arg)) != -2)
4644     {
4645         switch (ret)
4646         {
4647         case 0:
4648             if (!open_command)
4649             {
4650                 open_command = (char *) xmalloc (strlen(arg)+6);
4651                 strcpy (open_command, "open ");
4652                 strcat (open_command, arg);
4653             }
4654             else
4655             {
4656                 fprintf(stderr, "%s: Specify at most one server address\n",
4657                         prog);
4658                 exit(1);
4659             }
4660             break;
4661         case 'd':
4662             dump_file_prefix = arg;
4663             break;
4664         case 'k':
4665             kilobytes = atoi(arg);
4666             break;
4667         case 'm':
4668             if (!(marc_file = fopen (arg, "a")))
4669             {
4670                 perror (arg);
4671                 exit (1);
4672             }
4673             break;
4674         case 't':
4675             outputCharset = xstrdup(arg);
4676             break;
4677         case 'c':
4678             strncpy (ccl_fields, arg, sizeof(ccl_fields)-1);
4679             ccl_fields[sizeof(ccl_fields)-1] = '\0';
4680             break;
4681         case 'q':
4682             strncpy (cql_fields, arg, sizeof(cql_fields)-1);
4683             cql_fields[sizeof(cql_fields)-1] = '\0';
4684             break;
4685         case 'b':
4686             if (!strcmp(arg, "-"))
4687                 ber_file=stderr;
4688             else
4689                 ber_file=fopen(arg, "a");
4690             break;
4691         case 'a':
4692             if (!strcmp(arg, "-"))
4693                 apdu_file=stderr;
4694             else
4695                 apdu_file=fopen(arg, "a");
4696             break;
4697         case 'x':
4698             hex_dump = 1;
4699             break;
4700         case 'p':
4701             yazProxy=strdup(arg);
4702             break;
4703         case 'u':
4704             if (!auth_command)
4705             {
4706                 auth_command = (char *) xmalloc (strlen(arg)+6);
4707                 strcpy (auth_command, "auth ");
4708                 strcat (auth_command, arg);
4709             }
4710             break;
4711         case 'v':
4712             yaz_log_init(yaz_log_mask_str(arg), "", 0);
4713             break;
4714         case 'V':
4715             show_version();
4716             break;
4717         default:
4718             fprintf (stderr, "Usage: %s "
4719                      " [-a <apdulog>]"
4720                      " [-b berdump]"
4721                      " [-d dump]\n"
4722                      " [-c cclfields]"
4723                      " [-k size]"
4724                      " [-m <marclog>]\n" 
4725                      " [-p <proxy-addr>]"
4726                      " [-q cqlfields]"
4727                      " [-u <auth>]"
4728                      " [-V]"
4729                      " [<server-addr>]\n",
4730                      prog);
4731             exit (1);
4732         }      
4733     }
4734     initialize();
4735     if (auth_command)
4736     {
4737 #ifdef HAVE_GETTIMEOFDAY
4738         gettimeofday (&tv_start, 0);
4739 #endif
4740         process_cmd_line (auth_command);
4741 #if HAVE_READLINE_HISTORY_H
4742         add_history(auth_command);
4743 #endif
4744         xfree(auth_command);
4745     }
4746     if (open_command)
4747     {
4748 #ifdef HAVE_GETTIMEOFDAY
4749         gettimeofday (&tv_start, 0);
4750 #endif
4751         process_cmd_line (open_command);
4752 #if HAVE_READLINE_HISTORY_H
4753         add_history(open_command);
4754 #endif
4755         xfree(open_command);
4756     }
4757     client ();
4758     exit (0);
4759 }
4760 /*
4761  * Local variables:
4762  * c-basic-offset: 4
4763  * indent-tabs-mode: nil
4764  * End:
4765  * vim: shiftwidth=4 tabstop=8 expandtab
4766  */
4767