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