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