Added second part of helper functions for CharSetandLanguageNegotaiation-3 Model.
[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.153 2002-05-19 15:39:54 oleg 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 #include <yaz/charneg.h>
24
25 #include <yaz/pquery.h>
26 #include <yaz/sortspec.h>
27
28 #if YAZ_MODULE_ill
29 #include <yaz/ill.h>
30 #endif
31
32 #if YAZ_MODULE_ccl
33 #include <yaz/yaz-ccl.h>
34 #endif
35
36 #if HAVE_READLINE_READLINE_H
37 #include <readline/readline.h>
38 #endif
39 #if HAVE_READLINE_HISTORY_H
40 #include <readline/history.h>
41 #endif
42
43 #include <sys/stat.h>
44
45
46 #include "admin.h"
47 #include "tabcomplete.h"
48
49 #define C_PROMPT "Z> "
50
51 static ODR out, in, print;              /* encoding and decoding streams */
52 static FILE *apdu_file = 0;
53 static COMSTACK conn = 0;               /* our z-association */
54 static Z_IdAuthentication *auth = 0;    /* our current auth definition */
55 char *databaseNames[128];
56 int num_databaseNames = 0;
57 static Z_External *record_last = 0;
58 static int setnumber = -1;               /* current result set number */
59 static int smallSetUpperBound = 0;
60 static int largeSetLowerBound = 1;
61 static int mediumSetPresentNumber = 0;
62 static Z_ElementSetNames *elementSetNames = 0; 
63 static int setno = 1;                   /* current set offset */
64 static enum oid_proto protocol = PROTO_Z3950;      /* current app protocol */
65 static enum oid_value recordsyntax = VAL_USMARC;
66 static enum oid_value schema = VAL_NONE;
67 static int sent_close = 0;
68 static NMEM session_mem = NULL;      /* memory handle for init-response */
69 static Z_InitResponse *session = 0;     /* session parameters */
70 static char last_scan_line[512] = "0";
71 static char last_scan_query[512] = "0";
72 static char ccl_fields[512] = "default.bib";
73 static char* esPackageName = 0;
74 static char* yazProxy = 0;
75 static int kilobytes = 1024;
76 static char* yazCharset = 0;
77 static char* yazLang = 0;
78
79 static char last_cmd[32] = "?";
80 static FILE *marcdump = 0;
81 static char *refid = NULL;
82
83 typedef enum {
84     QueryType_Prefix,
85     QueryType_CCL,
86     QueryType_CCL2RPN
87 } QueryType;
88
89 static QueryType queryType = QueryType_Prefix;
90
91 #if YAZ_MODULE_ccl
92 static CCL_bibset bibset;               /* CCL bibset handle */
93 #endif
94
95 #if HAVE_READLINE_COMPLETION_OVER
96
97 #else
98 /* readline doesn't have this var. Define it ourselves. */
99 int rl_attempted_completion_over = 0;
100 #endif
101
102 /* set this one to 1, to avoid decode of unknown MARCs  */
103 #define AVOID_MARC_DECODE 1
104
105 /* nice helper macro as extensive tabbing gives spaces at the en of the args lines */
106 #define REMOVE_TAILING_BLANKS(a) {\
107   char* args_end=(a)+strlen(a)-1; \
108   while(isspace(*args_end)) {*args_end=0;--args_end;}; \
109   }
110
111
112 void process_cmd_line(char* line);
113 char ** readline_completer(char *text, int start, int end);
114 char *command_generator(const char *text, int state);
115
116
117 ODR getODROutputStream()
118 {
119     return out;
120 }
121
122 void send_apdu(Z_APDU *a)
123 {
124     char *buf;
125     int len;
126
127     if (apdu_file)
128     {
129         z_APDU(print, &a, 0, 0);
130         odr_reset(print);
131     }
132     if (!z_APDU(out, &a, 0, 0))
133     {
134         odr_perror(out, "Encoding APDU");
135         exit(1);
136     }
137     buf = odr_getbuf(out, &len, 0);
138     /* printf ("sending APDU of size %d\n", len); */
139     if (cs_put(conn, buf, len) < 0)
140     {
141         fprintf(stderr, "cs_put: %s", cs_errmsg(cs_errno(conn)));
142         exit(1);
143     }
144     odr_reset(out); /* release the APDU structure  */
145 }
146
147 static void print_stringn(const unsigned char *buf, size_t len)
148 {
149    size_t i;
150    for (i = 0; i<len; i++)
151        if ((buf[i] <= 126 && buf[i] >= 32) || strchr ("\n\r\t\f", buf[i]))
152            printf ("%c", buf[i]);
153        else
154            printf ("\\X%02X", buf[i]);
155 }
156
157 static void print_refid (Z_ReferenceId *id)
158 {
159     if (id)
160     {
161         printf ("Reference Id: ");
162         print_stringn (id->buf, id->len);
163         printf ("\n");
164     }
165 }
166
167 static Z_ReferenceId *set_refid (ODR out)
168 {
169     Z_ReferenceId *id;
170     if (!refid)
171         return 0;
172     id = (Z_ReferenceId *) odr_malloc (out, sizeof(*id));
173     id->size = id->len = strlen(refid);
174     id->buf = (unsigned char *) odr_malloc (out, id->len);
175     memcpy (id->buf, refid, id->len);
176     return id;
177 }   
178
179 /* INIT SERVICE ------------------------------- */
180
181 static void send_initRequest(const char* type_and_host)
182 {
183     Z_APDU *apdu = zget_APDU(out, Z_APDU_initRequest);
184     Z_InitRequest *req = apdu->u.initRequest;
185
186     ODR_MASK_SET(req->options, Z_Options_search);
187     ODR_MASK_SET(req->options, Z_Options_present);
188     ODR_MASK_SET(req->options, Z_Options_namedResultSets);
189     ODR_MASK_SET(req->options, Z_Options_triggerResourceCtrl);
190     ODR_MASK_SET(req->options, Z_Options_scan);
191     ODR_MASK_SET(req->options, Z_Options_sort);
192     ODR_MASK_SET(req->options, Z_Options_extendedServices);
193     ODR_MASK_SET(req->options, Z_Options_delSet);
194
195     ODR_MASK_SET(req->protocolVersion, Z_ProtocolVersion_1);
196     ODR_MASK_SET(req->protocolVersion, Z_ProtocolVersion_2);
197     ODR_MASK_SET(req->protocolVersion, Z_ProtocolVersion_3);
198
199     *req->maximumRecordSize = 1024*kilobytes;
200     *req->preferredMessageSize = 1024*kilobytes;
201
202     req->idAuthentication = auth;
203
204     req->referenceId = set_refid (out);
205
206     if (yazProxy) 
207         yaz_oi_set_string_oidval(&req->otherInfo, out, VAL_PROXY,
208         1, type_and_host);
209     
210     if (yazCharset || yazLang) {
211         Z_OtherInformation **p;
212         Z_OtherInformationUnit *p0;
213         
214         yaz_oi_APDU(apdu, &p);
215         
216         if (p0=yaz_oi_update(p, out, NULL, 0, 0)) {
217                 ODR_MASK_SET(req->options, Z_Options_negotiationModel);
218                 
219                 p0->which = Z_OtherInfo_externallyDefinedInfo;
220                 p0->information.externallyDefinedInfo =
221                         yaz_set_proposal_charneg(out,
222                                 (const char**)&yazCharset, (yazCharset)?1:0,
223                                 (const char**)&yazLang, (yazLang)?1:0, 1);
224         }
225     }
226     
227     send_apdu(apdu);
228     printf("Sent initrequest.\n");
229 }
230
231 static int process_initResponse(Z_InitResponse *res)
232 {
233     /* save session parameters for later use */
234     session_mem = odr_extract_mem(in);
235     session = res;
236
237     if (!*res->result)
238         printf("Connection rejected by target.\n");
239     else
240         printf("Connection accepted by target.\n");
241     if (res->implementationId)
242         printf("ID     : %s\n", res->implementationId);
243     if (res->implementationName)
244         printf("Name   : %s\n", res->implementationName);
245     if (res->implementationVersion)
246         printf("Version: %s\n", res->implementationVersion);
247     if (res->userInformationField)
248     {
249         printf("UserInformationfield:\n");
250         if (!z_External(print, (Z_External**)&res-> userInformationField,
251             0, 0))
252         {
253             odr_perror(print, "Printing userinfo\n");
254             odr_reset(print);
255         }
256         if (res->userInformationField->which == Z_External_octet)
257         {
258             printf("Guessing visiblestring:\n");
259             printf("'%s'\n", res->userInformationField->u. octet_aligned->buf);
260         }
261         odr_reset (print);
262     }
263     printf ("Options:");
264     if (ODR_MASK_GET(res->options, Z_Options_search))
265         printf (" search");
266     if (ODR_MASK_GET(res->options, Z_Options_present))
267         printf (" present");
268     if (ODR_MASK_GET(res->options, Z_Options_delSet))
269         printf (" delSet");
270     if (ODR_MASK_GET(res->options, Z_Options_resourceReport))
271         printf (" resourceReport");
272     if (ODR_MASK_GET(res->options, Z_Options_resourceCtrl))
273         printf (" resourceCtrl");
274     if (ODR_MASK_GET(res->options, Z_Options_accessCtrl))
275         printf (" accessCtrl");
276     if (ODR_MASK_GET(res->options, Z_Options_scan))
277         printf (" scan");
278     if (ODR_MASK_GET(res->options, Z_Options_sort))
279         printf (" sort");
280     if (ODR_MASK_GET(res->options, Z_Options_extendedServices))
281         printf (" extendedServices");
282     if (ODR_MASK_GET(res->options, Z_Options_level_1Segmentation))
283         printf (" level1Segmentation");
284     if (ODR_MASK_GET(res->options, Z_Options_level_2Segmentation))
285         printf (" level2Segmentation");
286     if (ODR_MASK_GET(res->options, Z_Options_concurrentOperations))
287         printf (" concurrentOperations");
288     if (ODR_MASK_GET(res->options, Z_Options_namedResultSets))
289     {
290         printf (" namedResultSets");
291         setnumber = 0;
292     }
293     if (ODR_MASK_GET(res->options, Z_Options_encapsulation))
294         printf (" encapsulation");
295     if (ODR_MASK_GET(res->options, Z_Options_resultCount))
296         printf (" resultCount");
297     if (ODR_MASK_GET(res->options, Z_Options_negotiationModel))
298         printf (" negotiationModel");
299     if (ODR_MASK_GET(res->options, Z_Options_duplicateDetection))
300         printf (" duplicateDetection");
301     if (ODR_MASK_GET(res->options, Z_Options_queryType104))
302         printf (" queryType104");
303     printf ("\n");
304     
305     if (ODR_MASK_GET(res->options, Z_Options_negotiationModel)) {
306     
307         Z_CharSetandLanguageNegotiation *p =
308                 yaz_get_charneg_record(res->otherInfo);
309         
310         if (p) {
311         
312                 char *charset, *lang;
313                 int selected;
314                 
315                 yaz_get_response_charneg(session_mem, p, &charset, &lang, &selected);
316                 
317                 printf("Accepted character set : `%s'\n", charset);
318                 printf("Accepted code language : `%s'\n", lang);
319                 printf("Accepted records in ...: %d\n", selected );
320         }
321     }
322     fflush (stdout);
323     return 0;
324 }
325
326 static int cmd_base(char *arg)
327 {
328     int i;
329     char *cp;
330
331     if (!*arg)
332     {
333         printf("Usage: base <database> <database> ...\n");
334         return 0;
335     }
336     for (i = 0; i<num_databaseNames; i++)
337         xfree (databaseNames[i]);
338     num_databaseNames = 0;
339     while (1)
340     {
341         if (!(cp = strchr(arg, ' ')))
342             cp = arg + strlen(arg);
343         if (cp - arg < 1)
344             break;
345         databaseNames[num_databaseNames] = (char *)xmalloc (1 + cp - arg);
346         memcpy (databaseNames[num_databaseNames], arg, cp - arg);
347         databaseNames[num_databaseNames++][cp - arg] = '\0';
348         if (!*cp)
349             break;
350         arg = cp+1;
351     }
352     return 1;
353 }
354
355 int cmd_open(char *arg)
356 {
357     void *add;
358     char type_and_host[101], base[101];
359     CS_TYPE t;
360     
361     if (conn)
362     {
363         printf("Already connected.\n");
364         
365         cs_close (conn);
366         conn = NULL;
367         if (session_mem)
368         {
369             nmem_destroy (session_mem);
370             session_mem = NULL;
371         }
372     }
373     t = tcpip_type;
374     base[0] = '\0';
375     if (sscanf (arg, "%100[^/]/%100s", type_and_host, base) < 1)
376         return 0;
377     
378     if(yazProxy) 
379         conn = cs_create_host(yazProxy, 1, &add);
380     else 
381         conn = cs_create_host(type_and_host, 1, &add);
382     
383     if (!conn)
384     {
385         printf ("Couldn't create comstack\n");
386         return 0;
387     }
388     printf("Connecting...");
389     fflush(stdout);
390     if (cs_connect(conn, add) < 0)
391     {
392         printf ("error = %s\n", cs_strerror(conn));
393         if (conn->cerrno == CSYSERR)
394             perror("system");
395         cs_close(conn);
396         conn = 0;
397         return 0;
398     }
399     printf("Ok.\n");
400     
401     send_initRequest(type_and_host);
402     if (*base)
403         cmd_base (base);
404     return 2;
405 }
406
407 int cmd_authentication(char *arg)
408 {
409     static Z_IdAuthentication au;
410     static char user[40], group[40], pass[40];
411     static Z_IdPass idPass;
412     int r;
413
414     if (!*arg)
415     {
416         printf("Auth field set to null\n");
417         auth = 0;
418         return 1;
419     }
420     r = sscanf (arg, "%39s %39s %39s", user, group, pass);
421     if (r == 0)
422     {
423         printf("Auth field set to null\n");
424         auth = 0;
425     }
426     if (r == 1)
427     {
428         auth = &au;
429         au.which = Z_IdAuthentication_open;
430         au.u.open = user;
431     }
432     if (r == 3)
433     {
434         auth = &au;
435         au.which = Z_IdAuthentication_idPass;
436         au.u.idPass = &idPass;
437         idPass.groupId = group;
438         idPass.userId = user;
439         idPass.password = pass;
440     }
441     return 1;
442 }
443
444 /* SEARCH SERVICE ------------------------------ */
445
446 static void display_variant(Z_Variant *v, int level)
447 {
448     int i;
449
450     for (i = 0; i < v->num_triples; i++)
451     {
452         printf("%*sclass=%d,type=%d", level * 4, "", *v->triples[i]->zclass,
453             *v->triples[i]->type);
454         if (v->triples[i]->which == Z_Triple_internationalString)
455             printf(",value=%s\n", v->triples[i]->value.internationalString);
456         else
457             printf("\n");
458     }
459 }
460
461 static void display_grs1(Z_GenericRecord *r, int level)
462 {
463     int i;
464
465     if (!r)
466         return;
467     for (i = 0; i < r->num_elements; i++)
468     {
469         Z_TaggedElement *t;
470
471         printf("%*s", level * 4, "");
472         t = r->elements[i];
473         printf("(");
474         if (t->tagType)
475             printf("%d,", *t->tagType);
476         else
477             printf("?,");
478         if (t->tagValue->which == Z_StringOrNumeric_numeric)
479             printf("%d) ", *t->tagValue->u.numeric);
480         else
481             printf("%s) ", t->tagValue->u.string);
482         if (t->content->which == Z_ElementData_subtree)
483         {
484             printf("\n");
485             display_grs1(t->content->u.subtree, level+1);
486         }
487         else if (t->content->which == Z_ElementData_string)
488             printf("%s\n", t->content->u.string);
489         else if (t->content->which == Z_ElementData_numeric)
490             printf("%d\n", *t->content->u.numeric);
491         else if (t->content->which == Z_ElementData_oid)
492         {
493             int *ip = t->content->u.oid;
494             oident *oent;
495             
496             if ((oent = oid_getentbyoid(t->content->u.oid)))
497                 printf("OID: %s\n", oent->desc);
498             else
499             {
500                 printf("{");
501                 while (ip && *ip >= 0)
502                     printf(" %d", *(ip++));
503                 printf(" }\n");
504             }
505         }
506         else if (t->content->which == Z_ElementData_noDataRequested)
507             printf("[No data requested]\n");
508         else if (t->content->which == Z_ElementData_elementEmpty)
509             printf("[Element empty]\n");
510         else if (t->content->which == Z_ElementData_elementNotThere)
511             printf("[Element not there]\n");
512         else
513             printf("??????\n");
514         if (t->appliedVariant)
515             display_variant(t->appliedVariant, level+1);
516         if (t->metaData && t->metaData->supportedVariants)
517         {
518             int c;
519
520             printf("%*s---- variant list\n", (level+1)*4, "");
521             for (c = 0; c < t->metaData->num_supportedVariants; c++)
522             {
523                 printf("%*svariant #%d\n", (level+1)*4, "", c);
524                 display_variant(t->metaData->supportedVariants[c], level + 2);
525             }
526         }
527     }
528 }
529
530
531 static void print_record(const unsigned char *buf, size_t len)
532 {
533     size_t i = len;
534     print_stringn (buf, len);
535     /* add newline if not already added ... */
536     if (i <= 0 || buf[i-1] != '\n')
537         printf ("\n");
538 }
539
540 static void display_record(Z_External *r)
541 {
542     oident *ent = oid_getentbyoid(r->direct_reference);
543
544     record_last = r;
545     /*
546      * Tell the user what we got.
547      */
548     if (r->direct_reference)
549     {
550         printf("Record type: ");
551         if (ent)
552             printf("%s\n", ent->desc);
553         else if (!odr_oid(print, &r->direct_reference, 0, 0))
554         {
555             odr_perror(print, "print oid");
556             odr_reset(print);
557         }
558     }
559     /* Check if this is a known, ASN.1 type tucked away in an octet string */
560     if (ent && r->which == Z_External_octet)
561     {
562         Z_ext_typeent *type = z_ext_getentbyref(ent->value);
563         void *rr;
564
565         if (type)
566         {
567             /*
568              * Call the given decoder to process the record.
569              */
570             odr_setbuf(in, (char*)r->u.octet_aligned->buf,
571                 r->u.octet_aligned->len, 0);
572             if (!(*type->fun)(in, (char **)&rr, 0, 0))
573             {
574                 odr_perror(in, "Decoding constructed record.");
575                 fprintf(stderr, "[Near %d]\n", odr_offset(in));
576                 fprintf(stderr, "Packet dump:\n---------\n");
577                 odr_dumpBER(stderr, (char*)r->u.octet_aligned->buf,
578                     r->u.octet_aligned->len);
579                 fprintf(stderr, "---------\n");
580                 exit(1);
581             }
582             /*
583              * Note: we throw away the original, BER-encoded record here.
584              * Do something else with it if you want to keep it.
585              */
586             r->u.sutrs = (Z_SUTRS *) rr; /* we don't actually check the type here. */
587             r->which = type->what;
588         }
589     }
590     if (ent && ent->value == VAL_SOIF)
591         print_record((const unsigned char *) r->u.octet_aligned->buf,
592                      r->u.octet_aligned->len);
593     else if (r->which == Z_External_octet && r->u.octet_aligned->len)
594     {
595         const char *octet_buf = (char*)r->u.octet_aligned->buf;
596         if (ent->value == VAL_TEXT_XML || ent->value == VAL_APPLICATION_XML ||
597             ent->value == VAL_HTML)
598         {
599             print_record((const unsigned char *) octet_buf,
600                          r->u.octet_aligned->len);
601         }
602         else if (ent->value == VAL_POSTSCRIPT)
603         {
604             int size = r->u.octet_aligned->len;
605             if (size > 100)
606                 size = 100;
607             print_record((const unsigned char *) octet_buf, size);
608         }
609         else
610         {
611             if ( 
612 #if AVOID_MARC_DECODE
613                 /* primitive check for a marc OID 5.1-29 except 16 */
614                 ent->oidsuffix[0] == 5 && ent->oidsuffix[1] < 30 &&
615                 ent->oidsuffix[1] != 16
616 #else
617                 1
618 #endif
619                 )
620             {
621                 if (marc_display_exl (octet_buf, NULL, 0 /* debug */,
622                                       r->u.octet_aligned->len) <= 0)
623                 {
624                     printf ("bad MARC. Dumping as it is:\n");
625                     print_record((const unsigned char*) octet_buf,
626                                  r->u.octet_aligned->len);
627                 }
628             }
629             else
630             {
631                 print_record((const unsigned char*) octet_buf,
632                              r->u.octet_aligned->len);
633             }
634         }
635         if (marcdump)
636             fwrite (octet_buf, 1, r->u.octet_aligned->len, marcdump);
637     }
638     else if (ent && ent->value == VAL_SUTRS)
639     {
640         if (r->which != Z_External_sutrs)
641         {
642             printf("Expecting single SUTRS type for SUTRS.\n");
643             return;
644         }
645         print_record(r->u.sutrs->buf, r->u.sutrs->len);
646     }
647     else if (ent && ent->value == VAL_GRS1)
648     {
649         if (r->which != Z_External_grs1)
650         {
651             printf("Expecting single GRS type for GRS.\n");
652             return;
653         }
654         display_grs1(r->u.grs1, 0);
655     }
656     else 
657     {
658         printf("Unknown record representation.\n");
659         if (!z_External(print, &r, 0, 0))
660         {
661             odr_perror(print, "Printing external");
662             odr_reset(print);
663         }
664     }
665 }
666
667 static void display_diagrecs(Z_DiagRec **pp, int num)
668 {
669     int i;
670     oident *ent;
671     Z_DefaultDiagFormat *r;
672
673     printf("Diagnostic message(s) from database:\n");
674     for (i = 0; i<num; i++)
675     {
676         Z_DiagRec *p = pp[i];
677         if (p->which != Z_DiagRec_defaultFormat)
678         {
679             printf("Diagnostic record not in default format.\n");
680             return;
681         }
682         else
683             r = p->u.defaultFormat;
684         if (!(ent = oid_getentbyoid(r->diagnosticSetId)) ||
685             ent->oclass != CLASS_DIAGSET || ent->value != VAL_BIB1)
686             printf("Missing or unknown diagset\n");
687         printf("    [%d] %s", *r->condition, diagbib1_str(*r->condition));
688         switch (r->which)
689         {
690         case Z_DefaultDiagFormat_v2Addinfo:
691             printf (" -- v2 addinfo '%s'\n", r->u.v2Addinfo);
692             break;
693         case Z_DefaultDiagFormat_v3Addinfo:
694             printf (" -- v3 addinfo '%s'\n", r->u.v3Addinfo);
695             break;
696         }
697     }
698 }
699
700
701 static void display_nameplusrecord(Z_NamePlusRecord *p)
702 {
703     if (p->databaseName)
704         printf("[%s]", p->databaseName);
705     if (p->which == Z_NamePlusRecord_surrogateDiagnostic)
706         display_diagrecs(&p->u.surrogateDiagnostic, 1);
707     else if (p->which == Z_NamePlusRecord_databaseRecord)
708         display_record(p->u.databaseRecord);
709 }
710
711 static void display_records(Z_Records *p)
712 {
713     int i;
714
715     if (p->which == Z_Records_NSD)
716     {
717         Z_DiagRec dr, *dr_p = &dr;
718         dr.which = Z_DiagRec_defaultFormat;
719         dr.u.defaultFormat = p->u.nonSurrogateDiagnostic;
720         display_diagrecs (&dr_p, 1);
721     }
722     else if (p->which == Z_Records_multipleNSD)
723         display_diagrecs (p->u.multipleNonSurDiagnostics->diagRecs,
724                           p->u.multipleNonSurDiagnostics->num_diagRecs);
725     else 
726     {
727         printf("Records: %d\n", p->u.databaseOrSurDiagnostics->num_records);
728         for (i = 0; i < p->u.databaseOrSurDiagnostics->num_records; i++)
729             display_nameplusrecord(p->u.databaseOrSurDiagnostics->records[i]);
730     }
731 }
732
733 static int send_deleteResultSetRequest(char *arg)
734 {
735     char names[8][32];
736     int i;
737
738     Z_APDU *apdu = zget_APDU(out, Z_APDU_deleteResultSetRequest);
739     Z_DeleteResultSetRequest *req = apdu->u.deleteResultSetRequest;
740
741     req->referenceId = set_refid (out);
742
743     req->num_resultSetList =
744         sscanf (arg, "%30s %30s %30s %30s %30s %30s %30s %30s",
745                 names[0], names[1], names[2], names[3],
746                 names[4], names[5], names[6], names[7]);
747
748     req->deleteFunction = (int *)
749         odr_malloc (out, sizeof(*req->deleteFunction));
750     if (req->num_resultSetList > 0)
751     {
752         *req->deleteFunction = Z_DeleteRequest_list;
753         req->resultSetList = (char **)
754             odr_malloc (out, sizeof(*req->resultSetList)*
755                         req->num_resultSetList);
756         for (i = 0; i<req->num_resultSetList; i++)
757             req->resultSetList[i] = names[i];
758     }
759     else
760     {
761         *req->deleteFunction = Z_DeleteRequest_all;
762         req->resultSetList = 0;
763     }
764     
765     send_apdu(apdu);
766     printf("Sent deleteResultSetRequest.\n");
767     return 2;
768 }
769
770 static int send_searchRequest(char *arg)
771 {
772     Z_APDU *apdu = zget_APDU(out, Z_APDU_searchRequest);
773     Z_SearchRequest *req = apdu->u.searchRequest;
774     Z_Query query;
775     int oid[OID_SIZE];
776 #if YAZ_MODULE_ccl
777     struct ccl_rpn_node *rpn = NULL;
778     int error, pos;
779 #endif
780     char setstring[100];
781     Z_RPNQuery *RPNquery;
782     Odr_oct ccl_query;
783
784 #if YAZ_MODULE_ccl
785     if (queryType == QueryType_CCL2RPN)
786     {
787         rpn = ccl_find_str(bibset, arg, &error, &pos);
788         if (error)
789         {
790             printf("CCL ERROR: %s\n", ccl_err_msg(error));
791             return 0;
792         }
793     }
794 #endif
795     req->referenceId = set_refid (out);
796     if (!strcmp(arg, "@big")) /* strictly for troublemaking */
797     {
798         static unsigned char big[2100];
799         static Odr_oct bigo;
800
801         /* send a very big referenceid to test transport stack etc. */
802         memset(big, 'A', 2100);
803         bigo.len = bigo.size = 2100;
804         bigo.buf = big;
805         req->referenceId = &bigo;
806     }
807     
808     if (setnumber >= 0)
809     {
810         sprintf(setstring, "%d", ++setnumber);
811         req->resultSetName = setstring;
812     }
813     *req->smallSetUpperBound = smallSetUpperBound;
814     *req->largeSetLowerBound = largeSetLowerBound;
815     *req->mediumSetPresentNumber = mediumSetPresentNumber;
816     if (smallSetUpperBound > 0 || (largeSetLowerBound > 1 &&
817         mediumSetPresentNumber > 0))
818     {
819         oident prefsyn;
820
821         prefsyn.proto = protocol;
822         prefsyn.oclass = CLASS_RECSYN;
823         prefsyn.value = recordsyntax;
824         req->preferredRecordSyntax =
825             odr_oiddup(out, oid_ent_to_oid(&prefsyn, oid));
826         req->smallSetElementSetNames =
827             req->mediumSetElementSetNames = elementSetNames;
828     }
829     req->num_databaseNames = num_databaseNames;
830     req->databaseNames = databaseNames;
831
832     req->query = &query;
833
834     switch (queryType)
835     {
836     case QueryType_Prefix:
837         query.which = Z_Query_type_1;
838         RPNquery = p_query_rpn (out, protocol, arg);
839         if (!RPNquery)
840         {
841             printf("Prefix query error\n");
842             return 0;
843         }
844         query.u.type_1 = RPNquery;
845         break;
846     case QueryType_CCL:
847         query.which = Z_Query_type_2;
848         query.u.type_2 = &ccl_query;
849         ccl_query.buf = (unsigned char*) arg;
850         ccl_query.len = strlen(arg);
851         break;
852 #if YAZ_MODULE_ccl
853     case QueryType_CCL2RPN:
854         query.which = Z_Query_type_1;
855         RPNquery = ccl_rpn_query(out, rpn);
856         if (!RPNquery)
857         {
858             printf ("Couldn't convert from CCL to RPN\n");
859             return 0;
860         }
861         query.u.type_1 = RPNquery;
862         ccl_rpn_delete (rpn);
863         break;
864 #endif
865     default:
866         printf ("Unsupported query type\n");
867         return 0;
868     }
869     send_apdu(apdu);
870     setno = 1;
871     printf("Sent searchRequest.\n");
872     return 2;
873 }
874
875 /* display Query Expression as part of searchResult-1 */
876 static void display_queryExpression (Z_QueryExpression *qe)
877 {
878     if (!qe)
879         return;
880     if (qe->which == Z_QueryExpression_term)
881     {
882         if (qe->u.term->queryTerm)
883         {
884             Z_Term *term = qe->u.term->queryTerm;
885             if (term->which == Z_Term_general)
886                 printf (" %.*s", term->u.general->len, term->u.general->buf);
887         }
888     }
889
890 }
891
892 /* see if we can find USR:SearchResult-1 */
893 static void display_searchResult (Z_OtherInformation *o)
894 {
895     int i;
896     if (!o)
897         return ;
898     for (i = 0; i < o->num_elements; i++)
899     {
900         if (o->list[i]->which == Z_OtherInfo_externallyDefinedInfo)
901         {
902             Z_External *ext = o->list[i]->information.externallyDefinedInfo;
903             
904             if (ext->which == Z_External_searchResult1)
905             {
906                 int j;
907                 Z_SearchInfoReport *sr = ext->u.searchResult1;
908                 printf ("SearchResult-1:");
909                 for (j = 0; j < sr->num; j++)
910                 {
911                     if (!sr->elements[j]->subqueryExpression)
912                         printf (" %d", j);
913                     display_queryExpression (
914                         sr->elements[j]->subqueryExpression);
915                     display_queryExpression (
916                         sr->elements[j]->subqueryInterpretation);
917                     display_queryExpression (
918                         sr->elements[j]->subqueryRecommendation);
919                     if (sr->elements[j]->subqueryCount)
920                         printf ("(%d)", *sr->elements[j]->subqueryCount);
921                 }
922                 printf ("\n");
923             }
924         }
925     }
926 }
927
928 static int process_searchResponse(Z_SearchResponse *res)
929 {
930     printf ("Received SearchResponse.\n");
931     print_refid (res->referenceId);
932     if (*res->searchStatus)
933         printf("Search was a success.\n");
934     else
935         printf("Search was a bloomin' failure.\n");
936     printf("Number of hits: %d", *res->resultCount);
937     if (setnumber >= 0)
938         printf (", setno %d", setnumber);
939     printf ("\n");
940     display_searchResult (res->additionalSearchInfo);
941     printf("records returned: %d\n",
942            *res->numberOfRecordsReturned);
943     setno += *res->numberOfRecordsReturned;
944     if (res->records)
945         display_records(res->records);
946     return 0;
947 }
948
949 static void print_level(int iLevel)
950 {
951     int i;
952     for (i = 0; i < iLevel * 4; i++)
953         printf(" ");
954 }
955
956 static void print_int(int iLevel, const char *pTag, int *pInt)
957 {
958     if (pInt != NULL)
959     {
960         print_level(iLevel);
961         printf("%s: %d\n", pTag, *pInt);
962     }
963 }
964
965 static void print_string(int iLevel, const char *pTag, const char *pString)
966 {
967     if (pString != NULL)
968     {
969         print_level(iLevel);
970         printf("%s: %s\n", pTag, pString);
971     }
972 }
973
974 static void print_oid(int iLevel, const char *pTag, Odr_oid *pOid)
975 {
976     if (pOid != NULL)
977     {
978         int *pInt = pOid;
979
980         print_level(iLevel);
981         printf("%s:", pTag);
982         for (; *pInt != -1; pInt++)
983             printf(" %d", *pInt);
984         printf("\n");
985     }
986 }
987
988 static void print_referenceId(int iLevel, Z_ReferenceId *referenceId)
989 {
990     if (referenceId != NULL)
991     {
992         int i;
993
994         print_level(iLevel);
995         printf("Ref Id (%d, %d): ", referenceId->len, referenceId->size);
996         for (i = 0; i < referenceId->len; i++)
997             printf("%c", referenceId->buf[i]);
998         printf("\n");
999     }
1000 }
1001
1002 static void print_string_or_numeric(int iLevel, const char *pTag, Z_StringOrNumeric *pStringNumeric)
1003 {
1004     if (pStringNumeric != NULL)
1005     {
1006         switch (pStringNumeric->which)
1007         {
1008         case Z_StringOrNumeric_string:
1009             print_string(iLevel, pTag, pStringNumeric->u.string);
1010             break;
1011             
1012         case Z_StringOrNumeric_numeric:
1013             print_int(iLevel, pTag, pStringNumeric->u.numeric);
1014             break;
1015             
1016         default:
1017             print_level(iLevel);
1018             printf("%s: valid type for Z_StringOrNumeric\n", pTag);
1019             break;
1020         }
1021     }
1022 }
1023
1024 static void print_universe_report_duplicate(int iLevel, Z_UniverseReportDuplicate *pUniverseReportDuplicate)
1025 {
1026     if (pUniverseReportDuplicate != NULL)
1027     {
1028         print_level(iLevel);
1029         printf("Universe Report Duplicate: \n");
1030         iLevel++;
1031         print_string_or_numeric(iLevel, "Hit No",
1032                                 pUniverseReportDuplicate->hitno);
1033     }
1034 }
1035
1036 static void
1037 print_universe_report_hits(int iLevel,
1038                            Z_UniverseReportHits *pUniverseReportHits)
1039 {
1040     if (pUniverseReportHits != NULL)
1041     {
1042         print_level(iLevel);
1043         printf("Universe Report Hits: \n");
1044         iLevel++;
1045         print_string_or_numeric(iLevel, "Database",
1046                                 pUniverseReportHits->database);
1047         print_string_or_numeric(iLevel, "Hits", pUniverseReportHits->hits);
1048     }
1049 }
1050
1051 static void print_universe_report(int iLevel, Z_UniverseReport *pUniverseReport)
1052 {
1053     if (pUniverseReport != NULL)
1054     {
1055         print_level(iLevel);
1056         printf("Universe Report: \n");
1057         iLevel++;
1058         print_int(iLevel, "Total Hits", pUniverseReport->totalHits);
1059         switch (pUniverseReport->which)
1060         {
1061         case Z_UniverseReport_databaseHits:
1062             print_universe_report_hits(iLevel, pUniverseReport->u.databaseHits);
1063             break;
1064             
1065         case Z_UniverseReport_duplicate:
1066             print_universe_report_duplicate(iLevel, pUniverseReport->u.duplicate);
1067             break;
1068             
1069         default:
1070             print_level(iLevel);
1071             printf("Type: %d\n", pUniverseReport->which);
1072             break;
1073         }
1074     }
1075 }
1076
1077 static void print_external(int iLevel, Z_External *pExternal)
1078 {
1079     if (pExternal != NULL)
1080     {
1081         print_level(iLevel);
1082         printf("External: \n");
1083         iLevel++;
1084         print_oid(iLevel, "Direct Reference", pExternal->direct_reference);
1085         print_int(iLevel, "InDirect Reference", pExternal->indirect_reference);
1086         print_string(iLevel, "Descriptor", pExternal->descriptor);
1087         switch (pExternal->which)
1088         {
1089         case Z_External_universeReport:
1090             print_universe_report(iLevel, pExternal->u.universeReport);
1091             break;
1092             
1093         default:
1094             print_level(iLevel);
1095             printf("Type: %d\n", pExternal->which);
1096             break;
1097         }
1098     }
1099 }
1100
1101 static int process_resourceControlRequest (Z_ResourceControlRequest *req)
1102 {
1103     printf ("Received ResourceControlRequest.\n");
1104     print_referenceId(1, req->referenceId);
1105     print_int(1, "Suspended Flag", req->suspendedFlag);
1106     print_int(1, "Partial Results Available", req->partialResultsAvailable);
1107     print_int(1, "Response Required", req->responseRequired);
1108     print_int(1, "Triggered Request Flag", req->triggeredRequestFlag);
1109     print_external(1, req->resourceReport);
1110     return 0;
1111 }
1112
1113 void process_ESResponse(Z_ExtendedServicesResponse *res)
1114 {
1115     printf("Status: ");
1116     switch (*res->operationStatus)
1117     {
1118     case Z_ExtendedServicesResponse_done:
1119         printf ("done\n");
1120         break;
1121     case Z_ExtendedServicesResponse_accepted:
1122         printf ("accepted\n");
1123         break;
1124     case Z_ExtendedServicesResponse_failure:
1125         printf ("failure\n");
1126         display_diagrecs(res->diagnostics, res->num_diagnostics);
1127         break;
1128     default:
1129         printf ("unknown\n");
1130     }
1131     if ( (*res->operationStatus != Z_ExtendedServicesResponse_failure) &&
1132         (res->num_diagnostics != 0) ) {
1133         display_diagrecs(res->diagnostics, res->num_diagnostics);
1134     }
1135     print_refid (res->referenceId);
1136     if (res->taskPackage && 
1137         res->taskPackage->which == Z_External_extendedService)
1138     {
1139         Z_TaskPackage *taskPackage = res->taskPackage->u.extendedService;
1140         Odr_oct *id = taskPackage->targetReference;
1141         Z_External *ext = taskPackage->taskSpecificParameters;
1142         
1143         if (id)
1144         {
1145             printf ("Target Reference: ");
1146             print_stringn (id->buf, id->len);
1147             printf ("\n");
1148         }
1149         if (ext->which == Z_External_update)
1150         {
1151             Z_IUUpdateTaskPackage *utp = ext->u.update->u.taskPackage;
1152             if (utp && utp->targetPart)
1153             {
1154                 Z_IUTargetPart *targetPart = utp->targetPart;
1155                 int i;
1156
1157                 for (i = 0; i<targetPart->num_taskPackageRecords;  i++)
1158                 {
1159
1160                     Z_IUTaskPackageRecordStructure *tpr =
1161                         targetPart->taskPackageRecords[i];
1162                     printf ("task package record %d\n", i+1);
1163                     if (tpr->which == Z_IUTaskPackageRecordStructure_record)
1164                     {
1165                         display_record (tpr->u.record);
1166                     }
1167                     else
1168                     {
1169                         printf ("other type\n");
1170                     }
1171                 }
1172             }
1173         }
1174     }
1175 }
1176
1177 #if YAZ_MODULE_ill
1178
1179 const char *get_ill_element (void *clientData, const char *element)
1180 {
1181     return 0;
1182 }
1183
1184 static Z_External *create_external_itemRequest()
1185 {
1186     struct ill_get_ctl ctl;
1187     ILL_ItemRequest *req;
1188     Z_External *r = 0;
1189     int item_request_size = 0;
1190     char *item_request_buf = 0;
1191
1192     ctl.odr = out;
1193     ctl.clientData = 0;
1194     ctl.f = get_ill_element;
1195     
1196     req = ill_get_ItemRequest(&ctl, "ill", 0);
1197     if (!req)
1198         printf ("ill_get_ItemRequest failed\n");
1199         
1200     if (!ill_ItemRequest (out, &req, 0, 0))
1201     {
1202         if (apdu_file)
1203         {
1204             ill_ItemRequest(print, &req, 0, 0);
1205             odr_reset(print);
1206         }
1207         item_request_buf = odr_getbuf (out, &item_request_size, 0);
1208         if (item_request_buf)
1209             odr_setbuf (out, item_request_buf, item_request_size, 1);
1210         printf ("Couldn't encode ItemRequest, size %d\n", item_request_size);
1211         return 0;
1212     }
1213     else
1214     {
1215         oident oid;
1216         
1217         item_request_buf = odr_getbuf (out, &item_request_size, 0);
1218         oid.proto = PROTO_GENERAL;
1219         oid.oclass = CLASS_GENERAL;
1220         oid.value = VAL_ISO_ILL_1;
1221         
1222         r = (Z_External *) odr_malloc (out, sizeof(*r));
1223         r->direct_reference = odr_oiddup(out,oid_getoidbyent(&oid)); 
1224         r->indirect_reference = 0;
1225         r->descriptor = 0;
1226         r->which = Z_External_single;
1227         
1228         r->u.single_ASN1_type = (Odr_oct *)
1229             odr_malloc (out, sizeof(*r->u.single_ASN1_type));
1230         r->u.single_ASN1_type->buf = (unsigned char *)
1231         odr_malloc (out, item_request_size);
1232         r->u.single_ASN1_type->len = item_request_size;
1233         r->u.single_ASN1_type->size = item_request_size;
1234         memcpy (r->u.single_ASN1_type->buf, item_request_buf,
1235                 item_request_size);
1236         printf ("len = %d\n", item_request_size);
1237     }
1238     return r;
1239 }
1240 #endif
1241
1242 #ifdef YAZ_MODULE_ill
1243 static Z_External *create_external_ILL_APDU(int which)
1244 {
1245     struct ill_get_ctl ctl;
1246     ILL_APDU *ill_apdu;
1247     Z_External *r = 0;
1248     int ill_request_size = 0;
1249     char *ill_request_buf = 0;
1250         
1251     ctl.odr = out;
1252     ctl.clientData = 0;
1253     ctl.f = get_ill_element;
1254
1255     ill_apdu = ill_get_APDU(&ctl, "ill", 0);
1256
1257     if (!ill_APDU (out, &ill_apdu, 0, 0))
1258     {
1259         if (apdu_file)
1260         {
1261             printf ("-------------------\n");
1262             ill_APDU(print, &ill_apdu, 0, 0);
1263             odr_reset(print);
1264             printf ("-------------------\n");
1265         }
1266         ill_request_buf = odr_getbuf (out, &ill_request_size, 0);
1267         if (ill_request_buf)
1268             odr_setbuf (out, ill_request_buf, ill_request_size, 1);
1269         printf ("Couldn't encode ILL-Request, size %d\n", ill_request_size);
1270         return 0;
1271     }
1272     else
1273     {
1274         oident oid;
1275         ill_request_buf = odr_getbuf (out, &ill_request_size, 0);
1276         
1277         oid.proto = PROTO_GENERAL;
1278         oid.oclass = CLASS_GENERAL;
1279         oid.value = VAL_ISO_ILL_1;
1280         
1281         r = (Z_External *) odr_malloc (out, sizeof(*r));
1282         r->direct_reference = odr_oiddup(out,oid_getoidbyent(&oid)); 
1283         r->indirect_reference = 0;
1284         r->descriptor = 0;
1285         r->which = Z_External_single;
1286         
1287         r->u.single_ASN1_type = (Odr_oct *)
1288             odr_malloc (out, sizeof(*r->u.single_ASN1_type));
1289         r->u.single_ASN1_type->buf = (unsigned char *)
1290         odr_malloc (out, ill_request_size);
1291         r->u.single_ASN1_type->len = ill_request_size;
1292         r->u.single_ASN1_type->size = ill_request_size;
1293         memcpy (r->u.single_ASN1_type->buf, ill_request_buf, ill_request_size);
1294         printf ("len = %d\n", ill_request_size);
1295     }
1296     return r;
1297 }
1298 #endif
1299
1300
1301 static Z_External *create_ItemOrderExternal(const char *type, int itemno)
1302 {
1303     Z_External *r = (Z_External *) odr_malloc(out, sizeof(Z_External));
1304     oident ItemOrderRequest;
1305   
1306     ItemOrderRequest.proto = PROTO_Z3950;
1307     ItemOrderRequest.oclass = CLASS_EXTSERV;
1308     ItemOrderRequest.value = VAL_ITEMORDER;
1309  
1310     r->direct_reference = odr_oiddup(out,oid_getoidbyent(&ItemOrderRequest)); 
1311     r->indirect_reference = 0;
1312     r->descriptor = 0;
1313
1314     r->which = Z_External_itemOrder;
1315
1316     r->u.itemOrder = (Z_ItemOrder *) odr_malloc(out,sizeof(Z_ItemOrder));
1317     memset(r->u.itemOrder, 0, sizeof(Z_ItemOrder));
1318     r->u.itemOrder->which=Z_IOItemOrder_esRequest;
1319
1320     r->u.itemOrder->u.esRequest = (Z_IORequest *) 
1321         odr_malloc(out,sizeof(Z_IORequest));
1322     memset(r->u.itemOrder->u.esRequest, 0, sizeof(Z_IORequest));
1323
1324     r->u.itemOrder->u.esRequest->toKeep = (Z_IOOriginPartToKeep *)
1325         odr_malloc(out,sizeof(Z_IOOriginPartToKeep));
1326     memset(r->u.itemOrder->u.esRequest->toKeep, 0, sizeof(Z_IOOriginPartToKeep));
1327     r->u.itemOrder->u.esRequest->notToKeep = (Z_IOOriginPartNotToKeep *)
1328         odr_malloc(out,sizeof(Z_IOOriginPartNotToKeep));
1329     memset(r->u.itemOrder->u.esRequest->notToKeep, 0, sizeof(Z_IOOriginPartNotToKeep));
1330
1331     r->u.itemOrder->u.esRequest->toKeep->supplDescription = NULL;
1332     r->u.itemOrder->u.esRequest->toKeep->contact = NULL;
1333     r->u.itemOrder->u.esRequest->toKeep->addlBilling = NULL;
1334
1335     r->u.itemOrder->u.esRequest->notToKeep->resultSetItem =
1336         (Z_IOResultSetItem *) odr_malloc(out, sizeof(Z_IOResultSetItem));
1337     memset(r->u.itemOrder->u.esRequest->notToKeep->resultSetItem, 0, sizeof(Z_IOResultSetItem));
1338     r->u.itemOrder->u.esRequest->notToKeep->resultSetItem->resultSetId = "1";
1339
1340     r->u.itemOrder->u.esRequest->notToKeep->resultSetItem->item =
1341         (int *) odr_malloc(out, sizeof(int));
1342     *r->u.itemOrder->u.esRequest->notToKeep->resultSetItem->item = itemno;
1343
1344 #if YAZ_MODULE_ill
1345     if (!strcmp (type, "item") || !strcmp(type, "2"))
1346     {
1347         printf ("using item-request\n");
1348         r->u.itemOrder->u.esRequest->notToKeep->itemRequest = 
1349             create_external_itemRequest();
1350     }
1351     else if (!strcmp(type, "ill") || !strcmp(type, "1"))
1352     {
1353         printf ("using ILL-request\n");
1354         r->u.itemOrder->u.esRequest->notToKeep->itemRequest = 
1355             create_external_ILL_APDU(ILL_APDU_ILL_Request);
1356     }
1357     else if (!strcmp(type, "xml") || !strcmp(type, "3"))
1358     {
1359     const char *xml_buf =
1360         "<itemorder>\n"
1361         "  <type>request</type>\n"
1362         "  <libraryNo>000200</libraryNo>\n"
1363         "  <borrowerTicketNo> 1212 </borrowerTicketNo>\n"
1364         "</itemorder>";
1365         r->u.itemOrder->u.esRequest->notToKeep->itemRequest =
1366             z_ext_record (out, VAL_TEXT_XML, xml_buf, strlen(xml_buf));
1367     }
1368     else
1369         r->u.itemOrder->u.esRequest->notToKeep->itemRequest = 0;
1370
1371 #else
1372     r->u.itemOrder->u.esRequest->notToKeep->itemRequest = 0;
1373 #endif
1374     return r;
1375 }
1376
1377 static int send_itemorder(const char *type, int itemno)
1378 {
1379     Z_APDU *apdu = zget_APDU(out, Z_APDU_extendedServicesRequest);
1380     Z_ExtendedServicesRequest *req = apdu->u.extendedServicesRequest;
1381     oident ItemOrderRequest;
1382
1383     ItemOrderRequest.proto = PROTO_Z3950;
1384     ItemOrderRequest.oclass = CLASS_EXTSERV;
1385     ItemOrderRequest.value = VAL_ITEMORDER;
1386     req->packageType = odr_oiddup(out,oid_getoidbyent(&ItemOrderRequest));
1387     req->packageName = esPackageName;
1388
1389     req->taskSpecificParameters = create_ItemOrderExternal(type, itemno);
1390
1391     send_apdu(apdu);
1392     return 0;
1393 }
1394
1395 static int cmd_update(char *arg)
1396 {
1397     Z_APDU *apdu = zget_APDU(out, Z_APDU_extendedServicesRequest );
1398     Z_ExtendedServicesRequest *req = apdu->u.extendedServicesRequest;
1399     Z_External *r;
1400     int oid[OID_SIZE];
1401     Z_IUOriginPartToKeep *toKeep;
1402     Z_IUSuppliedRecords *notToKeep;
1403     oident update_oid;
1404     printf ("Update request\n");
1405     fflush(stdout);
1406     
1407     if (!record_last)
1408         return 0;
1409     update_oid.proto = PROTO_Z3950;
1410     update_oid.oclass = CLASS_EXTSERV;
1411     update_oid.value = VAL_DBUPDATE;
1412     oid_ent_to_oid (&update_oid, oid);
1413     req->packageType = odr_oiddup(out,oid);
1414     req->packageName = esPackageName;
1415     
1416     req->referenceId = set_refid (out);
1417
1418     r = req->taskSpecificParameters = (Z_External *)
1419         odr_malloc (out, sizeof(*r));
1420     r->direct_reference = odr_oiddup(out,oid);
1421     r->indirect_reference = 0;
1422     r->descriptor = 0;
1423     r->which = Z_External_update;
1424     r->u.update = (Z_IUUpdate *) odr_malloc(out, sizeof(*r->u.update));
1425     r->u.update->which = Z_IUUpdate_esRequest;
1426     r->u.update->u.esRequest = (Z_IUUpdateEsRequest *)
1427         odr_malloc(out, sizeof(*r->u.update->u.esRequest));
1428     toKeep = r->u.update->u.esRequest->toKeep = (Z_IUOriginPartToKeep *)
1429         odr_malloc(out, sizeof(*r->u.update->u.esRequest->toKeep));
1430     toKeep->databaseName = databaseNames[0];
1431     toKeep->schema = 0;
1432     toKeep->elementSetName = 0;
1433     toKeep->actionQualifier = 0;
1434     toKeep->action = (int *) odr_malloc(out, sizeof(*toKeep->action));
1435     *toKeep->action = Z_IUOriginPartToKeep_recordInsert;
1436
1437     notToKeep = r->u.update->u.esRequest->notToKeep = (Z_IUSuppliedRecords *)
1438         odr_malloc(out, sizeof(*r->u.update->u.esRequest->notToKeep));
1439     notToKeep->num = 1;
1440     notToKeep->elements = (Z_IUSuppliedRecords_elem **)
1441         odr_malloc(out, sizeof(*notToKeep->elements));
1442     notToKeep->elements[0] = (Z_IUSuppliedRecords_elem *)
1443         odr_malloc(out, sizeof(**notToKeep->elements));
1444     notToKeep->elements[0]->u.number = 0;
1445     notToKeep->elements[0]->supplementalId = 0;
1446     notToKeep->elements[0]->correlationInfo = 0;
1447     notToKeep->elements[0]->record = record_last;
1448     
1449     send_apdu(apdu);
1450
1451     return 2;
1452 }
1453
1454 static int cmd_itemorder(char *arg)
1455 {
1456     char type[12];
1457     int itemno;
1458     
1459     if (sscanf (arg, "%10s %d", type, &itemno) != 2)
1460         return 0;
1461
1462     printf("Item order request\n");
1463     fflush(stdout);
1464     send_itemorder(type, itemno);
1465     return 2;
1466 }
1467
1468 static int cmd_find(char *arg)
1469 {
1470     if (!*arg)
1471     {
1472         printf("Find what?\n");
1473         return 0;
1474     }
1475     if (!conn)
1476     {
1477         printf("Not connected yet\n");
1478         return 0;
1479     }
1480     if (!send_searchRequest(arg))
1481         return 0;
1482     return 2;
1483 }
1484
1485 static int cmd_delete(char *arg)
1486 {
1487     if (!conn)
1488     {
1489         printf("Not connected yet\n");
1490         return 0;
1491     }
1492     if (!send_deleteResultSetRequest(arg))
1493         return 0;
1494     return 2;
1495 }
1496
1497 static int cmd_ssub(char *arg)
1498 {
1499     if (!(smallSetUpperBound = atoi(arg)))
1500         return 0;
1501     return 1;
1502 }
1503
1504 static int cmd_lslb(char *arg)
1505 {
1506     if (!(largeSetLowerBound = atoi(arg)))
1507         return 0;
1508     return 1;
1509 }
1510
1511 static int cmd_mspn(char *arg)
1512 {
1513     if (!(mediumSetPresentNumber = atoi(arg)))
1514         return 0;
1515     return 1;
1516 }
1517
1518 static int cmd_status(char *arg)
1519 {
1520     printf("smallSetUpperBound: %d\n", smallSetUpperBound);
1521     printf("largeSetLowerBound: %d\n", largeSetLowerBound);
1522     printf("mediumSetPresentNumber: %d\n", mediumSetPresentNumber);
1523     return 1;
1524 }
1525
1526 static int cmd_setnames(char *arg)
1527 {
1528     if (*arg == '1')         /* enable ? */
1529         setnumber = 0;
1530     else if (*arg == '0')    /* disable ? */
1531         setnumber = -1;
1532     else if (setnumber < 0)  /* no args, toggle .. */
1533         setnumber = 0;
1534     else
1535         setnumber = -1;
1536    
1537     if (setnumber >= 0)
1538         printf("Set numbering enabled.\n");
1539     else
1540         printf("Set numbering disabled.\n");
1541     return 1;
1542 }
1543
1544 /* PRESENT SERVICE ----------------------------- */
1545
1546 static int send_presentRequest(char *arg)
1547 {
1548     Z_APDU *apdu = zget_APDU(out, Z_APDU_presentRequest);
1549     Z_PresentRequest *req = apdu->u.presentRequest;
1550     Z_RecordComposition compo;
1551     oident prefsyn;
1552     int nos = 1;
1553     int oid[OID_SIZE];
1554     char *p;
1555     char setstring[100];
1556
1557     req->referenceId = set_refid (out);
1558     if ((p = strchr(arg, '+')))
1559     {
1560         nos = atoi(p + 1);
1561         *p = 0;
1562     }
1563     if (*arg)
1564         setno = atoi(arg);
1565     if (p && (p=strchr(p+1, '+')))
1566     {
1567         strcpy (setstring, p+1);
1568         req->resultSetId = setstring;
1569     }
1570     else if (setnumber >= 0)
1571     {
1572         sprintf(setstring, "%d", setnumber);
1573         req->resultSetId = setstring;
1574     }
1575     req->resultSetStartPoint = &setno;
1576     req->numberOfRecordsRequested = &nos;
1577     prefsyn.proto = protocol;
1578     prefsyn.oclass = CLASS_RECSYN;
1579     prefsyn.value = recordsyntax;
1580     req->preferredRecordSyntax =
1581         odr_oiddup (out, oid_ent_to_oid(&prefsyn, oid));
1582
1583     if (schema != VAL_NONE)
1584     {
1585         oident prefschema;
1586
1587         prefschema.proto = protocol;
1588         prefschema.oclass = CLASS_SCHEMA;
1589         prefschema.value = schema;
1590
1591         req->recordComposition = &compo;
1592         compo.which = Z_RecordComp_complex;
1593         compo.u.complex = (Z_CompSpec *)
1594             odr_malloc(out, sizeof(*compo.u.complex));
1595         compo.u.complex->selectAlternativeSyntax = (bool_t *) 
1596             odr_malloc(out, sizeof(bool_t));
1597         *compo.u.complex->selectAlternativeSyntax = 0;
1598
1599         compo.u.complex->generic = (Z_Specification *)
1600             odr_malloc(out, sizeof(*compo.u.complex->generic));
1601         compo.u.complex->generic->schema = (Odr_oid *)
1602             odr_oiddup(out, oid_ent_to_oid(&prefschema, oid));
1603         if (!compo.u.complex->generic->schema)
1604         {
1605             /* OID wasn't a schema! Try record syntax instead. */
1606             prefschema.oclass = CLASS_RECSYN;
1607             compo.u.complex->generic->schema = (Odr_oid *)
1608                 odr_oiddup(out, oid_ent_to_oid(&prefschema, oid));
1609         }
1610         if (!elementSetNames)
1611             compo.u.complex->generic->elementSpec = 0;
1612         else
1613         {
1614             compo.u.complex->generic->elementSpec = (Z_ElementSpec *)
1615                 odr_malloc(out, sizeof(Z_ElementSpec));
1616             compo.u.complex->generic->elementSpec->which =
1617                 Z_ElementSpec_elementSetName;
1618             compo.u.complex->generic->elementSpec->u.elementSetName =
1619                 elementSetNames->u.generic;
1620         }
1621         compo.u.complex->num_dbSpecific = 0;
1622         compo.u.complex->dbSpecific = 0;
1623         compo.u.complex->num_recordSyntax = 0;
1624         compo.u.complex->recordSyntax = 0;
1625     }
1626     else if (elementSetNames)
1627     {
1628         req->recordComposition = &compo;
1629         compo.which = Z_RecordComp_simple;
1630         compo.u.simple = elementSetNames;
1631     }
1632     send_apdu(apdu);
1633     printf("Sent presentRequest (%d+%d).\n", setno, nos);
1634     return 2;
1635 }
1636     
1637 static void close_session (void)
1638 {
1639     cs_close (conn);
1640     conn = 0;
1641     if (session_mem)
1642     {
1643         nmem_destroy (session_mem);
1644         session_mem = NULL;
1645     }
1646     sent_close = 0;
1647 }
1648
1649 void process_close(Z_Close *req)
1650 {
1651     Z_APDU *apdu = zget_APDU(out, Z_APDU_close);
1652     Z_Close *res = apdu->u.close;
1653
1654     static char *reasons[] =
1655     {
1656         "finished",
1657         "shutdown",
1658         "system problem",
1659         "cost limit reached",
1660         "resources",
1661         "security violation",
1662         "protocolError",
1663         "lack of activity",
1664         "peer abort",
1665         "unspecified"
1666     };
1667
1668     printf("Reason: %s, message: %s\n", reasons[*req->closeReason],
1669         req->diagnosticInformation ? req->diagnosticInformation : "NULL");
1670     if (sent_close)
1671         close_session ();
1672     else
1673     {
1674         *res->closeReason = Z_Close_finished;
1675         send_apdu(apdu);
1676         printf("Sent response.\n");
1677         sent_close = 1;
1678     }
1679 }
1680
1681 static int cmd_show(char *arg)
1682 {
1683     if (!conn)
1684     {
1685         printf("Not connected yet\n");
1686         return 0;
1687     }
1688     if (!send_presentRequest(arg))
1689         return 0;
1690     return 2;
1691 }
1692
1693 int cmd_quit(char *arg)
1694 {
1695     printf("See you later, alligator.\n");
1696     xmalloc_trav ("");
1697     exit(0);
1698     return 0;
1699 }
1700
1701 int cmd_cancel(char *arg)
1702 {
1703     Z_APDU *apdu = zget_APDU(out, Z_APDU_triggerResourceControlRequest);
1704     Z_TriggerResourceControlRequest *req =
1705         apdu->u.triggerResourceControlRequest;
1706     bool_t rfalse = 0;
1707     
1708     if (!conn)
1709     {
1710         printf("Session not initialized yet\n");
1711         return 0;
1712     }
1713     if (!ODR_MASK_GET(session->options, Z_Options_triggerResourceCtrl))
1714     {
1715         printf("Target doesn't support cancel (trigger resource ctrl)\n");
1716         return 0;
1717     }
1718     *req->requestedAction = Z_TriggerResourceCtrl_cancel;
1719     req->resultSetWanted = &rfalse;
1720
1721     send_apdu(apdu);
1722     printf("Sent cancel request\n");
1723     return 2;
1724 }
1725
1726 int send_scanrequest(const char *query, int pp, int num, const char *term)
1727 {
1728     Z_APDU *apdu = zget_APDU(out, Z_APDU_scanRequest);
1729     Z_ScanRequest *req = apdu->u.scanRequest;
1730     int use_rpn = 1;
1731 #if YAZ_MODULE_ccl
1732     int oid[OID_SIZE];
1733     
1734     if (queryType == QueryType_CCL2RPN)
1735     {
1736         oident bib1;
1737         int error, pos;
1738         struct ccl_rpn_node *rpn;
1739
1740         rpn = ccl_find_str (bibset,  query, &error, &pos);
1741         if (error)
1742         {
1743             printf("CCL ERROR: %s\n", ccl_err_msg(error));
1744             return -1;
1745         }
1746         use_rpn = 0;
1747         bib1.proto = PROTO_Z3950;
1748         bib1.oclass = CLASS_ATTSET;
1749         bib1.value = VAL_BIB1;
1750         req->attributeSet = oid_ent_to_oid (&bib1, oid);
1751         if (!(req->termListAndStartPoint = ccl_scan_query (out, rpn)))
1752         {
1753             printf("Couldn't convert CCL to Scan term\n");
1754             return -1;
1755         }
1756         ccl_rpn_delete (rpn);
1757     }
1758 #endif
1759     if (use_rpn && !(req->termListAndStartPoint =
1760                      p_query_scan(out, protocol, &req->attributeSet, query)))
1761     {
1762         printf("Prefix query error\n");
1763         return -1;
1764     }
1765     if (term && *term)
1766     {
1767         if (req->termListAndStartPoint->term &&
1768             req->termListAndStartPoint->term->which == Z_Term_general &&
1769             req->termListAndStartPoint->term->u.general)
1770         {
1771             req->termListAndStartPoint->term->u.general->buf =
1772                 (unsigned char *) odr_strdup(out, term);
1773             req->termListAndStartPoint->term->u.general->len =
1774                 req->termListAndStartPoint->term->u.general->size =
1775                 strlen(term);
1776         }
1777     }
1778     req->referenceId = set_refid (out);
1779     req->num_databaseNames = num_databaseNames;
1780     req->databaseNames = databaseNames;
1781     req->numberOfTermsRequested = &num;
1782     req->preferredPositionInResponse = &pp;
1783     send_apdu(apdu);
1784     return 2;
1785 }
1786
1787 int send_sortrequest(char *arg, int newset)
1788 {
1789     Z_APDU *apdu = zget_APDU(out, Z_APDU_sortRequest);
1790     Z_SortRequest *req = apdu->u.sortRequest;
1791     Z_SortKeySpecList *sksl = (Z_SortKeySpecList *)
1792         odr_malloc (out, sizeof(*sksl));
1793     char setstring[32];
1794
1795     if (setnumber >= 0)
1796         sprintf (setstring, "%d", setnumber);
1797     else
1798         sprintf (setstring, "default");
1799
1800     req->referenceId = set_refid (out);
1801
1802     req->num_inputResultSetNames = 1;
1803     req->inputResultSetNames = (Z_InternationalString **)
1804         odr_malloc (out, sizeof(*req->inputResultSetNames));
1805     req->inputResultSetNames[0] = odr_strdup (out, setstring);
1806
1807     if (newset && setnumber >= 0)
1808         sprintf (setstring, "%d", ++setnumber);
1809
1810     req->sortedResultSetName = odr_strdup (out, setstring);
1811
1812     req->sortSequence = yaz_sort_spec (out, arg);
1813     if (!req->sortSequence)
1814     {
1815         printf ("Missing sort specifications\n");
1816         return -1;
1817     }
1818     send_apdu(apdu);
1819     return 2;
1820 }
1821
1822 void display_term(Z_TermInfo *t)
1823 {
1824     if (t->term->which == Z_Term_general)
1825     {
1826         printf("%.*s", t->term->u.general->len, t->term->u.general->buf);
1827         sprintf(last_scan_line, "%.*s", t->term->u.general->len,
1828             t->term->u.general->buf);
1829     }
1830     else
1831         printf("Term (not general)");
1832     if (t->globalOccurrences)
1833         printf (" (%d)\n", *t->globalOccurrences);
1834     else
1835         printf ("\n");
1836 }
1837
1838 void process_scanResponse(Z_ScanResponse *res)
1839 {
1840     int i;
1841     Z_Entry **entries = NULL;
1842     int num_entries = 0;
1843    
1844     printf("Received ScanResponse\n"); 
1845     print_refid (res->referenceId);
1846     printf("%d entries", *res->numberOfEntriesReturned);
1847     if (res->positionOfTerm)
1848         printf (", position=%d", *res->positionOfTerm); 
1849     printf ("\n");
1850     if (*res->scanStatus != Z_Scan_success)
1851         printf("Scan returned code %d\n", *res->scanStatus);
1852     if (!res->entries)
1853         return;
1854     if ((entries = res->entries->entries))
1855         num_entries = res->entries->num_entries;
1856     for (i = 0; i < num_entries; i++)
1857     {
1858         int pos_term = res->positionOfTerm ? *res->positionOfTerm : -1;
1859         if (entries[i]->which == Z_Entry_termInfo)
1860         {
1861             printf("%c ", i + 1 == pos_term ? '*' : ' ');
1862             display_term(entries[i]->u.termInfo);
1863         }
1864         else
1865             display_diagrecs(&entries[i]->u.surrogateDiagnostic, 1);
1866     }
1867     if (res->entries->nonsurrogateDiagnostics)
1868         display_diagrecs (res->entries->nonsurrogateDiagnostics,
1869                           res->entries->num_nonsurrogateDiagnostics);
1870 }
1871
1872 void process_sortResponse(Z_SortResponse *res)
1873 {
1874     printf("Received SortResponse: status=");
1875     switch (*res->sortStatus)
1876     {
1877     case Z_SortStatus_success:
1878         printf ("success"); break;
1879     case Z_SortStatus_partial_1:
1880         printf ("partial"); break;
1881     case Z_SortStatus_failure:
1882         printf ("failure"); break;
1883     default:
1884         printf ("unknown (%d)", *res->sortStatus);
1885     }
1886     printf ("\n");
1887     print_refid (res->referenceId);
1888     if (res->diagnostics)
1889         display_diagrecs(res->diagnostics,
1890                          res->num_diagnostics);
1891 }
1892
1893 void process_deleteResultSetResponse (Z_DeleteResultSetResponse *res)
1894 {
1895     printf("Got deleteResultSetResponse status=%d\n",
1896            *res->deleteOperationStatus);
1897     if (res->deleteListStatuses)
1898     {
1899         int i;
1900         for (i = 0; i < res->deleteListStatuses->num; i++)
1901         {
1902             printf ("%s status=%d\n", res->deleteListStatuses->elements[i]->id,
1903                     *res->deleteListStatuses->elements[i]->status);
1904         }
1905     }
1906 }
1907
1908 int cmd_sort_generic(char *arg, int newset)
1909 {
1910     if (!conn)
1911     {
1912         printf("Session not initialized yet\n");
1913         return 0;
1914     }
1915     if (!ODR_MASK_GET(session->options, Z_Options_sort))
1916     {
1917         printf("Target doesn't support sort\n");
1918         return 0;
1919     }
1920     if (*arg)
1921     {
1922         if (send_sortrequest(arg, newset) < 0)
1923             return 0;
1924         return 2;
1925     }
1926     return 0;
1927 }
1928
1929 int cmd_sort(char *arg)
1930 {
1931     return cmd_sort_generic (arg, 0);
1932 }
1933
1934 int cmd_sort_newset (char *arg)
1935 {
1936     return cmd_sort_generic (arg, 1);
1937 }
1938
1939 int cmd_scan(char *arg)
1940 {
1941     if (!conn)
1942     {
1943         printf("Session not initialized yet\n");
1944         return 0;
1945     }
1946     if (!ODR_MASK_GET(session->options, Z_Options_scan))
1947     {
1948         printf("Target doesn't support scan\n");
1949         return 0;
1950     }
1951     if (*arg)
1952     {
1953         strcpy (last_scan_query, arg);
1954         if (send_scanrequest(arg, 1, 20, 0) < 0)
1955             return 0;
1956     }
1957     else
1958     {
1959         if (send_scanrequest(last_scan_query, 1, 20, last_scan_line) < 0)
1960             return 0;
1961     }
1962     return 2;
1963 }
1964
1965 int cmd_schema(char *arg)
1966 {
1967     if (!arg || !*arg)
1968     {
1969         schema = VAL_NONE;
1970         return 1;
1971     }
1972     schema = oid_getvalbyname (arg);
1973     if (schema == VAL_NONE)
1974     {
1975         printf ("unknown schema\n");
1976         return 0;
1977     }
1978     return 1;
1979 }
1980
1981 int cmd_format(char *arg)
1982 {
1983     if (!arg || !*arg)
1984     {
1985         printf("Usage: format <recordsyntax>\n");
1986         return 0;
1987     }
1988     recordsyntax = oid_getvalbyname (arg);
1989     if (recordsyntax == VAL_NONE)
1990     {
1991         printf ("unknown record syntax\n");
1992         return 0;
1993     }
1994     return 1;
1995 }
1996
1997 int cmd_elements(char *arg)
1998 {
1999     static Z_ElementSetNames esn;
2000     static char what[100];
2001
2002     if (!arg || !*arg)
2003     {
2004         elementSetNames = 0;
2005         return 1;
2006     }
2007     strcpy(what, arg);
2008     esn.which = Z_ElementSetNames_generic;
2009     esn.u.generic = what;
2010     elementSetNames = &esn;
2011     return 1;
2012 }
2013
2014 int cmd_attributeset(char *arg)
2015 {
2016     char what[100];
2017
2018     if (!arg || !*arg)
2019     {
2020         printf("Usage: attributeset <setname>\n");
2021         return 0;
2022     }
2023     sscanf(arg, "%s", what);
2024     if (p_query_attset (what))
2025     {
2026         printf("Unknown attribute set name\n");
2027         return 0;
2028     }
2029     return 1;
2030 }
2031
2032 int cmd_querytype (char *arg)
2033 {
2034     if (!strcmp (arg, "ccl"))
2035         queryType = QueryType_CCL;
2036     else if (!strcmp (arg, "prefix") || !strcmp(arg, "rpn"))
2037         queryType = QueryType_Prefix;
2038 #if YAZ_MODULE_ccl
2039     else if (!strcmp (arg, "ccl2rpn") || !strcmp (arg, "cclrpn"))
2040         queryType = QueryType_CCL2RPN;
2041 #endif
2042     else
2043     {
2044         printf ("Querytype must be one of:\n");
2045         printf (" prefix         - Prefix query\n");
2046         printf (" ccl            - CCL query\n");
2047 #if YAZ_MODULE_ccl
2048         printf (" ccl2rpn        - CCL query converted to RPN\n");
2049 #endif
2050         return 0;
2051     }
2052     return 1;
2053 }
2054
2055 int cmd_refid (char *arg)
2056 {
2057     xfree (refid);
2058     refid = NULL;
2059     if (*arg)
2060     {
2061         refid = (char *) xmalloc (strlen(arg)+1);
2062         strcpy (refid, arg);
2063     }
2064     return 1;
2065 }
2066
2067 int cmd_close(char *arg)
2068 {
2069     Z_APDU *apdu;
2070     Z_Close *req;
2071     if (!conn)
2072         return 0;
2073
2074     apdu = zget_APDU(out, Z_APDU_close);
2075     req = apdu->u.close;
2076     *req->closeReason = Z_Close_finished;
2077     send_apdu(apdu);
2078     printf("Sent close request.\n");
2079     sent_close = 1;
2080     return 2;
2081 }
2082
2083 int cmd_packagename(char* arg)
2084 {
2085     xfree (esPackageName);
2086     esPackageName = NULL;
2087     if (*arg)
2088     {
2089         esPackageName = (char *) xmalloc (strlen(arg)+1);
2090         strcpy (esPackageName, arg);
2091     }
2092     return 1;
2093 }
2094
2095 int cmd_proxy(char* arg)
2096 {
2097     if (*arg == '\0') {
2098         printf("Current proxy is `%s'\n", (yazCharset)?yazProxy:NULL);
2099         return 1;
2100     }
2101     xfree (yazProxy);
2102     yazProxy = NULL;
2103     if (*arg)
2104     {
2105         yazProxy = (char *) xmalloc (strlen(arg)+1);
2106         strcpy (yazProxy, arg);
2107     } 
2108     return 1;
2109 }
2110
2111 int cmd_charset(char* arg)
2112 {
2113     if (*arg == '\0') {
2114         printf("Current character set is `%s'\n", (yazCharset)?yazCharset:NULL);
2115         return 1;
2116     }
2117     xfree (yazCharset);
2118     yazCharset = NULL;
2119     if (*arg)
2120     {
2121         yazCharset = (char *) xmalloc (strlen(arg)+1);
2122         strcpy (yazCharset, arg);
2123     } 
2124     return 1;
2125 }
2126
2127 int cmd_lang(char* arg)
2128 {
2129     if (*arg == '\0') {
2130         printf("Current language is `%s'\n", (yazLang)?yazLang:NULL);
2131         return 1;
2132     }
2133     xfree (yazLang);
2134     yazLang = NULL;
2135     if (*arg)
2136     {
2137         yazLang = (char *) xmalloc (strlen(arg)+1);
2138         strcpy (yazLang, arg);
2139     } 
2140     return 1;
2141 }
2142
2143 int cmd_source(char* arg) 
2144 {
2145     /* first should open the file and read one line at a time.. */
2146     FILE* includeFile;
2147     char line[1024], *cp;
2148
2149     {
2150         char* args_end=(arg)+strlen(arg)-1; 
2151         while(isspace(*args_end)) 
2152         {*args_end=0;
2153         --args_end;}; 
2154     }
2155
2156     REMOVE_TAILING_BLANKS(arg);
2157     
2158     if(strlen(arg)<1) {
2159         fprintf(stderr,"Error in source command use a filename\n");
2160         return -1;
2161     }
2162     
2163     includeFile = fopen (arg, "r");
2164     
2165     if(!includeFile) {
2166         fprintf(stderr,"Unable to open file %s for reading\n",arg);
2167         return -1;
2168     }
2169     
2170     while(!feof(includeFile)) {
2171         memset(line,0,sizeof(line));
2172         fgets(line,sizeof(line),includeFile);
2173         
2174         if(strlen(line) < 2) continue;
2175         if(line[0] == '#') continue;
2176         
2177         if ((cp = strrchr (line, '\n')))
2178             *cp = '\0';
2179         
2180         process_cmd_line(line);
2181     }
2182     
2183     if(fclose(includeFile)<0) {
2184         perror("unable to close include file");
2185         exit(1);
2186     }
2187     return 1;
2188 }
2189
2190 int cmd_subshell(char* args)
2191 {
2192     if(strlen(args)) 
2193         system(args);
2194     else 
2195         system(getenv("SHELL"));
2196     
2197     printf("\n");
2198     return 1;
2199 }
2200
2201 int cmd_set_apdufile(char* arg)
2202 {
2203     REMOVE_TAILING_BLANKS(arg);
2204   
2205     if(apdu_file && apdu_file != stderr) { /* don't close stdout*/
2206         perror("unable to close apdu log file");      
2207     }
2208     apdu_file=NULL;
2209   
2210     if(strlen(arg)<1) {
2211         return 1;
2212     }
2213   
2214     if(!strcmp(arg,"-")) 
2215         apdu_file=stderr;      
2216     else 
2217         apdu_file=fopen(arg, "a");
2218   
2219     if(!apdu_file) {
2220         perror("unable to open apdu log file no apdu log loaded");
2221     } else {
2222         odr_setprint(print, apdu_file); 
2223     }
2224   
2225     return 1;
2226 }
2227
2228 int cmd_set_cclfields(char* arg)
2229 {  
2230 #if YAZ_MODULE_ccl
2231     FILE *inf;
2232
2233     REMOVE_TAILING_BLANKS(arg);
2234
2235     bibset = ccl_qual_mk (); 
2236     inf = fopen (arg, "r");
2237     if (inf)
2238     {
2239         ccl_qual_file (bibset, inf);
2240         fclose (inf);
2241     }
2242 #else 
2243     fprintf(stderr,"Not compiled with the yaz ccl module\n");
2244 #endif
2245     
2246     return 1;
2247 }
2248
2249 int cmd_set_marcdump(char* arg)
2250 {
2251     if(marcdump && marcdump != stderr) { /* don't close stdout*/
2252         perror("unable to close apdu log file");      
2253     }
2254     marcdump=NULL;
2255     
2256     if(strlen(arg)<1) {
2257         return 1;
2258     }
2259   
2260     if(!strcmp(arg,"-")) 
2261         marcdump=stderr;      
2262     else 
2263         marcdump=fopen(arg, "a");
2264   
2265     if(!marcdump) {
2266         perror("unable to open apdu marcdump file no marcdump done\n");
2267     }
2268   
2269     return 1;
2270 }
2271
2272 int cmd_set_proxy(char* arg) {
2273     if(yazProxy) free(yazProxy);
2274     yazProxy=NULL;
2275
2276     if(strlen(arg) > 1) {
2277         yazProxy=strdup(arg);
2278     }
2279     return 1;
2280 }
2281
2282 /* 
2283    this command takes 3 arge {name class oid} 
2284  */
2285 int cmd_register_oid(char* args) {
2286     static struct {
2287         char* className;
2288         oid_class oclass;
2289     } oid_classes[] = {
2290         {"appctx",CLASS_APPCTX},
2291         {"absyn",CLASS_ABSYN},
2292         {"attset",CLASS_ATTSET},
2293         {"transyn",CLASS_TRANSYN},
2294         {"diagset",CLASS_DIAGSET},
2295         {"recsyn",CLASS_RECSYN},
2296         {"resform",CLASS_RESFORM},
2297         {"accform",CLASS_ACCFORM},
2298         {"extserv",CLASS_EXTSERV},
2299         {"userinfo",CLASS_USERINFO},
2300         {"elemspec",CLASS_ELEMSPEC},
2301         {"varset",CLASS_VARSET},
2302         {"schema",CLASS_SCHEMA},
2303         {"tagset",CLASS_TAGSET},
2304         {"general",CLASS_GENERAL},
2305         {0,0}
2306     };
2307     char oname_str[101], oclass_str[101], oid_str[101];  
2308     char* name;
2309     int i;
2310     oid_class oidclass = CLASS_GENERAL;
2311     int val = 0, oid[OID_SIZE];
2312     struct oident * new_oident=NULL;
2313     
2314     if (sscanf (args, "%100[^ ] %100[^ ] %100s",
2315                 oname_str,oclass_str, oid_str) < 1) {
2316         printf("Error in regristrate command \n");
2317         return 0;
2318     }
2319     
2320     for (i = 0; oid_classes[i].className; i++) {
2321         if (!strcmp(oid_classes[i].className, oclass_str))
2322         {
2323             oidclass=oid_classes[i].oclass;
2324             break;
2325         }
2326     }
2327     
2328     if(!(oid_classes[i].className)) {
2329         printf("Unknonwn oid class %s\n",oclass_str);
2330         return 0;
2331     }
2332
2333     i = 0;
2334     name = oid_str;
2335     val = 0;
2336     
2337     while (isdigit (*name))
2338     {
2339         val = val*10 + (*name - '0');
2340         name++;
2341         if (*name == '.')
2342         {
2343             if (i < OID_SIZE-1)
2344                 oid[i++] = val;
2345             val = 0;
2346             name++;
2347         }
2348     }
2349     oid[i] = val;
2350     oid[i+1] = -1;
2351     
2352     new_oident=oid_addent (oid,PROTO_GENERAL,oidclass,oname_str,VAL_DYNAMIC);  
2353     if(strcmp(new_oident->desc,oname_str)) {
2354         fprintf(stderr,"oid is already named as %s, regristration faild\n",
2355                 new_oident->desc);
2356     }
2357     return 1;  
2358 }
2359
2360 int cmd_push_command(char* arg) {
2361 #if HAVE_READLINE_HISTORY_H
2362     if(strlen(arg)>1) 
2363         add_history(arg);
2364 #else 
2365     fprintf(stderr,"Not compiled with the readline/history module\n");
2366 #endif
2367     return 1;
2368 }
2369
2370 void source_rcfile() {
2371     /*  Look for a $HOME/.yazclientrc and source it if it exists */
2372     struct stat statbuf;
2373     char buffer[1000];
2374     char* homedir=getenv("HOME");
2375     if(!homedir) return;
2376     
2377     sprintf(buffer,"%s/.yazclientrc",homedir);
2378     
2379     if(stat(buffer,&statbuf)==0) {
2380         cmd_source(buffer);
2381     }
2382     
2383     if(stat(".yazclientrc",&statbuf)==0) {
2384         cmd_source(".yazclientrc");
2385     }
2386 }
2387
2388
2389 static void initialize(void)
2390 {
2391 #if YAZ_MODULE_ccl
2392     FILE *inf;
2393 #endif
2394     if (!(out = odr_createmem(ODR_ENCODE)) ||
2395         !(in = odr_createmem(ODR_DECODE)) ||
2396         !(print = odr_createmem(ODR_PRINT)))
2397     {
2398         fprintf(stderr, "failed to allocate ODR streams\n");
2399         exit(1);
2400     }
2401     oid_init();
2402
2403     setvbuf(stdout, 0, _IONBF, 0);
2404     if (apdu_file)
2405         odr_setprint(print, apdu_file);
2406
2407 #if YAZ_MODULE_ccl
2408     bibset = ccl_qual_mk (); 
2409     inf = fopen (ccl_fields, "r");
2410     if (inf)
2411     {
2412         ccl_qual_file (bibset, inf);
2413         fclose (inf);
2414     }
2415 #endif
2416     cmd_base("Default");
2417
2418 #if HAVE_READLINE_READLINE_H
2419     rl_attempted_completion_function = (CPPFunction*)readline_completer;
2420 #endif
2421
2422     source_rcfile();
2423 }
2424
2425
2426 #if HAVE_GETTIMEOFDAY
2427 struct timeval tv_start, tv_end;
2428 #endif
2429
2430 void wait_and_handle_responce() 
2431 {
2432     
2433     int res;
2434     char *netbuffer= 0;
2435     int netbufferlen = 0;
2436     Z_APDU *apdu;
2437     
2438     
2439     if (conn)
2440     {
2441         do
2442         {
2443             if ((res = cs_get(conn, &netbuffer, &netbufferlen)) < 0)
2444             {
2445                 printf("Target closed connection\n");
2446                 close_session ();
2447                 break;
2448             }
2449             if (!res)
2450             {
2451                 printf("Target closed connection.\n");
2452                 close_session ();
2453                 break;
2454             }
2455             odr_reset(in); /* release APDU from last round */
2456             record_last = 0;
2457             odr_setbuf(in, netbuffer, res, 0);
2458             if (!z_APDU(in, &apdu, 0, 0))
2459             {
2460                 odr_perror(in, "Decoding incoming APDU");
2461                 fprintf(stderr, "[Near %d]\n", odr_offset(in));
2462                 fprintf(stderr, "Packet dump:\n---------\n");
2463                 odr_dumpBER(stderr, netbuffer, res);
2464                 fprintf(stderr, "---------\n");
2465                 if (apdu_file)
2466                     z_APDU(print, &apdu, 0, 0);
2467                 close_session ();
2468                 break;
2469             }
2470             if (apdu_file && !z_APDU(print, &apdu, 0, 0))
2471             {
2472                 odr_perror(print, "Failed to print incoming APDU");
2473                 odr_reset(print);
2474                 continue;
2475             }
2476             switch(apdu->which)
2477             {
2478             case Z_APDU_initResponse:
2479                 process_initResponse(apdu->u.initResponse);
2480                 break;
2481             case Z_APDU_searchResponse:
2482                 process_searchResponse(apdu->u.searchResponse);
2483                 break;
2484             case Z_APDU_scanResponse:
2485                 process_scanResponse(apdu->u.scanResponse);
2486                 break;
2487             case Z_APDU_presentResponse:
2488                 print_refid (apdu->u.presentResponse->referenceId);
2489                 setno +=
2490                     *apdu->u.presentResponse->numberOfRecordsReturned;
2491                 if (apdu->u.presentResponse->records)
2492                     display_records(apdu->u.presentResponse->records);
2493                 else
2494                     printf("No records.\n");
2495                 printf ("nextResultSetPosition = %d\n",
2496                         *apdu->u.presentResponse->nextResultSetPosition);
2497                 break;
2498             case Z_APDU_sortResponse:
2499                 process_sortResponse(apdu->u.sortResponse);
2500                 break;
2501             case Z_APDU_extendedServicesResponse:
2502                 printf("Got extended services response\n");
2503                 process_ESResponse(apdu->u.extendedServicesResponse);
2504                 break;
2505             case Z_APDU_close:
2506                 printf("Target has closed the association.\n");
2507                 process_close(apdu->u.close);
2508                 break;
2509             case Z_APDU_resourceControlRequest:
2510                 process_resourceControlRequest
2511                     (apdu->u.resourceControlRequest);
2512                 break;
2513             case Z_APDU_deleteResultSetResponse:
2514                 process_deleteResultSetResponse(apdu->u.
2515                                                 deleteResultSetResponse);
2516                 break;
2517             default:
2518                 printf("Received unknown APDU type (%d).\n", 
2519                        apdu->which);
2520                 close_session ();
2521             }
2522         }
2523         while (conn && cs_more(conn));
2524 #if HAVE_GETTIMEOFDAY
2525         gettimeofday (&tv_end, 0);
2526 #if 0
2527         printf ("S/U S/U=%ld/%ld %ld/%ld",
2528                 (long) tv_start.tv_sec,
2529                 (long) tv_start.tv_usec,
2530                 (long) tv_end.tv_sec,
2531                 (long) tv_end.tv_usec);
2532 #endif
2533         printf ("Elapsed: %.6f\n",
2534                 (double) tv_end.tv_usec / 1e6 + tv_end.tv_sec -
2535                 ((double) tv_start.tv_usec / 1e6 + tv_start.tv_sec));
2536 #endif
2537     }
2538     xfree (netbuffer);
2539 }
2540
2541
2542 static int cmd_help (char *line);
2543
2544 static struct {
2545     char *cmd;
2546     int (*fun)(char *arg);
2547     char *ad;
2548     char *(*rl_completerfunction)(const char *text, int state);
2549     int complete_filenames;
2550 } cmd[] = {
2551     {"open", cmd_open, "('tcp'|'ssl')':<host>[':'<port>][/<db>]",NULL,0},
2552     {"quit", cmd_quit, "",NULL,0},
2553     {"find", cmd_find, "<query>",NULL,0},
2554     {"delete", cmd_delete, "<setname>",NULL,0},
2555     {"base", cmd_base, "<base-name>",NULL,0},
2556     {"show", cmd_show, "<rec#>['+'<#recs>['+'<setname>]]",NULL,0},
2557     {"scan", cmd_scan, "<term>",NULL,0},
2558     {"sort", cmd_sort, "<sortkey> <flag> <sortkey> <flag> ...",NULL,0},
2559     {"sort+", cmd_sort_newset, "<sortkey> <flag> <sortkey> <flag> ...",NULL,0},
2560     {"authentication", cmd_authentication, "<acctstring>",NULL,0},
2561     {"lslb", cmd_lslb, "<largeSetLowerBound>",NULL,0},
2562     {"ssub", cmd_ssub, "<smallSetUpperBound>",NULL,0},
2563     {"mspn", cmd_mspn, "<mediumSetPresentNumber>",NULL,0},
2564     {"status", cmd_status, "",NULL,0},
2565     {"setnames", cmd_setnames, "",NULL,0},
2566     {"cancel", cmd_cancel, "",NULL,0},
2567     {"format", cmd_format, "<recordsyntax>",complete_format,0},
2568     {"schema", cmd_schema, "<schema>",complete_schema,0},
2569     {"elements", cmd_elements, "<elementSetName>",NULL,0},
2570     {"close", cmd_close, "",NULL,0},
2571     {"attributeset", cmd_attributeset, "<attrset>",complete_attributeset,0},
2572     {"querytype", cmd_querytype, "<type>",complete_querytype,0},
2573     {"refid", cmd_refid, "<id>",NULL,0},
2574     {"itemorder", cmd_itemorder, "ill|item <itemno>",NULL,0},
2575     {"update", cmd_update, "<item>",NULL,0},
2576     {"packagename", cmd_packagename, "<packagename>",NULL,0},
2577     {"proxy", cmd_proxy, "[('tcp'|'ssl')]<host>[':'<port>]",NULL,0},
2578     {"charset", cmd_charset, "<charset_name>",NULL,0},
2579     {"lang", cmd_lang, "<language_code>",NULL,0},
2580     {".", cmd_source, "<filename>",NULL,1},
2581     {"!", cmd_subshell, "Subshell command",NULL,0},
2582     {"set_apdufile", cmd_set_apdufile, "<filename>",NULL,0},
2583     {"set_marcdump", cmd_set_marcdump," <filename>",NULL,0},
2584     {"set_cclfields", cmd_set_cclfields,"<filename>",NULL,1}, 
2585     {"register_oid",cmd_register_oid,"<name> <class> <oid>",NULL,0},
2586     {"push_command",cmd_push_command,"<command>",command_generator,0},
2587     /* Server Admin Functions */
2588     {"adm-reindex", cmd_adm_reindex, "<database-name>",NULL,0},
2589     {"adm-truncate", cmd_adm_truncate, "('database'|'index')<object-name>",NULL,0},
2590     {"adm-create", cmd_adm_create, "",NULL,0},
2591     {"adm-drop", cmd_adm_drop, "('database'|'index')<object-name>",NULL,0},
2592     {"adm-import", cmd_adm_import, "<record-type> <dir> <pattern>",NULL,0},
2593     {"adm-refresh", cmd_adm_refresh, "",NULL,0},
2594     {"adm-commit", cmd_adm_commit, "",NULL,0},
2595     {"adm-shutdown", cmd_adm_shutdown, "",NULL,0},
2596     {"adm-startup", cmd_adm_startup, "",NULL,0},
2597     {"help", cmd_help, "", NULL},
2598     {0,0,0,0,0}
2599 };
2600
2601 static int cmd_help (char *line)
2602 {
2603     int i;
2604     char topic[21];
2605     
2606     *topic = 0;
2607     sscanf (line, "%20s", topic);
2608
2609     if (*topic == 0)
2610         printf("Commands:\n");
2611     for (i = 0; cmd[i].cmd; i++)
2612         if (*topic == 0 || strcmp (topic, cmd[i].cmd) == 0)
2613             printf("   %s %s\n", cmd[i].cmd, cmd[i].ad);
2614     if (strcmp (topic, "find") == 0)
2615     {
2616         printf ("RPN:\n");
2617         printf (" \"term\"                        Simple Term\n");
2618         printf (" @attr [attset] type=value op  Attribute\n");
2619         printf (" @and opl opr                  And\n");
2620         printf (" @or opl opr                   Or\n");
2621         printf (" @not opl opr                  And-Not\n");
2622         printf (" @set set                      Result set\n");
2623         printf ("\n");
2624         printf ("Bib-1 attribute types\n");
2625         printf ("1=Use:         ");
2626         printf ("4=Title 7=ISBN 8=ISSN 30=Date 62=Abstract 1003=Author 1016=Any\n");
2627         printf ("2=Relation:    ");
2628         printf ("1<   2<=  3=  4>=  5>  6!=  102=Relevance\n");
2629         printf ("3=Position:    ");
2630         printf ("1=First in Field  2=First in subfield  3=Any position\n");
2631         printf ("4=Structure:   ");
2632         printf ("1=Phrase  2=Word  3=Key  4=Year  5=Date  6=WordList\n");
2633         printf ("5=Truncation:  ");
2634         printf ("1=Right  2=Left  3=L&R  100=No  101=#  102=Re-1  103=Re-2\n");
2635         printf ("6=Completeness:");
2636         printf ("1=Incomplete subfield  2=Complete subfield  3=Complete field\n");
2637     }
2638     return 1;
2639 }
2640
2641 void process_cmd_line(char* line)
2642 {  
2643     int i,res;
2644     char word[32], arg[1024];
2645     
2646 #if HAVE_GETTIMEOFDAY
2647     gettimeofday (&tv_start, 0);
2648 #endif
2649     
2650     if ((res = sscanf(line, "%31s %1023[^;]", word, arg)) <= 0)
2651     {
2652         strcpy(word, last_cmd);
2653         *arg = '\0';
2654     }
2655     else if (res == 1)
2656         *arg = 0;
2657     strcpy(last_cmd, word);
2658     
2659     /* removed tailing spaces from the arg command */
2660     { 
2661         char* p;
2662         char* lastnonspace=NULL;
2663         p = arg;
2664         
2665         for(;*p; ++p) {
2666             if(!isspace(*p)) {
2667                 lastnonspace = p;
2668             }
2669         }
2670         if(lastnonspace) 
2671             *(++lastnonspace) = 0;
2672     }
2673     
2674
2675     for (i = 0; cmd[i].cmd; i++)
2676         if (!strncmp(cmd[i].cmd, word, strlen(word)))
2677         {
2678             res = (*cmd[i].fun)(arg);
2679             break;
2680         }
2681
2682     if (!cmd[i].cmd) /* dump our help-screen */
2683     {
2684         printf("Unknown command: %s.\n", word);
2685         cmd_help ("");
2686         res = 1;
2687     }
2688
2689     if(apdu_file) fflush(apdu_file);
2690     
2691     if (res >= 2)
2692         wait_and_handle_responce();
2693
2694     if(apdu_file)
2695         fflush(apdu_file);
2696     if(marcdump)
2697         fflush(marcdump);
2698 }
2699
2700
2701 char *command_generator(const char *text, int state) 
2702 {
2703     static int idx; 
2704     if (state==0) {
2705         idx = 0;
2706     }
2707     for( ; cmd[idx].cmd; ++idx) {
2708         if (!strncmp(cmd[idx].cmd,text,strlen(text))) {
2709             ++idx;  /* skip this entry on the next run */
2710             return strdup(cmd[idx-1].cmd);
2711         }
2712     }
2713     return NULL;
2714 }
2715
2716
2717 /* 
2718    This function only known how to complete on the first word
2719 */
2720 char ** readline_completer(char *text, int start, int end) {
2721 #if HAVE_READLINE_READLINE_H
2722
2723     if(start == 0) {
2724 #if HAVE_READLINE_RL_COMPLETION_MATCHES
2725         char** res=rl_completion_matches(text,
2726                                       command_generator); 
2727 #else
2728         char** res=completion_matches(text,
2729                                       (CPFunction*)command_generator); 
2730 #endif
2731         rl_attempted_completion_over = 1;
2732         return res;
2733     } else {
2734         char arg[1024],word[32];
2735         int i=0 ,res;
2736         if ((res = sscanf(rl_line_buffer, "%31s %1023[^;]", word, arg)) <= 0) {     
2737             rl_attempted_completion_over = 1;
2738             return NULL;
2739         }
2740     
2741         if(start != strlen(word) +1 ) {
2742             rl_attempted_completion_over = 1;
2743             return 0;
2744         }
2745         for (i = 0; cmd[i].cmd; i++) {
2746             if (!strncmp(cmd[i].cmd, word, strlen(word))) {
2747                 break;
2748             }
2749         }
2750     
2751
2752         if(!cmd[i].complete_filenames) 
2753             rl_attempted_completion_over = 1;    
2754         if(cmd[i].rl_completerfunction) {
2755 #ifdef HAVE_READLINE_RL_COMPLETION_MATCHES
2756             char** res=
2757                 rl_completion_matches(text,
2758                                    cmd[i].rl_completerfunction);
2759 #else
2760             char** res=
2761                 completion_matches(text,
2762                                    (CPFunction*)cmd[i].rl_completerfunction);
2763 #endif
2764             rl_attempted_completion_over = 1;    
2765             return res;
2766         } else {
2767             rl_attempted_completion_over = 1;
2768             return 0;
2769         }
2770     }
2771 #else 
2772     return 0;
2773 #endif 
2774 }
2775
2776
2777 static void client(void)
2778 {
2779     char line[1024];
2780
2781     line[1023] = '\0';
2782
2783 #if HAVE_GETTIMEOFDAY
2784     gettimeofday (&tv_start, 0);
2785 #endif
2786
2787     while (1)
2788     {
2789         char *line_in = NULL;
2790 #if HAVE_READLINE_READLINE_H
2791         if (isatty(0))
2792         {
2793             line_in=readline(C_PROMPT);
2794             if (!line_in)
2795                 break;
2796 #if HAVE_READLINE_HISTORY_H
2797             if (*line_in)
2798                 add_history(line_in);
2799 #endif
2800             strncpy(line, line_in, 1023);
2801             free (line_in);
2802         }
2803 #endif 
2804         if (!line_in)
2805         {
2806             char *end_p;
2807             printf (C_PROMPT);
2808             fflush(stdout);
2809             if (!fgets(line, 1023, stdin))
2810                 break;
2811             if ((end_p = strchr (line, '\n')))
2812                 *end_p = '\0';
2813         }
2814         process_cmd_line(line);
2815     }
2816 }
2817
2818 int main(int argc, char **argv)
2819 {
2820     char *prog = *argv;
2821     char *open_command = 0;
2822     char *auth_command = 0;
2823     char *arg;
2824     int ret;
2825     
2826     while ((ret = options("k:c:a:m:v:p:u:", argv, argc, &arg)) != -2)
2827     {
2828         switch (ret)
2829         {
2830         case 0:
2831             if (!open_command)
2832             {
2833                 open_command = (char *) xmalloc (strlen(arg)+6);
2834                 strcpy (open_command, "open ");
2835                 strcat (open_command, arg);
2836             }
2837             break;
2838         case 'k':
2839             kilobytes = atoi(arg);
2840             break;
2841         case 'm':
2842             if (!(marcdump = fopen (arg, "a")))
2843             {
2844                 perror (arg);
2845                 exit (1);
2846             }
2847             break;
2848     case 'c':
2849         strncpy (ccl_fields, arg, sizeof(ccl_fields)-1);
2850         ccl_fields[sizeof(ccl_fields)-1] = '\0';
2851         break;
2852         case 'a':
2853             if (!strcmp(arg, "-"))
2854                 apdu_file=stderr;
2855             else
2856                 apdu_file=fopen(arg, "a");
2857             break;
2858     case 'p':
2859         yazProxy=strdup(arg);
2860         break;
2861         case 'u':
2862             if (!auth_command)
2863             {
2864                 auth_command = (char *) xmalloc (strlen(arg)+6);
2865                 strcpy (auth_command, "auth ");
2866                 strcat (auth_command, arg);
2867             }
2868             break;
2869         case 'v':
2870             yaz_log_init (yaz_log_mask_str(arg), "", NULL);
2871             break;
2872         default:
2873             fprintf (stderr, "Usage: %s [-m <marclog>] [ -a <apdulog>] "
2874                      "[-c cclfields]\n      [-p <proxy-addr>] [-u <auth>] "
2875                      "[-k size] [<server-addr>]\n",
2876                      prog);
2877             exit (1);
2878         }      
2879     }
2880     initialize();
2881     if (auth_command)
2882     {
2883 #ifdef HAVE_GETTIMEOFDAY
2884         gettimeofday (&tv_start, 0);
2885 #endif
2886         process_cmd_line (auth_command);
2887 #if HAVE_READLINE_HISTORY_H
2888         add_history(auth_command);
2889 #endif
2890         xfree(auth_command);
2891     }
2892     if (open_command)
2893     {
2894 #ifdef HAVE_GETTIMEOFDAY
2895         gettimeofday (&tv_start, 0);
2896 #endif
2897         process_cmd_line (open_command);
2898 #if HAVE_READLINE_HISTORY_H
2899         add_history(open_command);
2900 #endif
2901         xfree(open_command);
2902     }
2903     client ();
2904     exit (0);
2905 }
2906
2907
2908 /*
2909  * Local variables:
2910  * tab-width: 4
2911  * c-basic-offset: 4
2912  * End:
2913  */