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