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