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