98b8bd5e078d5d90d9d71ce2d7869b7eaa5630f3
[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.169 2002-09-17 11:07:30 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 laiter */
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     printf ("Update request\n");
1540     fflush(stdout);
1541     
1542     if (!record_last)
1543         return 0;
1544     update_oid.proto = PROTO_Z3950;
1545     update_oid.oclass = CLASS_EXTSERV;
1546     update_oid.value = VAL_DBUPDATE;
1547     oid_ent_to_oid (&update_oid, oid);
1548     req->packageType = odr_oiddup(out,oid);
1549     req->packageName = esPackageName;
1550     
1551     req->referenceId = set_refid (out);
1552
1553     r = req->taskSpecificParameters = (Z_External *)
1554         odr_malloc (out, sizeof(*r));
1555     r->direct_reference = odr_oiddup(out,oid);
1556     r->indirect_reference = 0;
1557     r->descriptor = 0;
1558     r->which = Z_External_update;
1559     r->u.update = (Z_IUUpdate *) odr_malloc(out, sizeof(*r->u.update));
1560     r->u.update->which = Z_IUUpdate_esRequest;
1561     r->u.update->u.esRequest = (Z_IUUpdateEsRequest *)
1562         odr_malloc(out, sizeof(*r->u.update->u.esRequest));
1563     toKeep = r->u.update->u.esRequest->toKeep = (Z_IUOriginPartToKeep *)
1564         odr_malloc(out, sizeof(*r->u.update->u.esRequest->toKeep));
1565     toKeep->databaseName = databaseNames[0];
1566     toKeep->schema = 0;
1567     toKeep->elementSetName = 0;
1568     toKeep->actionQualifier = 0;
1569     toKeep->action = (int *) odr_malloc(out, sizeof(*toKeep->action));
1570     *toKeep->action = Z_IUOriginPartToKeep_recordInsert;
1571
1572     notToKeep = r->u.update->u.esRequest->notToKeep = (Z_IUSuppliedRecords *)
1573         odr_malloc(out, sizeof(*r->u.update->u.esRequest->notToKeep));
1574     notToKeep->num = 1;
1575     notToKeep->elements = (Z_IUSuppliedRecords_elem **)
1576         odr_malloc(out, sizeof(*notToKeep->elements));
1577     notToKeep->elements[0] = (Z_IUSuppliedRecords_elem *)
1578         odr_malloc(out, sizeof(**notToKeep->elements));
1579     notToKeep->elements[0]->u.number = 0;
1580     notToKeep->elements[0]->supplementalId = 0;
1581     notToKeep->elements[0]->correlationInfo = 0;
1582     notToKeep->elements[0]->record = record_last;
1583     
1584     send_apdu(apdu);
1585
1586     return 2;
1587 }
1588
1589 static int cmd_itemorder(char *arg)
1590 {
1591     char type[12];
1592     int itemno;
1593     
1594     if (sscanf (arg, "%10s %d", type, &itemno) != 2)
1595         return 0;
1596
1597     printf("Item order request\n");
1598     fflush(stdout);
1599     send_itemorder(type, itemno);
1600     return 2;
1601 }
1602
1603 static int cmd_find(char *arg)
1604 {
1605     if (!*arg)
1606     {
1607         printf("Find what?\n");
1608         return 0;
1609     }
1610     if (!conn)
1611     {
1612                 try_reconnect(); 
1613
1614                 if (!conn) {                                    
1615                         printf("Not connected yet\n");
1616                         return 0;
1617                 };
1618     }
1619     if (!send_searchRequest(arg))
1620         return 0;
1621     return 2;
1622 }
1623
1624 static int cmd_delete(char *arg)
1625 {
1626     if (!conn)
1627     {
1628         printf("Not connected yet\n");
1629         return 0;
1630     }
1631     if (!send_deleteResultSetRequest(arg))
1632         return 0;
1633     return 2;
1634 }
1635
1636 static int cmd_ssub(char *arg)
1637 {
1638     if (!(smallSetUpperBound = atoi(arg)))
1639         return 0;
1640     return 1;
1641 }
1642
1643 static int cmd_lslb(char *arg)
1644 {
1645     if (!(largeSetLowerBound = atoi(arg)))
1646         return 0;
1647     return 1;
1648 }
1649
1650 static int cmd_mspn(char *arg)
1651 {
1652     if (!(mediumSetPresentNumber = atoi(arg)))
1653         return 0;
1654     return 1;
1655 }
1656
1657 static int cmd_status(char *arg)
1658 {
1659     printf("smallSetUpperBound: %d\n", smallSetUpperBound);
1660     printf("largeSetLowerBound: %d\n", largeSetLowerBound);
1661     printf("mediumSetPresentNumber: %d\n", mediumSetPresentNumber);
1662     return 1;
1663 }
1664
1665 static int cmd_setnames(char *arg)
1666 {
1667     if (*arg == '1')         /* enable ? */
1668         setnumber = 0;
1669     else if (*arg == '0')    /* disable ? */
1670         setnumber = -1;
1671     else if (setnumber < 0)  /* no args, toggle .. */
1672         setnumber = 0;
1673     else
1674         setnumber = -1;
1675    
1676     if (setnumber >= 0)
1677         printf("Set numbering enabled.\n");
1678     else
1679         printf("Set numbering disabled.\n");
1680     return 1;
1681 }
1682
1683 /* PRESENT SERVICE ----------------------------- */
1684
1685 static int send_presentRequest(char *arg)
1686 {
1687     Z_APDU *apdu = zget_APDU(out, Z_APDU_presentRequest);
1688     Z_PresentRequest *req = apdu->u.presentRequest;
1689     Z_RecordComposition compo;
1690     oident prefsyn;
1691     int nos = 1;
1692     int oid[OID_SIZE];
1693     char *p;
1694     char setstring[100];
1695
1696     req->referenceId = set_refid (out);
1697     if ((p = strchr(arg, '+')))
1698     {
1699         nos = atoi(p + 1);
1700         *p = 0;
1701     }
1702     if (*arg)
1703         setno = atoi(arg);
1704     if (p && (p=strchr(p+1, '+')))
1705     {
1706         strcpy (setstring, p+1);
1707         req->resultSetId = setstring;
1708     }
1709     else if (setnumber >= 0)
1710     {
1711         sprintf(setstring, "%d", setnumber);
1712         req->resultSetId = setstring;
1713     }
1714     req->resultSetStartPoint = &setno;
1715     req->numberOfRecordsRequested = &nos;
1716     prefsyn.proto = protocol;
1717     prefsyn.oclass = CLASS_RECSYN;
1718     prefsyn.value = recordsyntax;
1719     req->preferredRecordSyntax =
1720         odr_oiddup (out, oid_ent_to_oid(&prefsyn, oid));
1721
1722     if (schema != VAL_NONE)
1723     {
1724         oident prefschema;
1725
1726         prefschema.proto = protocol;
1727         prefschema.oclass = CLASS_SCHEMA;
1728         prefschema.value = schema;
1729
1730         req->recordComposition = &compo;
1731         compo.which = Z_RecordComp_complex;
1732         compo.u.complex = (Z_CompSpec *)
1733             odr_malloc(out, sizeof(*compo.u.complex));
1734         compo.u.complex->selectAlternativeSyntax = (bool_t *) 
1735             odr_malloc(out, sizeof(bool_t));
1736         *compo.u.complex->selectAlternativeSyntax = 0;
1737
1738         compo.u.complex->generic = (Z_Specification *)
1739             odr_malloc(out, sizeof(*compo.u.complex->generic));
1740         compo.u.complex->generic->schema = (Odr_oid *)
1741             odr_oiddup(out, oid_ent_to_oid(&prefschema, oid));
1742         if (!compo.u.complex->generic->schema)
1743         {
1744             /* OID wasn't a schema! Try record syntax instead. */
1745             prefschema.oclass = CLASS_RECSYN;
1746             compo.u.complex->generic->schema = (Odr_oid *)
1747                 odr_oiddup(out, oid_ent_to_oid(&prefschema, oid));
1748         }
1749         if (!elementSetNames)
1750             compo.u.complex->generic->elementSpec = 0;
1751         else
1752         {
1753             compo.u.complex->generic->elementSpec = (Z_ElementSpec *)
1754                 odr_malloc(out, sizeof(Z_ElementSpec));
1755             compo.u.complex->generic->elementSpec->which =
1756                 Z_ElementSpec_elementSetName;
1757             compo.u.complex->generic->elementSpec->u.elementSetName =
1758                 elementSetNames->u.generic;
1759         }
1760         compo.u.complex->num_dbSpecific = 0;
1761         compo.u.complex->dbSpecific = 0;
1762         compo.u.complex->num_recordSyntax = 0;
1763         compo.u.complex->recordSyntax = 0;
1764     }
1765     else if (elementSetNames)
1766     {
1767         req->recordComposition = &compo;
1768         compo.which = Z_RecordComp_simple;
1769         compo.u.simple = elementSetNames;
1770     }
1771     send_apdu(apdu);
1772     printf("Sent presentRequest (%d+%d).\n", setno, nos);
1773     return 2;
1774 }
1775     
1776 static void close_session (void)
1777 {
1778     cs_close (conn);
1779     conn = 0;
1780     if (session_mem)
1781     {
1782         nmem_destroy (session_mem);
1783         session_mem = NULL;
1784     }
1785     sent_close = 0;
1786 }
1787
1788 void process_close(Z_Close *req)
1789 {
1790     Z_APDU *apdu = zget_APDU(out, Z_APDU_close);
1791     Z_Close *res = apdu->u.close;
1792
1793     static char *reasons[] =
1794     {
1795         "finished",
1796         "shutdown",
1797         "system problem",
1798         "cost limit reached",
1799         "resources",
1800         "security violation",
1801         "protocolError",
1802         "lack of activity",
1803         "peer abort",
1804         "unspecified"
1805     };
1806
1807     printf("Reason: %s, message: %s\n", reasons[*req->closeReason],
1808         req->diagnosticInformation ? req->diagnosticInformation : "NULL");
1809     if (sent_close)
1810         close_session ();
1811     else
1812     {
1813         *res->closeReason = Z_Close_finished;
1814         send_apdu(apdu);
1815         printf("Sent response.\n");
1816         sent_close = 1;
1817     }
1818 }
1819
1820 static int cmd_show(char *arg)
1821 {
1822     if (!conn)
1823     {
1824         printf("Not connected yet\n");
1825         return 0;
1826     }
1827     if (!send_presentRequest(arg))
1828         return 0;
1829     return 2;
1830 }
1831
1832 int cmd_quit(char *arg)
1833 {
1834     printf("See you later, alligator.\n");
1835     xmalloc_trav ("");
1836     exit(0);
1837     return 0;
1838 }
1839
1840 int cmd_cancel(char *arg)
1841 {
1842     Z_APDU *apdu = zget_APDU(out, Z_APDU_triggerResourceControlRequest);
1843     Z_TriggerResourceControlRequest *req =
1844         apdu->u.triggerResourceControlRequest;
1845     bool_t rfalse = 0;
1846     
1847     if (!conn)
1848     {
1849         printf("Session not initialized yet\n");
1850         return 0;
1851     }
1852     if (!ODR_MASK_GET(session->options, Z_Options_triggerResourceCtrl))
1853     {
1854         printf("Target doesn't support cancel (trigger resource ctrl)\n");
1855         return 0;
1856     }
1857     *req->requestedAction = Z_TriggerResourceCtrl_cancel;
1858     req->resultSetWanted = &rfalse;
1859
1860     send_apdu(apdu);
1861     printf("Sent cancel request\n");
1862     return 2;
1863 }
1864
1865 int send_scanrequest(const char *query, int pp, int num, const char *term)
1866 {
1867     Z_APDU *apdu = zget_APDU(out, Z_APDU_scanRequest);
1868     Z_ScanRequest *req = apdu->u.scanRequest;
1869     int oid[OID_SIZE];
1870     
1871     if (queryType == QueryType_CCL2RPN)
1872     {
1873         oident bib1;
1874         int error, pos;
1875         struct ccl_rpn_node *rpn;
1876
1877         rpn = ccl_find_str (bibset,  query, &error, &pos);
1878         if (error)
1879         {
1880             printf("CCL ERROR: %s\n", ccl_err_msg(error));
1881             return -1;
1882         }
1883         bib1.proto = PROTO_Z3950;
1884         bib1.oclass = CLASS_ATTSET;
1885         bib1.value = VAL_BIB1;
1886         req->attributeSet = oid_ent_to_oid (&bib1, oid);
1887         if (!(req->termListAndStartPoint = ccl_scan_query (out, rpn)))
1888         {
1889             printf("Couldn't convert CCL to Scan term\n");
1890             return -1;
1891         }
1892         ccl_rpn_delete (rpn);
1893     }
1894     else
1895     {
1896         YAZ_PQF_Parser pqf_parser = yaz_pqf_create ();
1897
1898         if (!(req->termListAndStartPoint =
1899               yaz_pqf_scan(pqf_parser, out, &req->attributeSet, query)))
1900         {
1901             const char *pqf_msg;
1902             size_t off;
1903             int code = yaz_pqf_error (pqf_parser, &pqf_msg, &off);
1904             printf("%*s^\n", off+7, "");
1905             printf("Prefix query error: %s (code %d)\n", pqf_msg, code);
1906             yaz_pqf_destroy (pqf_parser);
1907             return -1;
1908         }
1909         yaz_pqf_destroy (pqf_parser);
1910     }
1911     if (term && *term)
1912     {
1913         if (req->termListAndStartPoint->term &&
1914             req->termListAndStartPoint->term->which == Z_Term_general &&
1915             req->termListAndStartPoint->term->u.general)
1916         {
1917             req->termListAndStartPoint->term->u.general->buf =
1918                 (unsigned char *) odr_strdup(out, term);
1919             req->termListAndStartPoint->term->u.general->len =
1920                 req->termListAndStartPoint->term->u.general->size =
1921                 strlen(term);
1922         }
1923     }
1924     req->referenceId = set_refid (out);
1925     req->num_databaseNames = num_databaseNames;
1926     req->databaseNames = databaseNames;
1927     req->numberOfTermsRequested = &num;
1928     req->preferredPositionInResponse = &pp;
1929     send_apdu(apdu);
1930     return 2;
1931 }
1932
1933 int send_sortrequest(char *arg, int newset)
1934 {
1935     Z_APDU *apdu = zget_APDU(out, Z_APDU_sortRequest);
1936     Z_SortRequest *req = apdu->u.sortRequest;
1937     Z_SortKeySpecList *sksl = (Z_SortKeySpecList *)
1938         odr_malloc (out, sizeof(*sksl));
1939     char setstring[32];
1940
1941     if (setnumber >= 0)
1942         sprintf (setstring, "%d", setnumber);
1943     else
1944         sprintf (setstring, "default");
1945
1946     req->referenceId = set_refid (out);
1947
1948     req->num_inputResultSetNames = 1;
1949     req->inputResultSetNames = (Z_InternationalString **)
1950         odr_malloc (out, sizeof(*req->inputResultSetNames));
1951     req->inputResultSetNames[0] = odr_strdup (out, setstring);
1952
1953     if (newset && setnumber >= 0)
1954         sprintf (setstring, "%d", ++setnumber);
1955
1956     req->sortedResultSetName = odr_strdup (out, setstring);
1957
1958     req->sortSequence = yaz_sort_spec (out, arg);
1959     if (!req->sortSequence)
1960     {
1961         printf ("Missing sort specifications\n");
1962         return -1;
1963     }
1964     send_apdu(apdu);
1965     return 2;
1966 }
1967
1968 void display_term(Z_TermInfo *t)
1969 {
1970     if (t->term->which == Z_Term_general)
1971     {
1972         printf("%.*s", t->term->u.general->len, t->term->u.general->buf);
1973         sprintf(last_scan_line, "%.*s", t->term->u.general->len,
1974             t->term->u.general->buf);
1975     }
1976     else
1977         printf("Term (not general)");
1978     if (t->globalOccurrences)
1979         printf (" (%d)\n", *t->globalOccurrences);
1980     else
1981         printf ("\n");
1982 }
1983
1984 void process_scanResponse(Z_ScanResponse *res)
1985 {
1986     int i;
1987     Z_Entry **entries = NULL;
1988     int num_entries = 0;
1989    
1990     printf("Received ScanResponse\n"); 
1991     print_refid (res->referenceId);
1992     printf("%d entries", *res->numberOfEntriesReturned);
1993     if (res->positionOfTerm)
1994         printf (", position=%d", *res->positionOfTerm); 
1995     printf ("\n");
1996     if (*res->scanStatus != Z_Scan_success)
1997         printf("Scan returned code %d\n", *res->scanStatus);
1998     if (!res->entries)
1999         return;
2000     if ((entries = res->entries->entries))
2001         num_entries = res->entries->num_entries;
2002     for (i = 0; i < num_entries; i++)
2003     {
2004         int pos_term = res->positionOfTerm ? *res->positionOfTerm : -1;
2005         if (entries[i]->which == Z_Entry_termInfo)
2006         {
2007             printf("%c ", i + 1 == pos_term ? '*' : ' ');
2008             display_term(entries[i]->u.termInfo);
2009         }
2010         else
2011             display_diagrecs(&entries[i]->u.surrogateDiagnostic, 1);
2012     }
2013     if (res->entries->nonsurrogateDiagnostics)
2014         display_diagrecs (res->entries->nonsurrogateDiagnostics,
2015                           res->entries->num_nonsurrogateDiagnostics);
2016 }
2017
2018 void process_sortResponse(Z_SortResponse *res)
2019 {
2020     printf("Received SortResponse: status=");
2021     switch (*res->sortStatus)
2022     {
2023     case Z_SortStatus_success:
2024         printf ("success"); break;
2025     case Z_SortStatus_partial_1:
2026         printf ("partial"); break;
2027     case Z_SortStatus_failure:
2028         printf ("failure"); break;
2029     default:
2030         printf ("unknown (%d)", *res->sortStatus);
2031     }
2032     printf ("\n");
2033     print_refid (res->referenceId);
2034     if (res->diagnostics)
2035         display_diagrecs(res->diagnostics,
2036                          res->num_diagnostics);
2037 }
2038
2039 void process_deleteResultSetResponse (Z_DeleteResultSetResponse *res)
2040 {
2041     printf("Got deleteResultSetResponse status=%d\n",
2042            *res->deleteOperationStatus);
2043     if (res->deleteListStatuses)
2044     {
2045         int i;
2046         for (i = 0; i < res->deleteListStatuses->num; i++)
2047         {
2048             printf ("%s status=%d\n", res->deleteListStatuses->elements[i]->id,
2049                     *res->deleteListStatuses->elements[i]->status);
2050         }
2051     }
2052 }
2053
2054 int cmd_sort_generic(char *arg, int newset)
2055 {
2056     if (!conn)
2057     {
2058         printf("Session not initialized yet\n");
2059         return 0;
2060     }
2061     if (!ODR_MASK_GET(session->options, Z_Options_sort))
2062     {
2063         printf("Target doesn't support sort\n");
2064         return 0;
2065     }
2066     if (*arg)
2067     {
2068         if (send_sortrequest(arg, newset) < 0)
2069             return 0;
2070         return 2;
2071     }
2072     return 0;
2073 }
2074
2075 int cmd_sort(char *arg)
2076 {
2077     return cmd_sort_generic (arg, 0);
2078 }
2079
2080 int cmd_sort_newset (char *arg)
2081 {
2082     return cmd_sort_generic (arg, 1);
2083 }
2084
2085 int cmd_scan(char *arg)
2086 {
2087     if (!conn)
2088     {
2089                 try_reconnect();
2090                 
2091                 if (!conn) {                                                            
2092                         printf("Session not initialized yet\n");
2093                         return 0;
2094                 };
2095     }
2096     if (!ODR_MASK_GET(session->options, Z_Options_scan))
2097     {
2098         printf("Target doesn't support scan\n");
2099         return 0;
2100     }
2101     if (*arg)
2102     {
2103         strcpy (last_scan_query, arg);
2104         if (send_scanrequest(arg, 1, 20, 0) < 0)
2105             return 0;
2106     }
2107     else
2108     {
2109         if (send_scanrequest(last_scan_query, 1, 20, last_scan_line) < 0)
2110             return 0;
2111     }
2112     return 2;
2113 }
2114
2115 int cmd_schema(char *arg)
2116 {
2117     if (!arg || !*arg)
2118     {
2119         schema = VAL_NONE;
2120         return 1;
2121     }
2122     schema = oid_getvalbyname (arg);
2123     if (schema == VAL_NONE)
2124     {
2125         printf ("unknown schema\n");
2126         return 0;
2127     }
2128     return 1;
2129 }
2130
2131 int cmd_format(char *arg)
2132 {
2133     if (!arg || !*arg)
2134     {
2135         printf("Usage: format <recordsyntax>\n");
2136         return 0;
2137     }
2138     recordsyntax = oid_getvalbyname (arg);
2139     if (recordsyntax == VAL_NONE)
2140     {
2141         printf ("unknown record syntax\n");
2142         return 0;
2143     }
2144     return 1;
2145 }
2146
2147 int cmd_elements(char *arg)
2148 {
2149     static Z_ElementSetNames esn;
2150     static char what[100];
2151
2152     if (!arg || !*arg)
2153     {
2154         elementSetNames = 0;
2155         return 1;
2156     }
2157     strcpy(what, arg);
2158     esn.which = Z_ElementSetNames_generic;
2159     esn.u.generic = what;
2160     elementSetNames = &esn;
2161     return 1;
2162 }
2163
2164 int cmd_attributeset(char *arg)
2165 {
2166     char what[100];
2167
2168     if (!arg || !*arg)
2169     {
2170         printf("Usage: attributeset <setname>\n");
2171         return 0;
2172     }
2173     sscanf(arg, "%s", what);
2174     if (p_query_attset (what))
2175     {
2176         printf("Unknown attribute set name\n");
2177         return 0;
2178     }
2179     return 1;
2180 }
2181
2182 int cmd_querytype (char *arg)
2183 {
2184     if (!strcmp (arg, "ccl"))
2185         queryType = QueryType_CCL;
2186     else if (!strcmp (arg, "prefix") || !strcmp(arg, "rpn"))
2187         queryType = QueryType_Prefix;
2188     else if (!strcmp (arg, "ccl2rpn") || !strcmp (arg, "cclrpn"))
2189         queryType = QueryType_CCL2RPN;
2190     else
2191     {
2192         printf ("Querytype must be one of:\n");
2193         printf (" prefix         - Prefix query\n");
2194         printf (" ccl            - CCL query\n");
2195         printf (" ccl2rpn        - CCL query converted to RPN\n");
2196         return 0;
2197     }
2198     return 1;
2199 }
2200
2201 int cmd_refid (char *arg)
2202 {
2203     xfree (refid);
2204     refid = NULL;
2205     if (*arg)
2206     {
2207         refid = (char *) xmalloc (strlen(arg)+1);
2208         strcpy (refid, arg);
2209     }
2210     return 1;
2211 }
2212
2213 int cmd_close(char *arg)
2214 {
2215     Z_APDU *apdu;
2216     Z_Close *req;
2217     if (!conn)
2218         return 0;
2219
2220     apdu = zget_APDU(out, Z_APDU_close);
2221     req = apdu->u.close;
2222     *req->closeReason = Z_Close_finished;
2223     send_apdu(apdu);
2224     printf("Sent close request.\n");
2225     sent_close = 1;
2226     return 2;
2227 }
2228
2229 int cmd_packagename(char* arg)
2230 {
2231     xfree (esPackageName);
2232     esPackageName = NULL;
2233     if (*arg)
2234     {
2235         esPackageName = (char *) xmalloc (strlen(arg)+1);
2236         strcpy (esPackageName, arg);
2237     }
2238     return 1;
2239 }
2240
2241 int cmd_proxy(char* arg)
2242 {
2243     if (*arg == '\0') {
2244                 xfree (yazProxy);
2245                 yazProxy = NULL;
2246         
2247     }
2248     xfree (yazProxy);
2249     yazProxy = NULL;
2250     if (*arg)
2251     {
2252         yazProxy = (char *) xmalloc (strlen(arg)+1);
2253         strcpy (yazProxy, arg);
2254     } 
2255     return 1;
2256 }
2257
2258 int cmd_charset(char* arg)
2259 {
2260     char l1[30], l2[30];
2261
2262     *l1 = *l2 = 0;
2263     if (sscanf(arg, "%29s %29s", l1, l2) < 1)
2264     {
2265         printf("Current character set is `%s'\n", (yazCharset) ? yazCharset:NULL);
2266         return 1;
2267     }
2268     xfree (yazCharset);
2269     yazCharset = NULL;
2270     if (*l1)
2271         yazCharset = xstrdup(l1);
2272     if (*l2)
2273     {
2274         odr_set_charset (out, l1, l2);
2275         odr_set_charset (in, l2, l1);
2276     }
2277     return 1;
2278 }
2279
2280 int cmd_lang(char* arg)
2281 {
2282     if (*arg == '\0') {
2283         printf("Current language is `%s'\n", (yazLang)?yazLang:NULL);
2284         return 1;
2285     }
2286     xfree (yazLang);
2287     yazLang = NULL;
2288     if (*arg)
2289     {
2290         yazLang = (char *) xmalloc (strlen(arg)+1);
2291         strcpy (yazLang, arg);
2292     } 
2293     return 1;
2294 }
2295
2296 int cmd_source(char* arg) 
2297 {
2298     /* first should open the file and read one line at a time.. */
2299     FILE* includeFile;
2300     char line[1024], *cp;
2301
2302     {
2303         char* args_end=(arg)+strlen(arg)-1; 
2304         while(isspace(*args_end)) 
2305         {*args_end=0;
2306         --args_end;}; 
2307     }
2308
2309     REMOVE_TAILING_BLANKS(arg);
2310     
2311     if(strlen(arg)<1) {
2312         fprintf(stderr,"Error in source command use a filename\n");
2313         return -1;
2314     }
2315     
2316     includeFile = fopen (arg, "r");
2317     
2318     if(!includeFile) {
2319         fprintf(stderr,"Unable to open file %s for reading\n",arg);
2320         return -1;
2321     }
2322     
2323     while(!feof(includeFile)) {
2324         memset(line,0,sizeof(line));
2325         fgets(line,sizeof(line),includeFile);
2326         
2327         if(strlen(line) < 2) continue;
2328         if(line[0] == '#') continue;
2329         
2330         if ((cp = strrchr (line, '\n')))
2331             *cp = '\0';
2332         
2333         process_cmd_line(line);
2334     }
2335     
2336     if(fclose(includeFile)<0) {
2337         perror("unable to close include file");
2338         exit(1);
2339     }
2340     return 1;
2341 }
2342
2343 int cmd_subshell(char* args)
2344 {
2345     if(strlen(args)) 
2346         system(args);
2347     else 
2348         system(getenv("SHELL"));
2349     
2350     printf("\n");
2351     return 1;
2352 }
2353
2354 int cmd_set_apdufile(char* arg)
2355 {
2356     REMOVE_TAILING_BLANKS(arg);
2357   
2358     if(apdu_file && apdu_file != stderr) { /* don't close stdout*/
2359         perror("unable to close apdu log file");      
2360     }
2361     apdu_file=NULL;
2362   
2363     if(strlen(arg)<1) {
2364         return 1;
2365     }
2366   
2367     if(!strcmp(arg,"-")) 
2368         apdu_file=stderr;      
2369     else 
2370         apdu_file=fopen(arg, "a");
2371   
2372     if(!apdu_file) {
2373         perror("unable to open apdu log file no apdu log loaded");
2374     } else {
2375         odr_setprint(print, apdu_file); 
2376     }
2377   
2378     return 1;
2379 }
2380
2381 int cmd_set_cclfile(char* arg)
2382 {  
2383     FILE *inf;
2384
2385     REMOVE_TAILING_BLANKS(arg);
2386
2387     bibset = ccl_qual_mk (); 
2388     inf = fopen (arg, "r");
2389     if (inf)
2390     {
2391         ccl_qual_file (bibset, inf);
2392         fclose (inf);
2393     }
2394     strcpy(ccl_fields,arg);
2395     return 0;
2396 }
2397
2398
2399 int cmd_set_auto_reconnect(char* arg)
2400 {  
2401     REMOVE_TAILING_BLANKS(arg);
2402     
2403     if(strlen(arg)==0) {
2404         auto_reconnect = ! auto_reconnect;
2405     } else if(strcmp(arg,"on")==0) {
2406         auto_reconnect = 1;
2407     } else if(strcmp(arg,"off")==0) {
2408         auto_reconnect = 0;             
2409     } else {
2410         printf("Error use on or off\n");
2411         return 1;
2412     }
2413     
2414     if (auto_reconnect)
2415         printf("Set auto reconnect enabled.\n");
2416     else
2417         printf("Set auto reconnect disabled.\n");
2418     
2419     return 0;
2420 }
2421
2422 int cmd_set_marcdump(char* arg)
2423 {
2424     if(marcdump && marcdump != stderr) { /* don't close stdout*/
2425         perror("unable to close apdu log file");      
2426     }
2427     marcdump=NULL;
2428     
2429     if(strlen(arg)<1) {
2430         return 1;
2431     }
2432     
2433     if(!strcmp(arg,"-")) 
2434         marcdump=stderr;      
2435     else 
2436         marcdump=fopen(arg, "a");
2437     
2438     if(!marcdump) {
2439         perror("unable to open apdu marcdump file no marcdump done\n");
2440     }
2441     
2442     return 1;
2443 }
2444
2445 int cmd_set_proxy(char* arg)
2446 {
2447     if(yazProxy) free(yazProxy);
2448     yazProxy=NULL;
2449     
2450     if(strlen(arg) > 1) {
2451         yazProxy=strdup(arg);
2452     }
2453     return 1;
2454 }
2455
2456 /* 
2457    this command takes 3 arge {name class oid} 
2458 */
2459 int cmd_register_oid(char* args) {
2460     static struct {
2461         char* className;
2462         oid_class oclass;
2463     } oid_classes[] = {
2464         {"appctx",CLASS_APPCTX},
2465         {"absyn",CLASS_ABSYN},
2466         {"attset",CLASS_ATTSET},
2467         {"transyn",CLASS_TRANSYN},
2468         {"diagset",CLASS_DIAGSET},
2469         {"recsyn",CLASS_RECSYN},
2470         {"resform",CLASS_RESFORM},
2471         {"accform",CLASS_ACCFORM},
2472         {"extserv",CLASS_EXTSERV},
2473         {"userinfo",CLASS_USERINFO},
2474         {"elemspec",CLASS_ELEMSPEC},
2475         {"varset",CLASS_VARSET},
2476         {"schema",CLASS_SCHEMA},
2477         {"tagset",CLASS_TAGSET},
2478         {"general",CLASS_GENERAL},
2479         {0,0}
2480     };
2481     char oname_str[101], oclass_str[101], oid_str[101];  
2482     char* name;
2483     int i;
2484     oid_class oidclass = CLASS_GENERAL;
2485     int val = 0, oid[OID_SIZE];
2486     struct oident * new_oident=NULL;
2487     
2488     if (sscanf (args, "%100[^ ] %100[^ ] %100s",
2489                 oname_str,oclass_str, oid_str) < 1) {
2490         printf("Error in regristrate command \n");
2491         return 0;
2492     }
2493     
2494     for (i = 0; oid_classes[i].className; i++) {
2495         if (!strcmp(oid_classes[i].className, oclass_str))
2496         {
2497             oidclass=oid_classes[i].oclass;
2498             break;
2499         }
2500     }
2501     
2502     if(!(oid_classes[i].className)) {
2503         printf("Unknonwn oid class %s\n",oclass_str);
2504         return 0;
2505     }
2506     
2507     i = 0;
2508     name = oid_str;
2509     val = 0;
2510     
2511     while (isdigit (*name))
2512     {
2513         val = val*10 + (*name - '0');
2514         name++;
2515         if (*name == '.')
2516         {
2517             if (i < OID_SIZE-1)
2518                 oid[i++] = val;
2519             val = 0;
2520             name++;
2521         }
2522     }
2523     oid[i] = val;
2524     oid[i+1] = -1;
2525     
2526     new_oident=oid_addent (oid,PROTO_GENERAL,oidclass,oname_str,VAL_DYNAMIC);  
2527     if(strcmp(new_oident->desc,oname_str)) {
2528         fprintf(stderr,"oid is already named as %s, regristration faild\n",
2529                 new_oident->desc);
2530     }
2531     return 1;  
2532 }
2533
2534 int cmd_push_command(char* arg) 
2535 {
2536 #if HAVE_READLINE_HISTORY_H
2537     if(strlen(arg)>1) 
2538         add_history(arg);
2539 #else 
2540     fprintf(stderr,"Not compiled with the readline/history module\n");
2541 #endif
2542     return 1;
2543 }
2544
2545 void source_rcfile() 
2546 {
2547     /*  Look for a $HOME/.yazclientrc and source it if it exists */
2548     struct stat statbuf;
2549     char buffer[1000];
2550     char* homedir=getenv("HOME");
2551     
2552     if(!homedir) return;
2553     
2554     sprintf(buffer,"%s/.yazclientrc",homedir);
2555     
2556     if(stat(buffer,&statbuf)==0) {
2557         cmd_source(buffer);
2558     }
2559     
2560     if(stat(".yazclientrc",&statbuf)==0) {
2561         cmd_source(".yazclientrc");
2562     }
2563 }
2564
2565
2566 static void initialize(void)
2567 {
2568     FILE *inf;
2569     int i;
2570     
2571     if (!(out = odr_createmem(ODR_ENCODE)) ||
2572         !(in = odr_createmem(ODR_DECODE)) ||
2573         !(print = odr_createmem(ODR_PRINT)))
2574     {
2575         fprintf(stderr, "failed to allocate ODR streams\n");
2576         exit(1);
2577     }
2578     oid_init();
2579     
2580     setvbuf(stdout, 0, _IONBF, 0);
2581     if (apdu_file)
2582         odr_setprint(print, apdu_file);
2583
2584     bibset = ccl_qual_mk (); 
2585     inf = fopen (ccl_fields, "r");
2586     if (inf)
2587     {
2588         ccl_qual_file (bibset, inf);
2589         fclose (inf);
2590     }
2591     cmd_base("Default");
2592
2593 #if HAVE_READLINE_READLINE_H
2594     rl_attempted_completion_function = (CPPFunction*)readline_completer;
2595 #endif
2596     
2597     
2598     for(i=0; i<maxOtherInfosSupported; ++i) {
2599         extraOtherInfos[i].oidval = -1;
2600     }
2601     
2602     source_rcfile();
2603 }
2604
2605
2606 #if HAVE_GETTIMEOFDAY
2607 struct timeval tv_start, tv_end;
2608 #endif
2609
2610 void wait_and_handle_responce() 
2611 {
2612     
2613     int res;
2614     char *netbuffer= 0;
2615     int netbufferlen = 0;
2616     Z_APDU *apdu;
2617     
2618     
2619     if (conn)
2620     {
2621         do
2622         {
2623             if ((res = cs_get(conn, &netbuffer, &netbufferlen)) < 0)
2624             {
2625                 printf("Target closed connection\n");
2626                 close_session ();
2627                 break;
2628             }
2629             if (!res)
2630             {
2631                 printf("Target closed connection.\n");
2632                 close_session ();
2633                 break;
2634             }
2635             odr_reset(in); /* release APDU from last round */
2636             record_last = 0;
2637             odr_setbuf(in, netbuffer, res, 0);
2638             if (!z_APDU(in, &apdu, 0, 0))
2639             {
2640                 odr_perror(in, "Decoding incoming APDU");
2641                 fprintf(stderr, "[Near %d]\n", odr_offset(in));
2642                 fprintf(stderr, "Packet dump:\n---------\n");
2643                 odr_dumpBER(stderr, netbuffer, res);
2644                 fprintf(stderr, "---------\n");
2645                 if (apdu_file)
2646                     z_APDU(print, &apdu, 0, 0);
2647                 close_session ();
2648                 break;
2649             }
2650             if (apdu_file && !z_APDU(print, &apdu, 0, 0))
2651             {
2652                 odr_perror(print, "Failed to print incoming APDU");
2653                 odr_reset(print);
2654                 continue;
2655             }
2656             switch(apdu->which)
2657             {
2658             case Z_APDU_initResponse:
2659                 process_initResponse(apdu->u.initResponse);
2660                 break;
2661             case Z_APDU_searchResponse:
2662                 process_searchResponse(apdu->u.searchResponse);
2663                 break;
2664             case Z_APDU_scanResponse:
2665                 process_scanResponse(apdu->u.scanResponse);
2666                 break;
2667             case Z_APDU_presentResponse:
2668                 print_refid (apdu->u.presentResponse->referenceId);
2669                 setno +=
2670                     *apdu->u.presentResponse->numberOfRecordsReturned;
2671                 if (apdu->u.presentResponse->records)
2672                     display_records(apdu->u.presentResponse->records);
2673                 else
2674                     printf("No records.\n");
2675                 printf ("nextResultSetPosition = %d\n",
2676                         *apdu->u.presentResponse->nextResultSetPosition);
2677                 break;
2678             case Z_APDU_sortResponse:
2679                 process_sortResponse(apdu->u.sortResponse);
2680                 break;
2681             case Z_APDU_extendedServicesResponse:
2682                 printf("Got extended services response\n");
2683                 process_ESResponse(apdu->u.extendedServicesResponse);
2684                 break;
2685             case Z_APDU_close:
2686                 printf("Target has closed the association.\n");
2687                 process_close(apdu->u.close);
2688                 break;
2689             case Z_APDU_resourceControlRequest:
2690                 process_resourceControlRequest
2691                     (apdu->u.resourceControlRequest);
2692                 break;
2693             case Z_APDU_deleteResultSetResponse:
2694                 process_deleteResultSetResponse(apdu->u.
2695                                                 deleteResultSetResponse);
2696                 break;
2697             default:
2698                 printf("Received unknown APDU type (%d).\n", 
2699                        apdu->which);
2700                 close_session ();
2701             }
2702         }
2703         while (conn && cs_more(conn));
2704 #if HAVE_GETTIMEOFDAY
2705         gettimeofday (&tv_end, 0);
2706 #if 0
2707         printf ("S/U S/U=%ld/%ld %ld/%ld",
2708                 (long) tv_start.tv_sec,
2709                 (long) tv_start.tv_usec,
2710                 (long) tv_end.tv_sec,
2711                 (long) tv_end.tv_usec);
2712 #endif
2713         printf ("Elapsed: %.6f\n",
2714                 (double) tv_end.tv_usec / 1e6 + tv_end.tv_sec -
2715                 ((double) tv_start.tv_usec / 1e6 + tv_start.tv_sec));
2716 #endif
2717     }
2718     xfree (netbuffer);
2719 }
2720
2721
2722 int cmd_cclparse(char* arg) 
2723 {
2724     int error, pos;
2725     struct ccl_rpn_node *rpn=NULL;
2726     
2727     
2728     rpn = ccl_find_str (bibset, arg, &error, &pos);
2729     
2730     if (error) {
2731         printf ("%*s^ - ", 3+strlen(last_cmd)+1+pos, " ");
2732         printf ("%s\n", ccl_err_msg (error));
2733     }
2734     else
2735     {
2736         if (rpn)
2737         {       
2738             ccl_pr_tree(rpn, stdout); 
2739         }
2740     }
2741     if (rpn)
2742         ccl_rpn_delete(rpn);
2743     
2744     printf ("\n");
2745     
2746     return 0;
2747 }
2748
2749
2750 int cmd_set_otherinfo(char* args)
2751 {
2752     char oid[101], otherinfoString[101];
2753     int otherinfoNo;
2754     int sscan_res;
2755     int oidval;
2756     
2757     sscan_res = sscanf (args, "%d %100[^ ] %100s", &otherinfoNo, oid, otherinfoString);
2758     if(sscan_res==1) {
2759         /* reset this otherinfo */
2760         if(otherinfoNo>=maxOtherInfosSupported) {
2761             printf("Error otherinfo index to large (%d>%d)\n",otherinfoNo,maxOtherInfosSupported);
2762         }
2763         extraOtherInfos[otherinfoNo].oidval = -1;
2764         if(extraOtherInfos[otherinfoNo].value) free(extraOtherInfos[otherinfoNo].value);                        
2765         return 0;
2766     }
2767     if (sscan_res<3) {
2768         printf("Error in set_otherinfo command \n");
2769         return 0;
2770     }
2771     
2772     if(otherinfoNo>=maxOtherInfosSupported) {
2773         printf("Error otherinfo index to large (%d>%d)\n",otherinfoNo,maxOtherInfosSupported);
2774     }
2775     
2776     
2777     oidval = oid_getvalbyname (oid);
2778     if(oidval == -1 ) {
2779         printf("Error in set_otherinfo command unknown oid %s \n",oid);
2780         return 0;
2781     }
2782     extraOtherInfos[otherinfoNo].oidval = oidval;
2783     if(extraOtherInfos[otherinfoNo].value) free(extraOtherInfos[otherinfoNo].value);
2784     extraOtherInfos[otherinfoNo].value = strdup(otherinfoString);
2785     
2786     return 0;
2787 }
2788
2789 int cmd_list_otherinfo(char* args)
2790 {
2791     int i;         
2792     
2793     if(strlen(args)>0) {
2794         i = atoi(args);
2795         if( i >= maxOtherInfosSupported ) {
2796             printf("Error otherinfo index to large (%d>%d)\n",i,maxOtherInfosSupported);
2797             return 0;
2798         }
2799
2800         if(extraOtherInfos[i].oidval != -1) 
2801             printf("  otherinfo %d %s %s\n",i,yaz_z3950_oid_value_to_str(extraOtherInfos[i].oidval,CLASS_RECSYN), extraOtherInfos[i].value);
2802         
2803     } else {            
2804         for(i=0; i<maxOtherInfosSupported; ++i) {
2805             if(extraOtherInfos[i].oidval != -1) 
2806                 printf("  otherinfo %d %s %s\n",i,yaz_z3950_oid_value_to_str(extraOtherInfos[i].oidval,CLASS_RECSYN), extraOtherInfos[i].value);
2807         }
2808         
2809     }
2810     return 0;
2811 }
2812
2813
2814 int cmd_list_all(char* args) {
2815     int i;
2816     
2817     /* connection options */
2818     if(conn) {
2819         printf("Connected to         : %s\n",last_open_command);
2820     } else {
2821         if(last_open_command) 
2822             printf("Not connected to     : %s\n",last_open_command);
2823         else 
2824             printf("Not connected        : \n");
2825         
2826     }
2827     if(yazProxy) printf("using proxy          : %s\n",yazProxy);                
2828     
2829     printf("auto_reconnect       : %s\n",auto_reconnect?"on":"off");
2830     
2831     if (!auth) {
2832         printf("Authentication       : none\n");
2833     } else {
2834         switch(auth->which) {
2835         case Z_IdAuthentication_idPass:
2836             printf("Authentication       : IdPass\n"); 
2837             printf("    Login User       : %s\n",auth->u.idPass->userId?auth->u.idPass->userId:"");
2838             printf("    Login Group      : %s\n",auth->u.idPass->groupId?auth->u.idPass->groupId:"");
2839             printf("    Password         : %s\n",auth->u.idPass->password?auth->u.idPass->password:"");
2840             break;
2841         case Z_IdAuthentication_open:
2842             printf("Authentication       : psOpen\n");                  
2843             printf("    Open string      : %s\n",auth->u.open); 
2844             break;
2845         default:
2846             printf("Authentication       : Unknown\n");
2847         }
2848     }
2849     if ( yazCharset ) printf("Character set        : `%s'\n", (yazCharset) ? yazCharset:NULL);
2850     
2851     /* bases */
2852     printf("Bases                : ");
2853     for (i = 0; i<num_databaseNames; i++) printf("%s ",databaseNames[i]);
2854     printf("\n");
2855     
2856     /* Query options */
2857     printf("CCL file             : %s\n",ccl_fields);
2858     printf("Query type           : %s\n",query_type_as_string(queryType));
2859     
2860     printf("Named Result Sets    : %s\n",setnumber==-1?"off":"on");
2861     
2862     /* piggy back options */
2863     printf("ssub/lslb/mspn       : %d/%d/%d\n",smallSetUpperBound,largeSetLowerBound,mediumSetPresentNumber);
2864     
2865     /* print present related options */
2866     printf("Format               : %s\n",yaz_z3950_oid_value_to_str(recordsyntax,CLASS_RECSYN));
2867     printf("Schema               : %s\n",yaz_z3950_oid_value_to_str(schema,CLASS_SCHEMA));
2868     printf("Elements             : %s\n",elementSetNames?elementSetNames->u.generic:"");
2869     
2870     /* loging options */
2871     printf("APDU log             : %s\n",apdu_file?"on":"off");
2872     printf("Record log           : %s\n",marcdump?"on":"off");
2873     
2874     /* other infos */
2875     printf("Other Info: \n");
2876     cmd_list_otherinfo("");
2877     
2878     return 0;
2879 }
2880
2881 int cmd_clear_otherinfo(char* args) 
2882 {
2883     if(strlen(args)>0) {
2884         int otherinfoNo;
2885         otherinfoNo = atoi(args);
2886         if( otherinfoNo >= maxOtherInfosSupported ) {
2887             printf("Error otherinfo index to large (%d>%d)\n",otherinfoNo,maxOtherInfosSupported);
2888             return 0;
2889         }
2890         
2891         if(extraOtherInfos[otherinfoNo].oidval != -1) {                 
2892             /* only clear if set. */
2893             extraOtherInfos[otherinfoNo].oidval=-1;
2894             free(extraOtherInfos[otherinfoNo].value);
2895         }
2896     } else {
2897         int i;
2898         
2899         for(i=0; i<maxOtherInfosSupported; ++i) {
2900             if (extraOtherInfos[i].oidval!=-1 ) {                               
2901                 extraOtherInfos[i].oidval=-1;
2902                 free(extraOtherInfos[i].value);
2903             }
2904         }
2905     }
2906     return 0;
2907 }
2908
2909 static int cmd_help (char *line);
2910
2911 typedef char *(*completerFunctionType)(const char *text, int state);
2912
2913 static struct {
2914     char *cmd;
2915     int (*fun)(char *arg);
2916     char *ad;
2917         completerFunctionType rl_completerfunction;
2918     int complete_filenames;
2919     char **local_tabcompletes;
2920 } cmd[] = {
2921     {"open", cmd_open, "('tcp'|'ssl')':<host>[':'<port>][/<db>]",NULL,0,NULL},
2922     {"quit", cmd_quit, "",NULL,0,NULL},
2923     {"find", cmd_find, "<query>",NULL,0,NULL},
2924     {"delete", cmd_delete, "<setname>",NULL,0,NULL},
2925     {"base", cmd_base, "<base-name>",NULL,0,NULL},
2926     {"show", cmd_show, "<rec#>['+'<#recs>['+'<setname>]]",NULL,0,NULL},
2927     {"scan", cmd_scan, "<term>",NULL,0,NULL},
2928     {"sort", cmd_sort, "<sortkey> <flag> <sortkey> <flag> ...",NULL,0,NULL},
2929     {"sort+", cmd_sort_newset, "<sortkey> <flag> <sortkey> <flag> ...",NULL,0,NULL},
2930     {"authentication", cmd_authentication, "<acctstring>",NULL,0,NULL},
2931     {"lslb", cmd_lslb, "<largeSetLowerBound>",NULL,0,NULL},
2932     {"ssub", cmd_ssub, "<smallSetUpperBound>",NULL,0,NULL},
2933     {"mspn", cmd_mspn, "<mediumSetPresentNumber>",NULL,0,NULL},
2934     {"status", cmd_status, "",NULL,0,NULL},
2935     {"setnames", cmd_setnames, "",NULL,0,NULL},
2936     {"cancel", cmd_cancel, "",NULL,0,NULL},
2937     {"format", cmd_format, "<recordsyntax>",complete_format,0,NULL},
2938     {"schema", cmd_schema, "<schema>",complete_schema,0,NULL},
2939     {"elements", cmd_elements, "<elementSetName>",NULL,0,NULL},
2940     {"close", cmd_close, "",NULL,0,NULL},
2941     {"attributeset", cmd_attributeset, "<attrset>",complete_attributeset,0,NULL},
2942     {"querytype", cmd_querytype, "<type>",complete_querytype,0,NULL},
2943     {"refid", cmd_refid, "<id>",NULL,0,NULL},
2944     {"itemorder", cmd_itemorder, "ill|item <itemno>",NULL,0,NULL},
2945     {"update", cmd_update, "<item>",NULL,0,NULL},
2946     {"packagename", cmd_packagename, "<packagename>",NULL,0,NULL},
2947     {"proxy", cmd_proxy, "[('tcp'|'ssl')]<host>[':'<port>]",NULL,0,NULL},
2948     {"charset", cmd_charset, "<charset_name>",NULL,0,NULL},
2949     {"lang", cmd_lang, "<language_code>",NULL,0,NULL},
2950     {".", cmd_source, "<filename>",NULL,1,NULL},
2951     {"!", cmd_subshell, "Subshell command",NULL,1,NULL},
2952     {"set_apdufile", cmd_set_apdufile, "<filename>",NULL,1,NULL},
2953     {"set_marcdump", cmd_set_marcdump," <filename>",NULL,1,NULL},
2954     {"set_cclfile", cmd_set_cclfile," <filename>",NULL,1,NULL},
2955     {"set_auto_reconnect", cmd_set_auto_reconnect," on|off",complete_auto_reconnect,1,NULL},
2956         {"set_otherinfo", cmd_set_otherinfo,"<otherinfoinddex> <oid> <string>",NULL,0,NULL},
2957     {"register_oid", cmd_register_oid,"<name> <class> <oid>",NULL,0,NULL},
2958     {"push_command", cmd_push_command,"<command>",command_generator,0,NULL},
2959         {"register_tab", cmd_register_tab,"<commandname> <tab>",command_generator,0,NULL},
2960         {"cclparse", cmd_cclparse,"<ccl find command>",NULL,0,NULL},
2961         {"list_otherinfo",cmd_list_otherinfo,"[otherinfoinddex]",NULL,0,NULL},
2962         {"list_all",cmd_list_all,"",NULL,0,NULL},
2963         {"clear_otherinfo",cmd_clear_otherinfo,"",NULL,0,NULL},
2964     /* Server Admin Functions */
2965     {"adm-reindex", cmd_adm_reindex, "<database-name>",NULL,0,NULL},
2966     {"adm-truncate", cmd_adm_truncate, "('database'|'index')<object-name>",NULL,0,NULL},
2967     {"adm-create", cmd_adm_create, "",NULL,0,NULL},
2968     {"adm-drop", cmd_adm_drop, "('database'|'index')<object-name>",NULL,0,NULL},
2969     {"adm-import", cmd_adm_import, "<record-type> <dir> <pattern>",NULL,0,NULL},
2970     {"adm-refresh", cmd_adm_refresh, "",NULL,0,NULL},
2971     {"adm-commit", cmd_adm_commit, "",NULL,0,NULL},
2972     {"adm-shutdown", cmd_adm_shutdown, "",NULL,0,NULL},
2973     {"adm-startup", cmd_adm_startup, "",NULL,0,NULL},
2974     {"help", cmd_help, "", NULL,0,NULL},
2975     {0,0,0,0,0,0}
2976 };
2977
2978 static int cmd_help (char *line)
2979 {
2980     int i;
2981     char topic[21];
2982     
2983     *topic = 0;
2984     sscanf (line, "%20s", topic);
2985
2986     if (*topic == 0)
2987         printf("Commands:\n");
2988     for (i = 0; cmd[i].cmd; i++)
2989         if (*topic == 0 || strcmp (topic, cmd[i].cmd) == 0)
2990             printf("   %s %s\n", cmd[i].cmd, cmd[i].ad);
2991     if (strcmp (topic, "find") == 0)
2992     {
2993         printf ("RPN:\n");
2994         printf (" \"term\"                        Simple Term\n");
2995         printf (" @attr [attset] type=value op  Attribute\n");
2996         printf (" @and opl opr                  And\n");
2997         printf (" @or opl opr                   Or\n");
2998         printf (" @not opl opr                  And-Not\n");
2999         printf (" @set set                      Result set\n");
3000         printf ("\n");
3001         printf ("Bib-1 attribute types\n");
3002         printf ("1=Use:         ");
3003         printf ("4=Title 7=ISBN 8=ISSN 30=Date 62=Abstract 1003=Author 1016=Any\n");
3004         printf ("2=Relation:    ");
3005         printf ("1<   2<=  3=  4>=  5>  6!=  102=Relevance\n");
3006         printf ("3=Position:    ");
3007         printf ("1=First in Field  2=First in subfield  3=Any position\n");
3008         printf ("4=Structure:   ");
3009         printf ("1=Phrase  2=Word  3=Key  4=Year  5=Date  6=WordList\n");
3010         printf ("5=Truncation:  ");
3011         printf ("1=Right  2=Left  3=L&R  100=No  101=#  102=Re-1  103=Re-2\n");
3012         printf ("6=Completeness:");
3013         printf ("1=Incomplete subfield  2=Complete subfield  3=Complete field\n");
3014     }
3015     return 1;
3016 }
3017
3018 int cmd_register_tab(char* arg) {
3019         
3020     char command[101], tabargument[101];
3021     int i;
3022     int num_of_tabs;
3023     char** tabslist;
3024     
3025     if (sscanf (arg, "%100s %100s", command, tabargument) < 1) {
3026         return 0;
3027     }
3028     
3029     /* locate the amdn in the list */
3030     for (i = 0; cmd[i].cmd; i++) {
3031         if (!strncmp(cmd[i].cmd, command, strlen(command))) {
3032             break;
3033         }
3034     }
3035     
3036     if(!cmd[i].cmd) { 
3037         fprintf(stderr,"Unknown command %s\n",command);
3038         return 1;
3039     }
3040     
3041     
3042     
3043     if(!cmd[i].local_tabcompletes) {
3044         cmd[i].local_tabcompletes = calloc(1,sizeof(char**));
3045     }
3046     
3047     num_of_tabs=0;              
3048     
3049     tabslist = cmd[i].local_tabcompletes;
3050     for(;tabslist && *tabslist;tabslist++) {
3051         num_of_tabs++;
3052     }
3053     
3054     cmd[i].local_tabcompletes=realloc(cmd[i].local_tabcompletes,(num_of_tabs+2)*sizeof(char**));
3055     tabslist=cmd[i].local_tabcompletes;
3056     tabslist[num_of_tabs]=strdup(tabargument);
3057     tabslist[num_of_tabs+1]=NULL;
3058     return 1;
3059 }
3060
3061
3062 void process_cmd_line(char* line)
3063 {  
3064     int i,res;
3065     char word[32], arg[1024];
3066     
3067 #if HAVE_GETTIMEOFDAY
3068     gettimeofday (&tv_start, 0);
3069 #endif
3070     
3071     if ((res = sscanf(line, "%31s %1023[^;]", word, arg)) <= 0)
3072     {
3073         strcpy(word, last_cmd);
3074         *arg = '\0';
3075     }
3076     else if (res == 1)
3077         *arg = 0;
3078     strcpy(last_cmd, word);
3079     
3080     /* removed tailing spaces from the arg command */
3081     { 
3082         char* p;
3083         char* lastnonspace=NULL;
3084         p = arg;
3085         
3086         for(;*p; ++p) {
3087             if(!isspace(*p)) {
3088                 lastnonspace = p;
3089             }
3090         }
3091         if(lastnonspace) 
3092             *(++lastnonspace) = 0;
3093     }
3094     
3095     
3096     for (i = 0; cmd[i].cmd; i++)
3097         if (!strncmp(cmd[i].cmd, word, strlen(word)))
3098         {
3099             res = (*cmd[i].fun)(arg);
3100             break;
3101         }
3102     
3103     if (!cmd[i].cmd) /* dump our help-screen */
3104     {
3105         printf("Unknown command: %s.\n", word);
3106         printf("use help for list of commands\n");
3107         /* cmd_help (""); */
3108         res = 1;
3109     }
3110     
3111     if(apdu_file) fflush(apdu_file);
3112     
3113     if (res >= 2)
3114         wait_and_handle_responce();
3115     
3116     if(apdu_file)
3117         fflush(apdu_file);
3118     if(marcdump)
3119         fflush(marcdump);
3120 }
3121
3122
3123 char *command_generator(const char *text, int state) 
3124 {
3125     static int idx; 
3126     if (state==0) {
3127         idx = 0;
3128     }
3129     for( ; cmd[idx].cmd; ++idx) {
3130         if (!strncmp(cmd[idx].cmd,text,strlen(text))) {
3131             ++idx;  /* skip this entry on the next run */
3132             return strdup(cmd[idx-1].cmd);
3133         }
3134     }
3135     return NULL;
3136 }
3137
3138
3139 /* 
3140    This function only known how to complete on the first word
3141 */
3142 char ** readline_completer(char *text, int start, int end) {
3143 #if HAVE_READLINE_READLINE_H
3144
3145         completerFunctionType completerToUse;
3146         
3147     if(start == 0) {
3148 #if HAVE_READLINE_RL_COMPLETION_MATCHES
3149         char** res=rl_completion_matches(text,
3150                                       command_generator); 
3151 #else
3152         char** res=completion_matches(text,
3153                                       (CPFunction*)command_generator); 
3154 #endif
3155         rl_attempted_completion_over = 1;
3156         return res;
3157     } else {
3158         char arg[1024],word[32];
3159         int i=0 ,res;
3160         if ((res = sscanf(rl_line_buffer, "%31s %1023[^;]", word, arg)) <= 0) {     
3161             rl_attempted_completion_over = 1;
3162             return NULL;
3163         }
3164         
3165         for (i = 0; cmd[i].cmd; i++) {
3166             if (!strncmp(cmd[i].cmd, word, strlen(word))) {
3167                 break;
3168             }
3169         }
3170         
3171         if(!cmd[i].cmd) return NULL;
3172         
3173         
3174         curret_global_list = cmd[i].local_tabcompletes;
3175         
3176         completerToUse = cmd[i].rl_completerfunction;
3177         if(completerToUse==NULL)  /* if no pr. command completer is defined use the default completer */
3178             completerToUse = default_completer;
3179         
3180         if(completerToUse) {
3181 #ifdef HAVE_READLINE_RL_COMPLETION_MATCHES
3182             char** res=
3183                 rl_completion_matches(text,
3184                                       completerToUse);
3185 #else
3186             char** res=
3187                 completion_matches(text,
3188                                    (CPFunction*)completerToUse);
3189 #endif
3190             if(!cmd[i].complete_filenames) 
3191                 rl_attempted_completion_over = 1;
3192             return res;
3193         } else {
3194             if(!cmd[i].complete_filenames) 
3195                 rl_attempted_completion_over = 1;
3196             return 0;
3197         }
3198     }
3199 #else 
3200     return 0;
3201 #endif 
3202 }
3203
3204
3205 static void client(void)
3206 {
3207     char line[1024];
3208
3209     line[1023] = '\0';
3210
3211 #if HAVE_GETTIMEOFDAY
3212     gettimeofday (&tv_start, 0);
3213 #endif
3214
3215     while (1)
3216     {
3217         char *line_in = NULL;
3218 #if HAVE_READLINE_READLINE_H
3219         if (isatty(0))
3220         {
3221             line_in=readline(C_PROMPT);
3222             if (!line_in)
3223                 break;
3224 #if HAVE_READLINE_HISTORY_H
3225             if (*line_in)
3226                 add_history(line_in);
3227 #endif
3228             strncpy(line, line_in, 1023);
3229             free (line_in);
3230         }
3231 #endif 
3232         if (!line_in)
3233         {
3234             char *end_p;
3235             printf (C_PROMPT);
3236             fflush(stdout);
3237             if (!fgets(line, 1023, stdin))
3238                 break;
3239             if ((end_p = strchr (line, '\n')))
3240                 *end_p = '\0';
3241         }
3242         process_cmd_line(line);
3243     }
3244 }
3245
3246 int main(int argc, char **argv)
3247 {
3248     char *prog = *argv;
3249     char *open_command = 0;
3250     char *auth_command = 0;
3251     char *arg;
3252     int ret;
3253     
3254     while ((ret = options("k:c:a:m:v:p:u:", argv, argc, &arg)) != -2)
3255     {
3256         switch (ret)
3257         {
3258         case 0:
3259             if (!open_command)
3260             {
3261                 open_command = (char *) xmalloc (strlen(arg)+6);
3262                 strcpy (open_command, "open ");
3263                 strcat (open_command, arg);
3264             }
3265             break;
3266         case 'k':
3267             kilobytes = atoi(arg);
3268             break;
3269         case 'm':
3270             if (!(marcdump = fopen (arg, "a")))
3271             {
3272                 perror (arg);
3273                 exit (1);
3274             }
3275             break;
3276                 case 'c':
3277                         strncpy (ccl_fields, arg, sizeof(ccl_fields)-1);
3278                         ccl_fields[sizeof(ccl_fields)-1] = '\0';
3279                         break;
3280         case 'a':
3281             if (!strcmp(arg, "-"))
3282                 apdu_file=stderr;
3283             else
3284                 apdu_file=fopen(arg, "a");
3285             break;
3286                 case 'p':
3287                         yazProxy=strdup(arg);
3288                         break;
3289         case 'u':
3290             if (!auth_command)
3291             {
3292                 auth_command = (char *) xmalloc (strlen(arg)+6);
3293                 strcpy (auth_command, "auth ");
3294                 strcat (auth_command, arg);
3295             }
3296             break;
3297         case 'v':
3298             yaz_log_init (yaz_log_mask_str(arg), "", NULL);
3299             break;
3300         default:
3301             fprintf (stderr, "Usage: %s [-m <marclog>] [ -a <apdulog>] "
3302                      "[-c cclfields]\n      [-p <proxy-addr>] [-u <auth>] "
3303                      "[-k size] [<server-addr>]\n",
3304                      prog);
3305             exit (1);
3306         }      
3307     }
3308     initialize();
3309     if (auth_command)
3310     {
3311 #ifdef HAVE_GETTIMEOFDAY
3312         gettimeofday (&tv_start, 0);
3313 #endif
3314         process_cmd_line (auth_command);
3315 #if HAVE_READLINE_HISTORY_H
3316         add_history(auth_command);
3317 #endif
3318         xfree(auth_command);
3319     }
3320     if (open_command)
3321     {
3322 #ifdef HAVE_GETTIMEOFDAY
3323         gettimeofday (&tv_start, 0);
3324 #endif
3325         process_cmd_line (open_command);
3326 #if HAVE_READLINE_HISTORY_H
3327         add_history(open_command);
3328 #endif
3329         xfree(open_command);
3330     }
3331     client ();
3332     exit (0);
3333 }
3334
3335 /*
3336  * Local variables:
3337  * tab-width: 8
3338  * c-basic-offset: 4
3339  * End:
3340  * vim600: sw=4 ts=8 fdm=marker
3341  * vim<600: sw=4 ts=8
3342  */