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