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