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