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