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