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