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