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