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