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