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