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