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