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