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