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