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