Retrieval of post script files. -k option for client.
[yaz-moved-to-github.git] / client / client.c
1 /*
2  * Copyright (c) 1995-2002, Index Data
3  * See the file LICENSE for details.
4  *
5  * $Id: client.c,v 1.136 2002-01-23 22:40:36 adam Exp $
6  */
7
8 #include <stdio.h>
9 #include <stdlib.h>
10 #include <time.h>
11
12 #include <yaz/yaz-util.h>
13
14 #include <yaz/tcpip.h>
15 #ifdef USE_XTIMOSI
16 #include <yaz/xmosi.h>
17 #endif
18
19 #include <yaz/proto.h>
20 #include <yaz/marcdisp.h>
21 #include <yaz/diagbib1.h>
22 #include <yaz/otherinfo.h>
23
24 #include <yaz/pquery.h>
25 #include <yaz/sortspec.h>
26
27 #if YAZ_MODULE_ill
28 #include <yaz/ill.h>
29 #endif
30
31 #if YAZ_MODULE_ccl
32 #include <yaz/yaz-ccl.h>
33 #endif
34
35 #if HAVE_READLINE_READLINE_H
36 #include <readline/readline.h>
37 #endif
38 #if HAVE_READLINE_HISTORY_H
39 #include <readline/history.h>
40 #endif
41
42 #include "admin.h"
43
44 #define C_PROMPT "Z> "
45
46 static ODR out, in, print;              /* encoding and decoding streams */
47 static FILE *apdu_file = 0;
48 static COMSTACK conn = 0;               /* our z-association */
49 static Z_IdAuthentication *auth = 0;    /* our current auth definition */
50 char *databaseNames[128];
51 int num_databaseNames = 0;
52 static Z_External *record_last = 0;
53 static int setnumber = -1;               /* current result set number */
54 static int smallSetUpperBound = 0;
55 static int largeSetLowerBound = 1;
56 static int mediumSetPresentNumber = 0;
57 static Z_ElementSetNames *elementSetNames = 0; 
58 static int setno = 1;                   /* current set offset */
59 static enum oid_proto protocol = PROTO_Z3950;      /* current app protocol */
60 static enum oid_value recordsyntax = VAL_USMARC;
61 static enum oid_value schema = VAL_NONE;
62 static int sent_close = 0;
63 static NMEM session_mem = NULL;      /* memory handle for init-response */
64 static Z_InitResponse *session = 0;     /* session parameters */
65 static char last_scan_line[512] = "0";
66 static char last_scan_query[512] = "0";
67 static char ccl_fields[512] = "default.bib";
68 static char* esPackageName = 0;
69 static char* yazProxy = 0;
70 static int kilobytes = 1024;
71
72 static char last_cmd[32] = "?";
73 static FILE *marcdump = 0;
74 static char *refid = NULL;
75
76 typedef enum {
77     QueryType_Prefix,
78     QueryType_CCL,
79     QueryType_CCL2RPN
80 } QueryType;
81
82 static QueryType queryType = QueryType_Prefix;
83
84 #if YAZ_MODULE_ccl
85 static CCL_bibset bibset;               /* CCL bibset handle */
86 #endif
87
88
89 /* set this one to 1, to avoid decode of unknown MARCs  */
90 #define AVOID_MARC_DECODE 1
91
92 void process_cmd_line(char* line);
93
94 ODR getODROutputStream()
95 {
96     return out;
97 }
98
99 void send_apdu(Z_APDU *a)
100 {
101     char *buf;
102     int len;
103
104     if (apdu_file)
105     {
106         z_APDU(print, &a, 0, 0);
107         odr_reset(print);
108     }
109     if (!z_APDU(out, &a, 0, 0))
110     {
111         odr_perror(out, "Encoding APDU");
112         exit(1);
113     }
114     buf = odr_getbuf(out, &len, 0);
115     /* printf ("sending APDU of size %d\n", len); */
116     if (cs_put(conn, buf, len) < 0)
117     {
118         fprintf(stderr, "cs_put: %s", cs_errmsg(cs_errno(conn)));
119         exit(1);
120     }
121     odr_reset(out); /* release the APDU structure  */
122 }
123
124 static void print_stringn(const unsigned char *buf, size_t len)
125 {
126    size_t i;
127    for (i = 0; i<len; i++)
128        if ((buf[i] <= 126 && buf[i] >= 32) || strchr ("\n\r\t\f", buf[i]))
129            fputc (buf[i], stdout);
130        else
131            printf ("\\X%02X", buf[i]);
132 }
133
134 static void print_refid (Z_ReferenceId *id)
135 {
136     if (id)
137     {
138         printf ("Reference Id: ");
139         print_stringn (id->buf, id->len);
140         printf ("\n");
141     }
142 }
143
144 static Z_ReferenceId *set_refid (ODR out)
145 {
146     Z_ReferenceId *id;
147     if (!refid)
148         return 0;
149     id = (Z_ReferenceId *) odr_malloc (out, sizeof(*id));
150     id->size = id->len = strlen(refid);
151     id->buf = (unsigned char *) odr_malloc (out, id->len);
152     memcpy (id->buf, refid, id->len);
153     return id;
154 }   
155
156 /* INIT SERVICE ------------------------------- */
157
158 static void send_initRequest(const char* type_and_host)
159 {
160     Z_APDU *apdu = zget_APDU(out, Z_APDU_initRequest);
161     Z_InitRequest *req = apdu->u.initRequest;
162
163     ODR_MASK_SET(req->options, Z_Options_search);
164     ODR_MASK_SET(req->options, Z_Options_present);
165     ODR_MASK_SET(req->options, Z_Options_namedResultSets);
166     ODR_MASK_SET(req->options, Z_Options_triggerResourceCtrl);
167     ODR_MASK_SET(req->options, Z_Options_scan);
168     ODR_MASK_SET(req->options, Z_Options_sort);
169     ODR_MASK_SET(req->options, Z_Options_extendedServices);
170     ODR_MASK_SET(req->options, Z_Options_delSet);
171
172     ODR_MASK_SET(req->protocolVersion, Z_ProtocolVersion_1);
173     ODR_MASK_SET(req->protocolVersion, Z_ProtocolVersion_2);
174     ODR_MASK_SET(req->protocolVersion, Z_ProtocolVersion_3);
175
176     *req->maximumRecordSize = 1024*kilobytes;
177     *req->preferredMessageSize = 1024*kilobytes;
178
179     req->idAuthentication = auth;
180
181     req->referenceId = set_refid (out);
182
183     if (yazProxy) 
184         yaz_oi_set_string_oidval(&req->otherInfo, out, VAL_PROXY,
185         1, type_and_host);
186     
187     send_apdu(apdu);
188     printf("Sent initrequest.\n");
189 }
190
191 static int process_initResponse(Z_InitResponse *res)
192 {
193     /* save session parameters for later use */
194     session_mem = odr_extract_mem(in);
195     session = res;
196
197     if (!*res->result)
198         printf("Connection rejected by target.\n");
199     else
200         printf("Connection accepted by target.\n");
201     if (res->implementationId)
202         printf("ID     : %s\n", res->implementationId);
203     if (res->implementationName)
204         printf("Name   : %s\n", res->implementationName);
205     if (res->implementationVersion)
206         printf("Version: %s\n", res->implementationVersion);
207     if (res->userInformationField)
208     {
209         printf("UserInformationfield:\n");
210         if (!z_External(print, (Z_External**)&res-> userInformationField,
211             0, 0))
212         {
213             odr_perror(print, "Printing userinfo\n");
214             odr_reset(print);
215         }
216         if (res->userInformationField->which == Z_External_octet)
217         {
218             printf("Guessing visiblestring:\n");
219             printf("'%s'\n", res->userInformationField->u. octet_aligned->buf);
220         }
221         odr_reset (print);
222     }
223     printf ("Options:");
224     if (ODR_MASK_GET(res->options, Z_Options_search))
225         printf (" search");
226     if (ODR_MASK_GET(res->options, Z_Options_present))
227         printf (" present");
228     if (ODR_MASK_GET(res->options, Z_Options_delSet))
229         printf (" delSet");
230     if (ODR_MASK_GET(res->options, Z_Options_resourceReport))
231         printf (" resourceReport");
232     if (ODR_MASK_GET(res->options, Z_Options_resourceCtrl))
233         printf (" resourceCtrl");
234     if (ODR_MASK_GET(res->options, Z_Options_accessCtrl))
235         printf (" accessCtrl");
236     if (ODR_MASK_GET(res->options, Z_Options_scan))
237         printf (" scan");
238     if (ODR_MASK_GET(res->options, Z_Options_sort))
239         printf (" sort");
240     if (ODR_MASK_GET(res->options, Z_Options_extendedServices))
241         printf (" extendedServices");
242     if (ODR_MASK_GET(res->options, Z_Options_level_1Segmentation))
243         printf (" level1Segmentation");
244     if (ODR_MASK_GET(res->options, Z_Options_level_2Segmentation))
245         printf (" level2Segmentation");
246     if (ODR_MASK_GET(res->options, Z_Options_concurrentOperations))
247         printf (" concurrentOperations");
248     if (ODR_MASK_GET(res->options, Z_Options_namedResultSets))
249     {
250         printf (" namedResultSets");
251         setnumber = 0;
252     }
253     printf ("\n");
254     fflush (stdout);
255     return 0;
256 }
257
258 static int cmd_base(char *arg)
259 {
260     int i;
261     char *cp;
262
263     if (!*arg)
264     {
265         printf("Usage: base <database> <database> ...\n");
266         return 0;
267     }
268     for (i = 0; i<num_databaseNames; i++)
269         xfree (databaseNames[i]);
270     num_databaseNames = 0;
271     while (1)
272     {
273         if (!(cp = strchr(arg, ' ')))
274             cp = arg + strlen(arg);
275         if (cp - arg < 1)
276             break;
277         databaseNames[num_databaseNames] = (char *)xmalloc (1 + cp - arg);
278         memcpy (databaseNames[num_databaseNames], arg, cp - arg);
279         databaseNames[num_databaseNames++][cp - arg] = '\0';
280         if (!*cp)
281             break;
282         arg = cp+1;
283     }
284     return 1;
285 }
286
287
288 int cmd_open(char *arg)
289 {
290     void *add;
291     char type_and_host[101], base[101];
292     CS_TYPE t;
293
294     if (conn)
295     {
296         printf("Already connected.\n");
297
298         cs_close (conn);
299         conn = NULL;
300         if (session_mem)
301         {
302             nmem_destroy (session_mem);
303             session_mem = NULL;
304         }
305     }
306     t = tcpip_type;
307     base[0] = '\0';
308     if (sscanf (arg, "%100[^/]/%100s", type_and_host, base) < 1)
309         return 0;
310
311     if(yazProxy) 
312         conn = cs_create_host(yazProxy, 1, &add);
313     else 
314         conn = cs_create_host(type_and_host, 1, &add);
315         
316     if (!conn)
317     {
318         printf ("Couldn't create comstack\n");
319         return 0;
320     }
321     printf("Connecting...");
322     fflush(stdout);
323     if (cs_connect(conn, add) < 0)
324     {
325         printf ("error = %s\n", cs_strerror(conn));
326         if (conn->cerrno == CSYSERR)
327             perror("system");
328         cs_close(conn);
329         conn = 0;
330         return 0;
331     }
332     printf("Ok.\n");
333
334     send_initRequest(type_and_host);
335     if (*base)
336         cmd_base (base);
337     return 2;
338 }
339
340 int cmd_authentication(char *arg)
341 {
342     static Z_IdAuthentication au;
343     static char open[256];
344
345     if (!*arg)
346     {
347         printf("Auth field set to null\n");
348         auth = 0;
349         return 1;
350     }
351     auth = &au;
352     au.which = Z_IdAuthentication_open;
353     au.u.open = open;
354     strcpy(open, arg);
355     return 1;
356 }
357
358 /* SEARCH SERVICE ------------------------------ */
359
360 static void display_variant(Z_Variant *v, int level)
361 {
362     int i;
363
364     for (i = 0; i < v->num_triples; i++)
365     {
366         printf("%*sclass=%d,type=%d", level * 4, "", *v->triples[i]->zclass,
367             *v->triples[i]->type);
368         if (v->triples[i]->which == Z_Triple_internationalString)
369             printf(",value=%s\n", v->triples[i]->value.internationalString);
370         else
371             printf("\n");
372     }
373 }
374
375 static void display_grs1(Z_GenericRecord *r, int level)
376 {
377     int i;
378
379     if (!r)
380         return;
381     for (i = 0; i < r->num_elements; i++)
382     {
383         Z_TaggedElement *t;
384
385         printf("%*s", level * 4, "");
386         t = r->elements[i];
387         printf("(");
388         if (t->tagType)
389             printf("%d,", *t->tagType);
390         else
391             printf("?,");
392         if (t->tagValue->which == Z_StringOrNumeric_numeric)
393             printf("%d) ", *t->tagValue->u.numeric);
394         else
395             printf("%s) ", t->tagValue->u.string);
396         if (t->content->which == Z_ElementData_subtree)
397         {
398             printf("\n");
399             display_grs1(t->content->u.subtree, level+1);
400         }
401         else if (t->content->which == Z_ElementData_string)
402             printf("%s\n", t->content->u.string);
403         else if (t->content->which == Z_ElementData_numeric)
404             printf("%d\n", *t->content->u.numeric);
405         else if (t->content->which == Z_ElementData_oid)
406         {
407             int *ip = t->content->u.oid;
408             oident *oent;
409
410             if ((oent = oid_getentbyoid(t->content->u.oid)))
411                 printf("OID: %s\n", oent->desc);
412             else
413             {
414                 printf("{");
415                 while (ip && *ip >= 0)
416                     printf(" %d", *(ip++));
417                 printf(" }\n");
418             }
419         }
420         else if (t->content->which == Z_ElementData_noDataRequested)
421             printf("[No data requested]\n");
422         else if (t->content->which == Z_ElementData_elementEmpty)
423             printf("[Element empty]\n");
424         else if (t->content->which == Z_ElementData_elementNotThere)
425             printf("[Element not there]\n");
426         else
427             printf("??????\n");
428         if (t->appliedVariant)
429             display_variant(t->appliedVariant, level+1);
430         if (t->metaData && t->metaData->supportedVariants)
431         {
432             int c;
433
434             printf("%*s---- variant list\n", (level+1)*4, "");
435             for (c = 0; c < t->metaData->num_supportedVariants; c++)
436             {
437                 printf("%*svariant #%d\n", (level+1)*4, "", c);
438                 display_variant(t->metaData->supportedVariants[c], level + 2);
439             }
440         }
441     }
442 }
443
444
445 static void print_record(const unsigned char *buf, size_t len)
446 {
447     size_t i = len;
448     print_stringn (buf, len);
449     /* add newline if not already added ... */
450     if (i <= 0 || buf[i-1] != '\n')
451        fputc ('\n', stdout);
452 }
453
454 static void display_record(Z_External *r)
455 {
456     oident *ent = oid_getentbyoid(r->direct_reference);
457
458     record_last = r;
459     /*
460      * Tell the user what we got.
461      */
462     if (r->direct_reference)
463     {
464         printf("Record type: ");
465         if (ent)
466             printf("%s\n", ent->desc);
467         else if (!odr_oid(print, &r->direct_reference, 0, 0))
468         {
469             odr_perror(print, "print oid");
470             odr_reset(print);
471         }
472     }
473     /* Check if this is a known, ASN.1 type tucked away in an octet string */
474     if (ent && r->which == Z_External_octet)
475     {
476         Z_ext_typeent *type = z_ext_getentbyref(ent->value);
477         void *rr;
478
479         if (type)
480         {
481             /*
482              * Call the given decoder to process the record.
483              */
484             odr_setbuf(in, (char*)r->u.octet_aligned->buf,
485                 r->u.octet_aligned->len, 0);
486             if (!(*type->fun)(in, (char **)&rr, 0, 0))
487             {
488                 odr_perror(in, "Decoding constructed record.");
489                 fprintf(stderr, "[Near %d]\n", odr_offset(in));
490                 fprintf(stderr, "Packet dump:\n---------\n");
491                 odr_dumpBER(stderr, (char*)r->u.octet_aligned->buf,
492                     r->u.octet_aligned->len);
493                 fprintf(stderr, "---------\n");
494                 exit(1);
495             }
496             /*
497              * Note: we throw away the original, BER-encoded record here.
498              * Do something else with it if you want to keep it.
499              */
500             r->u.sutrs = (Z_SUTRS *) rr; /* we don't actually check the type here. */
501             r->which = type->what;
502         }
503     }
504     if (ent && ent->value == VAL_SOIF)
505         print_record((const unsigned char *) r->u.octet_aligned->buf,
506                      r->u.octet_aligned->len);
507     else if (r->which == Z_External_octet && r->u.octet_aligned->len)
508     {
509         const char *octet_buf = (char*)r->u.octet_aligned->buf;
510         if (ent->value == VAL_TEXT_XML || ent->value == VAL_APPLICATION_XML ||
511             ent->value == VAL_HTML)
512         {
513             print_record((const unsigned char *) octet_buf,
514                          r->u.octet_aligned->len);
515         }
516         else if (ent->value == VAL_POSTSCRIPT)
517         {
518             int size = r->u.octet_aligned->len;
519             if (size > 100)
520                 size = 100;
521             print_record((const unsigned char *) octet_buf, size);
522         }
523         else
524         {
525             if ( 
526 #if AVOID_MARC_DECODE
527                 /* primitive check for a marc OID 5.1-29 */
528                 ent->oidsuffix[0] == 5 && ent->oidsuffix[1] < 30 
529 #else
530                 1
531 #endif
532                 )
533             {
534                 if (marc_display_exl (octet_buf, NULL, 0 /* debug */,
535                                       r->u.octet_aligned->len) <= 0)
536                 {
537                     printf ("bad MARC. Dumping as it is:\n");
538                     print_record((const unsigned char*) octet_buf,
539                                  r->u.octet_aligned->len);
540                 }
541             }
542             else
543             {
544                 print_record((const unsigned char*) octet_buf,
545                              r->u.octet_aligned->len);
546             }
547         }
548         if (marcdump)
549             fwrite (octet_buf, 1, r->u.octet_aligned->len, marcdump);
550     }
551     else if (ent && ent->value == VAL_SUTRS)
552     {
553         if (r->which != Z_External_sutrs)
554         {
555             printf("Expecting single SUTRS type for SUTRS.\n");
556             return;
557         }
558         print_record(r->u.sutrs->buf, r->u.sutrs->len);
559     }
560     else if (ent && ent->value == VAL_GRS1)
561     {
562         if (r->which != Z_External_grs1)
563         {
564             printf("Expecting single GRS type for GRS.\n");
565             return;
566         }
567         display_grs1(r->u.grs1, 0);
568     }
569     else 
570     {
571         printf("Unknown record representation.\n");
572         if (!z_External(print, &r, 0, 0))
573         {
574             odr_perror(print, "Printing external");
575             odr_reset(print);
576         }
577     }
578 }
579
580
581 static void display_diagrecs(Z_DiagRec **pp, int num)
582 {
583     int i;
584     oident *ent;
585     Z_DefaultDiagFormat *r;
586
587     printf("Diagnostic message(s) from database:\n");
588     for (i = 0; i<num; i++)
589     {
590         Z_DiagRec *p = pp[i];
591         if (p->which != Z_DiagRec_defaultFormat)
592         {
593             printf("Diagnostic record not in default format.\n");
594             return;
595         }
596         else
597             r = p->u.defaultFormat;
598         if (!(ent = oid_getentbyoid(r->diagnosticSetId)) ||
599             ent->oclass != CLASS_DIAGSET || ent->value != VAL_BIB1)
600             printf("Missing or unknown diagset\n");
601         printf("    [%d] %s", *r->condition, diagbib1_str(*r->condition));
602         switch (r->which)
603         {
604         case Z_DefaultDiagFormat_v2Addinfo:
605             printf (" -- v2 addinfo '%s'\n", r->u.v2Addinfo);
606             break;
607         case Z_DefaultDiagFormat_v3Addinfo:
608             printf (" -- v3 addinfo '%s'\n", r->u.v3Addinfo);
609             break;
610         }
611     }
612 }
613
614
615 static void display_nameplusrecord(Z_NamePlusRecord *p)
616 {
617     if (p->databaseName)
618         printf("[%s]", p->databaseName);
619     if (p->which == Z_NamePlusRecord_surrogateDiagnostic)
620         display_diagrecs(&p->u.surrogateDiagnostic, 1);
621     else if (p->which == Z_NamePlusRecord_databaseRecord)
622         display_record(p->u.databaseRecord);
623 }
624
625 static void display_records(Z_Records *p)
626 {
627     int i;
628
629     if (p->which == Z_Records_NSD)
630     {
631         Z_DiagRec dr, *dr_p = &dr;
632         dr.which = Z_DiagRec_defaultFormat;
633         dr.u.defaultFormat = p->u.nonSurrogateDiagnostic;
634         display_diagrecs (&dr_p, 1);
635     }
636     else if (p->which == Z_Records_multipleNSD)
637         display_diagrecs (p->u.multipleNonSurDiagnostics->diagRecs,
638                           p->u.multipleNonSurDiagnostics->num_diagRecs);
639     else 
640     {
641         printf("Records: %d\n", p->u.databaseOrSurDiagnostics->num_records);
642         for (i = 0; i < p->u.databaseOrSurDiagnostics->num_records; i++)
643             display_nameplusrecord(p->u.databaseOrSurDiagnostics->records[i]);
644     }
645 }
646
647 static int send_deleteResultSetRequest(char *arg)
648 {
649     char names[8][32];
650     int i;
651
652     Z_APDU *apdu = zget_APDU(out, Z_APDU_deleteResultSetRequest);
653     Z_DeleteResultSetRequest *req = apdu->u.deleteResultSetRequest;
654
655     req->referenceId = set_refid (out);
656
657     req->num_resultSetList =
658         sscanf (arg, "%30s %30s %30s %30s %30s %30s %30s %30s",
659                 names[0], names[1], names[2], names[3],
660                 names[4], names[5], names[6], names[7]);
661
662     req->deleteFunction = (int *)
663         odr_malloc (out, sizeof(*req->deleteFunction));
664     if (req->num_resultSetList > 0)
665     {
666         *req->deleteFunction = Z_DeleteRequest_list;
667         req->resultSetList = (char **)
668             odr_malloc (out, sizeof(*req->resultSetList)*
669                         req->num_resultSetList);
670         for (i = 0; i<req->num_resultSetList; i++)
671             req->resultSetList[i] = names[i];
672     }
673     else
674     {
675         *req->deleteFunction = Z_DeleteRequest_all;
676         req->resultSetList = 0;
677     }
678     
679     send_apdu(apdu);
680     printf("Sent deleteResultSetRequest.\n");
681     return 2;
682 }
683
684 static int send_searchRequest(char *arg)
685 {
686     Z_APDU *apdu = zget_APDU(out, Z_APDU_searchRequest);
687     Z_SearchRequest *req = apdu->u.searchRequest;
688     Z_Query query;
689     int oid[OID_SIZE];
690 #if YAZ_MODULE_ccl
691     struct ccl_rpn_node *rpn = NULL;
692     int error, pos;
693 #endif
694     char setstring[100];
695     Z_RPNQuery *RPNquery;
696     Odr_oct ccl_query;
697
698 #if YAZ_MODULE_ccl
699     if (queryType == QueryType_CCL2RPN)
700     {
701         rpn = ccl_find_str(bibset, arg, &error, &pos);
702         if (error)
703         {
704             printf("CCL ERROR: %s\n", ccl_err_msg(error));
705             return 0;
706         }
707     }
708 #endif
709     req->referenceId = set_refid (out);
710     if (!strcmp(arg, "@big")) /* strictly for troublemaking */
711     {
712         static unsigned char big[2100];
713         static Odr_oct bigo;
714
715         /* send a very big referenceid to test transport stack etc. */
716         memset(big, 'A', 2100);
717         bigo.len = bigo.size = 2100;
718         bigo.buf = big;
719         req->referenceId = &bigo;
720     }
721     
722     if (setnumber >= 0)
723     {
724         sprintf(setstring, "%d", ++setnumber);
725         req->resultSetName = setstring;
726     }
727     *req->smallSetUpperBound = smallSetUpperBound;
728     *req->largeSetLowerBound = largeSetLowerBound;
729     *req->mediumSetPresentNumber = mediumSetPresentNumber;
730     if (smallSetUpperBound > 0 || (largeSetLowerBound > 1 &&
731         mediumSetPresentNumber > 0))
732     {
733         oident prefsyn;
734
735         prefsyn.proto = protocol;
736         prefsyn.oclass = CLASS_RECSYN;
737         prefsyn.value = recordsyntax;
738         req->preferredRecordSyntax =
739             odr_oiddup(out, oid_ent_to_oid(&prefsyn, oid));
740         req->smallSetElementSetNames =
741             req->mediumSetElementSetNames = elementSetNames;
742     }
743     req->num_databaseNames = num_databaseNames;
744     req->databaseNames = databaseNames;
745
746     req->query = &query;
747
748     switch (queryType)
749     {
750     case QueryType_Prefix:
751         query.which = Z_Query_type_1;
752         RPNquery = p_query_rpn (out, protocol, arg);
753         if (!RPNquery)
754         {
755             printf("Prefix query error\n");
756             return 0;
757         }
758         query.u.type_1 = RPNquery;
759         break;
760     case QueryType_CCL:
761         query.which = Z_Query_type_2;
762         query.u.type_2 = &ccl_query;
763         ccl_query.buf = (unsigned char*) arg;
764         ccl_query.len = strlen(arg);
765         break;
766 #if YAZ_MODULE_ccl
767     case QueryType_CCL2RPN:
768         query.which = Z_Query_type_1;
769         RPNquery = ccl_rpn_query(out, rpn);
770         if (!RPNquery)
771         {
772             printf ("Couldn't convert from CCL to RPN\n");
773             return 0;
774         }
775         query.u.type_1 = RPNquery;
776         ccl_rpn_delete (rpn);
777         break;
778 #endif
779     default:
780         printf ("Unsupported query type\n");
781         return 0;
782     }
783     send_apdu(apdu);
784     setno = 1;
785     printf("Sent searchRequest.\n");
786     return 2;
787 }
788
789 static int process_searchResponse(Z_SearchResponse *res)
790 {
791     printf ("Received SearchResponse.\n");
792     print_refid (res->referenceId);
793     if (*res->searchStatus)
794         printf("Search was a success.\n");
795     else
796         printf("Search was a bloomin' failure.\n");
797     printf("Number of hits: %d", *res->resultCount);
798     if (setnumber >= 0)
799         printf (", setno %d", setnumber);
800     printf("\nrecords returned: %d\n",
801         *res->numberOfRecordsReturned);
802     setno += *res->numberOfRecordsReturned;
803     if (res->records)
804         display_records(res->records);
805     return 0;
806 }
807
808 static void print_level(int iLevel)
809 {
810     int i;
811     for (i = 0; i < iLevel * 4; i++)
812         printf(" ");
813 }
814
815 static void print_int(int iLevel, const char *pTag, int *pInt)
816 {
817     if (pInt != NULL)
818     {
819         print_level(iLevel);
820         printf("%s: %d\n", pTag, *pInt);
821     }
822 }
823
824 static void print_string(int iLevel, const char *pTag, const char *pString)
825 {
826     if (pString != NULL)
827     {
828         print_level(iLevel);
829         printf("%s: %s\n", pTag, pString);
830     }
831 }
832
833 static void print_oid(int iLevel, const char *pTag, Odr_oid *pOid)
834 {
835     if (pOid != NULL)
836     {
837         int *pInt = pOid;
838
839         print_level(iLevel);
840         printf("%s:", pTag);
841         for (; *pInt != -1; pInt++)
842             printf(" %d", *pInt);
843         printf("\n");
844     }
845 }
846
847 static void print_referenceId(int iLevel, Z_ReferenceId *referenceId)
848 {
849     if (referenceId != NULL)
850     {
851         int i;
852
853         print_level(iLevel);
854         printf("Ref Id (%d, %d): ", referenceId->len, referenceId->size);
855         for (i = 0; i < referenceId->len; i++)
856             printf("%c", referenceId->buf[i]);
857         printf("\n");
858     }
859 }
860
861 static void print_string_or_numeric(int iLevel, const char *pTag, Z_StringOrNumeric *pStringNumeric)
862 {
863     if (pStringNumeric != NULL)
864     {
865         switch (pStringNumeric->which)
866         {
867             case Z_StringOrNumeric_string:
868                 print_string(iLevel, pTag, pStringNumeric->u.string);
869                 break;
870
871             case Z_StringOrNumeric_numeric:
872                 print_int(iLevel, pTag, pStringNumeric->u.numeric);
873                 break;
874
875             default:
876                 print_level(iLevel);
877                 printf("%s: valid type for Z_StringOrNumeric\n", pTag);
878                 break;
879         }
880     }
881 }
882
883 static void print_universe_report_duplicate(int iLevel, Z_UniverseReportDuplicate *pUniverseReportDuplicate)
884 {
885     if (pUniverseReportDuplicate != NULL)
886     {
887         print_level(iLevel);
888         printf("Universe Report Duplicate: \n");
889         iLevel++;
890         print_string_or_numeric(iLevel, "Hit No", pUniverseReportDuplicate->hitno);
891     }
892 }
893
894 static void print_universe_report_hits(int iLevel, Z_UniverseReportHits *pUniverseReportHits)
895 {
896     if (pUniverseReportHits != NULL)
897     {
898         print_level(iLevel);
899         printf("Universe Report Hits: \n");
900         iLevel++;
901         print_string_or_numeric(iLevel, "Database", pUniverseReportHits->database);
902         print_string_or_numeric(iLevel, "Hits", pUniverseReportHits->hits);
903     }
904 }
905
906 static void print_universe_report(int iLevel, Z_UniverseReport *pUniverseReport)
907 {
908     if (pUniverseReport != NULL)
909     {
910         print_level(iLevel);
911         printf("Universe Report: \n");
912         iLevel++;
913         print_int(iLevel, "Total Hits", pUniverseReport->totalHits);
914         switch (pUniverseReport->which)
915         {
916             case Z_UniverseReport_databaseHits:
917                 print_universe_report_hits(iLevel, pUniverseReport->u.databaseHits);
918                 break;
919
920             case Z_UniverseReport_duplicate:
921                 print_universe_report_duplicate(iLevel, pUniverseReport->u.duplicate);
922                 break;
923
924             default:
925                 print_level(iLevel);
926                 printf("Type: %d\n", pUniverseReport->which);
927                 break;
928         }
929     }
930 }
931
932 static void print_external(int iLevel, Z_External *pExternal)
933 {
934     if (pExternal != NULL)
935     {
936         print_level(iLevel);
937         printf("External: \n");
938         iLevel++;
939         print_oid(iLevel, "Direct Reference", pExternal->direct_reference);
940         print_int(iLevel, "InDirect Reference", pExternal->indirect_reference);
941         print_string(iLevel, "Descriptor", pExternal->descriptor);
942         switch (pExternal->which)
943         {
944             case Z_External_universeReport:
945                 print_universe_report(iLevel, pExternal->u.universeReport);
946                 break;
947
948             default:
949                 print_level(iLevel);
950                 printf("Type: %d\n", pExternal->which);
951                 break;
952         }
953     }
954 }
955
956 static int process_resourceControlRequest (Z_ResourceControlRequest *req)
957 {
958     printf ("Received ResourceControlRequest.\n");
959     print_referenceId(1, req->referenceId);
960     print_int(1, "Suspended Flag", req->suspendedFlag);
961     print_int(1, "Partial Results Available", req->partialResultsAvailable);
962     print_int(1, "Response Required", req->responseRequired);
963     print_int(1, "Triggered Request Flag", req->triggeredRequestFlag);
964     print_external(1, req->resourceReport);
965     return 0;
966 }
967
968 void process_ESResponse(Z_ExtendedServicesResponse *res)
969 {
970     printf("Status: ");
971     switch (*res->operationStatus)
972     {
973     case Z_ExtendedServicesResponse_done:
974         printf ("done\n");
975         break;
976     case Z_ExtendedServicesResponse_accepted:
977         printf ("accepted\n");
978         break;
979     case Z_ExtendedServicesResponse_failure:
980         printf ("failure\n");
981         display_diagrecs(res->diagnostics, res->num_diagnostics);
982         break;
983     default:
984         printf ("unknown\n");
985     }
986     if ( (*res->operationStatus != Z_ExtendedServicesResponse_failure) &&
987         (res->num_diagnostics != 0) ) {
988         display_diagrecs(res->diagnostics, res->num_diagnostics);
989     }
990     print_refid (res->referenceId);
991     if (res->taskPackage && 
992         res->taskPackage->which == Z_External_extendedService)
993     {
994         Z_TaskPackage *taskPackage = res->taskPackage->u.extendedService;
995         Odr_oct *id = taskPackage->targetReference;
996         Z_External *ext = taskPackage->taskSpecificParameters;
997         
998         if (id)
999         {
1000             printf ("Target Reference: ");
1001             print_stringn (id->buf, id->len);
1002             printf ("\n");
1003         }
1004         if (ext->which == Z_External_update)
1005         {
1006             Z_IUUpdateTaskPackage *utp = ext->u.update->u.taskPackage;
1007             if (utp && utp->targetPart)
1008             {
1009                 Z_IUTargetPart *targetPart = utp->targetPart;
1010                 int i;
1011
1012                 for (i = 0; i<targetPart->num_taskPackageRecords;  i++)
1013                 {
1014
1015                     Z_IUTaskPackageRecordStructure *tpr =
1016                         targetPart->taskPackageRecords[i];
1017                     printf ("task package record %d\n", i+1);
1018                     if (tpr->which == Z_IUTaskPackageRecordStructure_record)
1019                     {
1020                         display_record (tpr->u.record);
1021                     }
1022                     else
1023                     {
1024                         printf ("other type\n");
1025                     }
1026                 }
1027             }
1028         }
1029     }
1030 }
1031
1032 #if YAZ_MODULE_ill
1033
1034 const char *get_ill_element (void *clientData, const char *element)
1035 {
1036     return 0;
1037 }
1038
1039 static Z_External *create_external_itemRequest()
1040 {
1041     struct ill_get_ctl ctl;
1042     ILL_ItemRequest *req;
1043     Z_External *r = 0;
1044     int item_request_size = 0;
1045     char *item_request_buf = 0;
1046
1047     ctl.odr = out;
1048     ctl.clientData = 0;
1049     ctl.f = get_ill_element;
1050
1051     req = ill_get_ItemRequest(&ctl, "ill", 0);
1052     if (!req)
1053         printf ("ill_get_ItemRequest failed\n");
1054         
1055     if (!ill_ItemRequest (out, &req, 0, 0))
1056     {
1057         if (apdu_file)
1058         {
1059             ill_ItemRequest(print, &req, 0, 0);
1060             odr_reset(print);
1061         }
1062         item_request_buf = odr_getbuf (out, &item_request_size, 0);
1063         if (item_request_buf)
1064             odr_setbuf (out, item_request_buf, item_request_size, 1);
1065         printf ("Couldn't encode ItemRequest, size %d\n", item_request_size);
1066         return 0;
1067     }
1068     else
1069     {
1070         oident oid;
1071         
1072         item_request_buf = odr_getbuf (out, &item_request_size, 0);
1073         oid.proto = PROTO_GENERAL;
1074         oid.oclass = CLASS_GENERAL;
1075         oid.value = VAL_ISO_ILL_1;
1076         
1077         r = (Z_External *) odr_malloc (out, sizeof(*r));
1078         r->direct_reference = odr_oiddup(out,oid_getoidbyent(&oid)); 
1079         r->indirect_reference = 0;
1080         r->descriptor = 0;
1081         r->which = Z_External_single;
1082         
1083         r->u.single_ASN1_type = (Odr_oct *)
1084             odr_malloc (out, sizeof(*r->u.single_ASN1_type));
1085         r->u.single_ASN1_type->buf = (unsigned char *)
1086             odr_malloc (out, item_request_size);
1087         r->u.single_ASN1_type->len = item_request_size;
1088         r->u.single_ASN1_type->size = item_request_size;
1089         memcpy (r->u.single_ASN1_type->buf, item_request_buf,
1090                 item_request_size);
1091         printf ("len = %d\n", item_request_size);
1092     }
1093     return r;
1094 }
1095 #endif
1096
1097 #ifdef YAZ_MODULE_ill
1098 static Z_External *create_external_ILL_APDU(int which)
1099 {
1100     struct ill_get_ctl ctl;
1101     ILL_APDU *ill_apdu;
1102     Z_External *r = 0;
1103     int ill_request_size = 0;
1104     char *ill_request_buf = 0;
1105         
1106     ctl.odr = out;
1107     ctl.clientData = 0;
1108     ctl.f = get_ill_element;
1109
1110     ill_apdu = ill_get_APDU(&ctl, "ill", 0);
1111
1112     if (!ill_APDU (out, &ill_apdu, 0, 0))
1113     {
1114         if (apdu_file)
1115         {
1116             printf ("-------------------\n");
1117             ill_APDU(print, &ill_apdu, 0, 0);
1118             odr_reset(print);
1119             printf ("-------------------\n");
1120         }
1121         ill_request_buf = odr_getbuf (out, &ill_request_size, 0);
1122         if (ill_request_buf)
1123             odr_setbuf (out, ill_request_buf, ill_request_size, 1);
1124         printf ("Couldn't encode ILL-Request, size %d\n", ill_request_size);
1125         return 0;
1126     }
1127     else
1128     {
1129         oident oid;
1130         ill_request_buf = odr_getbuf (out, &ill_request_size, 0);
1131         
1132         oid.proto = PROTO_GENERAL;
1133         oid.oclass = CLASS_GENERAL;
1134         oid.value = VAL_ISO_ILL_1;
1135         
1136         r = (Z_External *) odr_malloc (out, sizeof(*r));
1137         r->direct_reference = odr_oiddup(out,oid_getoidbyent(&oid)); 
1138         r->indirect_reference = 0;
1139         r->descriptor = 0;
1140         r->which = Z_External_single;
1141         
1142         r->u.single_ASN1_type = (Odr_oct *)
1143             odr_malloc (out, sizeof(*r->u.single_ASN1_type));
1144         r->u.single_ASN1_type->buf = (unsigned char *)
1145             odr_malloc (out, ill_request_size);
1146         r->u.single_ASN1_type->len = ill_request_size;
1147         r->u.single_ASN1_type->size = ill_request_size;
1148         memcpy (r->u.single_ASN1_type->buf, ill_request_buf, ill_request_size);
1149         printf ("len = %d\n", ill_request_size);
1150     }
1151     return r;
1152 }
1153 #endif
1154
1155
1156 static Z_External *create_ItemOrderExternal(const char *type, int itemno)
1157 {
1158     Z_External *r = (Z_External *) odr_malloc(out, sizeof(Z_External));
1159     oident ItemOrderRequest;
1160   
1161     ItemOrderRequest.proto = PROTO_Z3950;
1162     ItemOrderRequest.oclass = CLASS_EXTSERV;
1163     ItemOrderRequest.value = VAL_ITEMORDER;
1164  
1165     r->direct_reference = odr_oiddup(out,oid_getoidbyent(&ItemOrderRequest)); 
1166     r->indirect_reference = 0;
1167     r->descriptor = 0;
1168
1169     r->which = Z_External_itemOrder;
1170
1171     r->u.itemOrder = (Z_ItemOrder *) odr_malloc(out,sizeof(Z_ItemOrder));
1172     memset(r->u.itemOrder, 0, sizeof(Z_ItemOrder));
1173     r->u.itemOrder->which=Z_IOItemOrder_esRequest;
1174
1175     r->u.itemOrder->u.esRequest = (Z_IORequest *) 
1176         odr_malloc(out,sizeof(Z_IORequest));
1177     memset(r->u.itemOrder->u.esRequest, 0, sizeof(Z_IORequest));
1178
1179     r->u.itemOrder->u.esRequest->toKeep = (Z_IOOriginPartToKeep *)
1180         odr_malloc(out,sizeof(Z_IOOriginPartToKeep));
1181     memset(r->u.itemOrder->u.esRequest->toKeep, 0, sizeof(Z_IOOriginPartToKeep));
1182     r->u.itemOrder->u.esRequest->notToKeep = (Z_IOOriginPartNotToKeep *)
1183         odr_malloc(out,sizeof(Z_IOOriginPartNotToKeep));
1184     memset(r->u.itemOrder->u.esRequest->notToKeep, 0, sizeof(Z_IOOriginPartNotToKeep));
1185
1186     r->u.itemOrder->u.esRequest->toKeep->supplDescription = NULL;
1187     r->u.itemOrder->u.esRequest->toKeep->contact = NULL;
1188     r->u.itemOrder->u.esRequest->toKeep->addlBilling = NULL;
1189
1190     r->u.itemOrder->u.esRequest->notToKeep->resultSetItem =
1191         (Z_IOResultSetItem *) odr_malloc(out, sizeof(Z_IOResultSetItem));
1192     memset(r->u.itemOrder->u.esRequest->notToKeep->resultSetItem, 0, sizeof(Z_IOResultSetItem));
1193     r->u.itemOrder->u.esRequest->notToKeep->resultSetItem->resultSetId = "1";
1194
1195     r->u.itemOrder->u.esRequest->notToKeep->resultSetItem->item =
1196         (int *) odr_malloc(out, sizeof(int));
1197     *r->u.itemOrder->u.esRequest->notToKeep->resultSetItem->item = itemno;
1198
1199 #if YAZ_MODULE_ill
1200     if (!strcmp (type, "item") || !strcmp(type, "2"))
1201     {
1202         printf ("using item-request\n");
1203         r->u.itemOrder->u.esRequest->notToKeep->itemRequest = 
1204             create_external_itemRequest();
1205     }
1206     else if (!strcmp(type, "ill") || !strcmp(type, "1"))
1207     {
1208         printf ("using ILL-request\n");
1209         r->u.itemOrder->u.esRequest->notToKeep->itemRequest = 
1210             create_external_ILL_APDU(ILL_APDU_ILL_Request);
1211     }
1212     else if (!strcmp(type, "xml") || !strcmp(type, "3"))
1213     {
1214         const char *xml_buf =
1215                 "<itemorder>\n"
1216                 "  <type>request</type>\n"
1217                 "  <libraryNo>000200</libraryNo>\n"
1218                 "  <borrowerTicketNo> 1212 </borrowerTicketNo>\n"
1219                 "</itemorder>";
1220         r->u.itemOrder->u.esRequest->notToKeep->itemRequest =
1221             z_ext_record (out, VAL_TEXT_XML, xml_buf, strlen(xml_buf));
1222     }
1223     else
1224         r->u.itemOrder->u.esRequest->notToKeep->itemRequest = 0;
1225
1226 #else
1227     r->u.itemOrder->u.esRequest->notToKeep->itemRequest = 0;
1228 #endif
1229     return r;
1230 }
1231
1232 static int send_itemorder(const char *type, int itemno)
1233 {
1234     Z_APDU *apdu = zget_APDU(out, Z_APDU_extendedServicesRequest);
1235     Z_ExtendedServicesRequest *req = apdu->u.extendedServicesRequest;
1236     oident ItemOrderRequest;
1237
1238     ItemOrderRequest.proto = PROTO_Z3950;
1239     ItemOrderRequest.oclass = CLASS_EXTSERV;
1240     ItemOrderRequest.value = VAL_ITEMORDER;
1241     req->packageType = odr_oiddup(out,oid_getoidbyent(&ItemOrderRequest));
1242     req->packageName = esPackageName;
1243
1244     req->taskSpecificParameters = create_ItemOrderExternal(type, itemno);
1245
1246     send_apdu(apdu);
1247     return 0;
1248 }
1249
1250 static int cmd_update(char *arg)
1251 {
1252     Z_APDU *apdu = zget_APDU(out, Z_APDU_extendedServicesRequest );
1253     Z_ExtendedServicesRequest *req = apdu->u.extendedServicesRequest;
1254     Z_External *r;
1255     int oid[OID_SIZE];
1256     Z_IUOriginPartToKeep *toKeep;
1257     Z_IUSuppliedRecords *notToKeep;
1258     oident update_oid;
1259     printf ("Update request\n");
1260     fflush(stdout);
1261
1262     if (!record_last)
1263         return 0;
1264     update_oid.proto = PROTO_Z3950;
1265     update_oid.oclass = CLASS_EXTSERV;
1266     update_oid.value = VAL_DBUPDATE;
1267     oid_ent_to_oid (&update_oid, oid);
1268     req->packageType = odr_oiddup(out,oid);
1269     req->packageName = esPackageName;
1270     
1271     req->referenceId = set_refid (out);
1272
1273     r = req->taskSpecificParameters = (Z_External *)
1274         odr_malloc (out, sizeof(*r));
1275     r->direct_reference = odr_oiddup(out,oid);
1276     r->indirect_reference = 0;
1277     r->descriptor = 0;
1278     r->which = Z_External_update;
1279     r->u.update = (Z_IUUpdate *) odr_malloc(out, sizeof(*r->u.update));
1280     r->u.update->which = Z_IUUpdate_esRequest;
1281     r->u.update->u.esRequest = (Z_IUUpdateEsRequest *)
1282         odr_malloc(out, sizeof(*r->u.update->u.esRequest));
1283     toKeep = r->u.update->u.esRequest->toKeep = (Z_IUOriginPartToKeep *)
1284         odr_malloc(out, sizeof(*r->u.update->u.esRequest->toKeep));
1285     toKeep->databaseName = databaseNames[0];
1286     toKeep->schema = 0;
1287     toKeep->elementSetName = 0;
1288     toKeep->actionQualifier = 0;
1289     toKeep->action = (int *) odr_malloc(out, sizeof(*toKeep->action));
1290     *toKeep->action = Z_IUOriginPartToKeep_recordInsert;
1291
1292     notToKeep = r->u.update->u.esRequest->notToKeep = (Z_IUSuppliedRecords *)
1293         odr_malloc(out, sizeof(*r->u.update->u.esRequest->notToKeep));
1294     notToKeep->num = 1;
1295     notToKeep->elements = (Z_IUSuppliedRecords_elem **)
1296         odr_malloc(out, sizeof(*notToKeep->elements));
1297     notToKeep->elements[0] = (Z_IUSuppliedRecords_elem *)
1298         odr_malloc(out, sizeof(**notToKeep->elements));
1299     notToKeep->elements[0]->u.number = 0;
1300     notToKeep->elements[0]->supplementalId = 0;
1301     notToKeep->elements[0]->correlationInfo = 0;
1302     notToKeep->elements[0]->record = record_last;
1303     
1304     send_apdu(apdu);
1305
1306     return 2;
1307 }
1308
1309 /* II : Added to do DALI Item Order Extended services request */
1310 static int cmd_itemorder(char *arg)
1311 {
1312     char type[12];
1313     int itemno;
1314
1315     if (sscanf (arg, "%10s %d", type, &itemno) != 2)
1316         return 0;
1317
1318     printf("Item order request\n");
1319     fflush(stdout);
1320     send_itemorder(type, itemno);
1321     return(2);
1322 }
1323
1324 static int cmd_find(char *arg)
1325 {
1326     if (!*arg)
1327     {
1328         printf("Find what?\n");
1329         return 0;
1330     }
1331     if (!conn)
1332     {
1333         printf("Not connected yet\n");
1334         return 0;
1335     }
1336     if (!send_searchRequest(arg))
1337         return 0;
1338     return 2;
1339 }
1340
1341 static int cmd_delete(char *arg)
1342 {
1343     if (!conn)
1344     {
1345         printf("Not connected yet\n");
1346         return 0;
1347     }
1348     if (!send_deleteResultSetRequest(arg))
1349         return 0;
1350     return 2;
1351 }
1352
1353 static int cmd_ssub(char *arg)
1354 {
1355     if (!(smallSetUpperBound = atoi(arg)))
1356         return 0;
1357     return 1;
1358 }
1359
1360 static int cmd_lslb(char *arg)
1361 {
1362     if (!(largeSetLowerBound = atoi(arg)))
1363         return 0;
1364     return 1;
1365 }
1366
1367 static int cmd_mspn(char *arg)
1368 {
1369     if (!(mediumSetPresentNumber = atoi(arg)))
1370         return 0;
1371     return 1;
1372 }
1373
1374 static int cmd_status(char *arg)
1375 {
1376     printf("smallSetUpperBound: %d\n", smallSetUpperBound);
1377     printf("largeSetLowerBound: %d\n", largeSetLowerBound);
1378     printf("mediumSetPresentNumber: %d\n", mediumSetPresentNumber);
1379     return 1;
1380 }
1381
1382 static int cmd_setnames(char *arg)
1383 {
1384     if (*arg == '1')         /* enable ? */
1385         setnumber = 0;
1386     else if (*arg == '0')    /* disable ? */
1387         setnumber = -1;
1388     else if (setnumber < 0)  /* no args, toggle .. */
1389         setnumber = 0;
1390     else
1391         setnumber = -1;
1392    
1393     if (setnumber >= 0)
1394         printf("Set numbering enabled.\n");
1395     else
1396         printf("Set numbering disabled.\n");
1397     return 1;
1398 }
1399
1400 /* PRESENT SERVICE ----------------------------- */
1401
1402 static int send_presentRequest(char *arg)
1403 {
1404     Z_APDU *apdu = zget_APDU(out, Z_APDU_presentRequest);
1405     Z_PresentRequest *req = apdu->u.presentRequest;
1406     Z_RecordComposition compo;
1407     oident prefsyn;
1408     int nos = 1;
1409     int oid[OID_SIZE];
1410     char *p;
1411     char setstring[100];
1412
1413     req->referenceId = set_refid (out);
1414     if ((p = strchr(arg, '+')))
1415     {
1416         nos = atoi(p + 1);
1417         *p = 0;
1418     }
1419     if (*arg)
1420         setno = atoi(arg);
1421     if (p && (p=strchr(p+1, '+')))
1422     {
1423         strcpy (setstring, p+1);
1424         req->resultSetId = setstring;
1425     }
1426     else if (setnumber >= 0)
1427     {
1428         sprintf(setstring, "%d", setnumber);
1429         req->resultSetId = setstring;
1430     }
1431 #if 0
1432     if (1)
1433     {
1434         static Z_Range range;
1435         static Z_Range *rangep = &range;
1436     req->num_ranges = 1;
1437 #endif
1438     req->resultSetStartPoint = &setno;
1439     req->numberOfRecordsRequested = &nos;
1440     prefsyn.proto = protocol;
1441     prefsyn.oclass = CLASS_RECSYN;
1442     prefsyn.value = recordsyntax;
1443     req->preferredRecordSyntax =
1444         odr_oiddup (out, oid_ent_to_oid(&prefsyn, oid));
1445
1446     if (schema != VAL_NONE)
1447     {
1448         oident prefschema;
1449
1450         prefschema.proto = protocol;
1451         prefschema.oclass = CLASS_SCHEMA;
1452         prefschema.value = schema;
1453
1454         req->recordComposition = &compo;
1455         compo.which = Z_RecordComp_complex;
1456         compo.u.complex = (Z_CompSpec *)
1457             odr_malloc(out, sizeof(*compo.u.complex));
1458         compo.u.complex->selectAlternativeSyntax = (bool_t *) 
1459             odr_malloc(out, sizeof(bool_t));
1460         *compo.u.complex->selectAlternativeSyntax = 0;
1461
1462         compo.u.complex->generic = (Z_Specification *)
1463             odr_malloc(out, sizeof(*compo.u.complex->generic));
1464         compo.u.complex->generic->schema = (Odr_oid *)
1465             odr_oiddup(out, oid_ent_to_oid(&prefschema, oid));
1466         if (!compo.u.complex->generic->schema)
1467         {
1468             /* OID wasn't a schema! Try record syntax instead. */
1469             prefschema.oclass = CLASS_RECSYN;
1470             compo.u.complex->generic->schema = (Odr_oid *)
1471                 odr_oiddup(out, oid_ent_to_oid(&prefschema, oid));
1472         }
1473         if (!elementSetNames)
1474             compo.u.complex->generic->elementSpec = 0;
1475         else
1476         {
1477             compo.u.complex->generic->elementSpec = (Z_ElementSpec *)
1478                 odr_malloc(out, sizeof(Z_ElementSpec));
1479             compo.u.complex->generic->elementSpec->which =
1480                 Z_ElementSpec_elementSetName;
1481             compo.u.complex->generic->elementSpec->u.elementSetName =
1482                 elementSetNames->u.generic;
1483         }
1484         compo.u.complex->num_dbSpecific = 0;
1485         compo.u.complex->dbSpecific = 0;
1486         compo.u.complex->num_recordSyntax = 0;
1487         compo.u.complex->recordSyntax = 0;
1488     }
1489     else if (elementSetNames)
1490     {
1491         req->recordComposition = &compo;
1492         compo.which = Z_RecordComp_simple;
1493         compo.u.simple = elementSetNames;
1494     }
1495     send_apdu(apdu);
1496     printf("Sent presentRequest (%d+%d).\n", setno, nos);
1497     return 2;
1498 }
1499
1500 void process_close(Z_Close *req)
1501 {
1502     Z_APDU *apdu = zget_APDU(out, Z_APDU_close);
1503     Z_Close *res = apdu->u.close;
1504
1505     static char *reasons[] =
1506     {
1507         "finished",
1508         "shutdown",
1509         "system problem",
1510         "cost limit reached",
1511         "resources",
1512         "security violation",
1513         "protocolError",
1514         "lack of activity",
1515         "peer abort",
1516         "unspecified"
1517     };
1518
1519     printf("Reason: %s, message: %s\n", reasons[*req->closeReason],
1520         req->diagnosticInformation ? req->diagnosticInformation : "NULL");
1521     if (sent_close)
1522     {
1523         cs_close (conn);
1524         conn = NULL;
1525         if (session_mem)
1526         {
1527             nmem_destroy (session_mem);
1528             session_mem = NULL;
1529         }
1530         sent_close = 0;
1531     }
1532     else
1533     {
1534         *res->closeReason = Z_Close_finished;
1535         send_apdu(apdu);
1536         printf("Sent response.\n");
1537         sent_close = 1;
1538     }
1539 }
1540
1541 static int cmd_show(char *arg)
1542 {
1543     if (!conn)
1544     {
1545         printf("Not connected yet\n");
1546         return 0;
1547     }
1548     if (!send_presentRequest(arg))
1549         return 0;
1550     return 2;
1551 }
1552
1553 int cmd_quit(char *arg)
1554 {
1555     printf("See you later, alligator.\n");
1556     xmalloc_trav ("");
1557     exit(0);
1558     return 0;
1559 }
1560
1561 int cmd_cancel(char *arg)
1562 {
1563     Z_APDU *apdu = zget_APDU(out, Z_APDU_triggerResourceControlRequest);
1564     Z_TriggerResourceControlRequest *req =
1565         apdu->u.triggerResourceControlRequest;
1566     bool_t rfalse = 0;
1567     
1568     if (!conn)
1569     {
1570         printf("Session not initialized yet\n");
1571         return 0;
1572     }
1573     if (!ODR_MASK_GET(session->options, Z_Options_triggerResourceCtrl))
1574     {
1575         printf("Target doesn't support cancel (trigger resource ctrl)\n");
1576         return 0;
1577     }
1578     *req->requestedAction = Z_TriggerResourceCtrl_cancel;
1579     req->resultSetWanted = &rfalse;
1580
1581     send_apdu(apdu);
1582     printf("Sent cancel request\n");
1583     return 2;
1584 }
1585
1586 int send_scanrequest(const char *query, int pp, int num, const char *term)
1587 {
1588     Z_APDU *apdu = zget_APDU(out, Z_APDU_scanRequest);
1589     Z_ScanRequest *req = apdu->u.scanRequest;
1590     int use_rpn = 1;
1591 #if YAZ_MODULE_ccl
1592     int oid[OID_SIZE];
1593     
1594     if (queryType == QueryType_CCL2RPN)
1595     {
1596         oident bib1;
1597         int error, pos;
1598         struct ccl_rpn_node *rpn;
1599
1600         rpn = ccl_find_str (bibset,  query, &error, &pos);
1601         if (error)
1602         {
1603             printf("CCL ERROR: %s\n", ccl_err_msg(error));
1604             return -1;
1605         }
1606         use_rpn = 0;
1607         bib1.proto = PROTO_Z3950;
1608         bib1.oclass = CLASS_ATTSET;
1609         bib1.value = VAL_BIB1;
1610         req->attributeSet = oid_ent_to_oid (&bib1, oid);
1611         if (!(req->termListAndStartPoint = ccl_scan_query (out, rpn)))
1612         {
1613             printf("Couldn't convert CCL to Scan term\n");
1614             return -1;
1615         }
1616         ccl_rpn_delete (rpn);
1617     }
1618 #endif
1619     if (use_rpn && !(req->termListAndStartPoint =
1620                      p_query_scan(out, protocol, &req->attributeSet, query)))
1621     {
1622         printf("Prefix query error\n");
1623         return -1;
1624     }
1625     if (term && *term)
1626     {
1627         if (req->termListAndStartPoint->term &&
1628             req->termListAndStartPoint->term->which == Z_Term_general &&
1629             req->termListAndStartPoint->term->u.general)
1630         {
1631             req->termListAndStartPoint->term->u.general->buf =
1632                 (unsigned char *) odr_strdup(out, term);
1633             req->termListAndStartPoint->term->u.general->len =
1634                 req->termListAndStartPoint->term->u.general->size =
1635                 strlen(term);
1636         }
1637     }
1638     req->referenceId = set_refid (out);
1639     req->num_databaseNames = num_databaseNames;
1640     req->databaseNames = databaseNames;
1641     req->numberOfTermsRequested = &num;
1642     req->preferredPositionInResponse = &pp;
1643     send_apdu(apdu);
1644     return 2;
1645 }
1646
1647 int send_sortrequest(char *arg, int newset)
1648 {
1649     Z_APDU *apdu = zget_APDU(out, Z_APDU_sortRequest);
1650     Z_SortRequest *req = apdu->u.sortRequest;
1651     Z_SortKeySpecList *sksl = (Z_SortKeySpecList *)
1652         odr_malloc (out, sizeof(*sksl));
1653     char setstring[32];
1654
1655     if (setnumber >= 0)
1656         sprintf (setstring, "%d", setnumber);
1657     else
1658         sprintf (setstring, "default");
1659
1660     req->referenceId = set_refid (out);
1661
1662     req->num_inputResultSetNames = 1;
1663     req->inputResultSetNames = (Z_InternationalString **)
1664         odr_malloc (out, sizeof(*req->inputResultSetNames));
1665     req->inputResultSetNames[0] = odr_strdup (out, setstring);
1666
1667     if (newset && setnumber >= 0)
1668         sprintf (setstring, "%d", ++setnumber);
1669
1670     req->sortedResultSetName = odr_strdup (out, setstring);
1671
1672     req->sortSequence = yaz_sort_spec (out, arg);
1673     if (!req->sortSequence)
1674     {
1675         printf ("Missing sort specifications\n");
1676         return -1;
1677     }
1678     send_apdu(apdu);
1679     return 2;
1680 }
1681
1682 void display_term(Z_TermInfo *t)
1683 {
1684     if (t->term->which == Z_Term_general)
1685     {
1686         printf("%.*s", t->term->u.general->len, t->term->u.general->buf);
1687         sprintf(last_scan_line, "%.*s", t->term->u.general->len,
1688             t->term->u.general->buf);
1689     }
1690     else
1691         printf("Term (not general)");
1692     if (t->globalOccurrences)
1693         printf (" (%d)\n", *t->globalOccurrences);
1694     else
1695         printf ("\n");
1696 }
1697
1698 void process_scanResponse(Z_ScanResponse *res)
1699 {
1700     int i;
1701     Z_Entry **entries = NULL;
1702     int num_entries = 0;
1703    
1704     printf("Received ScanResponse\n"); 
1705     print_refid (res->referenceId);
1706     printf("%d entries", *res->numberOfEntriesReturned);
1707     if (res->positionOfTerm)
1708         printf (", position=%d", *res->positionOfTerm); 
1709     printf ("\n");
1710     if (*res->scanStatus != Z_Scan_success)
1711         printf("Scan returned code %d\n", *res->scanStatus);
1712     if (!res->entries)
1713         return;
1714     if ((entries = res->entries->entries))
1715         num_entries = res->entries->num_entries;
1716     for (i = 0; i < num_entries; i++)
1717     {
1718         int pos_term = res->positionOfTerm ? *res->positionOfTerm : -1;
1719         if (entries[i]->which == Z_Entry_termInfo)
1720         {
1721             printf("%c ", i + 1 == pos_term ? '*' : ' ');
1722             display_term(entries[i]->u.termInfo);
1723         }
1724         else
1725             display_diagrecs(&entries[i]->u.surrogateDiagnostic, 1);
1726     }
1727     if (res->entries->nonsurrogateDiagnostics)
1728         display_diagrecs (res->entries->nonsurrogateDiagnostics,
1729                           res->entries->num_nonsurrogateDiagnostics);
1730 }
1731
1732 void process_sortResponse(Z_SortResponse *res)
1733 {
1734     printf("Received SortResponse: status=");
1735     switch (*res->sortStatus)
1736     {
1737     case Z_SortStatus_success:
1738         printf ("success"); break;
1739     case Z_SortStatus_partial_1:
1740         printf ("partial"); break;
1741     case Z_SortStatus_failure:
1742         printf ("failure"); break;
1743     default:
1744         printf ("unknown (%d)", *res->sortStatus);
1745     }
1746     printf ("\n");
1747     print_refid (res->referenceId);
1748     if (res->diagnostics)
1749         display_diagrecs(res->diagnostics,
1750                          res->num_diagnostics);
1751 }
1752
1753 void process_deleteResultSetResponse (Z_DeleteResultSetResponse *res)
1754 {
1755     printf("Got deleteResultSetResponse status=%d\n",
1756            *res->deleteOperationStatus);
1757     if (res->deleteListStatuses)
1758     {
1759         int i;
1760         for (i = 0; i < res->deleteListStatuses->num; i++)
1761         {
1762             printf ("%s status=%d\n", res->deleteListStatuses->elements[i]->id,
1763                     *res->deleteListStatuses->elements[i]->status);
1764         }
1765     }
1766 }
1767
1768 int cmd_sort_generic(char *arg, int newset)
1769 {
1770     if (!conn)
1771     {
1772         printf("Session not initialized yet\n");
1773         return 0;
1774     }
1775     if (!ODR_MASK_GET(session->options, Z_Options_sort))
1776     {
1777         printf("Target doesn't support sort\n");
1778         return 0;
1779     }
1780     if (*arg)
1781     {
1782         if (send_sortrequest(arg, newset) < 0)
1783             return 0;
1784         return 2;
1785     }
1786     return 0;
1787 }
1788
1789 int cmd_sort(char *arg)
1790 {
1791     return cmd_sort_generic (arg, 0);
1792 }
1793
1794 int cmd_sort_newset (char *arg)
1795 {
1796     return cmd_sort_generic (arg, 1);
1797 }
1798
1799 int cmd_scan(char *arg)
1800 {
1801     if (!conn)
1802     {
1803         printf("Session not initialized yet\n");
1804         return 0;
1805     }
1806     if (!ODR_MASK_GET(session->options, Z_Options_scan))
1807     {
1808         printf("Target doesn't support scan\n");
1809         return 0;
1810     }
1811     if (*arg)
1812     {
1813         strcpy (last_scan_query, arg);
1814         if (send_scanrequest(arg, 1, 20, 0) < 0)
1815             return 0;
1816     }
1817     else
1818     {
1819         if (send_scanrequest(last_scan_query, 1, 20, last_scan_line) < 0)
1820             return 0;
1821     }
1822     return 2;
1823 }
1824
1825 int cmd_schema(char *arg)
1826 {
1827     if (!arg || !*arg)
1828     {
1829         schema = VAL_NONE;
1830         return 1;
1831     }
1832     schema = oid_getvalbyname (arg);
1833     if (schema == VAL_NONE)
1834     {
1835         printf ("unknown schema\n");
1836         return 0;
1837     }
1838     return 1;
1839 }
1840
1841 int cmd_format(char *arg)
1842 {
1843     if (!arg || !*arg)
1844     {
1845         printf("Usage: format <recordsyntax>\n");
1846         return 0;
1847     }
1848     recordsyntax = oid_getvalbyname (arg);
1849     if (recordsyntax == VAL_NONE)
1850     {
1851         printf ("unknown record syntax\n");
1852         return 0;
1853     }
1854     return 1;
1855 }
1856
1857 int cmd_elements(char *arg)
1858 {
1859     static Z_ElementSetNames esn;
1860     static char what[100];
1861
1862     if (!arg || !*arg)
1863     {
1864         elementSetNames = 0;
1865         return 1;
1866     }
1867     strcpy(what, arg);
1868     esn.which = Z_ElementSetNames_generic;
1869     esn.u.generic = what;
1870     elementSetNames = &esn;
1871     return 1;
1872 }
1873
1874 int cmd_attributeset(char *arg)
1875 {
1876     char what[100];
1877
1878     if (!arg || !*arg)
1879     {
1880         printf("Usage: attributeset <setname>\n");
1881         return 0;
1882     }
1883     sscanf(arg, "%s", what);
1884     if (p_query_attset (what))
1885     {
1886         printf("Unknown attribute set name\n");
1887         return 0;
1888     }
1889     return 1;
1890 }
1891
1892 int cmd_querytype (char *arg)
1893 {
1894     if (!strcmp (arg, "ccl"))
1895         queryType = QueryType_CCL;
1896     else if (!strcmp (arg, "prefix") || !strcmp(arg, "rpn"))
1897         queryType = QueryType_Prefix;
1898 #if YAZ_MODULE_ccl
1899     else if (!strcmp (arg, "ccl2rpn") || !strcmp (arg, "cclrpn"))
1900         queryType = QueryType_CCL2RPN;
1901 #endif
1902     else
1903     {
1904         printf ("Querytype must be one of:\n");
1905         printf (" prefix         - Prefix query\n");
1906         printf (" ccl            - CCL query\n");
1907 #if YAZ_MODULE_ccl
1908         printf (" ccl2rpn        - CCL query converted to RPN\n");
1909 #endif
1910         return 0;
1911     }
1912     return 1;
1913 }
1914
1915 int cmd_refid (char *arg)
1916 {
1917     xfree (refid);
1918     refid = NULL;
1919     if (*arg)
1920     {
1921         refid = (char *) xmalloc (strlen(arg)+1);
1922         strcpy (refid, arg);
1923     }
1924     return 1;
1925 }
1926
1927 int cmd_close(char *arg)
1928 {
1929     Z_APDU *apdu;
1930     Z_Close *req;
1931     if (!conn)
1932         return 0;
1933
1934     apdu = zget_APDU(out, Z_APDU_close);
1935     req = apdu->u.close;
1936     *req->closeReason = Z_Close_finished;
1937     send_apdu(apdu);
1938     printf("Sent close request.\n");
1939     sent_close = 1;
1940     return 2;
1941 }
1942
1943 int cmd_packagename(char* arg) {
1944     xfree (esPackageName);
1945     esPackageName = NULL;
1946     if (*arg)
1947     {
1948         esPackageName = (char *) xmalloc (strlen(arg)+1);
1949         strcpy (esPackageName, arg);
1950     }
1951     return 1;
1952 };
1953
1954 int cmd_proxy(char* arg) {
1955     xfree (yazProxy);
1956     yazProxy = NULL;
1957     if (*arg)
1958     {
1959         yazProxy = (char *) xmalloc (strlen(arg)+1);
1960         strcpy (yazProxy, arg);
1961     } 
1962     return 1;
1963 };
1964
1965 int cmd_source(char* arg) 
1966 {
1967     /* first should open the file and read one line at a time.. */
1968     FILE* includeFile;
1969     char line[1024], *cp;
1970     
1971     if(strlen(arg)<1) {
1972         fprintf(stderr,"Error in source command use a filename");
1973         return -1;
1974     };
1975     
1976     includeFile = fopen (arg, "r");
1977     
1978     if(!includeFile) {
1979         fprintf(stderr,"Unable to open file %s for reading\n",arg);
1980         return -1;
1981     };
1982     
1983     
1984     while(!feof(includeFile)) {
1985         memset(line,0,sizeof(line));
1986         fgets(line,sizeof(line),includeFile);
1987         
1988         if(strlen(line) < 2) continue;
1989         if(line[0] == '#') continue;
1990         
1991         if ((cp = strrchr (line, '\n')))
1992             *cp = '\0';
1993         
1994         process_cmd_line(line);
1995     };  
1996     
1997     
1998     if(fclose(includeFile)<0) {
1999         perror("unable to close include file");
2000         exit(1);
2001     }
2002     return 1;
2003 }
2004
2005 int cmd_subshell(char* args) {
2006     system(args);
2007     return 1;
2008 }
2009
2010 static void initialize(void)
2011 {
2012 #if YAZ_MODULE_ccl
2013     FILE *inf;
2014 #endif
2015     if (!(out = odr_createmem(ODR_ENCODE)) ||
2016         !(in = odr_createmem(ODR_DECODE)) ||
2017         !(print = odr_createmem(ODR_PRINT)))
2018     {
2019         fprintf(stderr, "failed to allocate ODR streams\n");
2020         exit(1);
2021     }
2022     setvbuf(stdout, 0, _IONBF, 0);
2023     if (apdu_file)
2024         odr_setprint(print, apdu_file);
2025
2026 #if YAZ_MODULE_ccl
2027     bibset = ccl_qual_mk (); 
2028     inf = fopen (ccl_fields, "r");
2029     if (inf)
2030     {
2031         ccl_qual_file (bibset, inf);
2032         fclose (inf);
2033     }
2034 #endif
2035     cmd_base("Default");
2036 }
2037
2038
2039 #if HAVE_GETTIMEOFDAY
2040 struct timeval tv_start, tv_end;
2041 #endif
2042
2043 void  wait_and_handle_responce() 
2044 {
2045     
2046     int res;
2047     char *netbuffer= 0;
2048     int netbufferlen = 0;
2049     Z_APDU *apdu;
2050     
2051     
2052     if (conn
2053 #ifdef USE_SELECT
2054         && FD_ISSET(cs_fileno(conn), &input)
2055 #endif
2056         )
2057     {
2058         do
2059         {
2060             if ((res = cs_get(conn, &netbuffer, &netbufferlen)) < 0)
2061             {
2062                 perror("cs_get");
2063                 exit(1);
2064             }
2065             if (!res)
2066             {
2067                 printf("Target closed connection.\n");
2068                 exit(1);
2069             }
2070             odr_reset(in); /* release APDU from last round */
2071             record_last = 0;
2072             odr_setbuf(in, netbuffer, res, 0);
2073             if (!z_APDU(in, &apdu, 0, 0))
2074             {
2075                 odr_perror(in, "Decoding incoming APDU");
2076                 fprintf(stderr, "[Near %d]\n", odr_offset(in));
2077                 fprintf(stderr, "Packet dump:\n---------\n");
2078                 odr_dumpBER(stderr, netbuffer, res);
2079                 fprintf(stderr, "---------\n");
2080                 if (apdu_file)
2081                     z_APDU(print, &apdu, 0, 0);
2082                 exit(1);
2083             }
2084             if (apdu_file && !z_APDU(print, &apdu, 0, 0))
2085             {
2086                 odr_perror(print, "Failed to print incoming APDU");
2087                 odr_reset(print);
2088                 continue;
2089             }
2090             switch(apdu->which)
2091             {
2092             case Z_APDU_initResponse:
2093                 process_initResponse(apdu->u.initResponse);
2094                 break;
2095             case Z_APDU_searchResponse:
2096                 process_searchResponse(apdu->u.searchResponse);
2097                 break;
2098             case Z_APDU_scanResponse:
2099                 process_scanResponse(apdu->u.scanResponse);
2100                 break;
2101             case Z_APDU_presentResponse:
2102                 print_refid (apdu->u.presentResponse->referenceId);
2103                 setno +=
2104                     *apdu->u.presentResponse->numberOfRecordsReturned;
2105                 if (apdu->u.presentResponse->records)
2106                     display_records(apdu->u.presentResponse->records);
2107                 else
2108                     printf("No records.\n");
2109                 printf ("nextResultSetPosition = %d\n",
2110                         *apdu->u.presentResponse->nextResultSetPosition);
2111                 break;
2112             case Z_APDU_sortResponse:
2113                 process_sortResponse(apdu->u.sortResponse);
2114                 break;
2115             case Z_APDU_extendedServicesResponse:
2116                 printf("Got extended services response\n");
2117                 process_ESResponse(apdu->u.extendedServicesResponse);
2118                 break;
2119             case Z_APDU_close:
2120                 printf("Target has closed the association.\n");
2121                 process_close(apdu->u.close);
2122                 break;
2123             case Z_APDU_resourceControlRequest:
2124                 process_resourceControlRequest
2125                     (apdu->u.resourceControlRequest);
2126                 break;
2127             case Z_APDU_deleteResultSetResponse:
2128                 process_deleteResultSetResponse(apdu->u.
2129                                                 deleteResultSetResponse);
2130                 break;
2131             default:
2132                 printf("Received unknown APDU type (%d).\n", 
2133                        apdu->which);
2134                 exit(1);
2135             }
2136         }
2137         while (conn && cs_more(conn));
2138 #if HAVE_GETTIMEOFDAY
2139         gettimeofday (&tv_end, 0);
2140 #if 0
2141         printf ("S/U S/U=%ld/%ld %ld/%ld",
2142                 (long) tv_start.tv_sec,
2143                 (long) tv_start.tv_usec,
2144                 (long) tv_end.tv_sec,
2145                 (long) tv_end.tv_usec);
2146 #endif
2147         printf ("Elapsed: %.6f\n",
2148                 (double) tv_end.tv_usec / 1e6 + tv_end.tv_sec -
2149                 ((double) tv_start.tv_usec / 1e6 + tv_start.tv_sec));
2150 #endif
2151     }
2152 }
2153
2154 void process_cmd_line(char* line)
2155 {
2156     static struct {
2157         char *cmd;
2158         int (*fun)(char *arg);
2159         char *ad;
2160     } cmd[] = {
2161         {"open", cmd_open, "('tcp'|'ssl')':<host>[':'<port>][/<db>]"},
2162         {"quit", cmd_quit, ""},
2163         {"find", cmd_find, "<query>"},
2164         {"delete", cmd_delete, "<setname>"},
2165         {"base", cmd_base, "<base-name>"},
2166         {"show", cmd_show, "<rec#>['+'<#recs>['+'<setname>]]"},
2167         {"scan", cmd_scan, "<term>"},
2168         {"sort", cmd_sort, "<sortkey> <flag> <sortkey> <flag> ..."},
2169         {"sort+", cmd_sort_newset, "<sortkey> <flag> <sortkey> <flag> ..."},
2170         {"authentication", cmd_authentication, "<acctstring>"},
2171         {"lslb", cmd_lslb, "<largeSetLowerBound>"},
2172         {"ssub", cmd_ssub, "<smallSetUpperBound>"},
2173         {"mspn", cmd_mspn, "<mediumSetPresentNumber>"},
2174         {"status", cmd_status, ""},
2175         {"setnames", cmd_setnames, ""},
2176         {"cancel", cmd_cancel, ""},
2177         {"format", cmd_format, "<recordsyntax>"},
2178         {"schema", cmd_schema, "<schema>"},
2179         {"elements", cmd_elements, "<elementSetName>"},
2180         {"close", cmd_close, ""},
2181         {"attributeset", cmd_attributeset, "<attrset>"},
2182         {"querytype", cmd_querytype, "<type>"},
2183         {"refid", cmd_refid, "<id>"},
2184         {"itemorder", cmd_itemorder, "ill|item <itemno>"},
2185         {"update", cmd_update, "<item>"},
2186         {"packagename", cmd_packagename, "<packagename>"},
2187         {"proxy", cmd_proxy, "('tcp'|'osi')':'[<tsel>'/']<host>[':'<port>]"},
2188         {".", cmd_source, "<filename>"},
2189         {"!", cmd_subshell, "Subshell command"},
2190         /* Server Admin Functions */
2191         {"adm-reindex", cmd_adm_reindex, "<database-name>"},
2192         {"adm-truncate", cmd_adm_truncate, "('database'|'index')<object-name>"},
2193         {"adm-create", cmd_adm_create, ""},
2194         {"adm-drop", cmd_adm_drop, "('database'|'index')<object-name>"},
2195         {"adm-import", cmd_adm_import, "<record-type> <dir> <pattern>"},
2196         {"adm-refresh", cmd_adm_refresh, ""},
2197         {"adm-commit", cmd_adm_commit, ""},
2198         {"adm-shutdown", cmd_adm_shutdown, ""},
2199         {"adm-startup", cmd_adm_startup, ""},
2200         {0,0}
2201     };
2202     int i,res;
2203     char word[32], arg[1024];
2204     
2205     
2206 #if HAVE_GETTIMEOFDAY
2207     gettimeofday (&tv_start, 0);
2208 #endif
2209     
2210     if ((res = sscanf(line, "%31s %1023[^;]", word, arg)) <= 0)
2211     {
2212         strcpy(word, last_cmd);
2213         *arg = '\0';
2214     }
2215     else if (res == 1)
2216         *arg = 0;
2217     strcpy(last_cmd, word);
2218     for (i = 0; cmd[i].cmd; i++)
2219         if (!strncmp(cmd[i].cmd, word, strlen(word)))
2220         {
2221             res = (*cmd[i].fun)(arg);
2222             break;
2223         }
2224     if (!cmd[i].cmd) /* dump our help-screen */
2225     {
2226         printf("Unknown command: %s.\n", word);
2227         printf("Currently recognized commands:\n");
2228         for (i = 0; cmd[i].cmd; i++)
2229             printf("   %s %s\n", cmd[i].cmd, cmd[i].ad);
2230         return;
2231     }
2232     if (res >= 2)
2233         wait_and_handle_responce();
2234 }
2235
2236
2237
2238 static void client(void)
2239 {
2240
2241 #if HAVE_GETTIMEOFDAY
2242     gettimeofday (&tv_start, 0);
2243 #endif
2244
2245     while (1)
2246     {
2247 #ifdef USE_SELECT
2248         fd_set input;
2249 #endif
2250         char line[1024];
2251         
2252         {
2253 #if HAVE_READLINE_READLINE_H
2254             char* line_in;
2255             line_in=readline(C_PROMPT);
2256             if (!line_in)
2257                 break;
2258 #if HAVE_READLINE_HISTORY_H
2259             if (*line_in)
2260                 add_history(line_in);
2261 #endif
2262             strcpy(line,line_in);
2263             free (line_in);
2264 #else    
2265             char *end_p;
2266             printf (C_PROMPT);
2267             fflush(stdout);
2268             if (!fgets(line, 1023, stdin))
2269                 break;
2270             if ((end_p = strchr (line, '\n')))
2271                 *end_p = '\0';
2272 #endif 
2273             process_cmd_line(line);
2274         }
2275     }
2276 }
2277
2278 int main(int argc, char **argv)
2279 {
2280     char *prog = *argv;
2281     char *open_command = 0;
2282     char *auth_command = 0;
2283     char *arg;
2284     int ret;
2285
2286     while ((ret = options("k:c:a:m:v:p:u:", argv, argc, &arg)) != -2)
2287     {
2288         switch (ret)
2289         {
2290         case 0:
2291             if (!open_command)
2292             {
2293                 open_command = xmalloc (strlen(arg)+6);
2294                 strcpy (open_command, "open ");
2295                 strcat (open_command, arg);
2296             }
2297             break;
2298         case 'k':
2299             kilobytes = atoi(arg);
2300             break;
2301         case 'm':
2302             if (!(marcdump = fopen (arg, "a")))
2303             {
2304                 perror (arg);
2305                 exit (1);
2306             }
2307             break;
2308         case 'c':
2309             strncpy (ccl_fields, arg, sizeof(ccl_fields)-1);
2310             ccl_fields[sizeof(ccl_fields)-1] = '\0';
2311             break;
2312         case 'a':
2313             if (!strcmp(arg, "-"))
2314                 apdu_file=stderr;
2315             else
2316                 apdu_file=fopen(arg, "a");
2317             break;
2318         case 'p':
2319             yazProxy=strdup(arg);
2320             break;
2321         case 'u':
2322             if (!auth_command)
2323             {
2324                 auth_command = xmalloc (strlen(arg)+6);
2325                 strcpy (auth_command, "auth ");
2326                 strcat (auth_command, arg);
2327             }
2328             break;
2329         case 'v':
2330             yaz_log_init (yaz_log_mask_str(arg), "", NULL);
2331             break;
2332         default:
2333             fprintf (stderr, "Usage: %s [-m <marclog>] [ -a <apdulog>] "
2334                      "[-c cclfields]\n      [-p <proxy-addr>] [-u <auth>] "
2335                      "[<server-addr>]\n",
2336                      prog);
2337             exit (1);
2338         }
2339     }
2340     initialize();
2341     if (auth_command)
2342     {
2343 #ifdef HAVE_GETTIMEOFDAY
2344         gettimeofday (&tv_start, 0);
2345 #endif
2346         process_cmd_line (auth_command);
2347 #if HAVE_READLINE_HISTORY_H
2348         add_history(auth_command);
2349 #endif
2350         xfree(auth_command);
2351     }
2352     if (open_command)
2353     {
2354 #ifdef HAVE_GETTIMEOFDAY
2355         gettimeofday (&tv_start, 0);
2356 #endif
2357         process_cmd_line (open_command);
2358 #if HAVE_READLINE_HISTORY_H
2359         add_history(open_command);
2360 #endif
2361         xfree(open_command);
2362     }
2363     client ();
2364     exit (0);
2365 }