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