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