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