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