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