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