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