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