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