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