Proper ifdefs for non-libxml2 systems
[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.188 2003-04-29 21:13:08 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 #if HAVE_XML2
2879 static void handle_srw_response(Z_SRW_searchRetrieveResponse *res)
2880 {
2881     int i;
2882
2883     printf ("Received SRW SearchRetrieveResponse\n");
2884     
2885     for (i = 0; i<res->num_diagnostics; i++)
2886     {
2887         printf ("SRW diagnostic %d %s\nDetails: %s\n",
2888                 *res->diagnostics[i].code,
2889                 yaz_diag_srw_str(*res->diagnostics[i].code),
2890                 res->diagnostics[i].details);
2891     }
2892     if (res->numberOfRecords)
2893         printf ("Number of hits: %d\n", *res->numberOfRecords);
2894     for (i = 0; i<res->num_records; i++)
2895     {
2896         int pos;
2897         Z_SRW_record *rec = res->records + i;
2898
2899         if (rec->recordPosition)
2900         {
2901             printf ("pos=%d", *rec->recordPosition);
2902             setno = *rec->recordPosition + 1;
2903         }
2904         if (rec->recordSchema)
2905             printf (" scheam=%d", *rec->recordSchema);
2906         printf ("\n");
2907         if (rec->recordData_buf && rec->recordData_len)
2908         {
2909             fwrite(rec->recordData_buf, 1, rec->recordData_len, stdout);
2910             printf ("\n");
2911         }
2912     }
2913 }
2914
2915 static void set_HTTP_error (int error,
2916                             const char *addinfo, const char *addinfo2)
2917 {
2918
2919
2920 }
2921
2922
2923 static void http_response(Z_HTTP_Response *hres)
2924 {
2925     int ret = -1;
2926     const char *content_type = z_HTTP_header_lookup(hres->headers,
2927                                                     "Content-Type");
2928     const char *connection_head = z_HTTP_header_lookup(hres->headers,
2929                                                        "Connection");
2930     yaz_log (LOG_LOG, "http_response");
2931
2932     if (content_type && !yaz_strcmp_del("text/xml", content_type, "; "))
2933     {
2934         Z_SOAP *soap_package = 0;
2935         ODR o = odr_createmem(ODR_DECODE);
2936         Z_SOAP_Handler soap_handlers[2] = {
2937             {"http://www.loc.gov/zing/srw/v1.0/", 0,
2938              (Z_SOAP_fun) yaz_srw_codec},
2939             {0, 0, 0}
2940         };
2941         ret = z_soap_codec(o, &soap_package,
2942                            &hres->content_buf, &hres->content_len,
2943                            soap_handlers);
2944         if (!ret && soap_package->which == Z_SOAP_generic &&
2945             soap_package->u.generic->no == 0)
2946         {
2947             Z_SRW_PDU *sr = soap_package->u.generic->p;
2948             if (sr->which == Z_SRW_searchRetrieve_response)
2949                 handle_srw_response(sr->u.response);
2950             else
2951                 ret = -1;
2952         }
2953         else if (!ret && (soap_package->which == Z_SOAP_fault
2954                           || soap_package->which == Z_SOAP_error))
2955         {
2956             printf ("HTTP Error Status=%d\n", hres->code);
2957             printf ("SOAP Fault code %s\n",
2958                     soap_package->u.fault->fault_code);
2959             printf ("SOAP Fault string %s\n", 
2960                     soap_package->u.fault->fault_string);
2961         }
2962         else
2963             ret = -1;
2964         odr_destroy(o);
2965     }
2966     if (ret)
2967     {
2968         if (hres->code != 200)
2969             set_HTTP_error(hres->code, 0, 0);
2970         else
2971         {
2972             printf ("decoding of SRW package failed\n");
2973         }
2974         close_session();
2975     }
2976     if (!strcmp(hres->version, "1.0"))
2977     {
2978         /* HTTP 1.0: only if Keep-Alive we stay alive.. */
2979         if (!connection_head || strcmp(connection_head, "Keep-Alive"))
2980             close_session();
2981     }
2982     else 
2983     {
2984         /* HTTP 1.1: only if no close we stay alive .. */
2985         if (connection_head && !strcmp(connection_head, "close"))
2986             close_session();
2987     }
2988 }
2989 #endif
2990
2991 void wait_and_handle_response() 
2992 {
2993     int reconnect_ok = 1;
2994     int res;
2995     char *netbuffer= 0;
2996     int netbufferlen = 0;
2997     Z_GDU *gdu;
2998     
2999     while(conn)
3000     {
3001         printf ("cs_get....\n");
3002         res = cs_get(conn, &netbuffer, &netbufferlen);
3003         if (reconnect_ok && res <= 0 && conn->protocol == PROTO_HTTP)
3004         {
3005             cs_close(conn);
3006             conn = 0;
3007             cmd_open(0);
3008             reconnect_ok = 0;
3009             if (conn)
3010             {
3011                 char *buf_out;
3012                 int len_out;
3013                 
3014                 buf_out = odr_getbuf(out, &len_out, 0);
3015                 
3016                 cs_put(conn, buf_out, len_out);
3017                 
3018                 odr_reset(out);
3019                 continue;
3020             }
3021         }
3022         else if (res <= 0)
3023         {
3024             printf("Target closed connection\n");
3025             close_session();
3026             break;
3027         }
3028         odr_reset(out);
3029         odr_reset(in); /* release APDU from last round */
3030         record_last = 0;
3031         odr_setbuf(in, netbuffer, res, 0);
3032         
3033         printf ("got input packet %d bytes\n", res);
3034         if (!z_GDU(in, &gdu, 0, 0))
3035         {
3036             FILE *f = ber_file ? ber_file : stdout;
3037             odr_perror(in, "Decoding incoming APDU");
3038             fprintf(f, "[Near %d]\n", odr_offset(in));
3039             fprintf(f, "Packet dump:\n---------\n");
3040             odr_dumpBER(f, netbuffer, res);
3041             fprintf(f, "---------\n");
3042             if (apdu_file)
3043                 z_GDU(print, &gdu, 0, 0);
3044             close_session ();
3045             break;
3046         }
3047         if (ber_file)
3048             odr_dumpBER(ber_file, netbuffer, res);
3049         if (apdu_file && !z_GDU(print, &gdu, 0, 0))
3050         {
3051             odr_perror(print, "Failed to print incoming APDU");
3052             odr_reset(print);
3053                 continue;
3054         }
3055         if (gdu->which == Z_GDU_Z3950)
3056         {
3057             Z_APDU *apdu = gdu->u.z3950;
3058             switch(apdu->which)
3059             {
3060             case Z_APDU_initResponse:
3061                 process_initResponse(apdu->u.initResponse);
3062                 break;
3063             case Z_APDU_searchResponse:
3064                 process_searchResponse(apdu->u.searchResponse);
3065                 break;
3066             case Z_APDU_scanResponse:
3067                 process_scanResponse(apdu->u.scanResponse);
3068                 break;
3069             case Z_APDU_presentResponse:
3070                 print_refid (apdu->u.presentResponse->referenceId);
3071                 setno +=
3072                     *apdu->u.presentResponse->numberOfRecordsReturned;
3073                 if (apdu->u.presentResponse->records)
3074                     display_records(apdu->u.presentResponse->records);
3075                 else
3076                     printf("No records.\n");
3077                 printf ("nextResultSetPosition = %d\n",
3078                         *apdu->u.presentResponse->nextResultSetPosition);
3079                 break;
3080             case Z_APDU_sortResponse:
3081                 process_sortResponse(apdu->u.sortResponse);
3082                 break;
3083             case Z_APDU_extendedServicesResponse:
3084                 printf("Got extended services response\n");
3085                 process_ESResponse(apdu->u.extendedServicesResponse);
3086                 break;
3087             case Z_APDU_close:
3088                 printf("Target has closed the association.\n");
3089                 process_close(apdu->u.close);
3090                 break;
3091             case Z_APDU_resourceControlRequest:
3092                 process_resourceControlRequest
3093                     (apdu->u.resourceControlRequest);
3094                 break;
3095             case Z_APDU_deleteResultSetResponse:
3096                 process_deleteResultSetResponse(apdu->u.
3097                                                 deleteResultSetResponse);
3098                 break;
3099             default:
3100                 printf("Received unknown APDU type (%d).\n", 
3101                        apdu->which);
3102                 close_session ();
3103             }
3104         }
3105 #if HAVE_XML2
3106         else if (gdu->which == Z_GDU_HTTP_Response)
3107         {
3108             http_response(gdu->u.HTTP_Response);
3109         }
3110 #endif
3111         if (conn && !cs_more(conn))
3112             break;
3113     }
3114     if (conn)
3115     {
3116 #if HAVE_GETTIMEOFDAY
3117         gettimeofday (&tv_end, 0);
3118 #if 0
3119         printf ("S/U S/U=%ld/%ld %ld/%ld",
3120                 (long) tv_start.tv_sec,
3121                 (long) tv_start.tv_usec,
3122                 (long) tv_end.tv_sec,
3123                 (long) tv_end.tv_usec);
3124 #endif
3125         printf ("Elapsed: %.6f\n",
3126                 (double) tv_end.tv_usec / 1e6 + tv_end.tv_sec -
3127                 ((double) tv_start.tv_usec / 1e6 + tv_start.tv_sec));
3128 #endif
3129     }
3130     xfree (netbuffer);
3131 }
3132
3133
3134 int cmd_cclparse(const char* arg) 
3135 {
3136     int error, pos;
3137     struct ccl_rpn_node *rpn=NULL;
3138     
3139     
3140     rpn = ccl_find_str (bibset, arg, &error, &pos);
3141     
3142     if (error) {
3143         printf ("%*s^ - ", 3+strlen(last_cmd)+1+pos, " ");
3144         printf ("%s\n", ccl_err_msg (error));
3145     }
3146     else
3147     {
3148         if (rpn)
3149         {       
3150             ccl_pr_tree(rpn, stdout); 
3151         }
3152     }
3153     if (rpn)
3154         ccl_rpn_delete(rpn);
3155     
3156     printf ("\n");
3157     
3158     return 0;
3159 }
3160
3161
3162 int cmd_set_otherinfo(const char* args)
3163 {
3164     char oid[101], otherinfoString[101];
3165     int otherinfoNo;
3166     int sscan_res;
3167     int oidval;
3168     
3169     sscan_res = sscanf (args, "%d %100[^ ] %100s", &otherinfoNo, oid, otherinfoString);
3170     if(sscan_res==1) {
3171         /* reset this otherinfo */
3172         if(otherinfoNo>=maxOtherInfosSupported) {
3173             printf("Error otherinfo index to large (%d>%d)\n",otherinfoNo,maxOtherInfosSupported);
3174         }
3175         extraOtherInfos[otherinfoNo].oidval = -1;
3176         if(extraOtherInfos[otherinfoNo].value) free(extraOtherInfos[otherinfoNo].value);                        
3177         return 0;
3178     }
3179     if (sscan_res<3) {
3180         printf("Error in set_otherinfo command \n");
3181         return 0;
3182     }
3183     
3184     if(otherinfoNo>=maxOtherInfosSupported) {
3185         printf("Error otherinfo index to large (%d>%d)\n",otherinfoNo,maxOtherInfosSupported);
3186     }
3187     
3188     
3189     oidval = oid_getvalbyname (oid);
3190     if(oidval == -1 ) {
3191         printf("Error in set_otherinfo command unknown oid %s \n",oid);
3192         return 0;
3193     }
3194     extraOtherInfos[otherinfoNo].oidval = oidval;
3195     if(extraOtherInfos[otherinfoNo].value) free(extraOtherInfos[otherinfoNo].value);
3196     extraOtherInfos[otherinfoNo].value = strdup(otherinfoString);
3197     
3198     return 0;
3199 }
3200
3201 int cmd_list_otherinfo(const char* args)
3202 {
3203     int i;         
3204     
3205     if(strlen(args)>0) {
3206         i = atoi(args);
3207         if( i >= maxOtherInfosSupported ) {
3208             printf("Error otherinfo index to large (%d>%d)\n",i,maxOtherInfosSupported);
3209             return 0;
3210         }
3211
3212         if(extraOtherInfos[i].oidval != -1) 
3213             printf("  otherinfo %d %s %s\n",
3214                    i,
3215                    yaz_z3950_oid_value_to_str(
3216                        (enum oid_value) extraOtherInfos[i].oidval,
3217                        CLASS_RECSYN),
3218                    extraOtherInfos[i].value);
3219         
3220     } else {            
3221         for(i=0; i<maxOtherInfosSupported; ++i) {
3222             if(extraOtherInfos[i].oidval != -1) 
3223                 printf("  otherinfo %d %s %s\n",
3224                        i,
3225                        yaz_z3950_oid_value_to_str(
3226                            (enum oid_value) extraOtherInfos[i].oidval,
3227                            CLASS_RECSYN),
3228                        extraOtherInfos[i].value);
3229         }
3230         
3231     }
3232     return 0;
3233 }
3234
3235
3236 int cmd_list_all(const char* args) {
3237     int i;
3238     
3239     /* connection options */
3240     if(conn) {
3241         printf("Connected to         : %s\n",last_open_command);
3242     } else {
3243         if(last_open_command) 
3244             printf("Not connected to     : %s\n",last_open_command);
3245         else 
3246             printf("Not connected        : \n");
3247         
3248     }
3249     if(yazProxy) printf("using proxy          : %s\n",yazProxy);                
3250     
3251     printf("auto_reconnect       : %s\n",auto_reconnect?"on":"off");
3252     
3253     if (!auth) {
3254         printf("Authentication       : none\n");
3255     } else {
3256         switch(auth->which) {
3257         case Z_IdAuthentication_idPass:
3258             printf("Authentication       : IdPass\n"); 
3259             printf("    Login User       : %s\n",auth->u.idPass->userId?auth->u.idPass->userId:"");
3260             printf("    Login Group      : %s\n",auth->u.idPass->groupId?auth->u.idPass->groupId:"");
3261             printf("    Password         : %s\n",auth->u.idPass->password?auth->u.idPass->password:"");
3262             break;
3263         case Z_IdAuthentication_open:
3264             printf("Authentication       : psOpen\n");                  
3265             printf("    Open string      : %s\n",auth->u.open); 
3266             break;
3267         default:
3268             printf("Authentication       : Unknown\n");
3269         }
3270     }
3271     if ( yazCharset ) printf("Character set        : `%s'\n", (yazCharset) ? yazCharset:NULL);
3272     
3273     /* bases */
3274     printf("Bases                : ");
3275     for (i = 0; i<num_databaseNames; i++) printf("%s ",databaseNames[i]);
3276     printf("\n");
3277     
3278     /* Query options */
3279     printf("CCL file             : %s\n",ccl_fields);
3280     printf("Query type           : %s\n",query_type_as_string(queryType));
3281     
3282     printf("Named Result Sets    : %s\n",setnumber==-1?"off":"on");
3283     
3284     /* piggy back options */
3285     printf("ssub/lslb/mspn       : %d/%d/%d\n",smallSetUpperBound,largeSetLowerBound,mediumSetPresentNumber);
3286     
3287     /* print present related options */
3288     printf("Format               : %s\n",yaz_z3950_oid_value_to_str(recordsyntax,CLASS_RECSYN));
3289     printf("Schema               : %s\n",schema);
3290     printf("Elements             : %s\n",elementSetNames?elementSetNames->u.generic:"");
3291     
3292     /* loging options */
3293     printf("APDU log             : %s\n",apdu_file?"on":"off");
3294     printf("Record log           : %s\n",marc_file?"on":"off");
3295     
3296     /* other infos */
3297     printf("Other Info: \n");
3298     cmd_list_otherinfo("");
3299     
3300     return 0;
3301 }
3302
3303 int cmd_clear_otherinfo(const char* args) 
3304 {
3305     if(strlen(args)>0) {
3306         int otherinfoNo;
3307         otherinfoNo = atoi(args);
3308         if( otherinfoNo >= maxOtherInfosSupported ) {
3309             printf("Error otherinfo index to large (%d>%d)\n",otherinfoNo,maxOtherInfosSupported);
3310             return 0;
3311         }
3312         
3313         if(extraOtherInfos[otherinfoNo].oidval != -1) {                 
3314             /* only clear if set. */
3315             extraOtherInfos[otherinfoNo].oidval=-1;
3316             free(extraOtherInfos[otherinfoNo].value);
3317         }
3318     } else {
3319         int i;
3320         
3321         for(i=0; i<maxOtherInfosSupported; ++i) {
3322             if (extraOtherInfos[i].oidval!=-1 ) {                               
3323                 extraOtherInfos[i].oidval=-1;
3324                 free(extraOtherInfos[i].value);
3325             }
3326         }
3327     }
3328     return 0;
3329 }
3330
3331 static int cmd_help (const char *line);
3332
3333 typedef char *(*completerFunctionType)(const char *text, int state);
3334
3335 static struct {
3336     char *cmd;
3337     int (*fun)(const char *arg);
3338     char *ad;
3339         completerFunctionType rl_completerfunction;
3340     int complete_filenames;
3341     char **local_tabcompletes;
3342 } cmd_array[] = {
3343     {"open", cmd_open, "('tcp'|'ssl')':<host>[':'<port>][/<db>]",NULL,0,NULL},
3344     {"quit", cmd_quit, "",NULL,0,NULL},
3345     {"find", cmd_find, "<query>",NULL,0,NULL},
3346     {"delete", cmd_delete, "<setname>",NULL,0,NULL},
3347     {"base", cmd_base, "<base-name>",NULL,0,NULL},
3348     {"show", cmd_show, "<rec#>['+'<#recs>['+'<setname>]]",NULL,0,NULL},
3349     {"scan", cmd_scan, "<term>",NULL,0,NULL},
3350     {"sort", cmd_sort, "<sortkey> <flag> <sortkey> <flag> ...",NULL,0,NULL},
3351     {"sort+", cmd_sort_newset, "<sortkey> <flag> <sortkey> <flag> ...",NULL,0,NULL},
3352     {"authentication", cmd_authentication, "<acctstring>",NULL,0,NULL},
3353     {"lslb", cmd_lslb, "<largeSetLowerBound>",NULL,0,NULL},
3354     {"ssub", cmd_ssub, "<smallSetUpperBound>",NULL,0,NULL},
3355     {"mspn", cmd_mspn, "<mediumSetPresentNumber>",NULL,0,NULL},
3356     {"status", cmd_status, "",NULL,0,NULL},
3357     {"setnames", cmd_setnames, "",NULL,0,NULL},
3358     {"cancel", cmd_cancel, "",NULL,0,NULL},
3359     {"format", cmd_format, "<recordsyntax>",complete_format,0,NULL},
3360     {"schema", cmd_schema, "<schema>",complete_schema,0,NULL},
3361     {"elements", cmd_elements, "<elementSetName>",NULL,0,NULL},
3362     {"close", cmd_close, "",NULL,0,NULL},
3363     {"attributeset", cmd_attributeset, "<attrset>",complete_attributeset,0,NULL},
3364     {"querytype", cmd_querytype, "<type>",complete_querytype,0,NULL},
3365     {"refid", cmd_refid, "<id>",NULL,0,NULL},
3366     {"itemorder", cmd_itemorder, "ill|item <itemno>",NULL,0,NULL},
3367     {"update", cmd_update, "<action> <recid> [<file>]",NULL,0,NULL},
3368     {"packagename", cmd_packagename, "<packagename>",NULL,0,NULL},
3369     {"proxy", cmd_proxy, "[('tcp'|'ssl')]<host>[':'<port>]",NULL,0,NULL},
3370     {"charset", cmd_charset, "<charset_name>",NULL,0,NULL},
3371     {"lang", cmd_lang, "<language_code>",NULL,0,NULL},
3372     {".", cmd_source, "<filename>",NULL,1,NULL},
3373     {"!", cmd_subshell, "Subshell command",NULL,1,NULL},
3374     {"set_apdufile", cmd_set_apdufile, "<filename>",NULL,1,NULL},
3375     {"set_berfile", cmd_set_berfile, "<filename>",NULL,1,NULL},
3376     {"set_marcdump", cmd_set_marcdump," <filename>",NULL,1,NULL},
3377     {"set_cclfile", cmd_set_cclfile," <filename>",NULL,1,NULL},
3378     {"set_auto_reconnect", cmd_set_auto_reconnect," on|off",complete_auto_reconnect,1,NULL},
3379         {"set_otherinfo", cmd_set_otherinfo,"<otherinfoinddex> <oid> <string>",NULL,0,NULL},
3380     {"register_oid", cmd_register_oid,"<name> <class> <oid>",NULL,0,NULL},
3381     {"push_command", cmd_push_command,"<command>",command_generator,0,NULL},
3382     {"register_tab", cmd_register_tab,"<commandname> <tab>",command_generator,0,NULL},
3383     {"cclparse", cmd_cclparse,"<ccl find command>",NULL,0,NULL},
3384     {"list_otherinfo",cmd_list_otherinfo,"[otherinfoinddex]",NULL,0,NULL},
3385     {"list_all",cmd_list_all,"",NULL,0,NULL},
3386     {"clear_otherinfo",cmd_clear_otherinfo,"",NULL,0,NULL},
3387     /* Server Admin Functions */
3388     {"adm-reindex", cmd_adm_reindex, "<database-name>",NULL,0,NULL},
3389     {"adm-truncate", cmd_adm_truncate, "('database'|'index')<object-name>",NULL,0,NULL},
3390     {"adm-create", cmd_adm_create, "",NULL,0,NULL},
3391     {"adm-drop", cmd_adm_drop, "('database'|'index')<object-name>",NULL,0,NULL},
3392     {"adm-import", cmd_adm_import, "<record-type> <dir> <pattern>",NULL,0,NULL},
3393     {"adm-refresh", cmd_adm_refresh, "",NULL,0,NULL},
3394     {"adm-commit", cmd_adm_commit, "",NULL,0,NULL},
3395     {"adm-shutdown", cmd_adm_shutdown, "",NULL,0,NULL},
3396     {"adm-startup", cmd_adm_startup, "",NULL,0,NULL},
3397     {"help", cmd_help, "", NULL,0,NULL},
3398     {0,0,0,0,0,0}
3399 };
3400
3401 static int cmd_help (const char *line)
3402 {
3403     int i;
3404     char topic[21];
3405     
3406     *topic = 0;
3407     sscanf (line, "%20s", topic);
3408
3409     if (*topic == 0)
3410         printf("Commands:\n");
3411     for (i = 0; cmd_array[i].cmd; i++)
3412         if (*topic == 0 || strcmp (topic, cmd_array[i].cmd) == 0)
3413             printf("   %s %s\n", cmd_array[i].cmd, cmd_array[i].ad);
3414     if (strcmp (topic, "find") == 0)
3415     {
3416         printf ("RPN:\n");
3417         printf (" \"term\"                        Simple Term\n");
3418         printf (" @attr [attset] type=value op  Attribute\n");
3419         printf (" @and opl opr                  And\n");
3420         printf (" @or opl opr                   Or\n");
3421         printf (" @not opl opr                  And-Not\n");
3422         printf (" @set set                      Result set\n");
3423         printf ("\n");
3424         printf ("Bib-1 attribute types\n");
3425         printf ("1=Use:         ");
3426         printf ("4=Title 7=ISBN 8=ISSN 30=Date 62=Abstract 1003=Author 1016=Any\n");
3427         printf ("2=Relation:    ");
3428         printf ("1<   2<=  3=  4>=  5>  6!=  102=Relevance\n");
3429         printf ("3=Position:    ");
3430         printf ("1=First in Field  2=First in subfield  3=Any position\n");
3431         printf ("4=Structure:   ");
3432         printf ("1=Phrase  2=Word  3=Key  4=Year  5=Date  6=WordList\n");
3433         printf ("5=Truncation:  ");
3434         printf ("1=Right  2=Left  3=L&R  100=No  101=#  102=Re-1  103=Re-2\n");
3435         printf ("6=Completeness:");
3436         printf ("1=Incomplete subfield  2=Complete subfield  3=Complete field\n");
3437     }
3438     return 1;
3439 }
3440
3441 int cmd_register_tab(const char* arg) {
3442         
3443     char command[101], tabargument[101];
3444     int i;
3445     int num_of_tabs;
3446     char** tabslist;
3447     
3448     if (sscanf (arg, "%100s %100s", command, tabargument) < 1) {
3449         return 0;
3450     }
3451     
3452     /* locate the amdn in the list */
3453     for (i = 0; cmd_array[i].cmd; i++) {
3454         if (!strncmp(cmd_array[i].cmd, command, strlen(command))) {
3455             break;
3456         }
3457     }
3458     
3459     if(!cmd_array[i].cmd) { 
3460         fprintf(stderr,"Unknown command %s\n",command);
3461         return 1;
3462     }
3463     
3464         
3465     if(!cmd_array[i].local_tabcompletes)
3466         cmd_array[i].local_tabcompletes = (char **) calloc(1,sizeof(char**));
3467     
3468     num_of_tabs=0;              
3469     
3470     tabslist = cmd_array[i].local_tabcompletes;
3471     for(;tabslist && *tabslist;tabslist++) {
3472         num_of_tabs++;
3473     }
3474     
3475     cmd_array[i].local_tabcompletes =  (char **)
3476         realloc(cmd_array[i].local_tabcompletes,(num_of_tabs+2)*sizeof(char**));
3477     tabslist=cmd_array[i].local_tabcompletes;
3478     tabslist[num_of_tabs]=strdup(tabargument);
3479     tabslist[num_of_tabs+1]=NULL;
3480     return 1;
3481 }
3482
3483
3484 void process_cmd_line(char* line)
3485 {  
3486     int i,res;
3487     char word[32], arg[1024];
3488     
3489 #if HAVE_GETTIMEOFDAY
3490     gettimeofday (&tv_start, 0);
3491 #endif
3492     
3493     if ((res = sscanf(line, "%31s %1023[^;]", word, arg)) <= 0)
3494     {
3495         strcpy(word, last_cmd);
3496         *arg = '\0';
3497     }
3498     else if (res == 1)
3499         *arg = 0;
3500     strcpy(last_cmd, word);
3501     
3502     /* removed tailing spaces from the arg command */
3503     { 
3504         char* p = arg;
3505         char* lastnonspace=NULL;
3506         
3507         for(;*p; ++p) {
3508             if(!isspace(*p)) {
3509                 lastnonspace = p;
3510             }
3511         }
3512         if(lastnonspace) 
3513             *(++lastnonspace) = 0;
3514     }
3515     
3516     for (i = 0; cmd_array[i].cmd; i++)
3517         if (!strncmp(cmd_array[i].cmd, word, strlen(word)))
3518         {
3519             res = (*cmd_array[i].fun)(arg);
3520             break;
3521         }
3522     
3523     if (!cmd_array[i].cmd) /* dump our help-screen */
3524     {
3525         printf("Unknown command: %s.\n", word);
3526         printf("use help for list of commands\n");
3527         /* cmd_help (""); */
3528         res = 1;
3529     }
3530     
3531     if(apdu_file) fflush(apdu_file);
3532     
3533     if (res >= 2)
3534         wait_and_handle_response();
3535     
3536     if(apdu_file)
3537         fflush(apdu_file);
3538     if(marc_file)
3539         fflush(marc_file);
3540 }
3541
3542
3543 char *command_generator(const char *text, int state) 
3544 {
3545     static int idx; 
3546     if (state==0) {
3547         idx = 0;
3548     }
3549     for( ; cmd_array[idx].cmd; ++idx) {
3550         if (!strncmp(cmd_array[idx].cmd,text,strlen(text))) {
3551             ++idx;  /* skip this entry on the next run */
3552             return strdup(cmd_array[idx-1].cmd);
3553         }
3554     }
3555     return NULL;
3556 }
3557
3558
3559 /* 
3560    This function only known how to complete on the first word
3561 */
3562 char ** readline_completer(char *text, int start, int end) {
3563 #if HAVE_READLINE_READLINE_H
3564
3565         completerFunctionType completerToUse;
3566         
3567     if(start == 0) {
3568 #if HAVE_READLINE_RL_COMPLETION_MATCHES
3569         char** res=rl_completion_matches(text,
3570                                       command_generator); 
3571 #else
3572         char** res=completion_matches(text,
3573                                       (CPFunction*)command_generator); 
3574 #endif
3575         rl_attempted_completion_over = 1;
3576         return res;
3577     } else {
3578         char arg[1024],word[32];
3579         int i=0 ,res;
3580         if ((res = sscanf(rl_line_buffer, "%31s %1023[^;]", word, arg)) <= 0) {     
3581             rl_attempted_completion_over = 1;
3582             return NULL;
3583         }
3584         
3585         for (i = 0; cmd_array[i].cmd; i++) {
3586             if (!strncmp(cmd_array[i].cmd, word, strlen(word))) {
3587                 break;
3588             }
3589         }
3590         
3591         if(!cmd_array[i].cmd) return NULL;
3592         
3593         curret_global_list = cmd_array[i].local_tabcompletes;
3594         
3595         completerToUse = cmd_array[i].rl_completerfunction;
3596         if(completerToUse==NULL)  /* if no pr. command completer is defined use the default completer */
3597             completerToUse = default_completer;
3598         
3599         if(completerToUse) {
3600 #ifdef HAVE_READLINE_RL_COMPLETION_MATCHES
3601             char** res=
3602                 rl_completion_matches(text,
3603                                       completerToUse);
3604 #else
3605             char** res=
3606                 completion_matches(text,
3607                                    (CPFunction*)completerToUse);
3608 #endif
3609             if(!cmd_array[i].complete_filenames) 
3610                 rl_attempted_completion_over = 1;
3611             return res;
3612         } else {
3613             if(!cmd_array[i].complete_filenames) 
3614                 rl_attempted_completion_over = 1;
3615             return 0;
3616         }
3617     }
3618 #else 
3619     return 0;
3620 #endif 
3621 }
3622
3623
3624 static void client(void)
3625 {
3626     char line[1024];
3627
3628     line[1023] = '\0';
3629
3630 #if HAVE_GETTIMEOFDAY
3631     gettimeofday (&tv_start, 0);
3632 #endif
3633
3634     while (1)
3635     {
3636         char *line_in = NULL;
3637 #if HAVE_READLINE_READLINE_H
3638         if (isatty(0))
3639         {
3640             line_in=readline(C_PROMPT);
3641             if (!line_in)
3642                 break;
3643 #if HAVE_READLINE_HISTORY_H
3644             if (*line_in)
3645                 add_history(line_in);
3646 #endif
3647             strncpy(line, line_in, 1023);
3648             free (line_in);
3649         }
3650 #endif 
3651         if (!line_in)
3652         {
3653             char *end_p;
3654             printf (C_PROMPT);
3655             fflush(stdout);
3656             if (!fgets(line, 1023, stdin))
3657                 break;
3658             if ((end_p = strchr (line, '\n')))
3659                 *end_p = '\0';
3660         }
3661         process_cmd_line(line);
3662     }
3663 }
3664
3665 int main(int argc, char **argv)
3666 {
3667     char *prog = *argv;
3668     char *open_command = 0;
3669     char *auth_command = 0;
3670     char *arg;
3671     int ret;
3672     
3673 #if HAVE_LOCALE_H
3674     if (!setlocale(LC_CTYPE, ""))
3675         fprintf (stderr, "setlocale failed\n");
3676 #endif
3677 #if HAVE_LANGINFO_H
3678 #ifdef CODESET
3679     codeset = nl_langinfo(CODESET);
3680 #endif
3681 #endif
3682
3683     while ((ret = options("k:c:a:b:m:v:p:u:t:", argv, argc, &arg)) != -2)
3684     {
3685         switch (ret)
3686         {
3687         case 0:
3688             if (!open_command)
3689             {
3690                 open_command = (char *) xmalloc (strlen(arg)+6);
3691                 strcpy (open_command, "open ");
3692                 strcat (open_command, arg);
3693             }
3694             break;
3695         case 'k':
3696             kilobytes = atoi(arg);
3697             break;
3698         case 'm':
3699             if (!(marc_file = fopen (arg, "a")))
3700             {
3701                 perror (arg);
3702                 exit (1);
3703             }
3704             break;
3705         case 't':
3706             codeset = arg;
3707             break;
3708         case 'c':
3709             strncpy (ccl_fields, arg, sizeof(ccl_fields)-1);
3710             ccl_fields[sizeof(ccl_fields)-1] = '\0';
3711             break;
3712         case 'b':
3713             if (!strcmp(arg, "-"))
3714                 ber_file=stderr;
3715             else
3716                 ber_file=fopen(arg, "a");
3717             break;
3718         case 'a':
3719             if (!strcmp(arg, "-"))
3720                 apdu_file=stderr;
3721             else
3722                 apdu_file=fopen(arg, "a");
3723             break;
3724         case 'p':
3725             yazProxy=strdup(arg);
3726             break;
3727         case 'u':
3728             if (!auth_command)
3729             {
3730                 auth_command = (char *) xmalloc (strlen(arg)+6);
3731                 strcpy (auth_command, "auth ");
3732                 strcat (auth_command, arg);
3733             }
3734             break;
3735         case 'v':
3736             yaz_log_init (yaz_log_mask_str(arg), "", NULL);
3737             break;
3738         default:
3739             fprintf (stderr, "Usage: %s [-m <marclog>] [ -a <apdulog>] "
3740                      "[-b berdump] [-c cclfields]\n      [-p <proxy-addr>] [-u <auth>] "
3741                      "[-k size] [<server-addr>]\n",
3742                      prog);
3743             exit (1);
3744         }      
3745     }
3746     initialize();
3747     if (auth_command)
3748     {
3749 #ifdef HAVE_GETTIMEOFDAY
3750         gettimeofday (&tv_start, 0);
3751 #endif
3752         process_cmd_line (auth_command);
3753 #if HAVE_READLINE_HISTORY_H
3754         add_history(auth_command);
3755 #endif
3756         xfree(auth_command);
3757     }
3758     if (open_command)
3759     {
3760 #ifdef HAVE_GETTIMEOFDAY
3761         gettimeofday (&tv_start, 0);
3762 #endif
3763         process_cmd_line (open_command);
3764 #if HAVE_READLINE_HISTORY_H
3765         add_history(open_command);
3766 #endif
3767         xfree(open_command);
3768     }
3769     client ();
3770     exit (0);
3771 }
3772
3773 /*
3774  * Local variables:
3775  * tab-width: 8
3776  * c-basic-offset: 4
3777  * End:
3778  * vim600: sw=4 ts=8 fdm=marker
3779  * vim<600: sw=4 ts=8
3780  */