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