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