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