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