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