New PQF API. Old API preserved.
[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.166 2002-09-02 13:59:07 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,r->u.octet_aligned->len);
695                 fprintf(stderr, "---------\n");
696
697                                 /* note just ignores the error ant print the bytes form the octet_aligned laiter */
698             } else {
699                                 /*
700                                  * Note: we throw away the original, BER-encoded record here.
701                                  * Do something else with it if you want to keep it.
702                                  */
703                                 r->u.sutrs = (Z_SUTRS *) rr; /* we don't actually check the type here. */
704                                 r->which = type->what;
705                         };
706         }
707     }
708     if (ent && ent->oclass != CLASS_RECSYN) 
709         return;
710     if (ent && ent->value == VAL_SOIF)
711         print_record((const unsigned char *) r->u.octet_aligned->buf,
712                      r->u.octet_aligned->len);
713     else if (r->which == Z_External_octet && r->u.octet_aligned->len)
714     {
715         const char *octet_buf = (char*)r->u.octet_aligned->buf;
716         if (ent->value == VAL_TEXT_XML || ent->value == VAL_APPLICATION_XML ||
717             ent->value == VAL_HTML)
718         {
719             print_record((const unsigned char *) octet_buf,
720                          r->u.octet_aligned->len);
721         }
722         else if (ent->value == VAL_POSTSCRIPT)
723         {
724             int size = r->u.octet_aligned->len;
725             if (size > 100)
726                 size = 100;
727             print_record((const unsigned char *) octet_buf, size);
728         }
729         else
730         {
731             if ( 
732 #if AVOID_MARC_DECODE
733                 /* primitive check for a marc OID 5.1-29 except 16 */
734                 ent->oidsuffix[0] == 5 && ent->oidsuffix[1] < 30 &&
735                 ent->oidsuffix[1] != 16
736 #else
737                 1
738 #endif
739                 )
740             {
741                 if (marc_display_exl (octet_buf, NULL, 0 /* debug */,
742                                       r->u.octet_aligned->len) <= 0)
743                 {
744                     printf ("bad MARC. Dumping as it is:\n");
745                     print_record((const unsigned char*) octet_buf,
746                                  r->u.octet_aligned->len);
747                 }
748             }
749             else
750             {
751                 print_record((const unsigned char*) octet_buf,
752                              r->u.octet_aligned->len);
753             }
754         }
755         if (marcdump)
756             fwrite (octet_buf, 1, r->u.octet_aligned->len, marcdump);
757     }
758     else if (ent && ent->value == VAL_SUTRS)
759     {
760         if (r->which != Z_External_sutrs)
761         {
762             printf("Expecting single SUTRS type for SUTRS.\n");
763             return;
764         }
765         print_record(r->u.sutrs->buf, r->u.sutrs->len);
766     }
767     else if (ent && ent->value == VAL_GRS1)
768     {
769         if (r->which != Z_External_grs1)
770         {
771             printf("Expecting single GRS type for GRS.\n");
772             return;
773         }
774         display_grs1(r->u.grs1, 0);
775     }
776     else 
777     {
778         printf("Unknown record representation.\n");
779         if (!z_External(print, &r, 0, 0))
780         {
781             odr_perror(print, "Printing external");
782             odr_reset(print);
783         }
784     }
785 }
786
787 static void display_diagrecs(Z_DiagRec **pp, int num)
788 {
789     int i;
790     oident *ent;
791     Z_DefaultDiagFormat *r;
792
793     printf("Diagnostic message(s) from database:\n");
794     for (i = 0; i<num; i++)
795     {
796         Z_DiagRec *p = pp[i];
797         if (p->which != Z_DiagRec_defaultFormat)
798         {
799             printf("Diagnostic record not in default format.\n");
800             return;
801         }
802         else
803             r = p->u.defaultFormat;
804         if (!(ent = oid_getentbyoid(r->diagnosticSetId)) ||
805             ent->oclass != CLASS_DIAGSET || ent->value != VAL_BIB1)
806             printf("Missing or unknown diagset\n");
807         printf("    [%d] %s", *r->condition, diagbib1_str(*r->condition));
808         switch (r->which)
809         {
810         case Z_DefaultDiagFormat_v2Addinfo:
811             printf (" -- v2 addinfo '%s'\n", r->u.v2Addinfo);
812             break;
813         case Z_DefaultDiagFormat_v3Addinfo:
814             printf (" -- v3 addinfo '%s'\n", r->u.v3Addinfo);
815             break;
816         }
817     }
818 }
819
820
821 static void display_nameplusrecord(Z_NamePlusRecord *p)
822 {
823     if (p->databaseName)
824         printf("[%s]", p->databaseName);
825     if (p->which == Z_NamePlusRecord_surrogateDiagnostic)
826         display_diagrecs(&p->u.surrogateDiagnostic, 1);
827     else if (p->which == Z_NamePlusRecord_databaseRecord)
828         display_record(p->u.databaseRecord);
829 }
830
831 static void display_records(Z_Records *p)
832 {
833     int i;
834
835     if (p->which == Z_Records_NSD)
836     {
837         Z_DiagRec dr, *dr_p = &dr;
838         dr.which = Z_DiagRec_defaultFormat;
839         dr.u.defaultFormat = p->u.nonSurrogateDiagnostic;
840         display_diagrecs (&dr_p, 1);
841     }
842     else if (p->which == Z_Records_multipleNSD)
843         display_diagrecs (p->u.multipleNonSurDiagnostics->diagRecs,
844                           p->u.multipleNonSurDiagnostics->num_diagRecs);
845     else 
846     {
847         printf("Records: %d\n", p->u.databaseOrSurDiagnostics->num_records);
848         for (i = 0; i < p->u.databaseOrSurDiagnostics->num_records; i++)
849             display_nameplusrecord(p->u.databaseOrSurDiagnostics->records[i]);
850     }
851 }
852
853 static int send_deleteResultSetRequest(char *arg)
854 {
855     char names[8][32];
856     int i;
857
858     Z_APDU *apdu = zget_APDU(out, Z_APDU_deleteResultSetRequest);
859     Z_DeleteResultSetRequest *req = apdu->u.deleteResultSetRequest;
860
861     req->referenceId = set_refid (out);
862
863     req->num_resultSetList =
864         sscanf (arg, "%30s %30s %30s %30s %30s %30s %30s %30s",
865                 names[0], names[1], names[2], names[3],
866                 names[4], names[5], names[6], names[7]);
867
868     req->deleteFunction = (int *)
869         odr_malloc (out, sizeof(*req->deleteFunction));
870     if (req->num_resultSetList > 0)
871     {
872         *req->deleteFunction = Z_DeleteRequest_list;
873         req->resultSetList = (char **)
874             odr_malloc (out, sizeof(*req->resultSetList)*
875                         req->num_resultSetList);
876         for (i = 0; i<req->num_resultSetList; i++)
877             req->resultSetList[i] = names[i];
878     }
879     else
880     {
881         *req->deleteFunction = Z_DeleteRequest_all;
882         req->resultSetList = 0;
883     }
884     
885     send_apdu(apdu);
886     printf("Sent deleteResultSetRequest.\n");
887     return 2;
888 }
889
890 static int send_searchRequest(char *arg)
891 {
892     Z_APDU *apdu = zget_APDU(out, Z_APDU_searchRequest);
893     Z_SearchRequest *req = apdu->u.searchRequest;
894     Z_Query query;
895     int oid[OID_SIZE];
896     struct ccl_rpn_node *rpn = NULL;
897     int error, pos;
898     char setstring[100];
899     Z_RPNQuery *RPNquery;
900     Odr_oct ccl_query;
901     YAZ_PQF_Parser pqf_parser;
902
903     if (queryType == QueryType_CCL2RPN)
904     {
905         rpn = ccl_find_str(bibset, arg, &error, &pos);
906         if (error)
907         {
908             printf("CCL ERROR: %s\n", ccl_err_msg(error));
909             return 0;
910         }
911     }
912     req->referenceId = set_refid (out);
913     if (!strcmp(arg, "@big")) /* strictly for troublemaking */
914     {
915         static unsigned char big[2100];
916         static Odr_oct bigo;
917
918         /* send a very big referenceid to test transport stack etc. */
919         memset(big, 'A', 2100);
920         bigo.len = bigo.size = 2100;
921         bigo.buf = big;
922         req->referenceId = &bigo;
923     }
924     
925     if (setnumber >= 0)
926     {
927         sprintf(setstring, "%d", ++setnumber);
928         req->resultSetName = setstring;
929     }
930     *req->smallSetUpperBound = smallSetUpperBound;
931     *req->largeSetLowerBound = largeSetLowerBound;
932     *req->mediumSetPresentNumber = mediumSetPresentNumber;
933     if (smallSetUpperBound > 0 || (largeSetLowerBound > 1 &&
934         mediumSetPresentNumber > 0))
935     {
936         oident prefsyn;
937
938         prefsyn.proto = protocol;
939         prefsyn.oclass = CLASS_RECSYN;
940         prefsyn.value = recordsyntax;
941         req->preferredRecordSyntax =
942             odr_oiddup(out, oid_ent_to_oid(&prefsyn, oid));
943         req->smallSetElementSetNames =
944             req->mediumSetElementSetNames = elementSetNames;
945     }
946     req->num_databaseNames = num_databaseNames;
947     req->databaseNames = databaseNames;
948
949     req->query = &query;
950
951     switch (queryType)
952     {
953     case QueryType_Prefix:
954         query.which = Z_Query_type_1;
955         pqf_parser = yaz_pqf_create ();
956         RPNquery = yaz_pqf_parse (pqf_parser, out, arg);
957         if (!RPNquery)
958         {
959             const char *pqf_msg;
960             size_t off;
961             int code = yaz_pqf_error (pqf_parser, &pqf_msg, &off);
962             printf("%*s^\n", off+4, "");
963             printf("Prefix query error: %s (code %d)\n", pqf_msg, code);
964             
965             yaz_pqf_destroy (pqf_parser);
966             return 0;
967         }
968         yaz_pqf_destroy (pqf_parser);
969         query.u.type_1 = RPNquery;
970         break;
971     case QueryType_CCL:
972         query.which = Z_Query_type_2;
973         query.u.type_2 = &ccl_query;
974         ccl_query.buf = (unsigned char*) arg;
975         ccl_query.len = strlen(arg);
976         break;
977     case QueryType_CCL2RPN:
978         query.which = Z_Query_type_1;
979         RPNquery = ccl_rpn_query(out, rpn);
980         if (!RPNquery)
981         {
982             printf ("Couldn't convert from CCL to RPN\n");
983             return 0;
984         }
985         query.u.type_1 = RPNquery;
986         ccl_rpn_delete (rpn);
987         break;
988     default:
989         printf ("Unsupported query type\n");
990         return 0;
991     }
992     send_apdu(apdu);
993     setno = 1;
994     printf("Sent searchRequest.\n");
995     return 2;
996 }
997
998 /* display Query Expression as part of searchResult-1 */
999 static void display_queryExpression (Z_QueryExpression *qe)
1000 {
1001     if (!qe)
1002         return;
1003     if (qe->which == Z_QueryExpression_term)
1004     {
1005         if (qe->u.term->queryTerm)
1006         {
1007             Z_Term *term = qe->u.term->queryTerm;
1008             switch (term->which)
1009             {
1010             case Z_Term_general:
1011                 printf (" %.*s", term->u.general->len, term->u.general->buf);
1012                 break;
1013             case Z_Term_characterString:
1014                 printf (" %s", term->u.characterString);
1015                 break;
1016             case Z_Term_numeric:
1017                 printf (" %d", *term->u.numeric);
1018                 break;
1019             case Z_Term_null:
1020                 printf (" null");
1021                 break;
1022             }
1023         }
1024     }
1025 }
1026
1027 /* see if we can find USR:SearchResult-1 */
1028 static void display_searchResult (Z_OtherInformation *o)
1029 {
1030     int i;
1031     if (!o)
1032         return ;
1033     for (i = 0; i < o->num_elements; i++)
1034     {
1035         if (o->list[i]->which == Z_OtherInfo_externallyDefinedInfo)
1036         {
1037             Z_External *ext = o->list[i]->information.externallyDefinedInfo;
1038             
1039             if (ext->which == Z_External_searchResult1)
1040             {
1041                 int j;
1042                 Z_SearchInfoReport *sr = ext->u.searchResult1;
1043                 printf ("SearchResult-1:");
1044                 for (j = 0; j < sr->num; j++)
1045                 {
1046                     if (!sr->elements[j]->subqueryExpression)
1047                         printf (" %d", j);
1048                     display_queryExpression (
1049                         sr->elements[j]->subqueryExpression);
1050                     display_queryExpression (
1051                         sr->elements[j]->subqueryInterpretation);
1052                     display_queryExpression (
1053                         sr->elements[j]->subqueryRecommendation);
1054                     if (sr->elements[j]->subqueryCount)
1055                         printf ("(%d)", *sr->elements[j]->subqueryCount);
1056                 }
1057                 printf ("\n");
1058             }
1059         }
1060     }
1061 }
1062
1063 static int process_searchResponse(Z_SearchResponse *res)
1064 {
1065     printf ("Received SearchResponse.\n");
1066     print_refid (res->referenceId);
1067     if (*res->searchStatus)
1068         printf("Search was a success.\n");
1069     else
1070         printf("Search was a bloomin' failure.\n");
1071     printf("Number of hits: %d", *res->resultCount);
1072     if (setnumber >= 0)
1073         printf (", setno %d", setnumber);
1074     printf ("\n");
1075     display_searchResult (res->additionalSearchInfo);
1076     printf("records returned: %d\n",
1077            *res->numberOfRecordsReturned);
1078     setno += *res->numberOfRecordsReturned;
1079     if (res->records)
1080         display_records(res->records);
1081     return 0;
1082 }
1083
1084 static void print_level(int iLevel)
1085 {
1086     int i;
1087     for (i = 0; i < iLevel * 4; i++)
1088         printf(" ");
1089 }
1090
1091 static void print_int(int iLevel, const char *pTag, int *pInt)
1092 {
1093     if (pInt != NULL)
1094     {
1095         print_level(iLevel);
1096         printf("%s: %d\n", pTag, *pInt);
1097     }
1098 }
1099
1100 static void print_string(int iLevel, const char *pTag, const char *pString)
1101 {
1102     if (pString != NULL)
1103     {
1104         print_level(iLevel);
1105         printf("%s: %s\n", pTag, pString);
1106     }
1107 }
1108
1109 static void print_oid(int iLevel, const char *pTag, Odr_oid *pOid)
1110 {
1111     if (pOid != NULL)
1112     {
1113         int *pInt = pOid;
1114
1115         print_level(iLevel);
1116         printf("%s:", pTag);
1117         for (; *pInt != -1; pInt++)
1118             printf(" %d", *pInt);
1119         printf("\n");
1120     }
1121 }
1122
1123 static void print_referenceId(int iLevel, Z_ReferenceId *referenceId)
1124 {
1125     if (referenceId != NULL)
1126     {
1127         int i;
1128
1129         print_level(iLevel);
1130         printf("Ref Id (%d, %d): ", referenceId->len, referenceId->size);
1131         for (i = 0; i < referenceId->len; i++)
1132             printf("%c", referenceId->buf[i]);
1133         printf("\n");
1134     }
1135 }
1136
1137 static void print_string_or_numeric(int iLevel, const char *pTag, Z_StringOrNumeric *pStringNumeric)
1138 {
1139     if (pStringNumeric != NULL)
1140     {
1141         switch (pStringNumeric->which)
1142         {
1143         case Z_StringOrNumeric_string:
1144             print_string(iLevel, pTag, pStringNumeric->u.string);
1145             break;
1146             
1147         case Z_StringOrNumeric_numeric:
1148             print_int(iLevel, pTag, pStringNumeric->u.numeric);
1149             break;
1150             
1151         default:
1152             print_level(iLevel);
1153             printf("%s: valid type for Z_StringOrNumeric\n", pTag);
1154             break;
1155         }
1156     }
1157 }
1158
1159 static void print_universe_report_duplicate(int iLevel, Z_UniverseReportDuplicate *pUniverseReportDuplicate)
1160 {
1161     if (pUniverseReportDuplicate != NULL)
1162     {
1163         print_level(iLevel);
1164         printf("Universe Report Duplicate: \n");
1165         iLevel++;
1166         print_string_or_numeric(iLevel, "Hit No",
1167                                 pUniverseReportDuplicate->hitno);
1168     }
1169 }
1170
1171 static void
1172 print_universe_report_hits(int iLevel,
1173                            Z_UniverseReportHits *pUniverseReportHits)
1174 {
1175     if (pUniverseReportHits != NULL)
1176     {
1177         print_level(iLevel);
1178         printf("Universe Report Hits: \n");
1179         iLevel++;
1180         print_string_or_numeric(iLevel, "Database",
1181                                 pUniverseReportHits->database);
1182         print_string_or_numeric(iLevel, "Hits", pUniverseReportHits->hits);
1183     }
1184 }
1185
1186 static void print_universe_report(int iLevel, Z_UniverseReport *pUniverseReport)
1187 {
1188     if (pUniverseReport != NULL)
1189     {
1190         print_level(iLevel);
1191         printf("Universe Report: \n");
1192         iLevel++;
1193         print_int(iLevel, "Total Hits", pUniverseReport->totalHits);
1194         switch (pUniverseReport->which)
1195         {
1196         case Z_UniverseReport_databaseHits:
1197             print_universe_report_hits(iLevel, pUniverseReport->u.databaseHits);
1198             break;
1199             
1200         case Z_UniverseReport_duplicate:
1201             print_universe_report_duplicate(iLevel, pUniverseReport->u.duplicate);
1202             break;
1203             
1204         default:
1205             print_level(iLevel);
1206             printf("Type: %d\n", pUniverseReport->which);
1207             break;
1208         }
1209     }
1210 }
1211
1212 static void print_external(int iLevel, Z_External *pExternal)
1213 {
1214     if (pExternal != NULL)
1215     {
1216         print_level(iLevel);
1217         printf("External: \n");
1218         iLevel++;
1219         print_oid(iLevel, "Direct Reference", pExternal->direct_reference);
1220         print_int(iLevel, "InDirect Reference", pExternal->indirect_reference);
1221         print_string(iLevel, "Descriptor", pExternal->descriptor);
1222         switch (pExternal->which)
1223         {
1224         case Z_External_universeReport:
1225             print_universe_report(iLevel, pExternal->u.universeReport);
1226             break;
1227             
1228         default:
1229             print_level(iLevel);
1230             printf("Type: %d\n", pExternal->which);
1231             break;
1232         }
1233     }
1234 }
1235
1236 static int process_resourceControlRequest (Z_ResourceControlRequest *req)
1237 {
1238     printf ("Received ResourceControlRequest.\n");
1239     print_referenceId(1, req->referenceId);
1240     print_int(1, "Suspended Flag", req->suspendedFlag);
1241     print_int(1, "Partial Results Available", req->partialResultsAvailable);
1242     print_int(1, "Response Required", req->responseRequired);
1243     print_int(1, "Triggered Request Flag", req->triggeredRequestFlag);
1244     print_external(1, req->resourceReport);
1245     return 0;
1246 }
1247
1248 void process_ESResponse(Z_ExtendedServicesResponse *res)
1249 {
1250     printf("Status: ");
1251     switch (*res->operationStatus)
1252     {
1253     case Z_ExtendedServicesResponse_done:
1254         printf ("done\n");
1255         break;
1256     case Z_ExtendedServicesResponse_accepted:
1257         printf ("accepted\n");
1258         break;
1259     case Z_ExtendedServicesResponse_failure:
1260         printf ("failure\n");
1261         display_diagrecs(res->diagnostics, res->num_diagnostics);
1262         break;
1263     default:
1264         printf ("unknown\n");
1265     }
1266     if ( (*res->operationStatus != Z_ExtendedServicesResponse_failure) &&
1267         (res->num_diagnostics != 0) ) {
1268         display_diagrecs(res->diagnostics, res->num_diagnostics);
1269     }
1270     print_refid (res->referenceId);
1271     if (res->taskPackage && 
1272         res->taskPackage->which == Z_External_extendedService)
1273     {
1274         Z_TaskPackage *taskPackage = res->taskPackage->u.extendedService;
1275         Odr_oct *id = taskPackage->targetReference;
1276         Z_External *ext = taskPackage->taskSpecificParameters;
1277         
1278         if (id)
1279         {
1280             printf ("Target Reference: ");
1281             print_stringn (id->buf, id->len);
1282             printf ("\n");
1283         }
1284         if (ext->which == Z_External_update)
1285         {
1286             Z_IUUpdateTaskPackage *utp = ext->u.update->u.taskPackage;
1287             if (utp && utp->targetPart)
1288             {
1289                 Z_IUTargetPart *targetPart = utp->targetPart;
1290                 int i;
1291
1292                 for (i = 0; i<targetPart->num_taskPackageRecords;  i++)
1293                 {
1294
1295                     Z_IUTaskPackageRecordStructure *tpr =
1296                         targetPart->taskPackageRecords[i];
1297                     printf ("task package record %d\n", i+1);
1298                     if (tpr->which == Z_IUTaskPackageRecordStructure_record)
1299                     {
1300                         display_record (tpr->u.record);
1301                     }
1302                     else
1303                     {
1304                         printf ("other type\n");
1305                     }
1306                 }
1307             }
1308         }
1309     }
1310 }
1311
1312 const char *get_ill_element (void *clientData, const char *element)
1313 {
1314     return 0;
1315 }
1316
1317 static Z_External *create_external_itemRequest()
1318 {
1319     struct ill_get_ctl ctl;
1320     ILL_ItemRequest *req;
1321     Z_External *r = 0;
1322     int item_request_size = 0;
1323     char *item_request_buf = 0;
1324
1325     ctl.odr = out;
1326     ctl.clientData = 0;
1327     ctl.f = get_ill_element;
1328     
1329     req = ill_get_ItemRequest(&ctl, "ill", 0);
1330     if (!req)
1331         printf ("ill_get_ItemRequest failed\n");
1332         
1333     if (!ill_ItemRequest (out, &req, 0, 0))
1334     {
1335         if (apdu_file)
1336         {
1337             ill_ItemRequest(print, &req, 0, 0);
1338             odr_reset(print);
1339         }
1340         item_request_buf = odr_getbuf (out, &item_request_size, 0);
1341         if (item_request_buf)
1342             odr_setbuf (out, item_request_buf, item_request_size, 1);
1343         printf ("Couldn't encode ItemRequest, size %d\n", item_request_size);
1344         return 0;
1345     }
1346     else
1347     {
1348         oident oid;
1349         
1350         item_request_buf = odr_getbuf (out, &item_request_size, 0);
1351         oid.proto = PROTO_GENERAL;
1352         oid.oclass = CLASS_GENERAL;
1353         oid.value = VAL_ISO_ILL_1;
1354         
1355         r = (Z_External *) odr_malloc (out, sizeof(*r));
1356         r->direct_reference = odr_oiddup(out,oid_getoidbyent(&oid)); 
1357         r->indirect_reference = 0;
1358         r->descriptor = 0;
1359         r->which = Z_External_single;
1360         
1361         r->u.single_ASN1_type = (Odr_oct *)
1362             odr_malloc (out, sizeof(*r->u.single_ASN1_type));
1363         r->u.single_ASN1_type->buf = (unsigned char *)
1364         odr_malloc (out, item_request_size);
1365         r->u.single_ASN1_type->len = item_request_size;
1366         r->u.single_ASN1_type->size = item_request_size;
1367         memcpy (r->u.single_ASN1_type->buf, item_request_buf,
1368                 item_request_size);
1369                 
1370                 do_hex_dump(item_request_buf,item_request_size);
1371     }
1372     return r;
1373 }
1374
1375 static Z_External *create_external_ILL_APDU(int which)
1376 {
1377     struct ill_get_ctl ctl;
1378     ILL_APDU *ill_apdu;
1379     Z_External *r = 0;
1380     int ill_request_size = 0;
1381     char *ill_request_buf = 0;
1382         
1383     ctl.odr = out;
1384     ctl.clientData = 0;
1385     ctl.f = get_ill_element;
1386
1387     ill_apdu = ill_get_APDU(&ctl, "ill", 0);
1388
1389     if (!ill_APDU (out, &ill_apdu, 0, 0))
1390     {
1391         if (apdu_file)
1392         {
1393             printf ("-------------------\n");
1394             ill_APDU(print, &ill_apdu, 0, 0);
1395             odr_reset(print);
1396             printf ("-------------------\n");
1397         }
1398         ill_request_buf = odr_getbuf (out, &ill_request_size, 0);
1399         if (ill_request_buf)
1400             odr_setbuf (out, ill_request_buf, ill_request_size, 1);
1401         printf ("Couldn't encode ILL-Request, size %d\n", ill_request_size);
1402         return 0;
1403     }
1404     else
1405     {
1406         oident oid;
1407         ill_request_buf = odr_getbuf (out, &ill_request_size, 0);
1408         
1409         oid.proto = PROTO_GENERAL;
1410         oid.oclass = CLASS_GENERAL;
1411         oid.value = VAL_ISO_ILL_1;
1412         
1413         r = (Z_External *) odr_malloc (out, sizeof(*r));
1414         r->direct_reference = odr_oiddup(out,oid_getoidbyent(&oid)); 
1415         r->indirect_reference = 0;
1416         r->descriptor = 0;
1417         r->which = Z_External_single;
1418         
1419         r->u.single_ASN1_type = (Odr_oct *)
1420             odr_malloc (out, sizeof(*r->u.single_ASN1_type));
1421         r->u.single_ASN1_type->buf = (unsigned char *)
1422         odr_malloc (out, ill_request_size);
1423         r->u.single_ASN1_type->len = ill_request_size;
1424         r->u.single_ASN1_type->size = ill_request_size;
1425         memcpy (r->u.single_ASN1_type->buf, ill_request_buf, ill_request_size);
1426 /*         printf ("len = %d\n", ill_request_size); */
1427 /*              do_hex_dump(ill_request_buf,ill_request_size); */
1428 /*              printf("--- end of extenal\n"); */
1429
1430     }
1431     return r;
1432 }
1433
1434
1435 static Z_External *create_ItemOrderExternal(const char *type, int itemno)
1436 {
1437     Z_External *r = (Z_External *) odr_malloc(out, sizeof(Z_External));
1438     oident ItemOrderRequest;
1439   
1440     ItemOrderRequest.proto = PROTO_Z3950;
1441     ItemOrderRequest.oclass = CLASS_EXTSERV;
1442     ItemOrderRequest.value = VAL_ITEMORDER;
1443  
1444     r->direct_reference = odr_oiddup(out,oid_getoidbyent(&ItemOrderRequest)); 
1445     r->indirect_reference = 0;
1446     r->descriptor = 0;
1447
1448     r->which = Z_External_itemOrder;
1449
1450     r->u.itemOrder = (Z_ItemOrder *) odr_malloc(out,sizeof(Z_ItemOrder));
1451     memset(r->u.itemOrder, 0, sizeof(Z_ItemOrder));
1452     r->u.itemOrder->which=Z_IOItemOrder_esRequest;
1453
1454     r->u.itemOrder->u.esRequest = (Z_IORequest *) 
1455         odr_malloc(out,sizeof(Z_IORequest));
1456     memset(r->u.itemOrder->u.esRequest, 0, sizeof(Z_IORequest));
1457
1458     r->u.itemOrder->u.esRequest->toKeep = (Z_IOOriginPartToKeep *)
1459         odr_malloc(out,sizeof(Z_IOOriginPartToKeep));
1460     memset(r->u.itemOrder->u.esRequest->toKeep, 0, sizeof(Z_IOOriginPartToKeep));
1461     r->u.itemOrder->u.esRequest->notToKeep = (Z_IOOriginPartNotToKeep *)
1462         odr_malloc(out,sizeof(Z_IOOriginPartNotToKeep));
1463     memset(r->u.itemOrder->u.esRequest->notToKeep, 0, sizeof(Z_IOOriginPartNotToKeep));
1464
1465     r->u.itemOrder->u.esRequest->toKeep->supplDescription = NULL;
1466     r->u.itemOrder->u.esRequest->toKeep->contact = NULL;
1467     r->u.itemOrder->u.esRequest->toKeep->addlBilling = NULL;
1468
1469     r->u.itemOrder->u.esRequest->notToKeep->resultSetItem =
1470         (Z_IOResultSetItem *) odr_malloc(out, sizeof(Z_IOResultSetItem));
1471     memset(r->u.itemOrder->u.esRequest->notToKeep->resultSetItem, 0, sizeof(Z_IOResultSetItem));
1472     r->u.itemOrder->u.esRequest->notToKeep->resultSetItem->resultSetId = "1";
1473
1474     r->u.itemOrder->u.esRequest->notToKeep->resultSetItem->item =
1475         (int *) odr_malloc(out, sizeof(int));
1476     *r->u.itemOrder->u.esRequest->notToKeep->resultSetItem->item = itemno;
1477
1478     if (!strcmp (type, "item") || !strcmp(type, "2"))
1479     {
1480         printf ("using item-request\n");
1481         r->u.itemOrder->u.esRequest->notToKeep->itemRequest = 
1482             create_external_itemRequest();
1483     }
1484     else if (!strcmp(type, "ill") || !strcmp(type, "1"))
1485     {
1486         printf ("using ILL-request\n");
1487         r->u.itemOrder->u.esRequest->notToKeep->itemRequest = 
1488             create_external_ILL_APDU(ILL_APDU_ILL_Request);
1489     }
1490     else if (!strcmp(type, "xml") || !strcmp(type, "3"))
1491     {
1492     const char *xml_buf =
1493         "<itemorder>\n"
1494         "  <type>request</type>\n"
1495         "  <libraryNo>000200</libraryNo>\n"
1496         "  <borrowerTicketNo> 1212 </borrowerTicketNo>\n"
1497         "</itemorder>";
1498         r->u.itemOrder->u.esRequest->notToKeep->itemRequest =
1499             z_ext_record (out, VAL_TEXT_XML, xml_buf, strlen(xml_buf));
1500     }
1501     else
1502         r->u.itemOrder->u.esRequest->notToKeep->itemRequest = 0;
1503
1504     return r;
1505 }
1506
1507 static int send_itemorder(const char *type, int itemno)
1508 {
1509     Z_APDU *apdu = zget_APDU(out, Z_APDU_extendedServicesRequest);
1510     Z_ExtendedServicesRequest *req = apdu->u.extendedServicesRequest;
1511     oident ItemOrderRequest;
1512
1513     ItemOrderRequest.proto = PROTO_Z3950;
1514     ItemOrderRequest.oclass = CLASS_EXTSERV;
1515     ItemOrderRequest.value = VAL_ITEMORDER;
1516     req->packageType = odr_oiddup(out,oid_getoidbyent(&ItemOrderRequest));
1517     req->packageName = esPackageName;
1518
1519     req->taskSpecificParameters = create_ItemOrderExternal(type, itemno);
1520
1521     send_apdu(apdu);
1522     return 0;
1523 }
1524
1525 static int cmd_update(char *arg)
1526 {
1527     Z_APDU *apdu = zget_APDU(out, Z_APDU_extendedServicesRequest );
1528     Z_ExtendedServicesRequest *req = apdu->u.extendedServicesRequest;
1529     Z_External *r;
1530     int oid[OID_SIZE];
1531     Z_IUOriginPartToKeep *toKeep;
1532     Z_IUSuppliedRecords *notToKeep;
1533     oident update_oid;
1534     printf ("Update request\n");
1535     fflush(stdout);
1536     
1537     if (!record_last)
1538         return 0;
1539     update_oid.proto = PROTO_Z3950;
1540     update_oid.oclass = CLASS_EXTSERV;
1541     update_oid.value = VAL_DBUPDATE;
1542     oid_ent_to_oid (&update_oid, oid);
1543     req->packageType = odr_oiddup(out,oid);
1544     req->packageName = esPackageName;
1545     
1546     req->referenceId = set_refid (out);
1547
1548     r = req->taskSpecificParameters = (Z_External *)
1549         odr_malloc (out, sizeof(*r));
1550     r->direct_reference = odr_oiddup(out,oid);
1551     r->indirect_reference = 0;
1552     r->descriptor = 0;
1553     r->which = Z_External_update;
1554     r->u.update = (Z_IUUpdate *) odr_malloc(out, sizeof(*r->u.update));
1555     r->u.update->which = Z_IUUpdate_esRequest;
1556     r->u.update->u.esRequest = (Z_IUUpdateEsRequest *)
1557         odr_malloc(out, sizeof(*r->u.update->u.esRequest));
1558     toKeep = r->u.update->u.esRequest->toKeep = (Z_IUOriginPartToKeep *)
1559         odr_malloc(out, sizeof(*r->u.update->u.esRequest->toKeep));
1560     toKeep->databaseName = databaseNames[0];
1561     toKeep->schema = 0;
1562     toKeep->elementSetName = 0;
1563     toKeep->actionQualifier = 0;
1564     toKeep->action = (int *) odr_malloc(out, sizeof(*toKeep->action));
1565     *toKeep->action = Z_IUOriginPartToKeep_recordInsert;
1566
1567     notToKeep = r->u.update->u.esRequest->notToKeep = (Z_IUSuppliedRecords *)
1568         odr_malloc(out, sizeof(*r->u.update->u.esRequest->notToKeep));
1569     notToKeep->num = 1;
1570     notToKeep->elements = (Z_IUSuppliedRecords_elem **)
1571         odr_malloc(out, sizeof(*notToKeep->elements));
1572     notToKeep->elements[0] = (Z_IUSuppliedRecords_elem *)
1573         odr_malloc(out, sizeof(**notToKeep->elements));
1574     notToKeep->elements[0]->u.number = 0;
1575     notToKeep->elements[0]->supplementalId = 0;
1576     notToKeep->elements[0]->correlationInfo = 0;
1577     notToKeep->elements[0]->record = record_last;
1578     
1579     send_apdu(apdu);
1580
1581     return 2;
1582 }
1583
1584 static int cmd_itemorder(char *arg)
1585 {
1586     char type[12];
1587     int itemno;
1588     
1589     if (sscanf (arg, "%10s %d", type, &itemno) != 2)
1590         return 0;
1591
1592     printf("Item order request\n");
1593     fflush(stdout);
1594     send_itemorder(type, itemno);
1595     return 2;
1596 }
1597
1598 static int cmd_find(char *arg)
1599 {
1600     if (!*arg)
1601     {
1602         printf("Find what?\n");
1603         return 0;
1604     }
1605     if (!conn)
1606     {
1607                 try_reconnect(); 
1608
1609                 if (!conn) {                                    
1610                         printf("Not connected yet\n");
1611                         return 0;
1612                 };
1613     }
1614     if (!send_searchRequest(arg))
1615         return 0;
1616     return 2;
1617 }
1618
1619 static int cmd_delete(char *arg)
1620 {
1621     if (!conn)
1622     {
1623         printf("Not connected yet\n");
1624         return 0;
1625     }
1626     if (!send_deleteResultSetRequest(arg))
1627         return 0;
1628     return 2;
1629 }
1630
1631 static int cmd_ssub(char *arg)
1632 {
1633     if (!(smallSetUpperBound = atoi(arg)))
1634         return 0;
1635     return 1;
1636 }
1637
1638 static int cmd_lslb(char *arg)
1639 {
1640     if (!(largeSetLowerBound = atoi(arg)))
1641         return 0;
1642     return 1;
1643 }
1644
1645 static int cmd_mspn(char *arg)
1646 {
1647     if (!(mediumSetPresentNumber = atoi(arg)))
1648         return 0;
1649     return 1;
1650 }
1651
1652 static int cmd_status(char *arg)
1653 {
1654     printf("smallSetUpperBound: %d\n", smallSetUpperBound);
1655     printf("largeSetLowerBound: %d\n", largeSetLowerBound);
1656     printf("mediumSetPresentNumber: %d\n", mediumSetPresentNumber);
1657     return 1;
1658 }
1659
1660 static int cmd_setnames(char *arg)
1661 {
1662     if (*arg == '1')         /* enable ? */
1663         setnumber = 0;
1664     else if (*arg == '0')    /* disable ? */
1665         setnumber = -1;
1666     else if (setnumber < 0)  /* no args, toggle .. */
1667         setnumber = 0;
1668     else
1669         setnumber = -1;
1670    
1671     if (setnumber >= 0)
1672         printf("Set numbering enabled.\n");
1673     else
1674         printf("Set numbering disabled.\n");
1675     return 1;
1676 }
1677
1678 /* PRESENT SERVICE ----------------------------- */
1679
1680 static int send_presentRequest(char *arg)
1681 {
1682     Z_APDU *apdu = zget_APDU(out, Z_APDU_presentRequest);
1683     Z_PresentRequest *req = apdu->u.presentRequest;
1684     Z_RecordComposition compo;
1685     oident prefsyn;
1686     int nos = 1;
1687     int oid[OID_SIZE];
1688     char *p;
1689     char setstring[100];
1690
1691     req->referenceId = set_refid (out);
1692     if ((p = strchr(arg, '+')))
1693     {
1694         nos = atoi(p + 1);
1695         *p = 0;
1696     }
1697     if (*arg)
1698         setno = atoi(arg);
1699     if (p && (p=strchr(p+1, '+')))
1700     {
1701         strcpy (setstring, p+1);
1702         req->resultSetId = setstring;
1703     }
1704     else if (setnumber >= 0)
1705     {
1706         sprintf(setstring, "%d", setnumber);
1707         req->resultSetId = setstring;
1708     }
1709     req->resultSetStartPoint = &setno;
1710     req->numberOfRecordsRequested = &nos;
1711     prefsyn.proto = protocol;
1712     prefsyn.oclass = CLASS_RECSYN;
1713     prefsyn.value = recordsyntax;
1714     req->preferredRecordSyntax =
1715         odr_oiddup (out, oid_ent_to_oid(&prefsyn, oid));
1716
1717     if (schema != VAL_NONE)
1718     {
1719         oident prefschema;
1720
1721         prefschema.proto = protocol;
1722         prefschema.oclass = CLASS_SCHEMA;
1723         prefschema.value = schema;
1724
1725         req->recordComposition = &compo;
1726         compo.which = Z_RecordComp_complex;
1727         compo.u.complex = (Z_CompSpec *)
1728             odr_malloc(out, sizeof(*compo.u.complex));
1729         compo.u.complex->selectAlternativeSyntax = (bool_t *) 
1730             odr_malloc(out, sizeof(bool_t));
1731         *compo.u.complex->selectAlternativeSyntax = 0;
1732
1733         compo.u.complex->generic = (Z_Specification *)
1734             odr_malloc(out, sizeof(*compo.u.complex->generic));
1735         compo.u.complex->generic->schema = (Odr_oid *)
1736             odr_oiddup(out, oid_ent_to_oid(&prefschema, oid));
1737         if (!compo.u.complex->generic->schema)
1738         {
1739             /* OID wasn't a schema! Try record syntax instead. */
1740             prefschema.oclass = CLASS_RECSYN;
1741             compo.u.complex->generic->schema = (Odr_oid *)
1742                 odr_oiddup(out, oid_ent_to_oid(&prefschema, oid));
1743         }
1744         if (!elementSetNames)
1745             compo.u.complex->generic->elementSpec = 0;
1746         else
1747         {
1748             compo.u.complex->generic->elementSpec = (Z_ElementSpec *)
1749                 odr_malloc(out, sizeof(Z_ElementSpec));
1750             compo.u.complex->generic->elementSpec->which =
1751                 Z_ElementSpec_elementSetName;
1752             compo.u.complex->generic->elementSpec->u.elementSetName =
1753                 elementSetNames->u.generic;
1754         }
1755         compo.u.complex->num_dbSpecific = 0;
1756         compo.u.complex->dbSpecific = 0;
1757         compo.u.complex->num_recordSyntax = 0;
1758         compo.u.complex->recordSyntax = 0;
1759     }
1760     else if (elementSetNames)
1761     {
1762         req->recordComposition = &compo;
1763         compo.which = Z_RecordComp_simple;
1764         compo.u.simple = elementSetNames;
1765     }
1766     send_apdu(apdu);
1767     printf("Sent presentRequest (%d+%d).\n", setno, nos);
1768     return 2;
1769 }
1770     
1771 static void close_session (void)
1772 {
1773     cs_close (conn);
1774     conn = 0;
1775     if (session_mem)
1776     {
1777         nmem_destroy (session_mem);
1778         session_mem = NULL;
1779     }
1780     sent_close = 0;
1781 }
1782
1783 void process_close(Z_Close *req)
1784 {
1785     Z_APDU *apdu = zget_APDU(out, Z_APDU_close);
1786     Z_Close *res = apdu->u.close;
1787
1788     static char *reasons[] =
1789     {
1790         "finished",
1791         "shutdown",
1792         "system problem",
1793         "cost limit reached",
1794         "resources",
1795         "security violation",
1796         "protocolError",
1797         "lack of activity",
1798         "peer abort",
1799         "unspecified"
1800     };
1801
1802     printf("Reason: %s, message: %s\n", reasons[*req->closeReason],
1803         req->diagnosticInformation ? req->diagnosticInformation : "NULL");
1804     if (sent_close)
1805         close_session ();
1806     else
1807     {
1808         *res->closeReason = Z_Close_finished;
1809         send_apdu(apdu);
1810         printf("Sent response.\n");
1811         sent_close = 1;
1812     }
1813 }
1814
1815 static int cmd_show(char *arg)
1816 {
1817     if (!conn)
1818     {
1819         printf("Not connected yet\n");
1820         return 0;
1821     }
1822     if (!send_presentRequest(arg))
1823         return 0;
1824     return 2;
1825 }
1826
1827 int cmd_quit(char *arg)
1828 {
1829     printf("See you later, alligator.\n");
1830     xmalloc_trav ("");
1831     exit(0);
1832     return 0;
1833 }
1834
1835 int cmd_cancel(char *arg)
1836 {
1837     Z_APDU *apdu = zget_APDU(out, Z_APDU_triggerResourceControlRequest);
1838     Z_TriggerResourceControlRequest *req =
1839         apdu->u.triggerResourceControlRequest;
1840     bool_t rfalse = 0;
1841     
1842     if (!conn)
1843     {
1844         printf("Session not initialized yet\n");
1845         return 0;
1846     }
1847     if (!ODR_MASK_GET(session->options, Z_Options_triggerResourceCtrl))
1848     {
1849         printf("Target doesn't support cancel (trigger resource ctrl)\n");
1850         return 0;
1851     }
1852     *req->requestedAction = Z_TriggerResourceCtrl_cancel;
1853     req->resultSetWanted = &rfalse;
1854
1855     send_apdu(apdu);
1856     printf("Sent cancel request\n");
1857     return 2;
1858 }
1859
1860 int send_scanrequest(const char *query, int pp, int num, const char *term)
1861 {
1862     Z_APDU *apdu = zget_APDU(out, Z_APDU_scanRequest);
1863     Z_ScanRequest *req = apdu->u.scanRequest;
1864     int oid[OID_SIZE];
1865     
1866     if (queryType == QueryType_CCL2RPN)
1867     {
1868         oident bib1;
1869         int error, pos;
1870         struct ccl_rpn_node *rpn;
1871
1872         rpn = ccl_find_str (bibset,  query, &error, &pos);
1873         if (error)
1874         {
1875             printf("CCL ERROR: %s\n", ccl_err_msg(error));
1876             return -1;
1877         }
1878         bib1.proto = PROTO_Z3950;
1879         bib1.oclass = CLASS_ATTSET;
1880         bib1.value = VAL_BIB1;
1881         req->attributeSet = oid_ent_to_oid (&bib1, oid);
1882         if (!(req->termListAndStartPoint = ccl_scan_query (out, rpn)))
1883         {
1884             printf("Couldn't convert CCL to Scan term\n");
1885             return -1;
1886         }
1887         ccl_rpn_delete (rpn);
1888     }
1889     else
1890     {
1891         YAZ_PQF_Parser pqf_parser = yaz_pqf_create ();
1892
1893         if (!(req->termListAndStartPoint =
1894               yaz_pqf_scan(pqf_parser, out, &req->attributeSet, query)))
1895         {
1896             const char *pqf_msg;
1897             size_t off;
1898             int code = yaz_pqf_error (pqf_parser, &pqf_msg, &off);
1899             printf("%*s^\n", off+7, "");
1900             printf("Prefix query error: %s (code %d)\n", pqf_msg, code);
1901             yaz_pqf_destroy (pqf_parser);
1902             return -1;
1903         }
1904         yaz_pqf_destroy (pqf_parser);
1905     }
1906     if (term && *term)
1907     {
1908         if (req->termListAndStartPoint->term &&
1909             req->termListAndStartPoint->term->which == Z_Term_general &&
1910             req->termListAndStartPoint->term->u.general)
1911         {
1912             req->termListAndStartPoint->term->u.general->buf =
1913                 (unsigned char *) odr_strdup(out, term);
1914             req->termListAndStartPoint->term->u.general->len =
1915                 req->termListAndStartPoint->term->u.general->size =
1916                 strlen(term);
1917         }
1918     }
1919     req->referenceId = set_refid (out);
1920     req->num_databaseNames = num_databaseNames;
1921     req->databaseNames = databaseNames;
1922     req->numberOfTermsRequested = &num;
1923     req->preferredPositionInResponse = &pp;
1924     send_apdu(apdu);
1925     return 2;
1926 }
1927
1928 int send_sortrequest(char *arg, int newset)
1929 {
1930     Z_APDU *apdu = zget_APDU(out, Z_APDU_sortRequest);
1931     Z_SortRequest *req = apdu->u.sortRequest;
1932     Z_SortKeySpecList *sksl = (Z_SortKeySpecList *)
1933         odr_malloc (out, sizeof(*sksl));
1934     char setstring[32];
1935
1936     if (setnumber >= 0)
1937         sprintf (setstring, "%d", setnumber);
1938     else
1939         sprintf (setstring, "default");
1940
1941     req->referenceId = set_refid (out);
1942
1943     req->num_inputResultSetNames = 1;
1944     req->inputResultSetNames = (Z_InternationalString **)
1945         odr_malloc (out, sizeof(*req->inputResultSetNames));
1946     req->inputResultSetNames[0] = odr_strdup (out, setstring);
1947
1948     if (newset && setnumber >= 0)
1949         sprintf (setstring, "%d", ++setnumber);
1950
1951     req->sortedResultSetName = odr_strdup (out, setstring);
1952
1953     req->sortSequence = yaz_sort_spec (out, arg);
1954     if (!req->sortSequence)
1955     {
1956         printf ("Missing sort specifications\n");
1957         return -1;
1958     }
1959     send_apdu(apdu);
1960     return 2;
1961 }
1962
1963 void display_term(Z_TermInfo *t)
1964 {
1965     if (t->term->which == Z_Term_general)
1966     {
1967         printf("%.*s", t->term->u.general->len, t->term->u.general->buf);
1968         sprintf(last_scan_line, "%.*s", t->term->u.general->len,
1969             t->term->u.general->buf);
1970     }
1971     else
1972         printf("Term (not general)");
1973     if (t->globalOccurrences)
1974         printf (" (%d)\n", *t->globalOccurrences);
1975     else
1976         printf ("\n");
1977 }
1978
1979 void process_scanResponse(Z_ScanResponse *res)
1980 {
1981     int i;
1982     Z_Entry **entries = NULL;
1983     int num_entries = 0;
1984    
1985     printf("Received ScanResponse\n"); 
1986     print_refid (res->referenceId);
1987     printf("%d entries", *res->numberOfEntriesReturned);
1988     if (res->positionOfTerm)
1989         printf (", position=%d", *res->positionOfTerm); 
1990     printf ("\n");
1991     if (*res->scanStatus != Z_Scan_success)
1992         printf("Scan returned code %d\n", *res->scanStatus);
1993     if (!res->entries)
1994         return;
1995     if ((entries = res->entries->entries))
1996         num_entries = res->entries->num_entries;
1997     for (i = 0; i < num_entries; i++)
1998     {
1999         int pos_term = res->positionOfTerm ? *res->positionOfTerm : -1;
2000         if (entries[i]->which == Z_Entry_termInfo)
2001         {
2002             printf("%c ", i + 1 == pos_term ? '*' : ' ');
2003             display_term(entries[i]->u.termInfo);
2004         }
2005         else
2006             display_diagrecs(&entries[i]->u.surrogateDiagnostic, 1);
2007     }
2008     if (res->entries->nonsurrogateDiagnostics)
2009         display_diagrecs (res->entries->nonsurrogateDiagnostics,
2010                           res->entries->num_nonsurrogateDiagnostics);
2011 }
2012
2013 void process_sortResponse(Z_SortResponse *res)
2014 {
2015     printf("Received SortResponse: status=");
2016     switch (*res->sortStatus)
2017     {
2018     case Z_SortStatus_success:
2019         printf ("success"); break;
2020     case Z_SortStatus_partial_1:
2021         printf ("partial"); break;
2022     case Z_SortStatus_failure:
2023         printf ("failure"); break;
2024     default:
2025         printf ("unknown (%d)", *res->sortStatus);
2026     }
2027     printf ("\n");
2028     print_refid (res->referenceId);
2029     if (res->diagnostics)
2030         display_diagrecs(res->diagnostics,
2031                          res->num_diagnostics);
2032 }
2033
2034 void process_deleteResultSetResponse (Z_DeleteResultSetResponse *res)
2035 {
2036     printf("Got deleteResultSetResponse status=%d\n",
2037            *res->deleteOperationStatus);
2038     if (res->deleteListStatuses)
2039     {
2040         int i;
2041         for (i = 0; i < res->deleteListStatuses->num; i++)
2042         {
2043             printf ("%s status=%d\n", res->deleteListStatuses->elements[i]->id,
2044                     *res->deleteListStatuses->elements[i]->status);
2045         }
2046     }
2047 }
2048
2049 int cmd_sort_generic(char *arg, int newset)
2050 {
2051     if (!conn)
2052     {
2053         printf("Session not initialized yet\n");
2054         return 0;
2055     }
2056     if (!ODR_MASK_GET(session->options, Z_Options_sort))
2057     {
2058         printf("Target doesn't support sort\n");
2059         return 0;
2060     }
2061     if (*arg)
2062     {
2063         if (send_sortrequest(arg, newset) < 0)
2064             return 0;
2065         return 2;
2066     }
2067     return 0;
2068 }
2069
2070 int cmd_sort(char *arg)
2071 {
2072     return cmd_sort_generic (arg, 0);
2073 }
2074
2075 int cmd_sort_newset (char *arg)
2076 {
2077     return cmd_sort_generic (arg, 1);
2078 }
2079
2080 int cmd_scan(char *arg)
2081 {
2082     if (!conn)
2083     {
2084                 try_reconnect();
2085                 
2086                 if (!conn) {                                                            
2087                         printf("Session not initialized yet\n");
2088                         return 0;
2089                 };
2090     }
2091     if (!ODR_MASK_GET(session->options, Z_Options_scan))
2092     {
2093         printf("Target doesn't support scan\n");
2094         return 0;
2095     }
2096     if (*arg)
2097     {
2098         strcpy (last_scan_query, arg);
2099         if (send_scanrequest(arg, 1, 20, 0) < 0)
2100             return 0;
2101     }
2102     else
2103     {
2104         if (send_scanrequest(last_scan_query, 1, 20, last_scan_line) < 0)
2105             return 0;
2106     }
2107     return 2;
2108 }
2109
2110 int cmd_schema(char *arg)
2111 {
2112     if (!arg || !*arg)
2113     {
2114         schema = VAL_NONE;
2115         return 1;
2116     }
2117     schema = oid_getvalbyname (arg);
2118     if (schema == VAL_NONE)
2119     {
2120         printf ("unknown schema\n");
2121         return 0;
2122     }
2123     return 1;
2124 }
2125
2126 int cmd_format(char *arg)
2127 {
2128     if (!arg || !*arg)
2129     {
2130         printf("Usage: format <recordsyntax>\n");
2131         return 0;
2132     }
2133     recordsyntax = oid_getvalbyname (arg);
2134     if (recordsyntax == VAL_NONE)
2135     {
2136         printf ("unknown record syntax\n");
2137         return 0;
2138     }
2139     return 1;
2140 }
2141
2142 int cmd_elements(char *arg)
2143 {
2144     static Z_ElementSetNames esn;
2145     static char what[100];
2146
2147     if (!arg || !*arg)
2148     {
2149         elementSetNames = 0;
2150         return 1;
2151     }
2152     strcpy(what, arg);
2153     esn.which = Z_ElementSetNames_generic;
2154     esn.u.generic = what;
2155     elementSetNames = &esn;
2156     return 1;
2157 }
2158
2159 int cmd_attributeset(char *arg)
2160 {
2161     char what[100];
2162
2163     if (!arg || !*arg)
2164     {
2165         printf("Usage: attributeset <setname>\n");
2166         return 0;
2167     }
2168     sscanf(arg, "%s", what);
2169     if (p_query_attset (what))
2170     {
2171         printf("Unknown attribute set name\n");
2172         return 0;
2173     }
2174     return 1;
2175 }
2176
2177 int cmd_querytype (char *arg)
2178 {
2179     if (!strcmp (arg, "ccl"))
2180         queryType = QueryType_CCL;
2181     else if (!strcmp (arg, "prefix") || !strcmp(arg, "rpn"))
2182         queryType = QueryType_Prefix;
2183     else if (!strcmp (arg, "ccl2rpn") || !strcmp (arg, "cclrpn"))
2184         queryType = QueryType_CCL2RPN;
2185     else
2186     {
2187         printf ("Querytype must be one of:\n");
2188         printf (" prefix         - Prefix query\n");
2189         printf (" ccl            - CCL query\n");
2190         printf (" ccl2rpn        - CCL query converted to RPN\n");
2191         return 0;
2192     }
2193     return 1;
2194 }
2195
2196 int cmd_refid (char *arg)
2197 {
2198     xfree (refid);
2199     refid = NULL;
2200     if (*arg)
2201     {
2202         refid = (char *) xmalloc (strlen(arg)+1);
2203         strcpy (refid, arg);
2204     }
2205     return 1;
2206 }
2207
2208 int cmd_close(char *arg)
2209 {
2210     Z_APDU *apdu;
2211     Z_Close *req;
2212     if (!conn)
2213         return 0;
2214
2215     apdu = zget_APDU(out, Z_APDU_close);
2216     req = apdu->u.close;
2217     *req->closeReason = Z_Close_finished;
2218     send_apdu(apdu);
2219     printf("Sent close request.\n");
2220     sent_close = 1;
2221     return 2;
2222 }
2223
2224 int cmd_packagename(char* arg)
2225 {
2226     xfree (esPackageName);
2227     esPackageName = NULL;
2228     if (*arg)
2229     {
2230         esPackageName = (char *) xmalloc (strlen(arg)+1);
2231         strcpy (esPackageName, arg);
2232     }
2233     return 1;
2234 }
2235
2236 int cmd_proxy(char* arg)
2237 {
2238     if (*arg == '\0') {
2239                 xfree (yazProxy);
2240                 yazProxy = NULL;
2241         
2242     }
2243     xfree (yazProxy);
2244     yazProxy = NULL;
2245     if (*arg)
2246     {
2247         yazProxy = (char *) xmalloc (strlen(arg)+1);
2248         strcpy (yazProxy, arg);
2249     } 
2250     return 1;
2251 }
2252
2253 int cmd_charset(char* arg)
2254 {
2255     char l1[30], l2[30];
2256
2257     *l1 = *l2 = 0;
2258     if (sscanf(arg, "%29s %29s", l1, l2) < 1)
2259     {
2260         printf("Current character set is `%s'\n", (yazCharset) ? yazCharset:NULL);
2261         return 1;
2262     }
2263     xfree (yazCharset);
2264     yazCharset = NULL;
2265     if (*l1)
2266         yazCharset = xstrdup(l1);
2267     if (*l2)
2268     {
2269         odr_set_charset (out, l1, l2);
2270         odr_set_charset (in, l2, l1);
2271     }
2272     return 1;
2273 }
2274
2275 int cmd_lang(char* arg)
2276 {
2277     if (*arg == '\0') {
2278         printf("Current language is `%s'\n", (yazLang)?yazLang:NULL);
2279         return 1;
2280     }
2281     xfree (yazLang);
2282     yazLang = NULL;
2283     if (*arg)
2284     {
2285         yazLang = (char *) xmalloc (strlen(arg)+1);
2286         strcpy (yazLang, arg);
2287     } 
2288     return 1;
2289 }
2290
2291 int cmd_source(char* arg) 
2292 {
2293     /* first should open the file and read one line at a time.. */
2294     FILE* includeFile;
2295     char line[1024], *cp;
2296
2297     {
2298         char* args_end=(arg)+strlen(arg)-1; 
2299         while(isspace(*args_end)) 
2300         {*args_end=0;
2301         --args_end;}; 
2302     }
2303
2304     REMOVE_TAILING_BLANKS(arg);
2305     
2306     if(strlen(arg)<1) {
2307         fprintf(stderr,"Error in source command use a filename\n");
2308         return -1;
2309     }
2310     
2311     includeFile = fopen (arg, "r");
2312     
2313     if(!includeFile) {
2314         fprintf(stderr,"Unable to open file %s for reading\n",arg);
2315         return -1;
2316     }
2317     
2318     while(!feof(includeFile)) {
2319         memset(line,0,sizeof(line));
2320         fgets(line,sizeof(line),includeFile);
2321         
2322         if(strlen(line) < 2) continue;
2323         if(line[0] == '#') continue;
2324         
2325         if ((cp = strrchr (line, '\n')))
2326             *cp = '\0';
2327         
2328         process_cmd_line(line);
2329     }
2330     
2331     if(fclose(includeFile)<0) {
2332         perror("unable to close include file");
2333         exit(1);
2334     }
2335     return 1;
2336 }
2337
2338 int cmd_subshell(char* args)
2339 {
2340     if(strlen(args)) 
2341         system(args);
2342     else 
2343         system(getenv("SHELL"));
2344     
2345     printf("\n");
2346     return 1;
2347 }
2348
2349 int cmd_set_apdufile(char* arg)
2350 {
2351     REMOVE_TAILING_BLANKS(arg);
2352   
2353     if(apdu_file && apdu_file != stderr) { /* don't close stdout*/
2354         perror("unable to close apdu log file");      
2355     }
2356     apdu_file=NULL;
2357   
2358     if(strlen(arg)<1) {
2359         return 1;
2360     }
2361   
2362     if(!strcmp(arg,"-")) 
2363         apdu_file=stderr;      
2364     else 
2365         apdu_file=fopen(arg, "a");
2366   
2367     if(!apdu_file) {
2368         perror("unable to open apdu log file no apdu log loaded");
2369     } else {
2370         odr_setprint(print, apdu_file); 
2371     }
2372   
2373     return 1;
2374 }
2375
2376 int cmd_set_cclfile(char* arg)
2377 {  
2378     FILE *inf;
2379
2380     REMOVE_TAILING_BLANKS(arg);
2381
2382     bibset = ccl_qual_mk (); 
2383     inf = fopen (arg, "r");
2384     if (inf)
2385     {
2386         ccl_qual_file (bibset, inf);
2387         fclose (inf);
2388     }
2389
2390         strcpy(ccl_fields,arg);
2391     return 0;
2392 }
2393
2394
2395 int cmd_set_auto_reconnect(char* arg)
2396 {  
2397         REMOVE_TAILING_BLANKS(arg);
2398
2399         if(strlen(arg)==0) {
2400                 auto_reconnect = ! auto_reconnect;
2401         } else if(strcmp(arg,"on")==0) {
2402                 auto_reconnect = 1;
2403         } else if(strcmp(arg,"off")==0) {
2404                 auto_reconnect = 0;             
2405         } else {
2406                 printf("Error use on or off\n");
2407                 return 1;
2408         };
2409
2410     if (auto_reconnect)
2411         printf("Set auto reconnect enabled.\n");
2412     else
2413         printf("Set auto reconnect disabled.\n");
2414
2415     return 0;
2416 }
2417
2418 int cmd_set_marcdump(char* arg)
2419 {
2420     if(marcdump && marcdump != stderr) { /* don't close stdout*/
2421         perror("unable to close apdu log file");      
2422     }
2423     marcdump=NULL;
2424     
2425     if(strlen(arg)<1) {
2426         return 1;
2427     }
2428   
2429     if(!strcmp(arg,"-")) 
2430         marcdump=stderr;      
2431     else 
2432         marcdump=fopen(arg, "a");
2433   
2434     if(!marcdump) {
2435         perror("unable to open apdu marcdump file no marcdump done\n");
2436     }
2437   
2438     return 1;
2439 }
2440
2441 int cmd_set_proxy(char* arg) {
2442     if(yazProxy) free(yazProxy);
2443     yazProxy=NULL;
2444
2445     if(strlen(arg) > 1) {
2446         yazProxy=strdup(arg);
2447     }
2448     return 1;
2449 }
2450
2451 /* 
2452    this command takes 3 arge {name class oid} 
2453  */
2454 int cmd_register_oid(char* args) {
2455     static struct {
2456         char* className;
2457         oid_class oclass;
2458     } oid_classes[] = {
2459         {"appctx",CLASS_APPCTX},
2460         {"absyn",CLASS_ABSYN},
2461         {"attset",CLASS_ATTSET},
2462         {"transyn",CLASS_TRANSYN},
2463         {"diagset",CLASS_DIAGSET},
2464         {"recsyn",CLASS_RECSYN},
2465         {"resform",CLASS_RESFORM},
2466         {"accform",CLASS_ACCFORM},
2467         {"extserv",CLASS_EXTSERV},
2468         {"userinfo",CLASS_USERINFO},
2469         {"elemspec",CLASS_ELEMSPEC},
2470         {"varset",CLASS_VARSET},
2471         {"schema",CLASS_SCHEMA},
2472         {"tagset",CLASS_TAGSET},
2473         {"general",CLASS_GENERAL},
2474         {0,0}
2475     };
2476     char oname_str[101], oclass_str[101], oid_str[101];  
2477     char* name;
2478     int i;
2479     oid_class oidclass = CLASS_GENERAL;
2480     int val = 0, oid[OID_SIZE];
2481     struct oident * new_oident=NULL;
2482     
2483     if (sscanf (args, "%100[^ ] %100[^ ] %100s",
2484                 oname_str,oclass_str, oid_str) < 1) {
2485         printf("Error in regristrate command \n");
2486         return 0;
2487     }
2488     
2489     for (i = 0; oid_classes[i].className; i++) {
2490         if (!strcmp(oid_classes[i].className, oclass_str))
2491         {
2492             oidclass=oid_classes[i].oclass;
2493             break;
2494         }
2495     }
2496     
2497     if(!(oid_classes[i].className)) {
2498         printf("Unknonwn oid class %s\n",oclass_str);
2499         return 0;
2500     }
2501
2502     i = 0;
2503     name = oid_str;
2504     val = 0;
2505     
2506     while (isdigit (*name))
2507     {
2508         val = val*10 + (*name - '0');
2509         name++;
2510         if (*name == '.')
2511         {
2512             if (i < OID_SIZE-1)
2513                 oid[i++] = val;
2514             val = 0;
2515             name++;
2516         }
2517     }
2518     oid[i] = val;
2519     oid[i+1] = -1;
2520     
2521     new_oident=oid_addent (oid,PROTO_GENERAL,oidclass,oname_str,VAL_DYNAMIC);  
2522     if(strcmp(new_oident->desc,oname_str)) {
2523         fprintf(stderr,"oid is already named as %s, regristration faild\n",
2524                 new_oident->desc);
2525     }
2526     return 1;  
2527 }
2528
2529 int cmd_push_command(char* arg) 
2530 {
2531 #if HAVE_READLINE_HISTORY_H
2532     if(strlen(arg)>1) 
2533         add_history(arg);
2534 #else 
2535     fprintf(stderr,"Not compiled with the readline/history module\n");
2536 #endif
2537     return 1;
2538 }
2539
2540 void source_rcfile() 
2541 {
2542     /*  Look for a $HOME/.yazclientrc and source it if it exists */
2543     struct stat statbuf;
2544     char buffer[1000];
2545     char* homedir=getenv("HOME");
2546
2547     if(!homedir) return;
2548     
2549     sprintf(buffer,"%s/.yazclientrc",homedir);
2550     
2551     if(stat(buffer,&statbuf)==0) {
2552         cmd_source(buffer);
2553     }
2554     
2555     if(stat(".yazclientrc",&statbuf)==0) {
2556         cmd_source(".yazclientrc");
2557     }
2558 }
2559
2560
2561 static void initialize(void)
2562 {
2563     FILE *inf;
2564         int i;
2565
2566     if (!(out = odr_createmem(ODR_ENCODE)) ||
2567         !(in = odr_createmem(ODR_DECODE)) ||
2568         !(print = odr_createmem(ODR_PRINT)))
2569     {
2570         fprintf(stderr, "failed to allocate ODR streams\n");
2571         exit(1);
2572     }
2573     oid_init();
2574
2575     setvbuf(stdout, 0, _IONBF, 0);
2576     if (apdu_file)
2577         odr_setprint(print, apdu_file);
2578
2579     bibset = ccl_qual_mk (); 
2580     inf = fopen (ccl_fields, "r");
2581     if (inf)
2582     {
2583         ccl_qual_file (bibset, inf);
2584         fclose (inf);
2585     }
2586     cmd_base("Default");
2587
2588 #if HAVE_READLINE_READLINE_H
2589     rl_attempted_completion_function = (CPPFunction*)readline_completer;
2590 #endif
2591
2592
2593         for(i=0; i<maxOtherInfosSupported; ++i) {
2594                 extraOtherInfos[i].oidval = -1;
2595         };
2596
2597         source_rcfile();
2598 }
2599
2600
2601 #if HAVE_GETTIMEOFDAY
2602 struct timeval tv_start, tv_end;
2603 #endif
2604
2605 void wait_and_handle_responce() 
2606 {
2607     
2608     int res;
2609     char *netbuffer= 0;
2610     int netbufferlen = 0;
2611     Z_APDU *apdu;
2612     
2613     
2614     if (conn)
2615     {
2616         do
2617         {
2618             if ((res = cs_get(conn, &netbuffer, &netbufferlen)) < 0)
2619             {
2620                 printf("Target closed connection\n");
2621                 close_session ();
2622                 break;
2623             }
2624             if (!res)
2625             {
2626                 printf("Target closed connection.\n");
2627                 close_session ();
2628                 break;
2629             }
2630             odr_reset(in); /* release APDU from last round */
2631             record_last = 0;
2632             odr_setbuf(in, netbuffer, res, 0);
2633             if (!z_APDU(in, &apdu, 0, 0))
2634             {
2635                 odr_perror(in, "Decoding incoming APDU");
2636                 fprintf(stderr, "[Near %d]\n", odr_offset(in));
2637                 fprintf(stderr, "Packet dump:\n---------\n");
2638                 odr_dumpBER(stderr, netbuffer, res);
2639                 fprintf(stderr, "---------\n");
2640                 if (apdu_file)
2641                     z_APDU(print, &apdu, 0, 0);
2642                 close_session ();
2643                 break;
2644             }
2645             if (apdu_file && !z_APDU(print, &apdu, 0, 0))
2646             {
2647                 odr_perror(print, "Failed to print incoming APDU");
2648                 odr_reset(print);
2649                 continue;
2650             }
2651             switch(apdu->which)
2652             {
2653             case Z_APDU_initResponse:
2654                 process_initResponse(apdu->u.initResponse);
2655                 break;
2656             case Z_APDU_searchResponse:
2657                 process_searchResponse(apdu->u.searchResponse);
2658                 break;
2659             case Z_APDU_scanResponse:
2660                 process_scanResponse(apdu->u.scanResponse);
2661                 break;
2662             case Z_APDU_presentResponse:
2663                 print_refid (apdu->u.presentResponse->referenceId);
2664                 setno +=
2665                     *apdu->u.presentResponse->numberOfRecordsReturned;
2666                 if (apdu->u.presentResponse->records)
2667                     display_records(apdu->u.presentResponse->records);
2668                 else
2669                     printf("No records.\n");
2670                 printf ("nextResultSetPosition = %d\n",
2671                         *apdu->u.presentResponse->nextResultSetPosition);
2672                 break;
2673             case Z_APDU_sortResponse:
2674                 process_sortResponse(apdu->u.sortResponse);
2675                 break;
2676             case Z_APDU_extendedServicesResponse:
2677                 printf("Got extended services response\n");
2678                 process_ESResponse(apdu->u.extendedServicesResponse);
2679                 break;
2680             case Z_APDU_close:
2681                 printf("Target has closed the association.\n");
2682                 process_close(apdu->u.close);
2683                 break;
2684             case Z_APDU_resourceControlRequest:
2685                 process_resourceControlRequest
2686                     (apdu->u.resourceControlRequest);
2687                 break;
2688             case Z_APDU_deleteResultSetResponse:
2689                 process_deleteResultSetResponse(apdu->u.
2690                                                 deleteResultSetResponse);
2691                 break;
2692             default:
2693                 printf("Received unknown APDU type (%d).\n", 
2694                        apdu->which);
2695                 close_session ();
2696             }
2697         }
2698         while (conn && cs_more(conn));
2699 #if HAVE_GETTIMEOFDAY
2700         gettimeofday (&tv_end, 0);
2701 #if 0
2702         printf ("S/U S/U=%ld/%ld %ld/%ld",
2703                 (long) tv_start.tv_sec,
2704                 (long) tv_start.tv_usec,
2705                 (long) tv_end.tv_sec,
2706                 (long) tv_end.tv_usec);
2707 #endif
2708         printf ("Elapsed: %.6f\n",
2709                 (double) tv_end.tv_usec / 1e6 + tv_end.tv_sec -
2710                 ((double) tv_start.tv_usec / 1e6 + tv_start.tv_sec));
2711 #endif
2712     }
2713     xfree (netbuffer);
2714 }
2715
2716
2717 int cmd_cclparse(char* arg) 
2718 {
2719     int error, pos;
2720         struct ccl_rpn_node *rpn=NULL;
2721         
2722         
2723         rpn = ccl_find_str (bibset, arg, &error, &pos);
2724         
2725         if (error) {
2726                 printf ("%*s^ - ", 3+strlen(last_cmd)+1+pos, " ");
2727                 printf ("%s\n", ccl_err_msg (error));
2728         }
2729         else
2730         {
2731                 if (rpn)
2732                 {       
2733                         ccl_pr_tree(rpn, stdout); 
2734                 }
2735         }
2736         if (rpn)
2737                 ccl_rpn_delete(rpn);
2738
2739     printf ("\n");
2740         
2741         return 0;
2742 };
2743
2744
2745 int cmd_set_otherinfo(char* args)
2746 {
2747         char oid[101], otherinfoString[101];
2748         int otherinfoNo;
2749         int sscan_res;
2750         int oidval;
2751         
2752         sscan_res = sscanf (args, "%d %100[^ ] %100s", &otherinfoNo, oid, otherinfoString);
2753         if(sscan_res==1) {
2754                 /* reset this otherinfo */
2755                 if(otherinfoNo>=maxOtherInfosSupported) {
2756                         printf("Error otherinfo index to large (%d>%d)\n",otherinfoNo,maxOtherInfosSupported);
2757                 };
2758                 extraOtherInfos[otherinfoNo].oidval = -1;
2759                 if(extraOtherInfos[otherinfoNo].value) free(extraOtherInfos[otherinfoNo].value);                        
2760                 return 0;
2761         };
2762         if (sscan_res<3) {
2763         printf("Error in set_otherinfo command \n");
2764         return 0;
2765     }
2766
2767         if(otherinfoNo>=maxOtherInfosSupported) {
2768                 printf("Error otherinfo index to large (%d>%d)\n",otherinfoNo,maxOtherInfosSupported);
2769         };
2770
2771         
2772         oidval = oid_getvalbyname (oid);
2773         if(oidval == -1 ) {
2774         printf("Error in set_otherinfo command unknown oid %s \n",oid);
2775                 return 0;
2776         };
2777         extraOtherInfos[otherinfoNo].oidval = oidval;
2778         if(extraOtherInfos[otherinfoNo].value) free(extraOtherInfos[otherinfoNo].value);
2779         extraOtherInfos[otherinfoNo].value = strdup(otherinfoString);
2780         
2781         return 0;
2782 };
2783
2784 int cmd_list_otherinfo(char* args)
2785 {
2786         int i;     
2787
2788         if(strlen(args)>0) {
2789                 i = atoi(args);
2790                 if( i >= maxOtherInfosSupported ) {
2791                         printf("Error otherinfo index to large (%d>%d)\n",i,maxOtherInfosSupported);
2792                         return 0;
2793                 };
2794
2795                 if(extraOtherInfos[i].oidval != -1) 
2796                         printf("  otherinfo %d %s %s\n",i,yaz_z3950_oid_value_to_str(extraOtherInfos[i].oidval,CLASS_RECSYN), extraOtherInfos[i].value);
2797                 
2798         } else {                
2799                 for(i=0; i<maxOtherInfosSupported; ++i) {
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                 
2804         }
2805         return 0;
2806 };
2807
2808
2809 int cmd_list_all(char* args) {
2810         int i;
2811
2812         /* connection options */
2813         if(conn) {
2814                 printf("Connected to         : %s\n",last_open_command);
2815         } else {
2816                 if(last_open_command) 
2817                         printf("Not connected to     : %s\n",last_open_command);
2818                 else 
2819                         printf("Not connected        : \n");
2820
2821         };
2822         if(yazProxy) printf("using proxy          : %s\n",yazProxy);            
2823
2824         printf("auto_reconnect       : %s\n",auto_reconnect?"on":"off");
2825
2826         if (!auth) {
2827                 printf("Authentication       : none\n");
2828         } else {
2829                 switch(auth->which) {
2830                 case Z_IdAuthentication_idPass:
2831                         printf("Authentication       : IdPass\n"); 
2832                         printf("    Login User       : %s\n",auth->u.idPass->userId?auth->u.idPass->userId:"");
2833                         printf("    Login Group      : %s\n",auth->u.idPass->groupId?auth->u.idPass->groupId:"");
2834                         printf("    Password         : %s\n",auth->u.idPass->password?auth->u.idPass->password:"");
2835                         break;
2836                 case Z_IdAuthentication_open:
2837                         printf("Authentication       : psOpen\n");                      
2838                         printf("    Open string      : %s\n",auth->u.open);     
2839                         break;
2840                 default:
2841                         printf("Authentication       : Unknown\n");
2842                 };
2843         };
2844         if ( yazCharset ) printf("Character set        : `%s'\n", (yazCharset) ? yazCharset:NULL);
2845                 
2846         /* bases */
2847         printf("Bases                : ");
2848     for (i = 0; i<num_databaseNames; i++) printf("%s ",databaseNames[i]);
2849         printf("\n");
2850         
2851         /* Query options */
2852         printf("CCL file             : %s\n",ccl_fields);
2853         printf("Query type           : %s\n",query_type_as_string(queryType));
2854         
2855         printf("Named Result Sets    : %s\n",setnumber==-1?"off":"on");
2856
2857         /* piggy back options */
2858         printf("ssub/lslb/mspn       : %d/%d/%d\n",smallSetUpperBound,largeSetLowerBound,mediumSetPresentNumber);
2859         
2860         /* print present related options */
2861         printf("Format               : %s\n",yaz_z3950_oid_value_to_str(recordsyntax,CLASS_RECSYN));
2862         printf("Schema               : %s\n",yaz_z3950_oid_value_to_str(schema,CLASS_SCHEMA));
2863         printf("Elements             : %s\n",elementSetNames?elementSetNames->u.generic:"");
2864
2865         /* loging options */
2866         printf("APDU log             : %s\n",apdu_file?"on":"off");
2867         printf("Record log           : %s\n",marcdump?"on":"off");
2868         
2869         /* other infos */
2870         printf("Other Info: \n");
2871         cmd_list_otherinfo("");
2872
2873         return 0;
2874 };
2875
2876 int cmd_clear_otherinfo(char* args) 
2877 {
2878         if(strlen(args)>0) {
2879                 int otherinfoNo;
2880                 otherinfoNo = atoi(args);
2881                 if( otherinfoNo >= maxOtherInfosSupported ) {
2882                         printf("Error otherinfo index to large (%d>%d)\n",otherinfoNo,maxOtherInfosSupported);
2883                         return 0;
2884                 };
2885                 
2886                 if(extraOtherInfos[otherinfoNo].oidval != -1) {                 
2887                         /* only clear if set. */
2888                         extraOtherInfos[otherinfoNo].oidval=-1;
2889                         free(extraOtherInfos[otherinfoNo].value);
2890                 }; 
2891         } else {
2892                 int i;
2893         
2894                 for(i=0; i<maxOtherInfosSupported; ++i) {
2895                         if (extraOtherInfos[i].oidval!=-1 ) {                           
2896                                 extraOtherInfos[i].oidval=-1;
2897                                 free(extraOtherInfos[i].value);
2898                         };
2899                 };
2900         };
2901         return 0;
2902 };
2903
2904 static int cmd_help (char *line);
2905
2906 typedef char *(*completerFunctionType)(const char *text, int state);
2907
2908 static struct {
2909     char *cmd;
2910     int (*fun)(char *arg);
2911     char *ad;
2912         completerFunctionType rl_completerfunction;
2913     int complete_filenames;
2914         char **local_tabcompletes;
2915 } cmd[] = {
2916     {"open", cmd_open, "('tcp'|'ssl')':<host>[':'<port>][/<db>]",NULL,0,NULL},
2917     {"quit", cmd_quit, "",NULL,0,NULL},
2918     {"find", cmd_find, "<query>",NULL,0,NULL},
2919     {"delete", cmd_delete, "<setname>",NULL,0,NULL},
2920     {"base", cmd_base, "<base-name>",NULL,0,NULL},
2921     {"show", cmd_show, "<rec#>['+'<#recs>['+'<setname>]]",NULL,0,NULL},
2922     {"scan", cmd_scan, "<term>",NULL,0,NULL},
2923     {"sort", cmd_sort, "<sortkey> <flag> <sortkey> <flag> ...",NULL,0,NULL},
2924     {"sort+", cmd_sort_newset, "<sortkey> <flag> <sortkey> <flag> ...",NULL,0,NULL},
2925     {"authentication", cmd_authentication, "<acctstring>",NULL,0,NULL},
2926     {"lslb", cmd_lslb, "<largeSetLowerBound>",NULL,0,NULL},
2927     {"ssub", cmd_ssub, "<smallSetUpperBound>",NULL,0,NULL},
2928     {"mspn", cmd_mspn, "<mediumSetPresentNumber>",NULL,0,NULL},
2929     {"status", cmd_status, "",NULL,0,NULL},
2930     {"setnames", cmd_setnames, "",NULL,0,NULL},
2931     {"cancel", cmd_cancel, "",NULL,0,NULL},
2932     {"format", cmd_format, "<recordsyntax>",complete_format,0,NULL},
2933     {"schema", cmd_schema, "<schema>",complete_schema,0,NULL},
2934     {"elements", cmd_elements, "<elementSetName>",NULL,0,NULL},
2935     {"close", cmd_close, "",NULL,0,NULL},
2936     {"attributeset", cmd_attributeset, "<attrset>",complete_attributeset,0,NULL},
2937     {"querytype", cmd_querytype, "<type>",complete_querytype,0,NULL},
2938     {"refid", cmd_refid, "<id>",NULL,0,NULL},
2939     {"itemorder", cmd_itemorder, "ill|item <itemno>",NULL,0,NULL},
2940     {"update", cmd_update, "<item>",NULL,0,NULL},
2941     {"packagename", cmd_packagename, "<packagename>",NULL,0,NULL},
2942     {"proxy", cmd_proxy, "[('tcp'|'ssl')]<host>[':'<port>]",NULL,0,NULL},
2943     {"charset", cmd_charset, "<charset_name>",NULL,0,NULL},
2944     {"lang", cmd_lang, "<language_code>",NULL,0,NULL},
2945     {".", cmd_source, "<filename>",NULL,1,NULL},
2946     {"!", cmd_subshell, "Subshell command",NULL,1,NULL},
2947     {"set_apdufile", cmd_set_apdufile, "<filename>",NULL,1,NULL},
2948     {"set_marcdump", cmd_set_marcdump," <filename>",NULL,1,NULL},
2949     {"set_cclfile", cmd_set_cclfile," <filename>",NULL,1,NULL},
2950     {"set_auto_reconnect", cmd_set_auto_reconnect," on|off",complete_auto_reconnect,1,NULL},
2951         {"set_otherinfo", cmd_set_otherinfo,"<otherinfoinddex> <oid> <string>",NULL,0,NULL},
2952     {"register_oid", cmd_register_oid,"<name> <class> <oid>",NULL,0,NULL},
2953     {"push_command", cmd_push_command,"<command>",command_generator,0,NULL},
2954         {"register_tab", cmd_register_tab,"<commandname> <tab>",command_generator,0,NULL},
2955         {"cclparse", cmd_cclparse,"<ccl find command>",NULL,0,NULL},
2956         {"list_otherinfo",cmd_list_otherinfo,"[otherinfoinddex]",NULL,0,NULL},
2957         {"list_all",cmd_list_all,"",NULL,0,NULL},
2958         {"clear_otherinfo",cmd_clear_otherinfo,"",NULL,0,NULL},
2959     /* Server Admin Functions */
2960     {"adm-reindex", cmd_adm_reindex, "<database-name>",NULL,0,NULL},
2961     {"adm-truncate", cmd_adm_truncate, "('database'|'index')<object-name>",NULL,0,NULL},
2962     {"adm-create", cmd_adm_create, "",NULL,0,NULL},
2963     {"adm-drop", cmd_adm_drop, "('database'|'index')<object-name>",NULL,0,NULL},
2964     {"adm-import", cmd_adm_import, "<record-type> <dir> <pattern>",NULL,0,NULL},
2965     {"adm-refresh", cmd_adm_refresh, "",NULL,0,NULL},
2966     {"adm-commit", cmd_adm_commit, "",NULL,0,NULL},
2967     {"adm-shutdown", cmd_adm_shutdown, "",NULL,0,NULL},
2968     {"adm-startup", cmd_adm_startup, "",NULL,0,NULL},
2969     {"help", cmd_help, "", NULL,0,NULL},
2970     {0,0,0,0,0,0}
2971 };
2972
2973 static int cmd_help (char *line)
2974 {
2975     int i;
2976     char topic[21];
2977     
2978     *topic = 0;
2979     sscanf (line, "%20s", topic);
2980
2981     if (*topic == 0)
2982         printf("Commands:\n");
2983     for (i = 0; cmd[i].cmd; i++)
2984         if (*topic == 0 || strcmp (topic, cmd[i].cmd) == 0)
2985             printf("   %s %s\n", cmd[i].cmd, cmd[i].ad);
2986     if (strcmp (topic, "find") == 0)
2987     {
2988         printf ("RPN:\n");
2989         printf (" \"term\"                        Simple Term\n");
2990         printf (" @attr [attset] type=value op  Attribute\n");
2991         printf (" @and opl opr                  And\n");
2992         printf (" @or opl opr                   Or\n");
2993         printf (" @not opl opr                  And-Not\n");
2994         printf (" @set set                      Result set\n");
2995         printf ("\n");
2996         printf ("Bib-1 attribute types\n");
2997         printf ("1=Use:         ");
2998         printf ("4=Title 7=ISBN 8=ISSN 30=Date 62=Abstract 1003=Author 1016=Any\n");
2999         printf ("2=Relation:    ");
3000         printf ("1<   2<=  3=  4>=  5>  6!=  102=Relevance\n");
3001         printf ("3=Position:    ");
3002         printf ("1=First in Field  2=First in subfield  3=Any position\n");
3003         printf ("4=Structure:   ");
3004         printf ("1=Phrase  2=Word  3=Key  4=Year  5=Date  6=WordList\n");
3005         printf ("5=Truncation:  ");
3006         printf ("1=Right  2=Left  3=L&R  100=No  101=#  102=Re-1  103=Re-2\n");
3007         printf ("6=Completeness:");
3008         printf ("1=Incomplete subfield  2=Complete subfield  3=Complete field\n");
3009     }
3010     return 1;
3011 }
3012
3013 int cmd_register_tab(char* arg) {
3014         
3015         char command[101], tabargument[101];
3016         int i;
3017         int num_of_tabs;
3018         char** tabslist;
3019
3020         if (sscanf (arg, "%100s %100s", command, tabargument) < 1) {
3021                 return 0;
3022         };
3023
3024         /* locate the amdn in the list */
3025         for (i = 0; cmd[i].cmd; i++) {
3026                 if (!strncmp(cmd[i].cmd, command, strlen(command))) {
3027                         break;
3028                 }
3029         }
3030         
3031         if(!cmd[i].cmd) { 
3032                 fprintf(stderr,"Unknown command %s\n",command);
3033                 return 1;
3034         };
3035         
3036
3037
3038         if(!cmd[i].local_tabcompletes) {
3039                 cmd[i].local_tabcompletes = calloc(1,sizeof(char**));
3040         };
3041         
3042         num_of_tabs=0;          
3043         
3044         tabslist = cmd[i].local_tabcompletes;
3045         for(;tabslist && *tabslist;tabslist++) {
3046                 num_of_tabs++;
3047         };  
3048
3049         cmd[i].local_tabcompletes=realloc(cmd[i].local_tabcompletes,(num_of_tabs+2)*sizeof(char**));
3050         tabslist=cmd[i].local_tabcompletes;
3051         tabslist[num_of_tabs]=strdup(tabargument);
3052         tabslist[num_of_tabs+1]=NULL;
3053     return 1;
3054 }
3055
3056
3057 void process_cmd_line(char* line)
3058 {  
3059     int i,res;
3060     char word[32], arg[1024];
3061     
3062 #if HAVE_GETTIMEOFDAY
3063     gettimeofday (&tv_start, 0);
3064 #endif
3065     
3066     if ((res = sscanf(line, "%31s %1023[^;]", word, arg)) <= 0)
3067     {
3068         strcpy(word, last_cmd);
3069         *arg = '\0';
3070     }
3071     else if (res == 1)
3072         *arg = 0;
3073     strcpy(last_cmd, word);
3074     
3075     /* removed tailing spaces from the arg command */
3076     { 
3077         char* p;
3078         char* lastnonspace=NULL;
3079         p = arg;
3080         
3081         for(;*p; ++p) {
3082             if(!isspace(*p)) {
3083                 lastnonspace = p;
3084             }
3085         }
3086         if(lastnonspace) 
3087             *(++lastnonspace) = 0;
3088     }
3089     
3090
3091     for (i = 0; cmd[i].cmd; i++)
3092         if (!strncmp(cmd[i].cmd, word, strlen(word)))
3093         {
3094             res = (*cmd[i].fun)(arg);
3095             break;
3096         }
3097
3098     if (!cmd[i].cmd) /* dump our help-screen */
3099     {
3100         printf("Unknown command: %s.\n", word);
3101         printf("use help for list of commands\n");
3102         /* cmd_help (""); */
3103         res = 1;
3104     }
3105
3106     if(apdu_file) fflush(apdu_file);
3107     
3108     if (res >= 2)
3109         wait_and_handle_responce();
3110
3111     if(apdu_file)
3112         fflush(apdu_file);
3113     if(marcdump)
3114         fflush(marcdump);
3115 }
3116
3117
3118 char *command_generator(const char *text, int state) 
3119 {
3120     static int idx; 
3121     if (state==0) {
3122         idx = 0;
3123     }
3124     for( ; cmd[idx].cmd; ++idx) {
3125         if (!strncmp(cmd[idx].cmd,text,strlen(text))) {
3126             ++idx;  /* skip this entry on the next run */
3127             return strdup(cmd[idx-1].cmd);
3128         }
3129     }
3130     return NULL;
3131 }
3132
3133
3134 /* 
3135    This function only known how to complete on the first word
3136 */
3137 char ** readline_completer(char *text, int start, int end) {
3138 #if HAVE_READLINE_READLINE_H
3139
3140         completerFunctionType completerToUse;
3141         
3142     if(start == 0) {
3143 #if HAVE_READLINE_RL_COMPLETION_MATCHES
3144         char** res=rl_completion_matches(text,
3145                                       command_generator); 
3146 #else
3147         char** res=completion_matches(text,
3148                                       (CPFunction*)command_generator); 
3149 #endif
3150         rl_attempted_completion_over = 1;
3151         return res;
3152     } else {
3153         char arg[1024],word[32];
3154         int i=0 ,res;
3155         if ((res = sscanf(rl_line_buffer, "%31s %1023[^;]", word, arg)) <= 0) {     
3156             rl_attempted_completion_over = 1;
3157             return NULL;
3158         }
3159     
3160         for (i = 0; cmd[i].cmd; i++) {
3161             if (!strncmp(cmd[i].cmd, word, strlen(word))) {
3162                 break;
3163             }
3164         }
3165     
3166                 if(!cmd[i].cmd) return NULL;
3167
3168
3169                 curret_global_list = cmd[i].local_tabcompletes;
3170                 
3171                 completerToUse = cmd[i].rl_completerfunction;
3172                 if(completerToUse==NULL)  /* if no pr. command completer is defined use the default completer */
3173                         completerToUse = default_completer;
3174                 
3175         if(completerToUse) {
3176 #ifdef HAVE_READLINE_RL_COMPLETION_MATCHES
3177             char** res=
3178                 rl_completion_matches(text,
3179                                    completerToUse);
3180 #else
3181             char** res=
3182                 completion_matches(text,
3183                                    (CPFunction*)completerToUse);
3184 #endif
3185                         if(!cmd[i].complete_filenames) 
3186                                 rl_attempted_completion_over = 1;
3187                         return res;
3188         } else {
3189                         if(!cmd[i].complete_filenames) 
3190                                 rl_attempted_completion_over = 1;
3191             return 0;
3192         }
3193     }
3194 #else 
3195     return 0;
3196 #endif 
3197 }
3198
3199
3200 static void client(void)
3201 {
3202     char line[1024];
3203
3204     line[1023] = '\0';
3205
3206 #if HAVE_GETTIMEOFDAY
3207     gettimeofday (&tv_start, 0);
3208 #endif
3209
3210     while (1)
3211     {
3212         char *line_in = NULL;
3213 #if HAVE_READLINE_READLINE_H
3214         if (isatty(0))
3215         {
3216             line_in=readline(C_PROMPT);
3217             if (!line_in)
3218                 break;
3219 #if HAVE_READLINE_HISTORY_H
3220             if (*line_in)
3221                 add_history(line_in);
3222 #endif
3223             strncpy(line, line_in, 1023);
3224             free (line_in);
3225         }
3226 #endif 
3227         if (!line_in)
3228         {
3229             char *end_p;
3230             printf (C_PROMPT);
3231             fflush(stdout);
3232             if (!fgets(line, 1023, stdin))
3233                 break;
3234             if ((end_p = strchr (line, '\n')))
3235                 *end_p = '\0';
3236         }
3237         process_cmd_line(line);
3238     }
3239 }
3240
3241 int main(int argc, char **argv)
3242 {
3243     char *prog = *argv;
3244     char *open_command = 0;
3245     char *auth_command = 0;
3246     char *arg;
3247     int ret;
3248     
3249     while ((ret = options("k:c:a:m:v:p:u:", argv, argc, &arg)) != -2)
3250     {
3251         switch (ret)
3252         {
3253         case 0:
3254             if (!open_command)
3255             {
3256                 open_command = (char *) xmalloc (strlen(arg)+6);
3257                 strcpy (open_command, "open ");
3258                 strcat (open_command, arg);
3259             }
3260             break;
3261         case 'k':
3262             kilobytes = atoi(arg);
3263             break;
3264         case 'm':
3265             if (!(marcdump = fopen (arg, "a")))
3266             {
3267                 perror (arg);
3268                 exit (1);
3269             }
3270             break;
3271                 case 'c':
3272                         strncpy (ccl_fields, arg, sizeof(ccl_fields)-1);
3273                         ccl_fields[sizeof(ccl_fields)-1] = '\0';
3274                         break;
3275         case 'a':
3276             if (!strcmp(arg, "-"))
3277                 apdu_file=stderr;
3278             else
3279                 apdu_file=fopen(arg, "a");
3280             break;
3281                 case 'p':
3282                         yazProxy=strdup(arg);
3283                         break;
3284         case 'u':
3285             if (!auth_command)
3286             {
3287                 auth_command = (char *) xmalloc (strlen(arg)+6);
3288                 strcpy (auth_command, "auth ");
3289                 strcat (auth_command, arg);
3290             }
3291             break;
3292         case 'v':
3293             yaz_log_init (yaz_log_mask_str(arg), "", NULL);
3294             break;
3295         default:
3296             fprintf (stderr, "Usage: %s [-m <marclog>] [ -a <apdulog>] "
3297                      "[-c cclfields]\n      [-p <proxy-addr>] [-u <auth>] "
3298                      "[-k size] [<server-addr>]\n",
3299                      prog);
3300             exit (1);
3301         }      
3302     }
3303     initialize();
3304     if (auth_command)
3305     {
3306 #ifdef HAVE_GETTIMEOFDAY
3307         gettimeofday (&tv_start, 0);
3308 #endif
3309         process_cmd_line (auth_command);
3310 #if HAVE_READLINE_HISTORY_H
3311         add_history(auth_command);
3312 #endif
3313         xfree(auth_command);
3314     }
3315     if (open_command)
3316     {
3317 #ifdef HAVE_GETTIMEOFDAY
3318         gettimeofday (&tv_start, 0);
3319 #endif
3320         process_cmd_line (open_command);
3321 #if HAVE_READLINE_HISTORY_H
3322         add_history(open_command);
3323 #endif
3324         xfree(open_command);
3325     }
3326     client ();
3327     exit (0);
3328 }
3329
3330
3331 /*
3332  * Local variables:
3333  * tab-width: 4
3334  * c-basic-offset: 4
3335  * End:
3336  */