Fixed a few warnings on 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.189 2003-04-29 21:20:33 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 session_connect(const char *arg)
447 {
448     void *add;
449     char type_and_host[101];
450     const char *basep = 0;
451     if (conn)
452     {
453         printf("Already connected.\n");
454         
455         cs_close (conn);
456         conn = NULL;
457         if (session_mem)
458         {
459             nmem_destroy (session_mem);
460             session_mem = NULL;
461         }
462     }   
463     cs_get_host_args(arg, &basep);
464
465     strncpy(type_and_host, arg, sizeof(type_and_host)-1);
466     type_and_host[sizeof(type_and_host)-1] = '\0';
467
468     cmd_open_remember_last_open_command(arg,type_and_host);
469
470     if (yazProxy)
471         conn = cs_create_host(yazProxy, 1, &add);
472     else
473         conn = cs_create_host(arg, 1, &add);
474     if (!conn)
475     {
476         printf ("Couldn't create comstack\n");
477         return 0;
478     }
479 #if HAVE_XML2
480 #else
481     if (conn->protocol == PROTO_Z3950)
482     {
483         printf ("SRW not enabled in this YAZ\n");
484         cs_close(conn);
485         conn = 0;
486         return 0;
487     }
488 #endif
489     printf("Connecting...");
490     fflush(stdout);
491     if (cs_connect(conn, add) < 0)
492     {
493         printf ("error = %s\n", cs_strerror(conn));
494         if (conn->cerrno == CSYSERR)
495         {
496             char msg[256];
497             yaz_strerror(msg, sizeof(msg));
498             printf ("%s\n", msg);
499         }
500         cs_close(conn);
501         conn = 0;
502         return 0;
503     }
504     printf("OK.\n");
505     if (basep && *basep)
506         cmd_base (basep);
507     if (conn->protocol == PROTO_Z3950)
508     {
509         send_initRequest(type_and_host);
510         return 2;
511     }
512     return 0;
513 }
514
515 int cmd_open(const char *arg)
516 {
517     static char cur_host[200];
518     if (arg)
519     {
520         strncpy (cur_host, arg, sizeof(cur_host)-1);
521         cur_host[sizeof(cur_host)-1] = 0;
522     }
523     return session_connect(cur_host);
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 setstring[100];
1934
1935     req->referenceId = set_refid (out);
1936
1937     parse_show_args(arg, setstring, &setno, &nos);
1938     if (*setstring)
1939         req->resultSetId = setstring;
1940
1941     req->resultSetStartPoint = &setno;
1942     req->numberOfRecordsRequested = &nos;
1943     prefsyn.proto = protocol;
1944     prefsyn.oclass = CLASS_RECSYN;
1945     prefsyn.value = recordsyntax;
1946     req->preferredRecordSyntax =
1947         odr_oiddup (out, oid_ent_to_oid(&prefsyn, oid));
1948
1949     if (schema)
1950     {
1951         oident prefschema;
1952
1953         prefschema.proto = protocol;
1954         prefschema.oclass = CLASS_SCHEMA;
1955         prefschema.value = oid_getvalbyname(schema);
1956
1957         req->recordComposition = &compo;
1958         compo.which = Z_RecordComp_complex;
1959         compo.u.complex = (Z_CompSpec *)
1960             odr_malloc(out, sizeof(*compo.u.complex));
1961         compo.u.complex->selectAlternativeSyntax = (bool_t *) 
1962             odr_malloc(out, sizeof(bool_t));
1963         *compo.u.complex->selectAlternativeSyntax = 0;
1964
1965         compo.u.complex->generic = (Z_Specification *)
1966             odr_malloc(out, sizeof(*compo.u.complex->generic));
1967         compo.u.complex->generic->which = Z_Schema_oid;
1968         compo.u.complex->generic->schema.oid = (Odr_oid *)
1969             odr_oiddup(out, oid_ent_to_oid(&prefschema, oid));
1970         if (!compo.u.complex->generic->schema.oid)
1971         {
1972             /* OID wasn't a schema! Try record syntax instead. */
1973             prefschema.oclass = CLASS_RECSYN;
1974             compo.u.complex->generic->schema.oid = (Odr_oid *)
1975                 odr_oiddup(out, oid_ent_to_oid(&prefschema, oid));
1976         }
1977         if (!elementSetNames)
1978             compo.u.complex->generic->elementSpec = 0;
1979         else
1980         {
1981             compo.u.complex->generic->elementSpec = (Z_ElementSpec *)
1982                 odr_malloc(out, sizeof(Z_ElementSpec));
1983             compo.u.complex->generic->elementSpec->which =
1984                 Z_ElementSpec_elementSetName;
1985             compo.u.complex->generic->elementSpec->u.elementSetName =
1986                 elementSetNames->u.generic;
1987         }
1988         compo.u.complex->num_dbSpecific = 0;
1989         compo.u.complex->dbSpecific = 0;
1990         compo.u.complex->num_recordSyntax = 0;
1991         compo.u.complex->recordSyntax = 0;
1992     }
1993     else if (elementSetNames)
1994     {
1995         req->recordComposition = &compo;
1996         compo.which = Z_RecordComp_simple;
1997         compo.u.simple = elementSetNames;
1998     }
1999     send_apdu(apdu);
2000     printf("Sent presentRequest (%d+%d).\n", setno, nos);
2001     return 2;
2002 }
2003
2004 #if HAVE_XML2
2005 static int send_SRW_presentRequest(const char *arg)
2006 {
2007     char setstring[100];
2008     int nos = 1;
2009     Z_SRW_PDU *sr = srw_sr;
2010
2011     if (!sr)
2012         return 0;
2013     parse_show_args(arg, setstring, &setno, &nos);
2014     sr->u.request->startRecord = odr_intdup(out, setno);
2015     sr->u.request->maximumRecords = odr_intdup(out, nos);
2016     if (schema)
2017         sr->u.request->recordSchema = schema;
2018     return send_srw(sr);
2019 }
2020 #endif
2021
2022 static void close_session (void)
2023 {
2024     cs_close (conn);
2025     conn = 0;
2026     if (session_mem)
2027     {
2028         nmem_destroy (session_mem);
2029         session_mem = NULL;
2030     }
2031     if (srw_sr)
2032     {
2033         odr_destroy(srw_sr_odr_out);
2034         srw_sr_odr_out = 0;
2035         srw_sr = 0;
2036     }
2037     assert (srw_sr_odr_out == 0);
2038     sent_close = 0;
2039     odr_reset(out);
2040     odr_reset(in);
2041     odr_reset(print);
2042 }
2043
2044 void process_close(Z_Close *req)
2045 {
2046     Z_APDU *apdu = zget_APDU(out, Z_APDU_close);
2047     Z_Close *res = apdu->u.close;
2048
2049     static char *reasons[] =
2050     {
2051         "finished",
2052         "shutdown",
2053         "system problem",
2054         "cost limit reached",
2055         "resources",
2056         "security violation",
2057         "protocolError",
2058         "lack of activity",
2059         "peer abort",
2060         "unspecified"
2061     };
2062
2063     printf("Reason: %s, message: %s\n", reasons[*req->closeReason],
2064         req->diagnosticInformation ? req->diagnosticInformation : "NULL");
2065     if (sent_close)
2066         close_session ();
2067     else
2068     {
2069         *res->closeReason = Z_Close_finished;
2070         send_apdu(apdu);
2071         printf("Sent response.\n");
2072         sent_close = 1;
2073     }
2074 }
2075
2076 static int cmd_show(const char *arg)
2077 {
2078     if (!conn)
2079     {
2080         printf("Not connected yet\n");
2081         return 0;
2082     }
2083     if (conn->protocol == PROTO_HTTP)
2084     {
2085 #if HAVE_XML2
2086         if (!send_SRW_presentRequest(arg))
2087             return 0;
2088 #else
2089         return 0;
2090 #endif
2091     }
2092     else
2093     {
2094         if (!send_presentRequest(arg))
2095             return 0;
2096     }
2097     return 2;
2098 }
2099
2100 int cmd_quit(const char *arg)
2101 {
2102     printf("See you later, alligator.\n");
2103     xmalloc_trav ("");
2104     exit(0);
2105     return 0;
2106 }
2107
2108 int cmd_cancel(const char *arg)
2109 {
2110     Z_APDU *apdu = zget_APDU(out, Z_APDU_triggerResourceControlRequest);
2111     Z_TriggerResourceControlRequest *req =
2112         apdu->u.triggerResourceControlRequest;
2113     bool_t rfalse = 0;
2114     
2115     if (!conn)
2116     {
2117         printf("Session not initialized yet\n");
2118         return 0;
2119     }
2120     if (only_z3950())
2121         return 0;
2122     if (!ODR_MASK_GET(session->options, Z_Options_triggerResourceCtrl))
2123     {
2124         printf("Target doesn't support cancel (trigger resource ctrl)\n");
2125         return 0;
2126     }
2127     *req->requestedAction = Z_TriggerResourceCtrl_cancel;
2128     req->resultSetWanted = &rfalse;
2129
2130     send_apdu(apdu);
2131     printf("Sent cancel request\n");
2132     return 2;
2133 }
2134
2135 int send_scanrequest(const char *query, int pp, int num, const char *term)
2136 {
2137     Z_APDU *apdu = zget_APDU(out, Z_APDU_scanRequest);
2138     Z_ScanRequest *req = apdu->u.scanRequest;
2139     int oid[OID_SIZE];
2140     
2141     if (only_z3950())
2142         return 0;
2143     if (queryType == QueryType_CCL2RPN)
2144     {
2145         oident bib1;
2146         int error, pos;
2147         struct ccl_rpn_node *rpn;
2148
2149         rpn = ccl_find_str (bibset,  query, &error, &pos);
2150         if (error)
2151         {
2152             printf("CCL ERROR: %s\n", ccl_err_msg(error));
2153             return -1;
2154         }
2155         bib1.proto = PROTO_Z3950;
2156         bib1.oclass = CLASS_ATTSET;
2157         bib1.value = VAL_BIB1;
2158         req->attributeSet = oid_ent_to_oid (&bib1, oid);
2159         if (!(req->termListAndStartPoint = ccl_scan_query (out, rpn)))
2160         {
2161             printf("Couldn't convert CCL to Scan term\n");
2162             return -1;
2163         }
2164         ccl_rpn_delete (rpn);
2165     }
2166     else
2167     {
2168         YAZ_PQF_Parser pqf_parser = yaz_pqf_create ();
2169
2170         if (!(req->termListAndStartPoint =
2171               yaz_pqf_scan(pqf_parser, out, &req->attributeSet, query)))
2172         {
2173             const char *pqf_msg;
2174             size_t off;
2175             int code = yaz_pqf_error (pqf_parser, &pqf_msg, &off);
2176             printf("%*s^\n", off+7, "");
2177             printf("Prefix query error: %s (code %d)\n", pqf_msg, code);
2178             yaz_pqf_destroy (pqf_parser);
2179             return -1;
2180         }
2181         yaz_pqf_destroy (pqf_parser);
2182     }
2183     if (term && *term)
2184     {
2185         if (req->termListAndStartPoint->term &&
2186             req->termListAndStartPoint->term->which == Z_Term_general &&
2187             req->termListAndStartPoint->term->u.general)
2188         {
2189             req->termListAndStartPoint->term->u.general->buf =
2190                 (unsigned char *) odr_strdup(out, term);
2191             req->termListAndStartPoint->term->u.general->len =
2192                 req->termListAndStartPoint->term->u.general->size =
2193                 strlen(term);
2194         }
2195     }
2196     req->referenceId = set_refid (out);
2197     req->num_databaseNames = num_databaseNames;
2198     req->databaseNames = databaseNames;
2199     req->numberOfTermsRequested = &num;
2200     req->preferredPositionInResponse = &pp;
2201     send_apdu(apdu);
2202     return 2;
2203 }
2204
2205 int send_sortrequest(const char *arg, int newset)
2206 {
2207     Z_APDU *apdu = zget_APDU(out, Z_APDU_sortRequest);
2208     Z_SortRequest *req = apdu->u.sortRequest;
2209     Z_SortKeySpecList *sksl = (Z_SortKeySpecList *)
2210         odr_malloc (out, sizeof(*sksl));
2211     char setstring[32];
2212
2213     if (only_z3950())
2214         return 0;
2215     if (setnumber >= 0)
2216         sprintf (setstring, "%d", setnumber);
2217     else
2218         sprintf (setstring, "default");
2219
2220     req->referenceId = set_refid (out);
2221
2222     req->num_inputResultSetNames = 1;
2223     req->inputResultSetNames = (Z_InternationalString **)
2224         odr_malloc (out, sizeof(*req->inputResultSetNames));
2225     req->inputResultSetNames[0] = odr_strdup (out, setstring);
2226
2227     if (newset && setnumber >= 0)
2228         sprintf (setstring, "%d", ++setnumber);
2229
2230     req->sortedResultSetName = odr_strdup (out, setstring);
2231
2232     req->sortSequence = yaz_sort_spec (out, arg);
2233     if (!req->sortSequence)
2234     {
2235         printf ("Missing sort specifications\n");
2236         return -1;
2237     }
2238     send_apdu(apdu);
2239     return 2;
2240 }
2241
2242 void display_term(Z_TermInfo *t)
2243 {
2244     if (t->term->which == Z_Term_general)
2245     {
2246         printf("%.*s", t->term->u.general->len, t->term->u.general->buf);
2247         sprintf(last_scan_line, "%.*s", t->term->u.general->len,
2248             t->term->u.general->buf);
2249     }
2250     else
2251         printf("Term (not general)");
2252     if (t->globalOccurrences)
2253         printf (" (%d)\n", *t->globalOccurrences);
2254     else
2255         printf ("\n");
2256 }
2257
2258 void process_scanResponse(Z_ScanResponse *res)
2259 {
2260     int i;
2261     Z_Entry **entries = NULL;
2262     int num_entries = 0;
2263    
2264     printf("Received ScanResponse\n"); 
2265     print_refid (res->referenceId);
2266     printf("%d entries", *res->numberOfEntriesReturned);
2267     if (res->positionOfTerm)
2268         printf (", position=%d", *res->positionOfTerm); 
2269     printf ("\n");
2270     if (*res->scanStatus != Z_Scan_success)
2271         printf("Scan returned code %d\n", *res->scanStatus);
2272     if (!res->entries)
2273         return;
2274     if ((entries = res->entries->entries))
2275         num_entries = res->entries->num_entries;
2276     for (i = 0; i < num_entries; i++)
2277     {
2278         int pos_term = res->positionOfTerm ? *res->positionOfTerm : -1;
2279         if (entries[i]->which == Z_Entry_termInfo)
2280         {
2281             printf("%c ", i + 1 == pos_term ? '*' : ' ');
2282             display_term(entries[i]->u.termInfo);
2283         }
2284         else
2285             display_diagrecs(&entries[i]->u.surrogateDiagnostic, 1);
2286     }
2287     if (res->entries->nonsurrogateDiagnostics)
2288         display_diagrecs (res->entries->nonsurrogateDiagnostics,
2289                           res->entries->num_nonsurrogateDiagnostics);
2290 }
2291
2292 void process_sortResponse(Z_SortResponse *res)
2293 {
2294     printf("Received SortResponse: status=");
2295     switch (*res->sortStatus)
2296     {
2297     case Z_SortStatus_success:
2298         printf ("success"); break;
2299     case Z_SortStatus_partial_1:
2300         printf ("partial"); break;
2301     case Z_SortStatus_failure:
2302         printf ("failure"); break;
2303     default:
2304         printf ("unknown (%d)", *res->sortStatus);
2305     }
2306     printf ("\n");
2307     print_refid (res->referenceId);
2308     if (res->diagnostics)
2309         display_diagrecs(res->diagnostics,
2310                          res->num_diagnostics);
2311 }
2312
2313 void process_deleteResultSetResponse (Z_DeleteResultSetResponse *res)
2314 {
2315     printf("Got deleteResultSetResponse status=%d\n",
2316            *res->deleteOperationStatus);
2317     if (res->deleteListStatuses)
2318     {
2319         int i;
2320         for (i = 0; i < res->deleteListStatuses->num; i++)
2321         {
2322             printf ("%s status=%d\n", res->deleteListStatuses->elements[i]->id,
2323                     *res->deleteListStatuses->elements[i]->status);
2324         }
2325     }
2326 }
2327
2328 int cmd_sort_generic(const char *arg, int newset)
2329 {
2330     if (!conn)
2331     {
2332         printf("Session not initialized yet\n");
2333         return 0;
2334     }
2335     if (only_z3950())
2336         return 0;
2337     if (!ODR_MASK_GET(session->options, Z_Options_sort))
2338     {
2339         printf("Target doesn't support sort\n");
2340         return 0;
2341     }
2342     if (*arg)
2343     {
2344         if (send_sortrequest(arg, newset) < 0)
2345             return 0;
2346         return 2;
2347     }
2348     return 0;
2349 }
2350
2351 int cmd_sort(const char *arg)
2352 {
2353     return cmd_sort_generic (arg, 0);
2354 }
2355
2356 int cmd_sort_newset (const char *arg)
2357 {
2358     return cmd_sort_generic (arg, 1);
2359 }
2360
2361 int cmd_scan(const char *arg)
2362 {
2363     if (only_z3950())
2364         return 0;
2365     if (!conn)
2366     {
2367         try_reconnect();
2368         
2369         if (!conn) {                                                            
2370             printf("Session not initialized yet\n");
2371             return 0;
2372         }
2373     }
2374     if (!ODR_MASK_GET(session->options, Z_Options_scan))
2375     {
2376         printf("Target doesn't support scan\n");
2377         return 0;
2378     }
2379     if (*arg)
2380     {
2381         strcpy (last_scan_query, arg);
2382         if (send_scanrequest(arg, 1, 20, 0) < 0)
2383             return 0;
2384     }
2385     else
2386     {
2387         if (send_scanrequest(last_scan_query, 1, 20, last_scan_line) < 0)
2388             return 0;
2389     }
2390     return 2;
2391 }
2392
2393 int cmd_schema(const char *arg)
2394 {
2395     xfree(schema);
2396     schema = 0;
2397     if (arg && *arg)
2398         schema = xstrdup(arg);
2399     return 1;
2400 }
2401
2402 int cmd_format(const char *arg)
2403 {
2404     oid_value nsyntax;
2405     if (!arg || !*arg)
2406     {
2407         printf("Usage: format <recordsyntax>\n");
2408         return 0;
2409     }
2410     nsyntax = oid_getvalbyname (arg);
2411     if (strcmp(arg, "none") && nsyntax == VAL_NONE)
2412     {
2413         printf ("unknown record syntax\n");
2414         return 0;
2415     }
2416     recordsyntax = nsyntax;
2417     return 1;
2418 }
2419
2420 int cmd_elements(const char *arg)
2421 {
2422     static Z_ElementSetNames esn;
2423     static char what[100];
2424
2425     if (!arg || !*arg)
2426     {
2427         elementSetNames = 0;
2428         return 1;
2429     }
2430     strcpy(what, arg);
2431     esn.which = Z_ElementSetNames_generic;
2432     esn.u.generic = what;
2433     elementSetNames = &esn;
2434     return 1;
2435 }
2436
2437 int cmd_attributeset(const char *arg)
2438 {
2439     char what[100];
2440
2441     if (!arg || !*arg)
2442     {
2443         printf("Usage: attributeset <setname>\n");
2444         return 0;
2445     }
2446     sscanf(arg, "%s", what);
2447     if (p_query_attset (what))
2448     {
2449         printf("Unknown attribute set name\n");
2450         return 0;
2451     }
2452     return 1;
2453 }
2454
2455 int cmd_querytype (const char *arg)
2456 {
2457     if (!strcmp (arg, "ccl"))
2458         queryType = QueryType_CCL;
2459     else if (!strcmp (arg, "prefix") || !strcmp(arg, "rpn"))
2460         queryType = QueryType_Prefix;
2461     else if (!strcmp (arg, "ccl2rpn") || !strcmp (arg, "cclrpn"))
2462         queryType = QueryType_CCL2RPN;
2463     else if (!strcmp(arg, "cql"))
2464         queryType = QueryType_CQL;        
2465     else
2466     {
2467         printf ("Querytype must be one of:\n");
2468         printf (" prefix         - Prefix query\n");
2469         printf (" ccl            - CCL query\n");
2470         printf (" ccl2rpn        - CCL query converted to RPN\n");
2471         printf (" cql            - CQL\n");
2472         return 0;
2473     }
2474     return 1;
2475 }
2476
2477 int cmd_refid (const char *arg)
2478 {
2479     xfree (refid);
2480     refid = NULL;
2481     if (*arg)
2482     {
2483         refid = (char *) xmalloc (strlen(arg)+1);
2484         strcpy (refid, arg);
2485     }
2486     return 1;
2487 }
2488
2489 int cmd_close(const char *arg)
2490 {
2491     Z_APDU *apdu;
2492     Z_Close *req;
2493     if (!conn)
2494         return 0;
2495     if (only_z3950())
2496         return 0;
2497
2498     apdu = zget_APDU(out, Z_APDU_close);
2499     req = apdu->u.close;
2500     *req->closeReason = Z_Close_finished;
2501     send_apdu(apdu);
2502     printf("Sent close request.\n");
2503     sent_close = 1;
2504     return 2;
2505 }
2506
2507 int cmd_packagename(const char* arg)
2508 {
2509     xfree (esPackageName);
2510     esPackageName = NULL;
2511     if (*arg)
2512     {
2513         esPackageName = (char *) xmalloc (strlen(arg)+1);
2514         strcpy (esPackageName, arg);
2515     }
2516     return 1;
2517 }
2518
2519 int cmd_proxy(const char* arg)
2520 {
2521     if (*arg == '\0') {
2522                 xfree (yazProxy);
2523                 yazProxy = NULL;
2524         
2525     }
2526     xfree (yazProxy);
2527     yazProxy = NULL;
2528     if (*arg)
2529     {
2530         yazProxy = (char *) xmalloc (strlen(arg)+1);
2531         strcpy (yazProxy, arg);
2532     } 
2533     return 1;
2534 }
2535
2536 int cmd_charset(const char* arg)
2537 {
2538     char l1[30], l2[30];
2539
2540     *l1 = *l2 = 0;
2541     if (sscanf(arg, "%29s %29s", l1, l2) < 1)
2542     {
2543         printf("Current character set is `%s'\n", (yazCharset) ? yazCharset:NULL);
2544         return 1;
2545     }
2546     xfree (yazCharset);
2547     yazCharset = NULL;
2548     if (*l1)
2549         yazCharset = xstrdup(l1);
2550     if (*l2)
2551     {
2552         odr_set_charset (out, l1, l2);
2553         odr_set_charset (in, l2, l1);
2554     }
2555     return 1;
2556 }
2557
2558 int cmd_lang(const char* arg)
2559 {
2560     if (*arg == '\0') {
2561         printf("Current language is `%s'\n", (yazLang)?yazLang:NULL);
2562         return 1;
2563     }
2564     xfree (yazLang);
2565     yazLang = NULL;
2566     if (*arg)
2567     {
2568         yazLang = (char *) xmalloc (strlen(arg)+1);
2569         strcpy (yazLang, arg);
2570     } 
2571     return 1;
2572 }
2573
2574 int cmd_source(const char* arg) 
2575 {
2576     /* first should open the file and read one line at a time.. */
2577     FILE* includeFile;
2578     char line[1024], *cp;
2579
2580     if(strlen(arg)<1) {
2581         fprintf(stderr,"Error in source command use a filename\n");
2582         return -1;
2583     }
2584     
2585     includeFile = fopen (arg, "r");
2586     
2587     if(!includeFile) {
2588         fprintf(stderr,"Unable to open file %s for reading\n",arg);
2589         return -1;
2590     }
2591     
2592     while(!feof(includeFile)) {
2593         memset(line,0,sizeof(line));
2594         fgets(line,sizeof(line),includeFile);
2595         
2596         if(strlen(line) < 2) continue;
2597         if(line[0] == '#') continue;
2598         
2599         if ((cp = strrchr (line, '\n')))
2600             *cp = '\0';
2601         
2602         process_cmd_line(line);
2603     }
2604     
2605     if(fclose(includeFile)<0) {
2606         perror("unable to close include file");
2607         exit(1);
2608     }
2609     return 1;
2610 }
2611
2612 int cmd_subshell(const char* args)
2613 {
2614     if(strlen(args)) 
2615         system(args);
2616     else 
2617         system(getenv("SHELL"));
2618     
2619     printf("\n");
2620     return 1;
2621 }
2622
2623 int cmd_set_berfile(const char *arg)
2624 {
2625     if (ber_file && ber_file != stdout && ber_file != stderr)
2626         fclose(ber_file);
2627     if (!strcmp(arg, ""))
2628         ber_file = 0;
2629     else if (!strcmp(arg, "-"))
2630         ber_file = stdout;
2631     else
2632         ber_file = fopen(arg, "a");
2633     return 1;
2634 }
2635
2636 int cmd_set_apdufile(const char *arg)
2637 {
2638     if(apdu_file && apdu_file != stderr && apdu_file != stderr)
2639         fclose(apdu_file);
2640     if (!strcmp(arg, ""))
2641         apdu_file = 0;
2642     else if (!strcmp(arg, "-"))
2643         apdu_file = stderr;
2644     else
2645     {
2646         apdu_file = fopen(arg, "a");
2647         if (!apdu_file)
2648             perror("unable to open apdu log file");
2649     }
2650     if (apdu_file)
2651         odr_setprint(print, apdu_file);
2652     return 1;
2653 }
2654
2655 int cmd_set_cclfile(const char* arg)
2656 {  
2657     FILE *inf;
2658
2659     bibset = ccl_qual_mk (); 
2660     inf = fopen (arg, "r");
2661     if (!inf)
2662         perror("unable to open CCL file");
2663     else
2664     {
2665         ccl_qual_file (bibset, inf);
2666         fclose (inf);
2667     }
2668     strcpy(ccl_fields,arg);
2669     return 0;
2670 }
2671
2672 int cmd_set_auto_reconnect(const char* arg)
2673 {  
2674     if(strlen(arg)==0) {
2675         auto_reconnect = ! auto_reconnect;
2676     } else if(strcmp(arg,"on")==0) {
2677         auto_reconnect = 1;
2678     } else if(strcmp(arg,"off")==0) {
2679         auto_reconnect = 0;             
2680     } else {
2681         printf("Error use on or off\n");
2682         return 1;
2683     }
2684     
2685     if (auto_reconnect)
2686         printf("Set auto reconnect enabled.\n");
2687     else
2688         printf("Set auto reconnect disabled.\n");
2689     
2690     return 0;
2691 }
2692
2693 int cmd_set_marcdump(const char* arg)
2694 {
2695     if(marc_file && marc_file != stderr) { /* don't close stdout*/
2696         fclose(marc_file);
2697     }
2698
2699     if (!strcmp(arg, ""))
2700         marc_file = 0;
2701     else if (!strcmp(arg, "-"))
2702         marc_file = stderr;
2703     else
2704     {
2705         marc_file = fopen(arg, "a");
2706         if (!marc_file)
2707             perror("unable to open marc log file");
2708     }
2709     return 1;
2710 }
2711
2712 int cmd_set_proxy(const char* arg)
2713 {
2714     if(yazProxy) free(yazProxy);
2715     yazProxy=NULL;
2716     
2717     if(strlen(arg) > 1) {
2718         yazProxy=strdup(arg);
2719     }
2720     return 1;
2721 }
2722
2723 /* 
2724    this command takes 3 arge {name class oid} 
2725 */
2726 int cmd_register_oid(const char* args) {
2727     static struct {
2728         char* className;
2729         oid_class oclass;
2730     } oid_classes[] = {
2731         {"appctx",CLASS_APPCTX},
2732         {"absyn",CLASS_ABSYN},
2733         {"attset",CLASS_ATTSET},
2734         {"transyn",CLASS_TRANSYN},
2735         {"diagset",CLASS_DIAGSET},
2736         {"recsyn",CLASS_RECSYN},
2737         {"resform",CLASS_RESFORM},
2738         {"accform",CLASS_ACCFORM},
2739         {"extserv",CLASS_EXTSERV},
2740         {"userinfo",CLASS_USERINFO},
2741         {"elemspec",CLASS_ELEMSPEC},
2742         {"varset",CLASS_VARSET},
2743         {"schema",CLASS_SCHEMA},
2744         {"tagset",CLASS_TAGSET},
2745         {"general",CLASS_GENERAL},
2746         {0,(enum oid_class) 0}
2747     };
2748     char oname_str[101], oclass_str[101], oid_str[101];  
2749     char* name;
2750     int i;
2751     oid_class oidclass = CLASS_GENERAL;
2752     int val = 0, oid[OID_SIZE];
2753     struct oident * new_oident=NULL;
2754     
2755     if (sscanf (args, "%100[^ ] %100[^ ] %100s",
2756                 oname_str,oclass_str, oid_str) < 1) {
2757         printf("Error in regristrate command \n");
2758         return 0;
2759     }
2760     
2761     for (i = 0; oid_classes[i].className; i++) {
2762         if (!strcmp(oid_classes[i].className, oclass_str))
2763         {
2764             oidclass=oid_classes[i].oclass;
2765             break;
2766         }
2767     }
2768     
2769     if(!(oid_classes[i].className)) {
2770         printf("Unknonwn oid class %s\n",oclass_str);
2771         return 0;
2772     }
2773     
2774     i = 0;
2775     name = oid_str;
2776     val = 0;
2777     
2778     while (isdigit (*name))
2779     {
2780         val = val*10 + (*name - '0');
2781         name++;
2782         if (*name == '.')
2783         {
2784             if (i < OID_SIZE-1)
2785                 oid[i++] = val;
2786             val = 0;
2787             name++;
2788         }
2789     }
2790     oid[i] = val;
2791     oid[i+1] = -1;
2792     
2793     new_oident=oid_addent (oid,PROTO_GENERAL,oidclass,oname_str,VAL_DYNAMIC);  
2794     if(strcmp(new_oident->desc,oname_str)) {
2795         fprintf(stderr,"oid is already named as %s, regristration faild\n",
2796                 new_oident->desc);
2797     }
2798     return 1;  
2799 }
2800
2801 int cmd_push_command(const char* arg) 
2802 {
2803 #if HAVE_READLINE_HISTORY_H
2804     if(strlen(arg)>1) 
2805         add_history(arg);
2806 #else 
2807     fprintf(stderr,"Not compiled with the readline/history module\n");
2808 #endif
2809     return 1;
2810 }
2811
2812 void source_rcfile() 
2813 {
2814     /*  Look for a $HOME/.yazclientrc and source it if it exists */
2815     struct stat statbuf;
2816     char buffer[1000];
2817     char* homedir=getenv("HOME");
2818     
2819     if(!homedir) return;
2820     
2821     sprintf(buffer,"%s/.yazclientrc",homedir);
2822     
2823     if(stat(buffer,&statbuf)==0) {
2824         cmd_source(buffer);
2825     }
2826     
2827     if(stat(".yazclientrc",&statbuf)==0) {
2828         cmd_source(".yazclientrc");
2829     }
2830 }
2831
2832
2833 static void initialize(void)
2834 {
2835     FILE *inf;
2836     int i;
2837     
2838     if (!(out = odr_createmem(ODR_ENCODE)) ||
2839         !(in = odr_createmem(ODR_DECODE)) ||
2840         !(print = odr_createmem(ODR_PRINT)))
2841     {
2842         fprintf(stderr, "failed to allocate ODR streams\n");
2843         exit(1);
2844     }
2845     oid_init();
2846     
2847     setvbuf(stdout, 0, _IONBF, 0);
2848     if (apdu_file)
2849         odr_setprint(print, apdu_file);
2850
2851     bibset = ccl_qual_mk (); 
2852     inf = fopen (ccl_fields, "r");
2853     if (inf)
2854     {
2855         ccl_qual_file (bibset, inf);
2856         fclose (inf);
2857     }
2858     cmd_base("Default");
2859
2860 #if HAVE_READLINE_READLINE_H
2861     rl_attempted_completion_function = (CPPFunction*)readline_completer;
2862 #endif
2863     
2864     
2865     for(i=0; i<maxOtherInfosSupported; ++i) {
2866         extraOtherInfos[i].oidval = -1;
2867     }
2868     
2869     source_rcfile();
2870 }
2871
2872
2873 #if HAVE_GETTIMEOFDAY
2874 struct timeval tv_start, tv_end;
2875 #endif
2876
2877 #if HAVE_XML2
2878 static void handle_srw_response(Z_SRW_searchRetrieveResponse *res)
2879 {
2880     int i;
2881
2882     printf ("Received SRW SearchRetrieveResponse\n");
2883     
2884     for (i = 0; i<res->num_diagnostics; i++)
2885     {
2886         printf ("SRW diagnostic %d %s\nDetails: %s\n",
2887                 *res->diagnostics[i].code,
2888                 yaz_diag_srw_str(*res->diagnostics[i].code),
2889                 res->diagnostics[i].details);
2890     }
2891     if (res->numberOfRecords)
2892         printf ("Number of hits: %d\n", *res->numberOfRecords);
2893     for (i = 0; i<res->num_records; i++)
2894     {
2895         int pos;
2896         Z_SRW_record *rec = res->records + i;
2897
2898         if (rec->recordPosition)
2899         {
2900             printf ("pos=%d", *rec->recordPosition);
2901             setno = *rec->recordPosition + 1;
2902         }
2903         if (rec->recordSchema)
2904             printf (" scheam=%d", *rec->recordSchema);
2905         printf ("\n");
2906         if (rec->recordData_buf && rec->recordData_len)
2907         {
2908             fwrite(rec->recordData_buf, 1, rec->recordData_len, stdout);
2909             printf ("\n");
2910         }
2911     }
2912 }
2913
2914 static void set_HTTP_error (int error,
2915                             const char *addinfo, const char *addinfo2)
2916 {
2917
2918
2919 }
2920
2921
2922 static void http_response(Z_HTTP_Response *hres)
2923 {
2924     int ret = -1;
2925     const char *content_type = z_HTTP_header_lookup(hres->headers,
2926                                                     "Content-Type");
2927     const char *connection_head = z_HTTP_header_lookup(hres->headers,
2928                                                        "Connection");
2929     yaz_log (LOG_LOG, "http_response");
2930
2931     if (content_type && !yaz_strcmp_del("text/xml", content_type, "; "))
2932     {
2933         Z_SOAP *soap_package = 0;
2934         ODR o = odr_createmem(ODR_DECODE);
2935         Z_SOAP_Handler soap_handlers[2] = {
2936             {"http://www.loc.gov/zing/srw/v1.0/", 0,
2937              (Z_SOAP_fun) yaz_srw_codec},
2938             {0, 0, 0}
2939         };
2940         ret = z_soap_codec(o, &soap_package,
2941                            &hres->content_buf, &hres->content_len,
2942                            soap_handlers);
2943         if (!ret && soap_package->which == Z_SOAP_generic &&
2944             soap_package->u.generic->no == 0)
2945         {
2946             Z_SRW_PDU *sr = soap_package->u.generic->p;
2947             if (sr->which == Z_SRW_searchRetrieve_response)
2948                 handle_srw_response(sr->u.response);
2949             else
2950                 ret = -1;
2951         }
2952         else if (!ret && (soap_package->which == Z_SOAP_fault
2953                           || soap_package->which == Z_SOAP_error))
2954         {
2955             printf ("HTTP Error Status=%d\n", hres->code);
2956             printf ("SOAP Fault code %s\n",
2957                     soap_package->u.fault->fault_code);
2958             printf ("SOAP Fault string %s\n", 
2959                     soap_package->u.fault->fault_string);
2960         }
2961         else
2962             ret = -1;
2963         odr_destroy(o);
2964     }
2965     if (ret)
2966     {
2967         if (hres->code != 200)
2968             set_HTTP_error(hres->code, 0, 0);
2969         else
2970         {
2971             printf ("decoding of SRW package failed\n");
2972         }
2973         close_session();
2974     }
2975     if (!strcmp(hres->version, "1.0"))
2976     {
2977         /* HTTP 1.0: only if Keep-Alive we stay alive.. */
2978         if (!connection_head || strcmp(connection_head, "Keep-Alive"))
2979             close_session();
2980     }
2981     else 
2982     {
2983         /* HTTP 1.1: only if no close we stay alive .. */
2984         if (connection_head && !strcmp(connection_head, "close"))
2985             close_session();
2986     }
2987 }
2988 #endif
2989
2990 void wait_and_handle_response() 
2991 {
2992     int reconnect_ok = 1;
2993     int res;
2994     char *netbuffer= 0;
2995     int netbufferlen = 0;
2996     Z_GDU *gdu;
2997     
2998     while(conn)
2999     {
3000         printf ("cs_get....\n");
3001         res = cs_get(conn, &netbuffer, &netbufferlen);
3002         if (reconnect_ok && res <= 0 && conn->protocol == PROTO_HTTP)
3003         {
3004             cs_close(conn);
3005             conn = 0;
3006             cmd_open(0);
3007             reconnect_ok = 0;
3008             if (conn)
3009             {
3010                 char *buf_out;
3011                 int len_out;
3012                 
3013                 buf_out = odr_getbuf(out, &len_out, 0);
3014                 
3015                 cs_put(conn, buf_out, len_out);
3016                 
3017                 odr_reset(out);
3018                 continue;
3019             }
3020         }
3021         else if (res <= 0)
3022         {
3023             printf("Target closed connection\n");
3024             close_session();
3025             break;
3026         }
3027         odr_reset(out);
3028         odr_reset(in); /* release APDU from last round */
3029         record_last = 0;
3030         odr_setbuf(in, netbuffer, res, 0);
3031         
3032         printf ("got input packet %d bytes\n", res);
3033         if (!z_GDU(in, &gdu, 0, 0))
3034         {
3035             FILE *f = ber_file ? ber_file : stdout;
3036             odr_perror(in, "Decoding incoming APDU");
3037             fprintf(f, "[Near %d]\n", odr_offset(in));
3038             fprintf(f, "Packet dump:\n---------\n");
3039             odr_dumpBER(f, netbuffer, res);
3040             fprintf(f, "---------\n");
3041             if (apdu_file)
3042                 z_GDU(print, &gdu, 0, 0);
3043             close_session ();
3044             break;
3045         }
3046         if (ber_file)
3047             odr_dumpBER(ber_file, netbuffer, res);
3048         if (apdu_file && !z_GDU(print, &gdu, 0, 0))
3049         {
3050             odr_perror(print, "Failed to print incoming APDU");
3051             odr_reset(print);
3052                 continue;
3053         }
3054         if (gdu->which == Z_GDU_Z3950)
3055         {
3056             Z_APDU *apdu = gdu->u.z3950;
3057             switch(apdu->which)
3058             {
3059             case Z_APDU_initResponse:
3060                 process_initResponse(apdu->u.initResponse);
3061                 break;
3062             case Z_APDU_searchResponse:
3063                 process_searchResponse(apdu->u.searchResponse);
3064                 break;
3065             case Z_APDU_scanResponse:
3066                 process_scanResponse(apdu->u.scanResponse);
3067                 break;
3068             case Z_APDU_presentResponse:
3069                 print_refid (apdu->u.presentResponse->referenceId);
3070                 setno +=
3071                     *apdu->u.presentResponse->numberOfRecordsReturned;
3072                 if (apdu->u.presentResponse->records)
3073                     display_records(apdu->u.presentResponse->records);
3074                 else
3075                     printf("No records.\n");
3076                 printf ("nextResultSetPosition = %d\n",
3077                         *apdu->u.presentResponse->nextResultSetPosition);
3078                 break;
3079             case Z_APDU_sortResponse:
3080                 process_sortResponse(apdu->u.sortResponse);
3081                 break;
3082             case Z_APDU_extendedServicesResponse:
3083                 printf("Got extended services response\n");
3084                 process_ESResponse(apdu->u.extendedServicesResponse);
3085                 break;
3086             case Z_APDU_close:
3087                 printf("Target has closed the association.\n");
3088                 process_close(apdu->u.close);
3089                 break;
3090             case Z_APDU_resourceControlRequest:
3091                 process_resourceControlRequest
3092                     (apdu->u.resourceControlRequest);
3093                 break;
3094             case Z_APDU_deleteResultSetResponse:
3095                 process_deleteResultSetResponse(apdu->u.
3096                                                 deleteResultSetResponse);
3097                 break;
3098             default:
3099                 printf("Received unknown APDU type (%d).\n", 
3100                        apdu->which);
3101                 close_session ();
3102             }
3103         }
3104 #if HAVE_XML2
3105         else if (gdu->which == Z_GDU_HTTP_Response)
3106         {
3107             http_response(gdu->u.HTTP_Response);
3108         }
3109 #endif
3110         if (conn && !cs_more(conn))
3111             break;
3112     }
3113     if (conn)
3114     {
3115 #if HAVE_GETTIMEOFDAY
3116         gettimeofday (&tv_end, 0);
3117 #if 0
3118         printf ("S/U S/U=%ld/%ld %ld/%ld",
3119                 (long) tv_start.tv_sec,
3120                 (long) tv_start.tv_usec,
3121                 (long) tv_end.tv_sec,
3122                 (long) tv_end.tv_usec);
3123 #endif
3124         printf ("Elapsed: %.6f\n",
3125                 (double) tv_end.tv_usec / 1e6 + tv_end.tv_sec -
3126                 ((double) tv_start.tv_usec / 1e6 + tv_start.tv_sec));
3127 #endif
3128     }
3129     xfree (netbuffer);
3130 }
3131
3132
3133 int cmd_cclparse(const char* arg) 
3134 {
3135     int error, pos;
3136     struct ccl_rpn_node *rpn=NULL;
3137     
3138     
3139     rpn = ccl_find_str (bibset, arg, &error, &pos);
3140     
3141     if (error) {
3142         printf ("%*s^ - ", 3+strlen(last_cmd)+1+pos, " ");
3143         printf ("%s\n", ccl_err_msg (error));
3144     }
3145     else
3146     {
3147         if (rpn)
3148         {       
3149             ccl_pr_tree(rpn, stdout); 
3150         }
3151     }
3152     if (rpn)
3153         ccl_rpn_delete(rpn);
3154     
3155     printf ("\n");
3156     
3157     return 0;
3158 }
3159
3160
3161 int cmd_set_otherinfo(const char* args)
3162 {
3163     char oid[101], otherinfoString[101];
3164     int otherinfoNo;
3165     int sscan_res;
3166     int oidval;
3167     
3168     sscan_res = sscanf (args, "%d %100[^ ] %100s", &otherinfoNo, oid, otherinfoString);
3169     if(sscan_res==1) {
3170         /* reset this otherinfo */
3171         if(otherinfoNo>=maxOtherInfosSupported) {
3172             printf("Error otherinfo index to large (%d>%d)\n",otherinfoNo,maxOtherInfosSupported);
3173         }
3174         extraOtherInfos[otherinfoNo].oidval = -1;
3175         if(extraOtherInfos[otherinfoNo].value) free(extraOtherInfos[otherinfoNo].value);                        
3176         return 0;
3177     }
3178     if (sscan_res<3) {
3179         printf("Error in set_otherinfo command \n");
3180         return 0;
3181     }
3182     
3183     if(otherinfoNo>=maxOtherInfosSupported) {
3184         printf("Error otherinfo index to large (%d>%d)\n",otherinfoNo,maxOtherInfosSupported);
3185     }
3186     
3187     
3188     oidval = oid_getvalbyname (oid);
3189     if(oidval == -1 ) {
3190         printf("Error in set_otherinfo command unknown oid %s \n",oid);
3191         return 0;
3192     }
3193     extraOtherInfos[otherinfoNo].oidval = oidval;
3194     if(extraOtherInfos[otherinfoNo].value) free(extraOtherInfos[otherinfoNo].value);
3195     extraOtherInfos[otherinfoNo].value = strdup(otherinfoString);
3196     
3197     return 0;
3198 }
3199
3200 int cmd_list_otherinfo(const char* args)
3201 {
3202     int i;         
3203     
3204     if(strlen(args)>0) {
3205         i = atoi(args);
3206         if( i >= maxOtherInfosSupported ) {
3207             printf("Error otherinfo index to large (%d>%d)\n",i,maxOtherInfosSupported);
3208             return 0;
3209         }
3210
3211         if(extraOtherInfos[i].oidval != -1) 
3212             printf("  otherinfo %d %s %s\n",
3213                    i,
3214                    yaz_z3950_oid_value_to_str(
3215                        (enum oid_value) extraOtherInfos[i].oidval,
3216                        CLASS_RECSYN),
3217                    extraOtherInfos[i].value);
3218         
3219     } else {            
3220         for(i=0; i<maxOtherInfosSupported; ++i) {
3221             if(extraOtherInfos[i].oidval != -1) 
3222                 printf("  otherinfo %d %s %s\n",
3223                        i,
3224                        yaz_z3950_oid_value_to_str(
3225                            (enum oid_value) extraOtherInfos[i].oidval,
3226                            CLASS_RECSYN),
3227                        extraOtherInfos[i].value);
3228         }
3229         
3230     }
3231     return 0;
3232 }
3233
3234
3235 int cmd_list_all(const char* args) {
3236     int i;
3237     
3238     /* connection options */
3239     if(conn) {
3240         printf("Connected to         : %s\n",last_open_command);
3241     } else {
3242         if(last_open_command) 
3243             printf("Not connected to     : %s\n",last_open_command);
3244         else 
3245             printf("Not connected        : \n");
3246         
3247     }
3248     if(yazProxy) printf("using proxy          : %s\n",yazProxy);                
3249     
3250     printf("auto_reconnect       : %s\n",auto_reconnect?"on":"off");
3251     
3252     if (!auth) {
3253         printf("Authentication       : none\n");
3254     } else {
3255         switch(auth->which) {
3256         case Z_IdAuthentication_idPass:
3257             printf("Authentication       : IdPass\n"); 
3258             printf("    Login User       : %s\n",auth->u.idPass->userId?auth->u.idPass->userId:"");
3259             printf("    Login Group      : %s\n",auth->u.idPass->groupId?auth->u.idPass->groupId:"");
3260             printf("    Password         : %s\n",auth->u.idPass->password?auth->u.idPass->password:"");
3261             break;
3262         case Z_IdAuthentication_open:
3263             printf("Authentication       : psOpen\n");                  
3264             printf("    Open string      : %s\n",auth->u.open); 
3265             break;
3266         default:
3267             printf("Authentication       : Unknown\n");
3268         }
3269     }
3270     if ( yazCharset ) printf("Character set        : `%s'\n", (yazCharset) ? yazCharset:NULL);
3271     
3272     /* bases */
3273     printf("Bases                : ");
3274     for (i = 0; i<num_databaseNames; i++) printf("%s ",databaseNames[i]);
3275     printf("\n");
3276     
3277     /* Query options */
3278     printf("CCL file             : %s\n",ccl_fields);
3279     printf("Query type           : %s\n",query_type_as_string(queryType));
3280     
3281     printf("Named Result Sets    : %s\n",setnumber==-1?"off":"on");
3282     
3283     /* piggy back options */
3284     printf("ssub/lslb/mspn       : %d/%d/%d\n",smallSetUpperBound,largeSetLowerBound,mediumSetPresentNumber);
3285     
3286     /* print present related options */
3287     printf("Format               : %s\n",yaz_z3950_oid_value_to_str(recordsyntax,CLASS_RECSYN));
3288     printf("Schema               : %s\n",schema);
3289     printf("Elements             : %s\n",elementSetNames?elementSetNames->u.generic:"");
3290     
3291     /* loging options */
3292     printf("APDU log             : %s\n",apdu_file?"on":"off");
3293     printf("Record log           : %s\n",marc_file?"on":"off");
3294     
3295     /* other infos */
3296     printf("Other Info: \n");
3297     cmd_list_otherinfo("");
3298     
3299     return 0;
3300 }
3301
3302 int cmd_clear_otherinfo(const char* args) 
3303 {
3304     if(strlen(args)>0) {
3305         int otherinfoNo;
3306         otherinfoNo = atoi(args);
3307         if( otherinfoNo >= maxOtherInfosSupported ) {
3308             printf("Error otherinfo index to large (%d>%d)\n",otherinfoNo,maxOtherInfosSupported);
3309             return 0;
3310         }
3311         
3312         if(extraOtherInfos[otherinfoNo].oidval != -1) {                 
3313             /* only clear if set. */
3314             extraOtherInfos[otherinfoNo].oidval=-1;
3315             free(extraOtherInfos[otherinfoNo].value);
3316         }
3317     } else {
3318         int i;
3319         
3320         for(i=0; i<maxOtherInfosSupported; ++i) {
3321             if (extraOtherInfos[i].oidval!=-1 ) {                               
3322                 extraOtherInfos[i].oidval=-1;
3323                 free(extraOtherInfos[i].value);
3324             }
3325         }
3326     }
3327     return 0;
3328 }
3329
3330 static int cmd_help (const char *line);
3331
3332 typedef char *(*completerFunctionType)(const char *text, int state);
3333
3334 static struct {
3335     char *cmd;
3336     int (*fun)(const char *arg);
3337     char *ad;
3338         completerFunctionType rl_completerfunction;
3339     int complete_filenames;
3340     char **local_tabcompletes;
3341 } cmd_array[] = {
3342     {"open", cmd_open, "('tcp'|'ssl')':<host>[':'<port>][/<db>]",NULL,0,NULL},
3343     {"quit", cmd_quit, "",NULL,0,NULL},
3344     {"find", cmd_find, "<query>",NULL,0,NULL},
3345     {"delete", cmd_delete, "<setname>",NULL,0,NULL},
3346     {"base", cmd_base, "<base-name>",NULL,0,NULL},
3347     {"show", cmd_show, "<rec#>['+'<#recs>['+'<setname>]]",NULL,0,NULL},
3348     {"scan", cmd_scan, "<term>",NULL,0,NULL},
3349     {"sort", cmd_sort, "<sortkey> <flag> <sortkey> <flag> ...",NULL,0,NULL},
3350     {"sort+", cmd_sort_newset, "<sortkey> <flag> <sortkey> <flag> ...",NULL,0,NULL},
3351     {"authentication", cmd_authentication, "<acctstring>",NULL,0,NULL},
3352     {"lslb", cmd_lslb, "<largeSetLowerBound>",NULL,0,NULL},
3353     {"ssub", cmd_ssub, "<smallSetUpperBound>",NULL,0,NULL},
3354     {"mspn", cmd_mspn, "<mediumSetPresentNumber>",NULL,0,NULL},
3355     {"status", cmd_status, "",NULL,0,NULL},
3356     {"setnames", cmd_setnames, "",NULL,0,NULL},
3357     {"cancel", cmd_cancel, "",NULL,0,NULL},
3358     {"format", cmd_format, "<recordsyntax>",complete_format,0,NULL},
3359     {"schema", cmd_schema, "<schema>",complete_schema,0,NULL},
3360     {"elements", cmd_elements, "<elementSetName>",NULL,0,NULL},
3361     {"close", cmd_close, "",NULL,0,NULL},
3362     {"attributeset", cmd_attributeset, "<attrset>",complete_attributeset,0,NULL},
3363     {"querytype", cmd_querytype, "<type>",complete_querytype,0,NULL},
3364     {"refid", cmd_refid, "<id>",NULL,0,NULL},
3365     {"itemorder", cmd_itemorder, "ill|item <itemno>",NULL,0,NULL},
3366     {"update", cmd_update, "<action> <recid> [<file>]",NULL,0,NULL},
3367     {"packagename", cmd_packagename, "<packagename>",NULL,0,NULL},
3368     {"proxy", cmd_proxy, "[('tcp'|'ssl')]<host>[':'<port>]",NULL,0,NULL},
3369     {"charset", cmd_charset, "<charset_name>",NULL,0,NULL},
3370     {"lang", cmd_lang, "<language_code>",NULL,0,NULL},
3371     {".", cmd_source, "<filename>",NULL,1,NULL},
3372     {"!", cmd_subshell, "Subshell command",NULL,1,NULL},
3373     {"set_apdufile", cmd_set_apdufile, "<filename>",NULL,1,NULL},
3374     {"set_berfile", cmd_set_berfile, "<filename>",NULL,1,NULL},
3375     {"set_marcdump", cmd_set_marcdump," <filename>",NULL,1,NULL},
3376     {"set_cclfile", cmd_set_cclfile," <filename>",NULL,1,NULL},
3377     {"set_auto_reconnect", cmd_set_auto_reconnect," on|off",complete_auto_reconnect,1,NULL},
3378         {"set_otherinfo", cmd_set_otherinfo,"<otherinfoinddex> <oid> <string>",NULL,0,NULL},
3379     {"register_oid", cmd_register_oid,"<name> <class> <oid>",NULL,0,NULL},
3380     {"push_command", cmd_push_command,"<command>",command_generator,0,NULL},
3381     {"register_tab", cmd_register_tab,"<commandname> <tab>",command_generator,0,NULL},
3382     {"cclparse", cmd_cclparse,"<ccl find command>",NULL,0,NULL},
3383     {"list_otherinfo",cmd_list_otherinfo,"[otherinfoinddex]",NULL,0,NULL},
3384     {"list_all",cmd_list_all,"",NULL,0,NULL},
3385     {"clear_otherinfo",cmd_clear_otherinfo,"",NULL,0,NULL},
3386     /* Server Admin Functions */
3387     {"adm-reindex", cmd_adm_reindex, "<database-name>",NULL,0,NULL},
3388     {"adm-truncate", cmd_adm_truncate, "('database'|'index')<object-name>",NULL,0,NULL},
3389     {"adm-create", cmd_adm_create, "",NULL,0,NULL},
3390     {"adm-drop", cmd_adm_drop, "('database'|'index')<object-name>",NULL,0,NULL},
3391     {"adm-import", cmd_adm_import, "<record-type> <dir> <pattern>",NULL,0,NULL},
3392     {"adm-refresh", cmd_adm_refresh, "",NULL,0,NULL},
3393     {"adm-commit", cmd_adm_commit, "",NULL,0,NULL},
3394     {"adm-shutdown", cmd_adm_shutdown, "",NULL,0,NULL},
3395     {"adm-startup", cmd_adm_startup, "",NULL,0,NULL},
3396     {"help", cmd_help, "", NULL,0,NULL},
3397     {0,0,0,0,0,0}
3398 };
3399
3400 static int cmd_help (const char *line)
3401 {
3402     int i;
3403     char topic[21];
3404     
3405     *topic = 0;
3406     sscanf (line, "%20s", topic);
3407
3408     if (*topic == 0)
3409         printf("Commands:\n");
3410     for (i = 0; cmd_array[i].cmd; i++)
3411         if (*topic == 0 || strcmp (topic, cmd_array[i].cmd) == 0)
3412             printf("   %s %s\n", cmd_array[i].cmd, cmd_array[i].ad);
3413     if (strcmp (topic, "find") == 0)
3414     {
3415         printf ("RPN:\n");
3416         printf (" \"term\"                        Simple Term\n");
3417         printf (" @attr [attset] type=value op  Attribute\n");
3418         printf (" @and opl opr                  And\n");
3419         printf (" @or opl opr                   Or\n");
3420         printf (" @not opl opr                  And-Not\n");
3421         printf (" @set set                      Result set\n");
3422         printf ("\n");
3423         printf ("Bib-1 attribute types\n");
3424         printf ("1=Use:         ");
3425         printf ("4=Title 7=ISBN 8=ISSN 30=Date 62=Abstract 1003=Author 1016=Any\n");
3426         printf ("2=Relation:    ");
3427         printf ("1<   2<=  3=  4>=  5>  6!=  102=Relevance\n");
3428         printf ("3=Position:    ");
3429         printf ("1=First in Field  2=First in subfield  3=Any position\n");
3430         printf ("4=Structure:   ");
3431         printf ("1=Phrase  2=Word  3=Key  4=Year  5=Date  6=WordList\n");
3432         printf ("5=Truncation:  ");
3433         printf ("1=Right  2=Left  3=L&R  100=No  101=#  102=Re-1  103=Re-2\n");
3434         printf ("6=Completeness:");
3435         printf ("1=Incomplete subfield  2=Complete subfield  3=Complete field\n");
3436     }
3437     return 1;
3438 }
3439
3440 int cmd_register_tab(const char* arg) {
3441         
3442     char command[101], tabargument[101];
3443     int i;
3444     int num_of_tabs;
3445     char** tabslist;
3446     
3447     if (sscanf (arg, "%100s %100s", command, tabargument) < 1) {
3448         return 0;
3449     }
3450     
3451     /* locate the amdn in the list */
3452     for (i = 0; cmd_array[i].cmd; i++) {
3453         if (!strncmp(cmd_array[i].cmd, command, strlen(command))) {
3454             break;
3455         }
3456     }
3457     
3458     if(!cmd_array[i].cmd) { 
3459         fprintf(stderr,"Unknown command %s\n",command);
3460         return 1;
3461     }
3462     
3463         
3464     if(!cmd_array[i].local_tabcompletes)
3465         cmd_array[i].local_tabcompletes = (char **) calloc(1,sizeof(char**));
3466     
3467     num_of_tabs=0;              
3468     
3469     tabslist = cmd_array[i].local_tabcompletes;
3470     for(;tabslist && *tabslist;tabslist++) {
3471         num_of_tabs++;
3472     }
3473     
3474     cmd_array[i].local_tabcompletes =  (char **)
3475         realloc(cmd_array[i].local_tabcompletes,(num_of_tabs+2)*sizeof(char**));
3476     tabslist=cmd_array[i].local_tabcompletes;
3477     tabslist[num_of_tabs]=strdup(tabargument);
3478     tabslist[num_of_tabs+1]=NULL;
3479     return 1;
3480 }
3481
3482
3483 void process_cmd_line(char* line)
3484 {  
3485     int i,res;
3486     char word[32], arg[1024];
3487     
3488 #if HAVE_GETTIMEOFDAY
3489     gettimeofday (&tv_start, 0);
3490 #endif
3491     
3492     if ((res = sscanf(line, "%31s %1023[^;]", word, arg)) <= 0)
3493     {
3494         strcpy(word, last_cmd);
3495         *arg = '\0';
3496     }
3497     else if (res == 1)
3498         *arg = 0;
3499     strcpy(last_cmd, word);
3500     
3501     /* removed tailing spaces from the arg command */
3502     { 
3503         char* p = arg;
3504         char* lastnonspace=NULL;
3505         
3506         for(;*p; ++p) {
3507             if(!isspace(*p)) {
3508                 lastnonspace = p;
3509             }
3510         }
3511         if(lastnonspace) 
3512             *(++lastnonspace) = 0;
3513     }
3514     
3515     for (i = 0; cmd_array[i].cmd; i++)
3516         if (!strncmp(cmd_array[i].cmd, word, strlen(word)))
3517         {
3518             res = (*cmd_array[i].fun)(arg);
3519             break;
3520         }
3521     
3522     if (!cmd_array[i].cmd) /* dump our help-screen */
3523     {
3524         printf("Unknown command: %s.\n", word);
3525         printf("use help for list of commands\n");
3526         /* cmd_help (""); */
3527         res = 1;
3528     }
3529     
3530     if(apdu_file) fflush(apdu_file);
3531     
3532     if (res >= 2)
3533         wait_and_handle_response();
3534     
3535     if(apdu_file)
3536         fflush(apdu_file);
3537     if(marc_file)
3538         fflush(marc_file);
3539 }
3540
3541
3542 char *command_generator(const char *text, int state) 
3543 {
3544     static int idx; 
3545     if (state==0) {
3546         idx = 0;
3547     }
3548     for( ; cmd_array[idx].cmd; ++idx) {
3549         if (!strncmp(cmd_array[idx].cmd,text,strlen(text))) {
3550             ++idx;  /* skip this entry on the next run */
3551             return strdup(cmd_array[idx-1].cmd);
3552         }
3553     }
3554     return NULL;
3555 }
3556
3557
3558 /* 
3559    This function only known how to complete on the first word
3560 */
3561 char ** readline_completer(char *text, int start, int end) {
3562 #if HAVE_READLINE_READLINE_H
3563
3564         completerFunctionType completerToUse;
3565         
3566     if(start == 0) {
3567 #if HAVE_READLINE_RL_COMPLETION_MATCHES
3568         char** res=rl_completion_matches(text,
3569                                       command_generator); 
3570 #else
3571         char** res=completion_matches(text,
3572                                       (CPFunction*)command_generator); 
3573 #endif
3574         rl_attempted_completion_over = 1;
3575         return res;
3576     } else {
3577         char arg[1024],word[32];
3578         int i=0 ,res;
3579         if ((res = sscanf(rl_line_buffer, "%31s %1023[^;]", word, arg)) <= 0) {     
3580             rl_attempted_completion_over = 1;
3581             return NULL;
3582         }
3583         
3584         for (i = 0; cmd_array[i].cmd; i++) {
3585             if (!strncmp(cmd_array[i].cmd, word, strlen(word))) {
3586                 break;
3587             }
3588         }
3589         
3590         if(!cmd_array[i].cmd) return NULL;
3591         
3592         curret_global_list = cmd_array[i].local_tabcompletes;
3593         
3594         completerToUse = cmd_array[i].rl_completerfunction;
3595         if(completerToUse==NULL)  /* if no pr. command completer is defined use the default completer */
3596             completerToUse = default_completer;
3597         
3598         if(completerToUse) {
3599 #ifdef HAVE_READLINE_RL_COMPLETION_MATCHES
3600             char** res=
3601                 rl_completion_matches(text,
3602                                       completerToUse);
3603 #else
3604             char** res=
3605                 completion_matches(text,
3606                                    (CPFunction*)completerToUse);
3607 #endif
3608             if(!cmd_array[i].complete_filenames) 
3609                 rl_attempted_completion_over = 1;
3610             return res;
3611         } else {
3612             if(!cmd_array[i].complete_filenames) 
3613                 rl_attempted_completion_over = 1;
3614             return 0;
3615         }
3616     }
3617 #else 
3618     return 0;
3619 #endif 
3620 }
3621
3622
3623 static void client(void)
3624 {
3625     char line[1024];
3626
3627     line[1023] = '\0';
3628
3629 #if HAVE_GETTIMEOFDAY
3630     gettimeofday (&tv_start, 0);
3631 #endif
3632
3633     while (1)
3634     {
3635         char *line_in = NULL;
3636 #if HAVE_READLINE_READLINE_H
3637         if (isatty(0))
3638         {
3639             line_in=readline(C_PROMPT);
3640             if (!line_in)
3641                 break;
3642 #if HAVE_READLINE_HISTORY_H
3643             if (*line_in)
3644                 add_history(line_in);
3645 #endif
3646             strncpy(line, line_in, 1023);
3647             free (line_in);
3648         }
3649 #endif 
3650         if (!line_in)
3651         {
3652             char *end_p;
3653             printf (C_PROMPT);
3654             fflush(stdout);
3655             if (!fgets(line, 1023, stdin))
3656                 break;
3657             if ((end_p = strchr (line, '\n')))
3658                 *end_p = '\0';
3659         }
3660         process_cmd_line(line);
3661     }
3662 }
3663
3664 int main(int argc, char **argv)
3665 {
3666     char *prog = *argv;
3667     char *open_command = 0;
3668     char *auth_command = 0;
3669     char *arg;
3670     int ret;
3671     
3672 #if HAVE_LOCALE_H
3673     if (!setlocale(LC_CTYPE, ""))
3674         fprintf (stderr, "setlocale failed\n");
3675 #endif
3676 #if HAVE_LANGINFO_H
3677 #ifdef CODESET
3678     codeset = nl_langinfo(CODESET);
3679 #endif
3680 #endif
3681
3682     while ((ret = options("k:c:a:b:m:v:p:u:t:", argv, argc, &arg)) != -2)
3683     {
3684         switch (ret)
3685         {
3686         case 0:
3687             if (!open_command)
3688             {
3689                 open_command = (char *) xmalloc (strlen(arg)+6);
3690                 strcpy (open_command, "open ");
3691                 strcat (open_command, arg);
3692             }
3693             break;
3694         case 'k':
3695             kilobytes = atoi(arg);
3696             break;
3697         case 'm':
3698             if (!(marc_file = fopen (arg, "a")))
3699             {
3700                 perror (arg);
3701                 exit (1);
3702             }
3703             break;
3704         case 't':
3705             codeset = arg;
3706             break;
3707         case 'c':
3708             strncpy (ccl_fields, arg, sizeof(ccl_fields)-1);
3709             ccl_fields[sizeof(ccl_fields)-1] = '\0';
3710             break;
3711         case 'b':
3712             if (!strcmp(arg, "-"))
3713                 ber_file=stderr;
3714             else
3715                 ber_file=fopen(arg, "a");
3716             break;
3717         case 'a':
3718             if (!strcmp(arg, "-"))
3719                 apdu_file=stderr;
3720             else
3721                 apdu_file=fopen(arg, "a");
3722             break;
3723         case 'p':
3724             yazProxy=strdup(arg);
3725             break;
3726         case 'u':
3727             if (!auth_command)
3728             {
3729                 auth_command = (char *) xmalloc (strlen(arg)+6);
3730                 strcpy (auth_command, "auth ");
3731                 strcat (auth_command, arg);
3732             }
3733             break;
3734         case 'v':
3735             yaz_log_init (yaz_log_mask_str(arg), "", NULL);
3736             break;
3737         default:
3738             fprintf (stderr, "Usage: %s [-m <marclog>] [ -a <apdulog>] "
3739                      "[-b berdump] [-c cclfields]\n      [-p <proxy-addr>] [-u <auth>] "
3740                      "[-k size] [<server-addr>]\n",
3741                      prog);
3742             exit (1);
3743         }      
3744     }
3745     initialize();
3746     if (auth_command)
3747     {
3748 #ifdef HAVE_GETTIMEOFDAY
3749         gettimeofday (&tv_start, 0);
3750 #endif
3751         process_cmd_line (auth_command);
3752 #if HAVE_READLINE_HISTORY_H
3753         add_history(auth_command);
3754 #endif
3755         xfree(auth_command);
3756     }
3757     if (open_command)
3758     {
3759 #ifdef HAVE_GETTIMEOFDAY
3760         gettimeofday (&tv_start, 0);
3761 #endif
3762         process_cmd_line (open_command);
3763 #if HAVE_READLINE_HISTORY_H
3764         add_history(open_command);
3765 #endif
3766         xfree(open_command);
3767     }
3768     client ();
3769     exit (0);
3770 }
3771
3772 /*
3773  * Local variables:
3774  * tab-width: 8
3775  * c-basic-offset: 4
3776  * End:
3777  * vim600: sw=4 ts=8 fdm=marker
3778  * vim<600: sw=4 ts=8
3779  */