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