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