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