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