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