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