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