2 * Copyright (C) 1995-2007, Index Data ApS
3 * See the file LICENSE for details.
5 * $Id: client.c,v 1.334 2007-04-16 21:53:08 adam Exp $
8 * \brief yaz-client program
20 #include <sys/types.h>
38 #if HAVE_OPENSSL_SSL_H
39 #include <openssl/bio.h>
40 #include <openssl/crypto.h>
41 #include <openssl/x509.h>
42 #include <openssl/pem.h>
43 #include <openssl/ssl.h>
44 #include <openssl/err.h>
51 #define S_ISREG(x) (x & _S_IFREG)
52 #define S_ISDIR(x) (x & _S_IFDIR)
55 #include <yaz/yaz-util.h>
57 #include <yaz/comstack.h>
59 #include <yaz/oid_db.h>
61 #include <yaz/proto.h>
62 #include <yaz/marcdisp.h>
63 #include <yaz/diagbib1.h>
64 #include <yaz/otherinfo.h>
65 #include <yaz/charneg.h>
67 #include <yaz/pquery.h>
68 #include <yaz/sortspec.h>
72 #include <yaz/yaz-ccl.h>
76 #if HAVE_READLINE_READLINE_H
77 #include <readline/readline.h>
79 #if HAVE_READLINE_HISTORY_H
80 #include <readline/history.h>
85 #include "tabcomplete.h"
88 #define C_PROMPT "Z> "
90 static file_history_t file_history = 0;
92 static char *sru_method = "soap";
93 static char *codeset = 0; /* character set for output */
94 static int hex_dump = 0;
95 static char *dump_file_prefix = 0;
96 static ODR out, in, print; /* encoding and decoding streams */
98 static ODR srw_sr_odr_out = 0;
99 static Z_SRW_PDU *srw_sr = 0;
101 static FILE *apdu_file = 0;
102 static FILE *ber_file = 0;
103 static COMSTACK conn = 0; /* our z-association */
104 static Z_IdAuthentication *auth = 0; /* our current auth definition */
105 char *databaseNames[128];
106 int num_databaseNames = 0;
107 static Z_External *record_last = 0;
108 static int setnumber = -1; /* current result set number */
109 static int smallSetUpperBound = 0;
110 static int largeSetLowerBound = 1;
111 static int mediumSetPresentNumber = 0;
112 static Z_ElementSetNames *elementSetNames = 0;
113 static int setno = 1; /* current set offset */
114 static enum oid_proto protocol = PROTO_Z3950; /* current app protocol */
115 #define RECORDSYNTAX_MAX 20
116 static char *recordsyntax_list[RECORDSYNTAX_MAX];
117 static int recordsyntax_size = 0;
119 static char *record_schema = 0;
120 static int sent_close = 0;
121 static NMEM session_mem = NULL; /* memory handle for init-response */
122 static Z_InitResponse *session_initResponse = 0; /* session parameters */
123 static char last_scan_line[512] = "0";
124 static char last_scan_query[512] = "0";
125 static char ccl_fields[512] = "default.bib";
126 /* ### How can I set this path to use wherever YAZ is installed? */
127 static char cql_fields[512] = "/usr/local/share/yaz/etc/pqf.properties";
128 static char *esPackageName = 0;
129 static char *yazProxy = 0;
130 static int kilobytes = 1024;
131 static char *negotiationCharset = 0;
132 static int negotiationCharsetRecords = 1;
133 static int negotiationCharsetVersion = 3;
134 static char *outputCharset = 0;
135 static char *marcCharset = 0;
136 static char* yazLang = 0;
138 static char last_cmd[32] = "?";
139 static FILE *marc_file = 0;
140 static char *refid = NULL;
141 static char *last_open_command = NULL;
142 static int auto_reconnect = 0;
143 static int auto_wait = 1;
144 static Odr_bitmask z3950_options;
145 static int z3950_version = 3;
146 static int scan_stepSize = 0;
147 static int scan_position = 1;
148 static int scan_size = 20;
149 static char cur_host[200];
150 static int last_hit_count = 0;
160 static QueryType queryType = QueryType_Prefix;
162 static CCL_bibset bibset; /* CCL bibset handle */
163 static cql_transform_t cqltrans = 0; /* CQL context-set handle */
165 #if HAVE_READLINE_COMPLETION_OVER
168 /* readline doesn't have this var. Define it ourselves. */
169 int rl_attempted_completion_over = 0;
172 /* set this one to 1, to avoid decode of unknown MARCs */
173 #define AVOID_MARC_DECODE 1
175 #define maxOtherInfosSupported 10
179 } extraOtherInfos[maxOtherInfosSupported];
181 void process_cmd_line(char* line);
182 #if HAVE_READLINE_READLINE_H
183 char **readline_completer(char *text, int start, int end);
185 static char *command_generator(const char *text, int state);
186 int cmd_register_tab(const char* arg);
188 static void close_session (void);
190 ODR getODROutputStream(void)
195 const char* query_type_as_string(QueryType q)
198 case QueryType_Prefix: return "prefix (RPN sent to server)";
199 case QueryType_CCL: return "CCL (CCL sent to server) ";
200 case QueryType_CCL2RPN: return "CCL -> RPN (RPN sent to server)";
201 case QueryType_CQL: return "CQL (CQL sent to server)";
202 case QueryType_CQL2RPN: return "CQL -> RPN (RPN sent to server)";
204 return "unknown Query type internal yaz-client error";
208 static void do_hex_dump(const char* buf, int len)
213 for( i=0; i<len ; i=i+16 )
216 for(x=0 ; i+x<len && x<16; ++x)
218 printf("%2.2X ",(unsigned int)((unsigned char)buf[i+x]));
223 if (dump_file_prefix)
226 if (++no < 1000 && strlen(dump_file_prefix) < 500)
230 sprintf (fname, "%s.%03d.raw", dump_file_prefix, no);
231 of = fopen(fname, "wb");
233 fwrite (buf, 1, len, of);
240 void add_otherInfos(Z_APDU *a)
242 Z_OtherInformation **oi;
246 for(i=0; i<maxOtherInfosSupported; ++i)
248 if (oid_oidlen(extraOtherInfos[i].oid) > 0)
249 yaz_oi_set_string_oid(oi, out, extraOtherInfos[i].oid,
250 1, extraOtherInfos[i].value);
254 int send_apdu(Z_APDU *a)
263 z_APDU(print, &a, 0, 0);
266 if (!z_APDU(out, &a, 0, 0))
268 odr_perror(out, "Encoding APDU");
272 buf = odr_getbuf(out, &len, 0);
274 odr_dumpBER(ber_file, buf, len);
275 /* printf ("sending APDU of size %d\n", len); */
276 do_hex_dump(buf, len);
277 if (cs_put(conn, buf, len) < 0)
279 fprintf(stderr, "cs_put: %s", cs_errmsg(cs_errno(conn)));
283 odr_reset(out); /* release the APDU structure */
287 static void print_stringn(const unsigned char *buf, size_t len)
290 for (i = 0; i<len; i++)
291 if ((buf[i] <= 126 && buf[i] >= 32) || strchr ("\n\r\t\f", buf[i]))
292 printf ("%c", buf[i]);
294 printf ("\\X%02X", buf[i]);
297 static void print_refid (Z_ReferenceId *id)
301 printf ("Reference Id: ");
302 print_stringn (id->buf, id->len);
307 static Z_ReferenceId *set_refid (ODR out)
312 id = (Z_ReferenceId *) odr_malloc (out, sizeof(*id));
313 id->size = id->len = strlen(refid);
314 id->buf = (unsigned char *) odr_malloc (out, id->len);
315 memcpy (id->buf, refid, id->len);
319 /* INIT SERVICE ------------------------------- */
321 static void send_initRequest(const char* type_and_host)
323 Z_APDU *apdu = zget_APDU(out, Z_APDU_initRequest);
324 Z_InitRequest *req = apdu->u.initRequest;
327 req->options = &z3950_options;
329 ODR_MASK_ZERO(req->protocolVersion);
330 for (i = 0; i<z3950_version; i++)
331 ODR_MASK_SET(req->protocolVersion, i);
333 *req->maximumRecordSize = 1024*kilobytes;
334 *req->preferredMessageSize = 1024*kilobytes;
336 req->idAuthentication = auth;
338 req->referenceId = set_refid (out);
340 if (yazProxy && type_and_host)
342 yaz_oi_set_string_oid(&req->otherInfo, out, yaz_oid_userinfo_proxy,
346 if (negotiationCharset || yazLang) {
347 Z_OtherInformation **p;
348 Z_OtherInformationUnit *p0;
350 yaz_oi_APDU(apdu, &p);
352 if ((p0=yaz_oi_update(p, out, NULL, 0, 0))) {
353 ODR_MASK_SET(req->options, Z_Options_negotiationModel);
355 p0->which = Z_OtherInfo_externallyDefinedInfo;
356 p0->information.externallyDefinedInfo =
357 yaz_set_proposal_charneg_list(out, ",",
360 negotiationCharsetRecords);
365 printf("Sent initrequest.\n");
369 /* These two are used only from process_initResponse() */
370 static void render_initUserInfo(Z_OtherInformation *ui1);
371 static void render_diag(Z_DiagnosticFormat *diag);
373 static void pr_opt(const char *opt, void *clientData)
378 static int process_initResponse(Z_InitResponse *res)
381 /* save session parameters for later use */
382 session_mem = odr_extract_mem(in);
383 session_initResponse = res;
385 for (ver = 0; ver < 8; ver++)
386 if (!ODR_MASK_GET(res->protocolVersion, ver))
390 printf("Connection rejected by v%d target.\n", ver);
392 printf("Connection accepted by v%d target.\n", ver);
393 if (res->implementationId)
394 printf("ID : %s\n", res->implementationId);
395 if (res->implementationName)
396 printf("Name : %s\n", res->implementationName);
397 if (res->implementationVersion)
398 printf("Version: %s\n", res->implementationVersion);
399 if (res->userInformationField)
401 Z_External *uif = res->userInformationField;
402 if (uif->which == Z_External_userInfo1) {
403 render_initUserInfo(uif->u.userInfo1);
405 printf("UserInformationfield:\n");
406 if (!z_External(print, (Z_External**)&uif, 0, 0))
408 odr_perror(print, "Printing userinfo\n");
411 if (uif->which == Z_External_octet) {
412 printf("Guessing visiblestring:\n");
413 printf("'%.*s'\n", uif->u.octet_aligned->len,
414 uif->u.octet_aligned->buf);
416 else if (uif->which == Z_External_single)
418 const int *oclc_oid = yaz_string_to_oid(yaz_oid_std(),
421 Odr_any *sat = uif->u.single_ASN1_type;
422 if (!oid_oidcmp(uif->direct_reference, oclc_oid))
424 Z_OCLC_UserInformation *oclc_ui;
425 ODR decode = odr_createmem(ODR_DECODE);
426 odr_setbuf(decode, (char *) sat->buf, sat->len, 0);
427 if (!z_OCLC_UserInformation(decode, &oclc_ui, 0, 0))
428 printf ("Bad OCLC UserInformation:\n");
430 printf ("OCLC UserInformation:\n");
431 if (!z_OCLC_UserInformation(print, &oclc_ui, 0, 0))
432 printf ("Bad OCLC UserInformation spec\n");
437 /* Peek at any private Init-diagnostic APDUs */
438 printf("### NAUGHTY: External is '%.*s'\n",
446 yaz_init_opt_decode(res->options, pr_opt, 0);
449 if (ODR_MASK_GET(res->options, Z_Options_namedResultSets))
452 if (ODR_MASK_GET(res->options, Z_Options_negotiationModel)) {
454 Z_CharSetandLanguageNegotiation *p =
455 yaz_get_charneg_record(res->otherInfo);
459 char *charset=NULL, *lang=NULL;
462 yaz_get_response_charneg(session_mem, p, &charset, &lang,
465 if (outputCharset && negotiationCharset) {
466 odr_set_charset (out, charset, outputCharset);
467 odr_set_charset (in, outputCharset, charset);
470 odr_set_charset (out, 0, 0);
471 odr_set_charset (in, 0, 0);
474 printf("Accepted character set : %s\n", charset);
475 printf("Accepted code language : %s\n", lang ? lang : "none");
476 printf("Accepted records in ...: %d\n", selected );
484 static void render_initUserInfo(Z_OtherInformation *ui1) {
486 printf("Init response contains %d otherInfo unit%s:\n",
487 ui1->num_elements, ui1->num_elements == 1 ? "" : "s");
489 for (i = 0; i < ui1->num_elements; i++) {
490 Z_OtherInformationUnit *unit = ui1->list[i];
491 printf(" %d: otherInfo unit contains ", i+1);
492 if (unit->which == Z_OtherInfo_externallyDefinedInfo &&
493 unit->information.externallyDefinedInfo &&
494 unit->information.externallyDefinedInfo->which ==
496 render_diag(unit->information.externallyDefinedInfo->u.diag1);
498 else if (unit->which != Z_OtherInfo_externallyDefinedInfo)
500 printf("unsupported otherInfo unit->which = %d\n", unit->which);
504 printf("unsupported otherInfo unit external %d\n",
505 unit->information.externallyDefinedInfo ?
506 unit->information.externallyDefinedInfo->which : -2);
512 /* ### should this share code with display_diagrecs()? */
513 static void render_diag(Z_DiagnosticFormat *diag) {
516 printf("%d diagnostic%s:\n", diag->num, diag->num == 1 ? "" : "s");
517 for (i = 0; i < diag->num; i++) {
518 Z_DiagnosticFormat_s *ds = diag->elements[i];
519 printf(" %d: ", i+1);
521 case Z_DiagnosticFormat_s_defaultDiagRec: {
522 Z_DefaultDiagFormat *dd = ds->u.defaultDiagRec;
523 /* ### should check `dd->diagnosticSetId' */
524 printf("code=%d (%s)", *dd->condition,
525 diagbib1_str(*dd->condition));
526 /* Both types of addinfo are the same, so use type-pun */
527 if (dd->u.v2Addinfo != 0)
528 printf(",\n\taddinfo='%s'", dd->u.v2Addinfo);
531 case Z_DiagnosticFormat_s_explicitDiagnostic:
532 printf("Explicit diagnostic (not supported)");
535 printf("Unrecognised diagnostic type %d", ds->which);
539 if (ds->message != 0)
540 printf(", message='%s'", ds->message);
546 static int set_base(const char *arg)
551 for (i = 0; i<num_databaseNames; i++)
552 xfree (databaseNames[i]);
553 num_databaseNames = 0;
557 if (!(cp = strchr(arg, ' ')))
558 cp = arg + strlen(arg);
561 databaseNames[num_databaseNames] = (char *)xmalloc (1 + cp - arg);
562 memcpy (databaseNames[num_databaseNames], arg, cp - arg);
563 databaseNames[num_databaseNames][cp - arg] = '\0';
565 for (cp1 = databaseNames[num_databaseNames]; *cp1 ; cp1++)
574 if (num_databaseNames == 0)
576 num_databaseNames = 1;
577 databaseNames[0] = xstrdup("");
582 static int parse_cmd_doc(const char **arg, ODR out, char **buf,
586 while (**arg && strchr(" \t\n\r\f", **arg))
588 if ((*arg)[0] == '\"' && (sep=strchr(*arg+1, '"')))
592 *buf = odr_strdupn(out, *arg, *len);
596 else if ((*arg)[0] && (*arg)[0] != '\"')
600 const char *fname = *arg;
602 while (**arg != '\0' && **arg != ' ')
605 inf = fopen(fname, "rb");
608 printf("Couldn't open %s\n", fname);
611 if (fseek(inf, 0L, SEEK_END) == -1)
613 printf("Couldn't seek in %s\n", fname);
618 if (fseek(inf, 0L, SEEK_SET) == -1)
620 printf("Couldn't seek in %s\n", fname);
625 *buf = odr_malloc(out, fsize);
626 if (fread(*buf, 1, fsize, inf) != fsize)
628 printf("Unable to read %s\n", fname);
635 else if (**arg == '\0')
643 printf("Missing doc argument\n");
646 printf("Bad doc argument %s\n", *arg);
650 static int cmd_base(const char *arg)
654 printf("Usage: base <database> <database> ...\n");
657 return set_base(arg);
660 void cmd_open_remember_last_open_command(const char* arg, char* new_open_command)
662 if(last_open_command != arg)
664 if(last_open_command) xfree(last_open_command);
665 last_open_command = xstrdup(new_open_command);
669 int session_connect(const char *arg)
672 char type_and_host[101];
673 const char *basep = 0;
674 #if HAVE_OPENSSL_SSL_H
684 nmem_destroy (session_mem);
686 session_initResponse = 0;
688 cs_get_host_args(arg, &basep);
690 strncpy(type_and_host, arg, sizeof(type_and_host)-1);
691 type_and_host[sizeof(type_and_host)-1] = '\0';
693 cmd_open_remember_last_open_command(arg, type_and_host);
696 conn = cs_create_host(yazProxy, 1, &add);
698 conn = cs_create_host(arg, 1, &add);
701 printf ("Could not resolve address %s\n", arg);
705 if (conn->protocol == PROTO_HTTP)
706 queryType = QueryType_CQL;
708 if (conn->protocol == PROTO_HTTP)
710 printf ("SRW/HTTP not enabled in this YAZ\n");
716 protocol = conn->protocol;
717 if (conn->protocol == PROTO_HTTP)
721 printf("Connecting...");
723 if (cs_connect(conn, add) < 0)
725 printf ("error = %s\n", cs_strerror(conn));
731 #if HAVE_OPENSSL_SSL_H
732 if ((ssl = (SSL *) cs_get_ssl(conn)))
734 X509 *server_cert = SSL_get_peer_certificate (ssl);
740 BIO *bio = BIO_new(BIO_s_mem());
742 /* get PEM buffer in memory */
743 PEM_write_bio_X509(bio, server_cert);
744 pem_len = BIO_get_mem_data(bio, &pem_buf);
745 fwrite(pem_buf, pem_len, 1, stdout);
747 /* print all info on screen .. */
748 X509_print_fp(stdout, server_cert);
751 X509_free (server_cert);
757 if (protocol == PROTO_Z3950)
759 send_initRequest(type_and_host);
765 int cmd_open(const char *arg)
769 strncpy (cur_host, arg, sizeof(cur_host)-1);
770 cur_host[sizeof(cur_host)-1] = 0;
772 return session_connect(cur_host);
775 void try_reconnect(void)
779 if(!( auto_reconnect && last_open_command) ) return ;
781 open_command = (char *) xmalloc (strlen(last_open_command)+6);
782 strcpy (open_command, "open ");
784 strcat (open_command, last_open_command);
786 process_cmd_line(open_command);
791 int cmd_authentication(const char *arg)
793 static Z_IdAuthentication au;
794 static char user[40], group[40], pass[40];
795 static Z_IdPass idPass;
800 printf("Auth field set to null\n");
804 r = sscanf (arg, "%39s %39s %39s", user, group, pass);
807 printf("Authentication set to null\n");
813 if (!strcmp(user, "-")) {
814 au.which = Z_IdAuthentication_anonymous;
815 printf("Authentication set to Anonymous\n");
817 au.which = Z_IdAuthentication_open;
819 printf("Authentication set to Open (%s)\n", user);
825 au.which = Z_IdAuthentication_idPass;
826 au.u.idPass = &idPass;
827 idPass.groupId = NULL;
828 idPass.userId = user;
829 idPass.password = group;
830 printf("Authentication set to User (%s), Pass (%s)\n", user, group);
835 au.which = Z_IdAuthentication_idPass;
836 au.u.idPass = &idPass;
837 idPass.groupId = group;
838 idPass.userId = user;
839 idPass.password = pass;
840 printf("Authentication set to User (%s), Group (%s), Pass (%s)\n",
846 /* SEARCH SERVICE ------------------------------ */
847 static void display_record(Z_External *r);
849 static void print_record(const unsigned char *buf, size_t len)
852 print_stringn (buf, len);
853 /* add newline if not already added ... */
854 if (i <= 0 || buf[i-1] != '\n')
858 static void display_record(Z_External *r)
860 const int *oid = r->direct_reference;
864 * Tell the user what we got.
869 char oid_name_buf[OID_STR_MAX];
871 = yaz_oid_to_string_buf(oid, &oclass, oid_name_buf);
872 printf("Record type: ");
874 printf("%s\n", oid_name);
876 /* Check if this is a known, ASN.1 type tucked away in an octet string */
877 if (r->which == Z_External_octet)
879 Z_ext_typeent *type = z_ext_getentbyref(r->direct_reference);
885 * Call the given decoder to process the record.
887 odr_setbuf(in, (char*)r->u.octet_aligned->buf,
888 r->u.octet_aligned->len, 0);
889 if (!(*type->fun)(in, &rr, 0, 0))
891 odr_perror(in, "Decoding constructed record.");
892 fprintf(stdout, "[Near %ld]\n", (long) odr_offset(in));
893 fprintf(stdout, "Packet dump:\n---------\n");
894 odr_dumpBER(stdout, (char*)r->u.octet_aligned->buf,
895 r->u.octet_aligned->len);
896 fprintf(stdout, "---------\n");
898 /* note just ignores the error ant print the bytes form the octet_aligned later */
901 * Note: we throw away the original, BER-encoded record here.
902 * Do something else with it if you want to keep it.
904 r->u.sutrs = (Z_SUTRS *) rr; /* we don't actually check the type here. */
905 r->which = type->what;
909 if (oid && !oid_oidcmp(oid, yaz_oid_recsyn_soif))
911 print_record((const unsigned char *) r->u.octet_aligned->buf,
912 r->u.octet_aligned->len);
914 fwrite (r->u.octet_aligned->buf, 1, r->u.octet_aligned->len, marc_file);
916 else if (oid && r->which == Z_External_octet)
918 const char *octet_buf = (char*)r->u.octet_aligned->buf;
919 if (oid && (!oid_oidcmp(oid, yaz_oid_recsyn_xml)
920 || !oid_oidcmp(oid, yaz_oid_recsyn_xml)
921 || !oid_oidcmp(oid, yaz_oid_recsyn_html)))
923 print_record((const unsigned char *) octet_buf,
924 r->u.octet_aligned->len);
926 else if (oid && !oid_oidcmp(oid, yaz_oid_recsyn_postscript))
928 int size = r->u.octet_aligned->len;
931 print_record((const unsigned char *) octet_buf, size);
935 const int *oidsuffix = oid_oidlen(oid) > 1
936 ? oid + oid_oidlen(oid)-2 : 0;
938 #if AVOID_MARC_DECODE
939 /* primitive check for a marc OID 5.1-29 except 16 */
940 oidsuffix[0] == 5 && oidsuffix[1] < 30 && oidsuffix[1] != 16
949 yaz_marc_t mt = yaz_marc_create();
950 const char *from = 0;
952 if (marcCharset && !strcmp(marcCharset, "auto"))
954 if (!oid_oidcmp(oid, yaz_oid_recsyn_usmarc))
956 if (octet_buf[9] == 'a')
964 else if (marcCharset)
966 if (outputCharset && from)
968 cd = yaz_iconv_open(outputCharset, from);
969 printf ("convert from %s to %s", from,
972 printf (" unsupported\n");
975 yaz_marc_iconv(mt, cd);
980 if (yaz_marc_decode_buf(mt, octet_buf, r->u.octet_aligned->len,
983 fwrite (result, rlen, 1, stdout);
987 printf ("bad MARC. Dumping as it is:\n");
988 print_record((const unsigned char*) octet_buf,
989 r->u.octet_aligned->len);
991 yaz_marc_destroy(mt);
997 print_record((const unsigned char*) octet_buf,
998 r->u.octet_aligned->len);
1002 fwrite (octet_buf, 1, r->u.octet_aligned->len, marc_file);
1004 else if (oid && !oid_oidcmp(oid, yaz_oid_recsyn_sutrs))
1006 if (r->which != Z_External_sutrs)
1008 printf("Expecting single SUTRS type for SUTRS.\n");
1011 print_record(r->u.sutrs->buf, r->u.sutrs->len);
1013 fwrite (r->u.sutrs->buf, 1, r->u.sutrs->len, marc_file);
1015 else if (oid && !oid_oidcmp(oid, yaz_oid_recsyn_grs_1))
1018 if (r->which != Z_External_grs1)
1020 printf("Expecting single GRS type for GRS.\n");
1024 yaz_display_grs1(w, r->u.grs1, 0);
1025 puts (wrbuf_cstr(w));
1028 else if (oid && !oid_oidcmp(oid, yaz_oid_recsyn_opac))
1031 if (r->u.opac->bibliographicRecord)
1032 display_record(r->u.opac->bibliographicRecord);
1033 for (i = 0; i<r->u.opac->num_holdingsData; i++)
1035 Z_HoldingsRecord *h = r->u.opac->holdingsData[i];
1036 if (h->which == Z_HoldingsRecord_marcHoldingsRecord)
1038 printf ("MARC holdings %d\n", i);
1039 display_record(h->u.marcHoldingsRecord);
1041 else if (h->which == Z_HoldingsRecord_holdingsAndCirc)
1045 Z_HoldingsAndCircData *data = h->u.holdingsAndCirc;
1047 printf ("Data holdings %d\n", i);
1048 if (data->typeOfRecord)
1049 printf ("typeOfRecord: %s\n", data->typeOfRecord);
1050 if (data->encodingLevel)
1051 printf ("encodingLevel: %s\n", data->encodingLevel);
1052 if (data->receiptAcqStatus)
1053 printf ("receiptAcqStatus: %s\n", data->receiptAcqStatus);
1054 if (data->generalRetention)
1055 printf ("generalRetention: %s\n", data->generalRetention);
1056 if (data->completeness)
1057 printf ("completeness: %s\n", data->completeness);
1058 if (data->dateOfReport)
1059 printf ("dateOfReport: %s\n", data->dateOfReport);
1061 printf ("nucCode: %s\n", data->nucCode);
1062 if (data->localLocation)
1063 printf ("localLocation: %s\n", data->localLocation);
1064 if (data->shelvingLocation)
1065 printf ("shelvingLocation: %s\n", data->shelvingLocation);
1066 if (data->callNumber)
1067 printf ("callNumber: %s\n", data->callNumber);
1068 if (data->shelvingData)
1069 printf ("shelvingData: %s\n", data->shelvingData);
1070 if (data->copyNumber)
1071 printf ("copyNumber: %s\n", data->copyNumber);
1072 if (data->publicNote)
1073 printf ("publicNote: %s\n", data->publicNote);
1074 if (data->reproductionNote)
1075 printf ("reproductionNote: %s\n", data->reproductionNote);
1076 if (data->termsUseRepro)
1077 printf ("termsUseRepro: %s\n", data->termsUseRepro);
1078 if (data->enumAndChron)
1079 printf ("enumAndChron: %s\n", data->enumAndChron);
1080 for (j = 0; j<data->num_volumes; j++)
1082 printf ("volume %d\n", j);
1083 if (data->volumes[j]->enumeration)
1084 printf (" enumeration: %s\n",
1085 data->volumes[j]->enumeration);
1086 if (data->volumes[j]->chronology)
1087 printf (" chronology: %s\n",
1088 data->volumes[j]->chronology);
1089 if (data->volumes[j]->enumAndChron)
1090 printf (" enumAndChron: %s\n",
1091 data->volumes[j]->enumAndChron);
1093 for (j = 0; j<data->num_circulationData; j++)
1095 printf ("circulation %d\n", j);
1096 if (data->circulationData[j]->availableNow)
1097 printf (" availableNow: %d\n",
1098 *data->circulationData[j]->availableNow);
1099 if (data->circulationData[j]->availablityDate)
1100 printf (" availabiltyDate: %s\n",
1101 data->circulationData[j]->availablityDate);
1102 if (data->circulationData[j]->availableThru)
1103 printf (" availableThru: %s\n",
1104 data->circulationData[j]->availableThru);
1105 if (data->circulationData[j]->restrictions)
1106 printf (" restrictions: %s\n",
1107 data->circulationData[j]->restrictions);
1108 if (data->circulationData[j]->itemId)
1109 printf (" itemId: %s\n",
1110 data->circulationData[j]->itemId);
1111 if (data->circulationData[j]->renewable)
1112 printf (" renewable: %d\n",
1113 *data->circulationData[j]->renewable);
1114 if (data->circulationData[j]->onHold)
1115 printf (" onHold: %d\n",
1116 *data->circulationData[j]->onHold);
1117 if (data->circulationData[j]->enumAndChron)
1118 printf (" enumAndChron: %s\n",
1119 data->circulationData[j]->enumAndChron);
1120 if (data->circulationData[j]->midspine)
1121 printf (" midspine: %s\n",
1122 data->circulationData[j]->midspine);
1123 if (data->circulationData[j]->temporaryLocation)
1124 printf (" temporaryLocation: %s\n",
1125 data->circulationData[j]->temporaryLocation);
1132 printf("Unknown record representation.\n");
1133 if (!z_External(print, &r, 0, 0))
1135 odr_perror(print, "Printing external");
1141 static void display_diagrecs(Z_DiagRec **pp, int num)
1144 Z_DefaultDiagFormat *r;
1146 printf("Diagnostic message(s) from database:\n");
1147 for (i = 0; i<num; i++)
1149 Z_DiagRec *p = pp[i];
1150 if (p->which != Z_DiagRec_defaultFormat)
1152 printf("Diagnostic record not in default format.\n");
1156 r = p->u.defaultFormat;
1158 if (!r->diagnosticSetId)
1159 printf("Missing diagset\n");
1163 char diag_name_buf[OID_STR_MAX];
1164 const char *diag_name = 0;
1165 diag_name = yaz_oid_to_string_buf
1166 (r->diagnosticSetId, &oclass, diag_name_buf);
1167 if (oid_oidcmp(r->diagnosticSetId, yaz_oid_diagset_bib_1))
1168 printf("Unknown diagset: %s\n", diag_name);
1170 printf(" [%d] %s", *r->condition, diagbib1_str(*r->condition));
1173 case Z_DefaultDiagFormat_v2Addinfo:
1174 printf (" -- v2 addinfo '%s'\n", r->u.v2Addinfo);
1176 case Z_DefaultDiagFormat_v3Addinfo:
1177 printf (" -- v3 addinfo '%s'\n", r->u.v3Addinfo);
1184 static void display_nameplusrecord(Z_NamePlusRecord *p)
1186 if (p->databaseName)
1187 printf("[%s]", p->databaseName);
1188 if (p->which == Z_NamePlusRecord_surrogateDiagnostic)
1189 display_diagrecs(&p->u.surrogateDiagnostic, 1);
1190 else if (p->which == Z_NamePlusRecord_databaseRecord)
1191 display_record(p->u.databaseRecord);
1194 static void display_records(Z_Records *p)
1198 if (p->which == Z_Records_NSD)
1200 Z_DiagRec dr, *dr_p = &dr;
1201 dr.which = Z_DiagRec_defaultFormat;
1202 dr.u.defaultFormat = p->u.nonSurrogateDiagnostic;
1203 display_diagrecs (&dr_p, 1);
1205 else if (p->which == Z_Records_multipleNSD)
1206 display_diagrecs (p->u.multipleNonSurDiagnostics->diagRecs,
1207 p->u.multipleNonSurDiagnostics->num_diagRecs);
1210 printf("Records: %d\n", p->u.databaseOrSurDiagnostics->num_records);
1211 for (i = 0; i < p->u.databaseOrSurDiagnostics->num_records; i++)
1212 display_nameplusrecord(p->u.databaseOrSurDiagnostics->records[i]);
1216 static int send_deleteResultSetRequest(const char *arg)
1221 Z_APDU *apdu = zget_APDU(out, Z_APDU_deleteResultSetRequest);
1222 Z_DeleteResultSetRequest *req = apdu->u.deleteResultSetRequest;
1224 req->referenceId = set_refid (out);
1226 req->num_resultSetList =
1227 sscanf (arg, "%30s %30s %30s %30s %30s %30s %30s %30s",
1228 names[0], names[1], names[2], names[3],
1229 names[4], names[5], names[6], names[7]);
1231 req->deleteFunction = (int *)
1232 odr_malloc (out, sizeof(*req->deleteFunction));
1233 if (req->num_resultSetList > 0)
1235 *req->deleteFunction = Z_DeleteResultSetRequest_list;
1236 req->resultSetList = (char **)
1237 odr_malloc (out, sizeof(*req->resultSetList)*
1238 req->num_resultSetList);
1239 for (i = 0; i<req->num_resultSetList; i++)
1240 req->resultSetList[i] = names[i];
1244 *req->deleteFunction = Z_DeleteResultSetRequest_all;
1245 req->resultSetList = 0;
1249 printf("Sent deleteResultSetRequest.\n");
1254 static int send_srw(Z_SRW_PDU *sr)
1256 const char *charset = negotiationCharset;
1257 const char *host_port = cur_host;
1261 path = odr_malloc(out, 2+strlen(databaseNames[0]));
1263 strcpy(path+1, databaseNames[0]);
1265 gdu = z_get_HTTP_Request_host_path(out, host_port, path);
1267 if (!strcmp(sru_method, "get"))
1269 yaz_sru_get_encode(gdu->u.HTTP_Request, sr, out, charset);
1271 else if (!strcmp(sru_method, "post"))
1273 yaz_sru_post_encode(gdu->u.HTTP_Request, sr, out, charset);
1275 else if (!strcmp(sru_method, "soap"))
1277 yaz_sru_soap_encode(gdu->u.HTTP_Request, sr, out, charset);
1280 if (z_GDU(out, &gdu, 0, 0))
1288 if (!z_GDU(print, &gdu, 0, 0))
1289 printf ("Failed to print outgoing SRU package\n");
1292 buf_out = odr_getbuf(out, &len_out, 0);
1294 /* we don't odr_reset(out), since we may need the buffer again */
1296 do_hex_dump(buf_out, len_out);
1298 r = cs_put(conn, buf_out, len_out);
1308 static char *encode_SRW_term(ODR o, const char *q)
1310 const char *in_charset = "ISO-8859-1";
1311 WRBUF w = wrbuf_alloc();
1315 in_charset = outputCharset;
1316 cd = yaz_iconv_open("UTF-8", in_charset);
1320 return odr_strdup(o, q);
1322 wrbuf_iconv_write(w, cd, q, strlen(q));
1324 res = odr_strdup(o, wrbuf_cstr(w));
1326 res = odr_strdup(o, q);
1327 yaz_iconv_close(cd);
1333 static int send_SRW_scanRequest(const char *arg, int pos, int num)
1337 /* regular requestse .. */
1338 sr = yaz_srw_get(out, Z_SRW_scan_request);
1343 sr->u.scan_request->query_type = Z_SRW_query_type_cql;
1344 sr->u.scan_request->scanClause.cql = encode_SRW_term(out, arg);
1346 case QueryType_Prefix:
1347 sr->u.scan_request->query_type = Z_SRW_query_type_pqf;
1348 sr->u.scan_request->scanClause.pqf = encode_SRW_term(out, arg);
1351 printf ("Only CQL and PQF supported in SRW\n");
1354 sr->u.scan_request->responsePosition = odr_intdup(out, pos);
1355 sr->u.scan_request->maximumTerms = odr_intdup(out, num);
1356 return send_srw(sr);
1359 static int send_SRW_searchRequest(const char *arg)
1365 assert(srw_sr_odr_out == 0);
1366 srw_sr_odr_out = odr_createmem(ODR_ENCODE);
1368 odr_reset(srw_sr_odr_out);
1372 /* save this for later .. when fetching individual records */
1373 srw_sr = yaz_srw_get(srw_sr_odr_out, Z_SRW_searchRetrieve_request);
1375 /* regular request .. */
1376 sr = yaz_srw_get(out, Z_SRW_searchRetrieve_request);
1381 srw_sr->u.request->query_type = Z_SRW_query_type_cql;
1382 srw_sr->u.request->query.cql = encode_SRW_term(srw_sr_odr_out, arg);
1384 sr->u.request->query_type = Z_SRW_query_type_cql;
1385 sr->u.request->query.cql = encode_SRW_term(srw_sr_odr_out, arg);
1387 case QueryType_Prefix:
1388 srw_sr->u.request->query_type = Z_SRW_query_type_pqf;
1389 srw_sr->u.request->query.pqf = encode_SRW_term(srw_sr_odr_out, arg);
1391 sr->u.request->query_type = Z_SRW_query_type_pqf;
1392 sr->u.request->query.pqf = encode_SRW_term(srw_sr_odr_out, arg);
1395 printf ("Only CQL and PQF supported in SRW\n");
1398 sr->u.request->maximumRecords = odr_intdup(out, 0);
1401 sr->u.request->recordSchema = record_schema;
1402 if (recordsyntax_size == 1 && !yaz_matchstr(recordsyntax_list[0], "xml"))
1403 sr->u.request->recordPacking = "xml";
1404 return send_srw(sr);
1408 static int send_searchRequest(const char *arg)
1410 Z_APDU *apdu = zget_APDU(out, Z_APDU_searchRequest);
1411 Z_SearchRequest *req = apdu->u.searchRequest;
1413 struct ccl_rpn_node *rpn = NULL;
1415 char setstring[100];
1416 Z_RPNQuery *RPNquery;
1418 YAZ_PQF_Parser pqf_parser;
1420 QueryType myQueryType = queryType;
1423 if (myQueryType == QueryType_CCL2RPN)
1425 rpn = ccl_find_str(bibset, arg, &error, &pos);
1428 printf("CCL ERROR: %s\n", ccl_err_msg(error));
1431 } else if (myQueryType == QueryType_CQL2RPN) {
1432 /* ### All this code should be wrapped in a utility function */
1434 struct cql_node *node;
1435 const char *addinfo;
1436 if (cqltrans == 0) {
1437 printf("Can't use CQL: no translation file. Try set_cqlfile\n");
1440 parser = cql_parser_create();
1441 if ((error = cql_parser_string(parser, arg)) != 0) {
1442 printf("Can't parse CQL: must be a syntax error\n");
1445 node = cql_parser_result(parser);
1446 if ((error = cql_transform_buf(cqltrans, node, pqfbuf,
1447 sizeof pqfbuf)) != 0) {
1448 error = cql_transform_error(cqltrans, &addinfo);
1449 printf ("Can't convert CQL to PQF: %s (addinfo=%s)\n",
1450 cql_strerror(error), addinfo);
1454 myQueryType = QueryType_Prefix;
1457 req->referenceId = set_refid (out);
1458 if (!strcmp(arg, "@big")) /* strictly for troublemaking */
1460 static unsigned char big[2100];
1461 static Odr_oct bigo;
1463 /* send a very big referenceid to test transport stack etc. */
1464 memset(big, 'A', 2100);
1465 bigo.len = bigo.size = 2100;
1467 req->referenceId = &bigo;
1472 sprintf(setstring, "%d", ++setnumber);
1473 req->resultSetName = setstring;
1475 *req->smallSetUpperBound = smallSetUpperBound;
1476 *req->largeSetLowerBound = largeSetLowerBound;
1477 *req->mediumSetPresentNumber = mediumSetPresentNumber;
1478 if (smallSetUpperBound > 0 || (largeSetLowerBound > 1 &&
1479 mediumSetPresentNumber > 0))
1481 if (recordsyntax_size)
1482 req->preferredRecordSyntax =
1483 yaz_string_to_oid_odr(yaz_oid_std(),
1484 CLASS_RECSYN, recordsyntax_list[0], out);
1486 req->smallSetElementSetNames =
1487 req->mediumSetElementSetNames = elementSetNames;
1489 req->num_databaseNames = num_databaseNames;
1490 req->databaseNames = databaseNames;
1492 req->query = &query;
1494 switch (myQueryType)
1496 case QueryType_Prefix:
1497 query.which = Z_Query_type_1;
1498 pqf_parser = yaz_pqf_create ();
1499 RPNquery = yaz_pqf_parse (pqf_parser, out, arg);
1502 const char *pqf_msg;
1504 int code = yaz_pqf_error (pqf_parser, &pqf_msg, &off);
1506 printf("%*s^\n", ioff+4, "");
1507 printf("Prefix query error: %s (code %d)\n", pqf_msg, code);
1509 yaz_pqf_destroy (pqf_parser);
1512 yaz_pqf_destroy (pqf_parser);
1513 query.u.type_1 = RPNquery;
1516 query.which = Z_Query_type_2;
1517 query.u.type_2 = &ccl_query;
1518 ccl_query.buf = (unsigned char*) arg;
1519 ccl_query.len = strlen(arg);
1521 case QueryType_CCL2RPN:
1522 query.which = Z_Query_type_1;
1523 RPNquery = ccl_rpn_query(out, rpn);
1526 printf ("Couldn't convert from CCL to RPN\n");
1529 query.u.type_1 = RPNquery;
1530 ccl_rpn_delete (rpn);
1533 query.which = Z_Query_type_104;
1534 ext = (Z_External *) odr_malloc(out, sizeof(*ext));
1535 ext->direct_reference = odr_getoidbystr(out, "1.2.840.10003.16.2");
1536 ext->indirect_reference = 0;
1537 ext->descriptor = 0;
1538 ext->which = Z_External_CQL;
1539 ext->u.cql = odr_strdup(out, arg);
1540 query.u.type_104 = ext;
1543 printf ("Unsupported query type\n");
1546 if (send_apdu(apdu))
1547 printf("Sent searchRequest.\n");
1552 /* display Query Expression as part of searchResult-1 */
1553 static void display_queryExpression (const char *lead, Z_QueryExpression *qe)
1557 printf(" %s=", lead);
1558 if (qe->which == Z_QueryExpression_term)
1560 if (qe->u.term->queryTerm)
1562 Z_Term *term = qe->u.term->queryTerm;
1563 switch (term->which)
1565 case Z_Term_general:
1566 printf ("%.*s", term->u.general->len, term->u.general->buf);
1568 case Z_Term_characterString:
1569 printf ("%s", term->u.characterString);
1571 case Z_Term_numeric:
1572 printf ("%d", *term->u.numeric);
1582 /* see if we can find USR:SearchResult-1 */
1583 static void display_searchResult (Z_OtherInformation *o)
1588 for (i = 0; i < o->num_elements; i++)
1590 if (o->list[i]->which == Z_OtherInfo_externallyDefinedInfo)
1592 Z_External *ext = o->list[i]->information.externallyDefinedInfo;
1594 if (ext->which == Z_External_searchResult1)
1597 Z_SearchInfoReport *sr = ext->u.searchResult1;
1598 printf ("SearchResult-1:");
1599 for (j = 0; j < sr->num; j++)
1603 if (!sr->elements[j]->subqueryExpression)
1605 display_queryExpression("term",
1606 sr->elements[j]->subqueryExpression);
1607 display_queryExpression("interpretation",
1608 sr->elements[j]->subqueryInterpretation);
1609 display_queryExpression("recommendation",
1610 sr->elements[j]->subqueryRecommendation);
1611 if (sr->elements[j]->subqueryCount)
1612 printf(" cnt=%d", *sr->elements[j]->subqueryCount);
1613 if (sr->elements[j]->subqueryId)
1614 printf(" id=%s ", sr->elements[j]->subqueryId);
1622 static int process_searchResponse(Z_SearchResponse *res)
1624 printf ("Received SearchResponse.\n");
1625 print_refid (res->referenceId);
1626 if (*res->searchStatus)
1627 printf("Search was a success.\n");
1629 printf("Search was a bloomin' failure.\n");
1630 printf("Number of hits: %d", *res->resultCount);
1631 last_hit_count = *res->resultCount;
1633 printf (", setno %d", setnumber);
1635 if (res->resultSetStatus)
1637 printf("Result Set Status: ");
1638 switch(*res->resultSetStatus)
1640 case Z_SearchResponse_subset:
1641 printf("subset"); break;
1642 case Z_SearchResponse_interim:
1643 printf("interim"); break;
1644 case Z_SearchResponse_none:
1645 printf("none"); break;
1646 case Z_SearchResponse_estimate:
1647 printf("estimate"); break;
1649 printf("%d", *res->resultSetStatus);
1653 display_searchResult (res->additionalSearchInfo);
1654 printf("records returned: %d\n",
1655 *res->numberOfRecordsReturned);
1656 setno += *res->numberOfRecordsReturned;
1658 display_records(res->records);
1662 static void print_level(int iLevel)
1665 for (i = 0; i < iLevel * 4; i++)
1669 static void print_int(int iLevel, const char *pTag, int *pInt)
1673 print_level(iLevel);
1674 printf("%s: %d\n", pTag, *pInt);
1678 static void print_string(int iLevel, const char *pTag, const char *pString)
1680 if (pString != NULL)
1682 print_level(iLevel);
1683 printf("%s: %s\n", pTag, pString);
1687 static void print_oid(int iLevel, const char *pTag, Odr_oid *pOid)
1693 print_level(iLevel);
1694 printf("%s:", pTag);
1695 for (; *pInt != -1; pInt++)
1696 printf(" %d", *pInt);
1701 static void print_referenceId(int iLevel, Z_ReferenceId *referenceId)
1703 if (referenceId != NULL)
1707 print_level(iLevel);
1708 printf("Ref Id (%d, %d): ", referenceId->len, referenceId->size);
1709 for (i = 0; i < referenceId->len; i++)
1710 printf("%c", referenceId->buf[i]);
1715 static void print_string_or_numeric(int iLevel, const char *pTag, Z_StringOrNumeric *pStringNumeric)
1717 if (pStringNumeric != NULL)
1719 switch (pStringNumeric->which)
1721 case Z_StringOrNumeric_string:
1722 print_string(iLevel, pTag, pStringNumeric->u.string);
1725 case Z_StringOrNumeric_numeric:
1726 print_int(iLevel, pTag, pStringNumeric->u.numeric);
1730 print_level(iLevel);
1731 printf("%s: valid type for Z_StringOrNumeric\n", pTag);
1737 static void print_universe_report_duplicate(
1739 Z_UniverseReportDuplicate *pUniverseReportDuplicate)
1741 if (pUniverseReportDuplicate != NULL)
1743 print_level(iLevel);
1744 printf("Universe Report Duplicate: \n");
1746 print_string_or_numeric(iLevel, "Hit No",
1747 pUniverseReportDuplicate->hitno);
1751 static void print_universe_report_hits(
1753 Z_UniverseReportHits *pUniverseReportHits)
1755 if (pUniverseReportHits != NULL)
1757 print_level(iLevel);
1758 printf("Universe Report Hits: \n");
1760 print_string_or_numeric(iLevel, "Database",
1761 pUniverseReportHits->database);
1762 print_string_or_numeric(iLevel, "Hits", pUniverseReportHits->hits);
1766 static void print_universe_report(int iLevel, Z_UniverseReport *pUniverseReport)
1768 if (pUniverseReport != NULL)
1770 print_level(iLevel);
1771 printf("Universe Report: \n");
1773 print_int(iLevel, "Total Hits", pUniverseReport->totalHits);
1774 switch (pUniverseReport->which)
1776 case Z_UniverseReport_databaseHits:
1777 print_universe_report_hits(iLevel,
1778 pUniverseReport->u.databaseHits);
1781 case Z_UniverseReport_duplicate:
1782 print_universe_report_duplicate(iLevel,
1783 pUniverseReport->u.duplicate);
1787 print_level(iLevel);
1788 printf("Type: %d\n", pUniverseReport->which);
1794 static void print_external(int iLevel, Z_External *pExternal)
1796 if (pExternal != NULL)
1798 print_level(iLevel);
1799 printf("External: \n");
1801 print_oid(iLevel, "Direct Reference", pExternal->direct_reference);
1802 print_int(iLevel, "InDirect Reference", pExternal->indirect_reference);
1803 print_string(iLevel, "Descriptor", pExternal->descriptor);
1804 switch (pExternal->which)
1806 case Z_External_universeReport:
1807 print_universe_report(iLevel, pExternal->u.universeReport);
1811 print_level(iLevel);
1812 printf("Type: %d\n", pExternal->which);
1818 static int process_resourceControlRequest (Z_ResourceControlRequest *req)
1820 printf ("Received ResourceControlRequest.\n");
1821 print_referenceId(1, req->referenceId);
1822 print_int(1, "Suspended Flag", req->suspendedFlag);
1823 print_int(1, "Partial Results Available", req->partialResultsAvailable);
1824 print_int(1, "Response Required", req->responseRequired);
1825 print_int(1, "Triggered Request Flag", req->triggeredRequestFlag);
1826 print_external(1, req->resourceReport);
1830 void process_ESResponse(Z_ExtendedServicesResponse *res)
1833 switch (*res->operationStatus)
1835 case Z_ExtendedServicesResponse_done:
1838 case Z_ExtendedServicesResponse_accepted:
1839 printf ("accepted\n");
1841 case Z_ExtendedServicesResponse_failure:
1842 printf ("failure\n");
1843 display_diagrecs(res->diagnostics, res->num_diagnostics);
1846 printf ("unknown\n");
1848 if ( (*res->operationStatus != Z_ExtendedServicesResponse_failure) &&
1849 (res->num_diagnostics != 0) ) {
1850 display_diagrecs(res->diagnostics, res->num_diagnostics);
1852 print_refid (res->referenceId);
1853 if (res->taskPackage &&
1854 res->taskPackage->which == Z_External_extendedService)
1856 Z_TaskPackage *taskPackage = res->taskPackage->u.extendedService;
1857 Odr_oct *id = taskPackage->targetReference;
1858 Z_External *ext = taskPackage->taskSpecificParameters;
1862 printf ("Target Reference: ");
1863 print_stringn (id->buf, id->len);
1866 if (ext->which == Z_External_update)
1868 Z_IUUpdateTaskPackage *utp = ext->u.update->u.taskPackage;
1869 if (utp && utp->targetPart)
1871 Z_IUTargetPart *targetPart = utp->targetPart;
1874 for (i = 0; i<targetPart->num_taskPackageRecords; i++)
1877 Z_IUTaskPackageRecordStructure *tpr =
1878 targetPart->taskPackageRecords[i];
1879 printf ("task package record %d\n", i+1);
1880 if (tpr->which == Z_IUTaskPackageRecordStructure_record)
1882 display_record (tpr->u.record);
1886 printf ("other type\n");
1892 if (res->taskPackage && res->taskPackage->which == Z_External_octet)
1894 Odr_oct *doc = res->taskPackage->u.octet_aligned;
1895 printf("%.*s\n", doc->len, doc->buf);
1899 const char *get_ill_element (void *clientData, const char *element)
1904 static Z_External *create_external_itemRequest(void)
1906 struct ill_get_ctl ctl;
1907 ILL_ItemRequest *req;
1909 int item_request_size = 0;
1910 char *item_request_buf = 0;
1914 ctl.f = get_ill_element;
1916 req = ill_get_ItemRequest(&ctl, "ill", 0);
1918 printf ("ill_get_ItemRequest failed\n");
1920 if (!ill_ItemRequest (out, &req, 0, 0))
1924 ill_ItemRequest(print, &req, 0, 0);
1927 item_request_buf = odr_getbuf (out, &item_request_size, 0);
1928 if (item_request_buf)
1929 odr_setbuf (out, item_request_buf, item_request_size, 1);
1930 printf ("Couldn't encode ItemRequest, size %d\n", item_request_size);
1935 const int *ill_oid = yaz_string_to_oid(yaz_oid_std(),
1936 CLASS_GENERAL, "ISOILL-1");
1937 r = (Z_External *) odr_malloc (out, sizeof(*r));
1938 r->direct_reference = odr_oiddup(out, ill_oid);
1939 r->indirect_reference = 0;
1941 r->which = Z_External_single;
1943 r->u.single_ASN1_type = (Odr_oct *)
1944 odr_malloc (out, sizeof(*r->u.single_ASN1_type));
1945 r->u.single_ASN1_type->buf = (unsigned char *)
1946 odr_malloc (out, item_request_size);
1947 r->u.single_ASN1_type->len = item_request_size;
1948 r->u.single_ASN1_type->size = item_request_size;
1949 memcpy (r->u.single_ASN1_type->buf, item_request_buf,
1952 do_hex_dump(item_request_buf,item_request_size);
1957 static Z_External *create_external_ILL_APDU(int which)
1959 struct ill_get_ctl ctl;
1962 int ill_request_size = 0;
1963 char *ill_request_buf = 0;
1967 ctl.f = get_ill_element;
1969 ill_apdu = ill_get_APDU(&ctl, "ill", 0);
1971 if (!ill_APDU (out, &ill_apdu, 0, 0))
1975 printf ("-------------------\n");
1976 ill_APDU(print, &ill_apdu, 0, 0);
1978 printf ("-------------------\n");
1980 ill_request_buf = odr_getbuf (out, &ill_request_size, 0);
1981 if (ill_request_buf)
1982 odr_setbuf (out, ill_request_buf, ill_request_size, 1);
1983 printf ("Couldn't encode ILL-Request, size %d\n", ill_request_size);
1988 const int *ill_oid = yaz_string_to_oid(yaz_oid_std(),
1989 CLASS_GENERAL, "ISOILL-1");
1991 ill_request_buf = odr_getbuf (out, &ill_request_size, 0);
1993 r = (Z_External *) odr_malloc (out, sizeof(*r));
1994 r->direct_reference = odr_oiddup(out, ill_oid);
1995 r->indirect_reference = 0;
1997 r->which = Z_External_single;
1999 r->u.single_ASN1_type = (Odr_oct *)
2000 odr_malloc (out, sizeof(*r->u.single_ASN1_type));
2001 r->u.single_ASN1_type->buf = (unsigned char *)
2002 odr_malloc (out, ill_request_size);
2003 r->u.single_ASN1_type->len = ill_request_size;
2004 r->u.single_ASN1_type->size = ill_request_size;
2005 memcpy (r->u.single_ASN1_type->buf, ill_request_buf, ill_request_size);
2006 /* printf ("len = %d\n", ill_request_size); */
2007 /* do_hex_dump(ill_request_buf,ill_request_size); */
2008 /* printf("--- end of extenal\n"); */
2015 static Z_External *create_ItemOrderExternal(const char *type, int itemno)
2017 Z_External *r = (Z_External *) odr_malloc(out, sizeof(Z_External));
2018 const int *itemorder_oid = yaz_string_to_oid(yaz_oid_std(),
2021 r->direct_reference = odr_oiddup(out, itemorder_oid);
2022 r->indirect_reference = 0;
2025 r->which = Z_External_itemOrder;
2027 r->u.itemOrder = (Z_ItemOrder *) odr_malloc(out,sizeof(Z_ItemOrder));
2028 memset(r->u.itemOrder, 0, sizeof(Z_ItemOrder));
2029 r->u.itemOrder->which=Z_IOItemOrder_esRequest;
2031 r->u.itemOrder->u.esRequest = (Z_IORequest *)
2032 odr_malloc(out,sizeof(Z_IORequest));
2033 memset(r->u.itemOrder->u.esRequest, 0, sizeof(Z_IORequest));
2035 r->u.itemOrder->u.esRequest->toKeep = (Z_IOOriginPartToKeep *)
2036 odr_malloc(out,sizeof(Z_IOOriginPartToKeep));
2037 memset(r->u.itemOrder->u.esRequest->toKeep, 0, sizeof(Z_IOOriginPartToKeep));
2038 r->u.itemOrder->u.esRequest->notToKeep = (Z_IOOriginPartNotToKeep *)
2039 odr_malloc(out,sizeof(Z_IOOriginPartNotToKeep));
2040 memset(r->u.itemOrder->u.esRequest->notToKeep, 0, sizeof(Z_IOOriginPartNotToKeep));
2042 r->u.itemOrder->u.esRequest->toKeep->supplDescription = NULL;
2043 r->u.itemOrder->u.esRequest->toKeep->contact = NULL;
2044 r->u.itemOrder->u.esRequest->toKeep->addlBilling = NULL;
2046 r->u.itemOrder->u.esRequest->notToKeep->resultSetItem =
2047 (Z_IOResultSetItem *) odr_malloc(out, sizeof(Z_IOResultSetItem));
2048 memset(r->u.itemOrder->u.esRequest->notToKeep->resultSetItem, 0, sizeof(Z_IOResultSetItem));
2049 r->u.itemOrder->u.esRequest->notToKeep->resultSetItem->resultSetId = "1";
2051 r->u.itemOrder->u.esRequest->notToKeep->resultSetItem->item =
2052 (int *) odr_malloc(out, sizeof(int));
2053 *r->u.itemOrder->u.esRequest->notToKeep->resultSetItem->item = itemno;
2055 if (!strcmp (type, "item") || !strcmp(type, "2"))
2057 printf ("using item-request\n");
2058 r->u.itemOrder->u.esRequest->notToKeep->itemRequest =
2059 create_external_itemRequest();
2061 else if (!strcmp(type, "ill") || !strcmp(type, "1"))
2063 printf ("using ILL-request\n");
2064 r->u.itemOrder->u.esRequest->notToKeep->itemRequest =
2065 create_external_ILL_APDU(ILL_APDU_ILL_Request);
2067 else if (!strcmp(type, "xml") || !strcmp(type, "3"))
2069 const int *oid_xml = yaz_string_to_oid(yaz_oid_std(),
2070 CLASS_RECSYN, "xml");
2071 const char *xml_buf =
2073 " <type>request</type>\n"
2074 " <libraryNo>000200</libraryNo>\n"
2075 " <borrowerTicketNo> 1212 </borrowerTicketNo>\n"
2077 r->u.itemOrder->u.esRequest->notToKeep->itemRequest =
2078 z_ext_record_oid(out, oid_xml, xml_buf, strlen(xml_buf));
2081 r->u.itemOrder->u.esRequest->notToKeep->itemRequest = 0;
2086 static int send_itemorder(const char *type, int itemno)
2088 Z_APDU *apdu = zget_APDU(out, Z_APDU_extendedServicesRequest);
2089 Z_ExtendedServicesRequest *req = apdu->u.extendedServicesRequest;
2091 const int *itemorder_oid = yaz_string_to_oid(yaz_oid_std(),
2094 req->referenceId = set_refid (out);
2096 req->packageType = odr_oiddup(out, itemorder_oid);
2097 req->packageName = esPackageName;
2099 req->taskSpecificParameters = create_ItemOrderExternal(type, itemno);
2105 static int only_z3950(void)
2109 printf ("Not connected yet\n");
2112 if (protocol == PROTO_HTTP)
2114 printf ("Not supported by SRW\n");
2120 static int cmd_update_common(const char *arg, int version);
2122 static int cmd_update(const char *arg)
2124 return cmd_update_common(arg, 1);
2127 static int cmd_update0(const char *arg)
2129 return cmd_update_common(arg, 0);
2132 static int cmd_update_Z3950(int version, int action_no, const char *recid,
2133 char *rec_buf, int rec_len);
2135 static int cmd_update_SRW(int action_no, const char *recid,
2136 char *rec_buf, int rec_len);
2138 static int cmd_update_common(const char *arg, int version)
2140 char action[20], recid_buf[20];
2141 const char *recid = 0;
2149 sscanf (arg, "%19s %19s%n", action, recid_buf, &noread);
2152 printf("Use: update action recid [fname]\n");
2153 printf(" where action is one of insert,replace,delete.update\n");
2154 printf(" recid is some record ID. Use none for no ID\n");
2155 printf(" fname is file of record to be updated\n");
2159 if (!strcmp (action, "insert"))
2160 action_no = Z_IUOriginPartToKeep_recordInsert;
2161 else if (!strcmp (action, "replace"))
2162 action_no = Z_IUOriginPartToKeep_recordReplace;
2163 else if (!strcmp (action, "delete"))
2164 action_no = Z_IUOriginPartToKeep_recordDelete;
2165 else if (!strcmp (action, "update"))
2166 action_no = Z_IUOriginPartToKeep_specialUpdate;
2169 printf ("Bad action: %s\n", action);
2170 printf ("Possible values: insert, replace, delete, update\n");
2174 if (strcmp(recid_buf, "none")) /* none means no record ID */
2178 if (parse_cmd_doc(&arg, out, &rec_buf, &rec_len, 1) == 0)
2182 if (protocol == PROTO_HTTP)
2183 return cmd_update_SRW(action_no, recid, rec_buf, rec_len);
2185 return cmd_update_Z3950(version, action_no, recid, rec_buf, rec_len);
2189 static int cmd_update_SRW(int action_no, const char *recid,
2190 char *rec_buf, int rec_len)
2198 Z_SRW_PDU *srw = yaz_srw_get(out, Z_SRW_update_request);
2199 Z_SRW_updateRequest *sr = srw->u.update_request;
2203 case Z_IUOriginPartToKeep_recordInsert:
2204 sr->operation = "info:srw/action/1/create";
2206 case Z_IUOriginPartToKeep_recordReplace:
2207 sr->operation = "info:srw/action/1/replace";
2209 case Z_IUOriginPartToKeep_recordDelete:
2210 sr->operation = "info:srw/action/1/delete";
2215 sr->record = yaz_srw_get_record(out);
2216 sr->record->recordData_buf = rec_buf;
2217 sr->record->recordData_len = rec_len;
2218 sr->record->recordSchema = record_schema;
2221 sr->recordId = odr_strdup(out, recid);
2222 return send_srw(srw);
2227 static int cmd_update_Z3950(int version, int action_no, const char *recid,
2228 char *rec_buf, int rec_len)
2230 Z_APDU *apdu = zget_APDU(out, Z_APDU_extendedServicesRequest );
2231 Z_ExtendedServicesRequest *req = apdu->u.extendedServicesRequest;
2233 Z_External *record_this = 0;
2234 const int *oid_xml = yaz_string_to_oid(yaz_oid_std(),
2235 CLASS_RECSYN, "xml");
2238 record_this = z_ext_record_oid(out, oid_xml, rec_buf, rec_len);
2243 printf ("No last record (update ignored)\n");
2246 record_this = record_last;
2250 yaz_string_to_oid_odr(yaz_oid_std(),
2252 version == 0 ? "DB. Update (first version)" :
2254 req->packageName = esPackageName;
2256 req->referenceId = set_refid (out);
2258 r = req->taskSpecificParameters = (Z_External *)
2259 odr_malloc (out, sizeof(*r));
2260 r->direct_reference = req->packageType;
2261 r->indirect_reference = 0;
2265 Z_IU0OriginPartToKeep *toKeep;
2266 Z_IU0SuppliedRecords *notToKeep;
2268 r->which = Z_External_update0;
2269 r->u.update0 = (Z_IU0Update *) odr_malloc(out, sizeof(*r->u.update0));
2270 r->u.update0->which = Z_IUUpdate_esRequest;
2271 r->u.update0->u.esRequest = (Z_IU0UpdateEsRequest *)
2272 odr_malloc(out, sizeof(*r->u.update0->u.esRequest));
2273 toKeep = r->u.update0->u.esRequest->toKeep = (Z_IU0OriginPartToKeep *)
2274 odr_malloc(out, sizeof(*r->u.update0->u.esRequest->toKeep));
2276 toKeep->databaseName = databaseNames[0];
2278 toKeep->elementSetName = 0;
2280 toKeep->action = (int *) odr_malloc(out, sizeof(*toKeep->action));
2281 *toKeep->action = action_no;
2283 notToKeep = r->u.update0->u.esRequest->notToKeep = (Z_IU0SuppliedRecords *)
2284 odr_malloc(out, sizeof(*r->u.update0->u.esRequest->notToKeep));
2286 notToKeep->elements = (Z_IU0SuppliedRecords_elem **)
2287 odr_malloc(out, sizeof(*notToKeep->elements));
2288 notToKeep->elements[0] = (Z_IU0SuppliedRecords_elem *)
2289 odr_malloc(out, sizeof(**notToKeep->elements));
2290 notToKeep->elements[0]->which = Z_IUSuppliedRecords_elem_opaque;
2293 notToKeep->elements[0]->u.opaque = (Odr_oct *)
2294 odr_malloc (out, sizeof(Odr_oct));
2295 notToKeep->elements[0]->u.opaque->buf = (unsigned char *) recid;
2296 notToKeep->elements[0]->u.opaque->size = strlen(recid);
2297 notToKeep->elements[0]->u.opaque->len = strlen(recid);
2300 notToKeep->elements[0]->u.opaque = 0;
2301 notToKeep->elements[0]->supplementalId = 0;
2302 notToKeep->elements[0]->correlationInfo = 0;
2303 notToKeep->elements[0]->record = record_this;
2307 Z_IUOriginPartToKeep *toKeep;
2308 Z_IUSuppliedRecords *notToKeep;
2310 r->which = Z_External_update;
2311 r->u.update = (Z_IUUpdate *) odr_malloc(out, sizeof(*r->u.update));
2312 r->u.update->which = Z_IUUpdate_esRequest;
2313 r->u.update->u.esRequest = (Z_IUUpdateEsRequest *)
2314 odr_malloc(out, sizeof(*r->u.update->u.esRequest));
2315 toKeep = r->u.update->u.esRequest->toKeep = (Z_IUOriginPartToKeep *)
2316 odr_malloc(out, sizeof(*r->u.update->u.esRequest->toKeep));
2318 toKeep->databaseName = databaseNames[0];
2320 toKeep->elementSetName = 0;
2321 toKeep->actionQualifier = 0;
2322 toKeep->action = (int *) odr_malloc(out, sizeof(*toKeep->action));
2323 *toKeep->action = action_no;
2325 notToKeep = r->u.update->u.esRequest->notToKeep = (Z_IUSuppliedRecords *)
2326 odr_malloc(out, sizeof(*r->u.update->u.esRequest->notToKeep));
2328 notToKeep->elements = (Z_IUSuppliedRecords_elem **)
2329 odr_malloc(out, sizeof(*notToKeep->elements));
2330 notToKeep->elements[0] = (Z_IUSuppliedRecords_elem *)
2331 odr_malloc(out, sizeof(**notToKeep->elements));
2332 notToKeep->elements[0]->which = Z_IUSuppliedRecords_elem_opaque;
2335 notToKeep->elements[0]->u.opaque = (Odr_oct *)
2336 odr_malloc (out, sizeof(Odr_oct));
2337 notToKeep->elements[0]->u.opaque->buf = (unsigned char *) recid;
2338 notToKeep->elements[0]->u.opaque->size = strlen(recid);
2339 notToKeep->elements[0]->u.opaque->len = strlen(recid);
2342 notToKeep->elements[0]->u.opaque = 0;
2343 notToKeep->elements[0]->supplementalId = 0;
2344 notToKeep->elements[0]->correlationInfo = 0;
2345 notToKeep->elements[0]->record = record_this;
2353 static int cmd_xmles(const char *arg)
2363 Z_APDU *apdu = zget_APDU(out, Z_APDU_extendedServicesRequest);
2364 Z_ExtendedServicesRequest *req = apdu->u.extendedServicesRequest;
2367 Z_External *ext = (Z_External *) odr_malloc(out, sizeof(*ext));
2369 req->referenceId = set_refid (out);
2370 req->taskSpecificParameters = ext;
2371 ext->indirect_reference = 0;
2372 ext->descriptor = 0;
2373 ext->which = Z_External_octet;
2374 ext->u.single_ASN1_type = (Odr_oct *) odr_malloc (out, sizeof(Odr_oct));
2375 sscanf(arg, "%50s%n", oid_str, &noread);
2378 printf("Missing OID for xmles\n");
2382 if (parse_cmd_doc(&arg, out, &asn_buf,
2383 &ext->u.single_ASN1_type->len, 0) == 0)
2386 ext->u.single_ASN1_type->buf = (unsigned char *) asn_buf;
2388 oid = yaz_string_to_oid_odr(yaz_oid_std(),
2389 CLASS_EXTSERV, oid_str, out);
2392 printf("Bad OID: %s\n", oid_str);
2396 req->packageType = oid;
2398 ext->direct_reference = oid;
2406 static int cmd_itemorder(const char *arg)
2413 if (sscanf (arg, "%10s %d", type, &itemno) != 2)
2416 printf("Item order request\n");
2418 send_itemorder(type, itemno);
2422 static void show_opt(const char *arg, void *clientData)
2424 printf ("%s ", arg);
2427 static int cmd_zversion(const char *arg)
2430 z3950_version = atoi(arg);
2432 printf ("version is %d\n", z3950_version);
2436 static int cmd_options(const char *arg)
2442 r = yaz_init_opt_encode(&z3950_options, arg, &pos);
2444 printf("Unknown option(s) near %s\n", arg+pos);
2448 yaz_init_opt_decode(&z3950_options, show_opt, 0);
2454 static int cmd_explain(const char *arg)
2456 if (protocol != PROTO_HTTP)
2467 /* save this for later .. when fetching individual records */
2468 sr = yaz_srw_get(out, Z_SRW_explain_request);
2469 if (recordsyntax_size == 1
2470 && !yaz_matchstr(recordsyntax_list[0], "xml"))
2471 sr->u.explain_request->recordPacking = "xml";
2479 static int cmd_init(const char *arg)
2483 strncpy (cur_host, arg, sizeof(cur_host)-1);
2484 cur_host[sizeof(cur_host)-1] = 0;
2488 send_initRequest(cur_host);
2492 static int cmd_sru(const char *arg)
2496 printf("SRU method is: %s\n", sru_method);
2500 if (!yaz_matchstr(arg, "post"))
2501 sru_method = "post";
2502 else if (!yaz_matchstr(arg, "get"))
2504 else if (!yaz_matchstr(arg, "soap"))
2505 sru_method = "soap";
2508 printf("Unknown SRU method: %s\n", arg);
2509 printf("Specify one of POST, GET, SOAP\n");
2515 static int cmd_find(const char *arg)
2519 printf("Find what?\n");
2522 if (protocol == PROTO_HTTP)
2529 if (!send_SRW_searchRequest(arg))
2542 printf("Not connected yet\n");
2546 if (!send_searchRequest(arg))
2552 static int cmd_delete(const char *arg)
2556 if (!send_deleteResultSetRequest(arg))
2561 static int cmd_ssub(const char *arg)
2563 if (!(smallSetUpperBound = atoi(arg)))
2568 static int cmd_lslb(const char *arg)
2570 if (!(largeSetLowerBound = atoi(arg)))
2575 static int cmd_mspn(const char *arg)
2577 if (!(mediumSetPresentNumber = atoi(arg)))
2582 static int cmd_status(const char *arg)
2584 printf("smallSetUpperBound: %d\n", smallSetUpperBound);
2585 printf("largeSetLowerBound: %d\n", largeSetLowerBound);
2586 printf("mediumSetPresentNumber: %d\n", mediumSetPresentNumber);
2590 static int cmd_setnames(const char *arg)
2592 if (*arg == '1') /* enable ? */
2594 else if (*arg == '0') /* disable ? */
2596 else if (setnumber < 0) /* no args, toggle .. */
2602 printf("Set numbering enabled.\n");
2604 printf("Set numbering disabled.\n");
2608 /* PRESENT SERVICE ----------------------------- */
2610 static void parse_show_args(const char *arg_c, char *setstring,
2611 int *start, int *number)
2616 strncpy(arg, arg_c, sizeof(arg)-1);
2617 arg[sizeof(arg)-1] = '\0';
2619 if ((p = strchr(arg, '+')))
2621 *number = atoi(p + 1);
2626 if (!strcmp(arg, "all"))
2628 *number = last_hit_count;
2634 if (p && (p=strchr(p+1, '+')))
2635 strcpy (setstring, p+1);
2636 else if (setnumber >= 0)
2637 sprintf(setstring, "%d", setnumber);
2642 static int send_presentRequest(const char *arg)
2644 Z_APDU *apdu = zget_APDU(out, Z_APDU_presentRequest);
2645 Z_PresentRequest *req = apdu->u.presentRequest;
2646 Z_RecordComposition compo;
2648 char setstring[100];
2650 req->referenceId = set_refid (out);
2652 parse_show_args(arg, setstring, &setno, &nos);
2654 req->resultSetId = setstring;
2656 req->resultSetStartPoint = &setno;
2657 req->numberOfRecordsRequested = &nos;
2659 if (recordsyntax_size)
2660 req->preferredRecordSyntax =
2661 yaz_string_to_oid_odr(yaz_oid_std(),
2662 CLASS_RECSYN, recordsyntax_list[0], out);
2664 if (record_schema || recordsyntax_size >= 2)
2666 req->recordComposition = &compo;
2667 compo.which = Z_RecordComp_complex;
2668 compo.u.complex = (Z_CompSpec *)
2669 odr_malloc(out, sizeof(*compo.u.complex));
2670 compo.u.complex->selectAlternativeSyntax = (bool_t *)
2671 odr_malloc(out, sizeof(bool_t));
2672 *compo.u.complex->selectAlternativeSyntax = 0;
2674 compo.u.complex->generic = (Z_Specification *)
2675 odr_malloc(out, sizeof(*compo.u.complex->generic));
2677 compo.u.complex->generic->which = Z_Schema_oid;
2679 compo.u.complex->generic->schema.oid = 0;
2682 compo.u.complex->generic->schema.oid =
2683 yaz_string_to_oid_odr(yaz_oid_std(),
2684 CLASS_SCHEMA, record_schema, out);
2686 if (!compo.u.complex->generic->schema.oid)
2688 /* OID wasn't a schema! Try record syntax instead. */
2689 compo.u.complex->generic->schema.oid = (Odr_oid *)
2690 yaz_string_to_oid_odr(yaz_oid_std(),
2691 CLASS_RECSYN, record_schema, out);
2694 if (!elementSetNames)
2695 compo.u.complex->generic->elementSpec = 0;
2698 compo.u.complex->generic->elementSpec = (Z_ElementSpec *)
2699 odr_malloc(out, sizeof(Z_ElementSpec));
2700 compo.u.complex->generic->elementSpec->which =
2701 Z_ElementSpec_elementSetName;
2702 compo.u.complex->generic->elementSpec->u.elementSetName =
2703 elementSetNames->u.generic;
2705 compo.u.complex->num_dbSpecific = 0;
2706 compo.u.complex->dbSpecific = 0;
2708 compo.u.complex->num_recordSyntax = 0;
2709 compo.u.complex->recordSyntax = 0;
2710 if (recordsyntax_size >= 2)
2713 compo.u.complex->num_recordSyntax = recordsyntax_size;
2714 compo.u.complex->recordSyntax = (Odr_oid **)
2715 odr_malloc(out, recordsyntax_size * sizeof(Odr_oid*));
2716 for (i = 0; i < recordsyntax_size; i++)
2717 compo.u.complex->recordSyntax[i] =
2718 yaz_string_to_oid_odr(yaz_oid_std(),
2719 CLASS_RECSYN, recordsyntax_list[i], out);
2722 else if (elementSetNames)
2724 req->recordComposition = &compo;
2725 compo.which = Z_RecordComp_simple;
2726 compo.u.simple = elementSetNames;
2729 printf("Sent presentRequest (%d+%d).\n", setno, nos);
2734 static int send_SRW_presentRequest(const char *arg)
2736 char setstring[100];
2738 Z_SRW_PDU *sr = srw_sr;
2742 parse_show_args(arg, setstring, &setno, &nos);
2743 sr->u.request->startRecord = odr_intdup(out, setno);
2744 sr->u.request->maximumRecords = odr_intdup(out, nos);
2746 sr->u.request->recordSchema = record_schema;
2747 if (recordsyntax_size == 1 && !yaz_matchstr(recordsyntax_list[0], "xml"))
2748 sr->u.request->recordPacking = "xml";
2749 return send_srw(sr);
2753 static void close_session (void)
2765 void process_close(Z_Close *req)
2767 Z_APDU *apdu = zget_APDU(out, Z_APDU_close);
2768 Z_Close *res = apdu->u.close;
2770 static char *reasons[] =
2775 "cost limit reached",
2777 "security violation",
2784 printf("Reason: %s, message: %s\n", reasons[*req->closeReason],
2785 req->diagnosticInformation ? req->diagnosticInformation : "NULL");
2790 *res->closeReason = Z_Close_finished;
2792 printf("Sent response.\n");
2797 static int cmd_show(const char *arg)
2799 if (protocol == PROTO_HTTP)
2806 if (!send_SRW_presentRequest(arg))
2816 printf("Not connected yet\n");
2819 if (!send_presentRequest(arg))
2825 void exit_client(int code)
2827 file_history_save(file_history);
2828 file_history_destroy(&file_history);
2832 int cmd_quit(const char *arg)
2834 printf("See you later, alligator.\n");
2840 int cmd_cancel(const char *arg)
2842 Z_APDU *apdu = zget_APDU(out, Z_APDU_triggerResourceControlRequest);
2843 Z_TriggerResourceControlRequest *req =
2844 apdu->u.triggerResourceControlRequest;
2849 sscanf(arg, "%15s", command);
2853 if (session_initResponse &&
2854 !ODR_MASK_GET(session_initResponse->options,
2855 Z_Options_triggerResourceCtrl))
2857 printf("Target doesn't support cancel (trigger resource ctrl)\n");
2860 *req->requestedAction = Z_TriggerResourceControlRequest_cancel;
2861 req->resultSetWanted = &rfalse;
2862 req->referenceId = set_refid (out);
2865 printf("Sent cancel request\n");
2866 if (!strcmp(command, "wait"))
2872 int cmd_cancel_find(const char *arg) {
2876 return cmd_cancel("");
2881 int send_scanrequest(const char *query, int pp, int num, const char *term)
2883 Z_APDU *apdu = zget_APDU(out, Z_APDU_scanRequest);
2884 Z_ScanRequest *req = apdu->u.scanRequest;
2888 if (queryType == QueryType_CCL2RPN)
2891 struct ccl_rpn_node *rpn;
2893 rpn = ccl_find_str (bibset, query, &error, &pos);
2896 printf("CCL ERROR: %s\n", ccl_err_msg(error));
2900 yaz_string_to_oid_odr(yaz_oid_std(),
2901 CLASS_ATTSET, "Bib-1", out);
2902 if (!(req->termListAndStartPoint = ccl_scan_query (out, rpn)))
2904 printf("Couldn't convert CCL to Scan term\n");
2907 ccl_rpn_delete (rpn);
2911 YAZ_PQF_Parser pqf_parser = yaz_pqf_create ();
2913 if (!(req->termListAndStartPoint =
2914 yaz_pqf_scan(pqf_parser, out, &req->attributeSet, query)))
2916 const char *pqf_msg;
2918 int code = yaz_pqf_error (pqf_parser, &pqf_msg, &off);
2920 printf("%*s^\n", ioff+7, "");
2921 printf("Prefix query error: %s (code %d)\n", pqf_msg, code);
2922 yaz_pqf_destroy (pqf_parser);
2925 yaz_pqf_destroy (pqf_parser);
2929 if (req->termListAndStartPoint->term &&
2930 req->termListAndStartPoint->term->which == Z_Term_general &&
2931 req->termListAndStartPoint->term->u.general)
2933 req->termListAndStartPoint->term->u.general->buf =
2934 (unsigned char *) odr_strdup(out, term);
2935 req->termListAndStartPoint->term->u.general->len =
2936 req->termListAndStartPoint->term->u.general->size =
2940 req->referenceId = set_refid (out);
2941 req->num_databaseNames = num_databaseNames;
2942 req->databaseNames = databaseNames;
2943 req->numberOfTermsRequested = #
2944 req->preferredPositionInResponse = &pp;
2945 req->stepSize = odr_intdup(out, scan_stepSize);
2950 int send_sortrequest(const char *arg, int newset)
2952 Z_APDU *apdu = zget_APDU(out, Z_APDU_sortRequest);
2953 Z_SortRequest *req = apdu->u.sortRequest;
2954 Z_SortKeySpecList *sksl = (Z_SortKeySpecList *)
2955 odr_malloc (out, sizeof(*sksl));
2961 sprintf (setstring, "%d", setnumber);
2963 sprintf (setstring, "default");
2965 req->referenceId = set_refid (out);
2967 req->num_inputResultSetNames = 1;
2968 req->inputResultSetNames = (Z_InternationalString **)
2969 odr_malloc (out, sizeof(*req->inputResultSetNames));
2970 req->inputResultSetNames[0] = odr_strdup (out, setstring);
2972 if (newset && setnumber >= 0)
2973 sprintf (setstring, "%d", ++setnumber);
2975 req->sortedResultSetName = odr_strdup (out, setstring);
2977 req->sortSequence = yaz_sort_spec (out, arg);
2978 if (!req->sortSequence)
2980 printf ("Missing sort specifications\n");
2987 void display_term(Z_TermInfo *t)
2990 printf("%s", t->displayTerm);
2991 else if (t->term->which == Z_Term_general)
2993 printf("%.*s", t->term->u.general->len, t->term->u.general->buf);
2994 sprintf(last_scan_line, "%.*s", t->term->u.general->len,
2995 t->term->u.general->buf);
2998 printf("Term (not general)");
2999 if (t->globalOccurrences)
3000 printf (" (%d)\n", *t->globalOccurrences);
3005 void process_scanResponse(Z_ScanResponse *res)
3008 Z_Entry **entries = NULL;
3009 int num_entries = 0;
3011 printf("Received ScanResponse\n");
3012 print_refid (res->referenceId);
3013 printf("%d entries", *res->numberOfEntriesReturned);
3014 if (res->positionOfTerm)
3015 printf (", position=%d", *res->positionOfTerm);
3017 if (*res->scanStatus != Z_Scan_success)
3018 printf("Scan returned code %d\n", *res->scanStatus);
3021 if ((entries = res->entries->entries))
3022 num_entries = res->entries->num_entries;
3023 for (i = 0; i < num_entries; i++)
3025 int pos_term = res->positionOfTerm ? *res->positionOfTerm : -1;
3026 if (entries[i]->which == Z_Entry_termInfo)
3028 printf("%c ", i + 1 == pos_term ? '*' : ' ');
3029 display_term(entries[i]->u.termInfo);
3032 display_diagrecs(&entries[i]->u.surrogateDiagnostic, 1);
3034 if (res->entries->nonsurrogateDiagnostics)
3035 display_diagrecs (res->entries->nonsurrogateDiagnostics,
3036 res->entries->num_nonsurrogateDiagnostics);
3039 void process_sortResponse(Z_SortResponse *res)
3041 printf("Received SortResponse: status=");
3042 switch (*res->sortStatus)
3044 case Z_SortResponse_success:
3045 printf ("success"); break;
3046 case Z_SortResponse_partial_1:
3047 printf ("partial"); break;
3048 case Z_SortResponse_failure:
3049 printf ("failure"); break;
3051 printf ("unknown (%d)", *res->sortStatus);
3054 print_refid (res->referenceId);
3055 if (res->diagnostics)
3056 display_diagrecs(res->diagnostics,
3057 res->num_diagnostics);
3060 void process_deleteResultSetResponse (Z_DeleteResultSetResponse *res)
3062 printf("Got deleteResultSetResponse status=%d\n",
3063 *res->deleteOperationStatus);
3064 if (res->deleteListStatuses)
3067 for (i = 0; i < res->deleteListStatuses->num; i++)
3069 printf ("%s status=%d\n", res->deleteListStatuses->elements[i]->id,
3070 *res->deleteListStatuses->elements[i]->status);
3075 int cmd_sort_generic(const char *arg, int newset)
3079 if (session_initResponse &&
3080 !ODR_MASK_GET(session_initResponse->options, Z_Options_sort))
3082 printf("Target doesn't support sort\n");
3087 if (send_sortrequest(arg, newset) < 0)
3094 int cmd_sort(const char *arg)
3096 return cmd_sort_generic (arg, 0);
3099 int cmd_sort_newset (const char *arg)
3101 return cmd_sort_generic (arg, 1);
3104 int cmd_scanstep(const char *arg)
3106 scan_stepSize = atoi(arg);
3110 int cmd_scanpos(const char *arg)
3112 int r = sscanf(arg, "%d", &scan_position);
3118 int cmd_scansize(const char *arg)
3120 int r = sscanf(arg, "%d", &scan_size);
3126 int cmd_scan(const char *arg)
3128 if (protocol == PROTO_HTTP)
3137 if (send_SRW_scanRequest(arg, scan_position, scan_size) < 0)
3142 if (send_SRW_scanRequest(last_scan_line, 1, scan_size) < 0)
3157 printf("Session not initialized yet\n");
3161 if (session_initResponse &&
3162 !ODR_MASK_GET(session_initResponse->options, Z_Options_scan))
3164 printf("Target doesn't support scan\n");
3169 strcpy (last_scan_query, arg);
3170 if (send_scanrequest(arg, scan_position, scan_size, 0) < 0)
3175 if (send_scanrequest(last_scan_query, 1, scan_size, last_scan_line) < 0)
3182 int cmd_schema(const char *arg)
3184 xfree(record_schema);
3187 record_schema = xstrdup(arg);
3191 int cmd_format(const char *arg)
3193 const char *cp = arg;
3200 printf("Usage: format <recordsyntax>\n");
3203 for (i = 0; i < recordsyntax_size; i++)
3205 xfree(recordsyntax_list[i]);
3206 recordsyntax_list[i] = 0;
3209 while (sscanf(cp, "%40s%n", form_str, &nor) >= 1 && nor > 0
3210 && idx < RECORDSYNTAX_MAX)
3212 if (!strcmp(form_str, "none"))
3214 recordsyntax_list[idx] = xstrdup(form_str);
3218 recordsyntax_size = idx;
3222 int cmd_elements(const char *arg)
3224 static Z_ElementSetNames esn;
3225 static char what[100];
3229 elementSetNames = 0;
3233 esn.which = Z_ElementSetNames_generic;
3234 esn.u.generic = what;
3235 elementSetNames = &esn;
3239 int cmd_querytype (const char *arg)
3241 if (!strcmp (arg, "ccl"))
3242 queryType = QueryType_CCL;
3243 else if (!strcmp (arg, "prefix") || !strcmp(arg, "rpn"))
3244 queryType = QueryType_Prefix;
3245 else if (!strcmp (arg, "ccl2rpn") || !strcmp (arg, "cclrpn"))
3246 queryType = QueryType_CCL2RPN;
3247 else if (!strcmp(arg, "cql"))
3248 queryType = QueryType_CQL;
3249 else if (!strcmp (arg, "cql2rpn") || !strcmp (arg, "cqlrpn"))
3250 queryType = QueryType_CQL2RPN;
3253 printf ("Querytype must be one of:\n");
3254 printf (" prefix - Prefix query\n");
3255 printf (" ccl - CCL query\n");
3256 printf (" ccl2rpn - CCL query converted to RPN\n");
3257 printf (" cql - CQL\n");
3258 printf (" cql2rpn - CQL query converted to RPN\n");
3264 int cmd_refid (const char *arg)
3269 refid = xstrdup (arg);
3273 int cmd_close(const char *arg)
3279 apdu = zget_APDU(out, Z_APDU_close);
3280 req = apdu->u.close;
3281 *req->closeReason = Z_Close_finished;
3283 printf("Sent close request.\n");
3288 int cmd_packagename(const char* arg)
3290 xfree (esPackageName);
3291 esPackageName = NULL;
3293 esPackageName = xstrdup(arg);
3297 int cmd_proxy(const char* arg)
3302 yazProxy = xstrdup (arg);
3306 int cmd_marccharset(const char *arg)
3311 if (sscanf(arg, "%29s", l1) < 1)
3313 printf("MARC character set is `%s'\n",
3314 marcCharset ? marcCharset: "none");
3317 xfree (marcCharset);
3319 if (strcmp(l1, "-"))
3320 marcCharset = xstrdup(l1);
3324 int cmd_displaycharset(const char *arg)
3329 if (sscanf(arg, "%29s", l1) < 1)
3331 printf("Display character set is `%s'\n",
3332 outputCharset ? outputCharset: "none");
3336 xfree (outputCharset);
3338 if (!strcmp(l1, "auto") && codeset)
3342 printf ("Display character set: %s\n", codeset);
3343 outputCharset = xstrdup(codeset);
3346 printf ("No codeset found on this system\n");
3348 else if (strcmp(l1, "-") && strcmp(l1, "none"))
3349 outputCharset = xstrdup(l1);
3354 int cmd_negcharset(const char *arg)
3359 if (sscanf(arg, "%29s %d %d", l1, &negotiationCharsetRecords,
3360 &negotiationCharsetVersion) < 1)
3362 printf("Current negotiation character set is `%s'\n",
3363 negotiationCharset ? negotiationCharset: "none");
3364 printf("Records in charset %s\n", negotiationCharsetRecords ?
3366 printf("Charneg version %d\n", negotiationCharsetVersion);
3370 xfree (negotiationCharset);
3371 negotiationCharset = NULL;
3372 if (*l1 && strcmp(l1, "-") && strcmp(l1, "none"))
3374 negotiationCharset = xstrdup(l1);
3375 printf ("Character set negotiation : %s\n", negotiationCharset);
3381 int cmd_charset(const char* arg)
3383 char l1[30], l2[30], l3[30];
3385 *l1 = *l2 = *l3 = 0;
3386 if (sscanf(arg, "%29s %29s %29s", l1, l2, l3) < 1)
3389 cmd_displaycharset("");
3390 cmd_marccharset("");
3396 cmd_displaycharset(l2);
3398 cmd_marccharset(l3);
3403 int cmd_lang(const char* arg)
3406 printf("Current language is `%s'\n", (yazLang)?yazLang:NULL);
3412 yazLang = xstrdup(arg);
3416 int cmd_source(const char* arg, int echo )
3418 /* first should open the file and read one line at a time.. */
3420 char line[102400], *cp;
3423 fprintf(stderr,"Error in source command use a filename\n");
3427 includeFile = fopen (arg, "r");
3430 fprintf(stderr,"Unable to open file %s for reading\n",arg);
3434 while(!feof(includeFile)) {
3435 memset(line,0,sizeof(line));
3436 fgets(line,sizeof(line),includeFile);
3438 if(strlen(line) < 2) continue;
3439 if(line[0] == '#') continue;
3441 if ((cp = strrchr (line, '\n')))
3445 printf( "processing line: %s\n",line );
3447 process_cmd_line(line);
3450 if(fclose(includeFile)<0) {
3451 perror("unable to close include file");
3457 int cmd_source_echo(const char* arg)
3463 int cmd_source_noecho(const char* arg)
3470 int cmd_subshell(const char* args)
3475 system(getenv("SHELL"));
3481 int cmd_set_berfile(const char *arg)
3483 if (ber_file && ber_file != stdout && ber_file != stderr)
3485 if (!strcmp(arg, ""))
3487 else if (!strcmp(arg, "-"))
3490 ber_file = fopen(arg, "a");
3494 int cmd_set_apdufile(const char *arg)
3496 if(apdu_file && apdu_file != stderr && apdu_file != stderr)
3498 if (!strcmp(arg, ""))
3500 else if (!strcmp(arg, "-"))
3504 apdu_file = fopen(arg, "a");
3506 perror("unable to open apdu log file");
3509 odr_setprint(print, apdu_file);
3513 int cmd_set_cclfile(const char* arg)
3517 bibset = ccl_qual_mk ();
3518 inf = fopen (arg, "r");
3520 perror("unable to open CCL file");
3523 ccl_qual_file (bibset, inf);
3526 strcpy(ccl_fields,arg);
3530 int cmd_set_cqlfile(const char* arg)
3532 cql_transform_t newcqltrans;
3534 if ((newcqltrans = cql_transform_open_fname(arg)) == 0) {
3535 perror("unable to open CQL file");
3539 cql_transform_close(cqltrans);
3541 cqltrans = newcqltrans;
3542 strcpy(cql_fields, arg);
3546 int cmd_set_auto_reconnect(const char* arg)
3548 if(strlen(arg)==0) {
3549 auto_reconnect = ! auto_reconnect;
3550 } else if(strcmp(arg,"on")==0) {
3552 } else if(strcmp(arg,"off")==0) {
3555 printf("Error use on or off\n");
3560 printf("Set auto reconnect enabled.\n");
3562 printf("Set auto reconnect disabled.\n");
3568 int cmd_set_auto_wait(const char* arg)
3570 if(strlen(arg)==0) {
3571 auto_wait = ! auto_wait;
3572 } else if(strcmp(arg,"on")==0) {
3574 } else if(strcmp(arg,"off")==0) {
3577 printf("Error use on or off\n");
3582 printf("Set auto wait enabled.\n");
3584 printf("Set auto wait disabled.\n");
3589 int cmd_set_marcdump(const char* arg)
3591 if(marc_file && marc_file != stderr) { /* don't close stdout*/
3595 if (!strcmp(arg, ""))
3597 else if (!strcmp(arg, "-"))
3601 marc_file = fopen(arg, "a");
3603 perror("unable to open marc log file");
3609 this command takes 3 arge {name class oid}
3611 int cmd_register_oid(const char* args) {
3616 {"appctx",CLASS_APPCTX},
3617 {"absyn",CLASS_ABSYN},
3618 {"attset",CLASS_ATTSET},
3619 {"transyn",CLASS_TRANSYN},
3620 {"diagset",CLASS_DIAGSET},
3621 {"recsyn",CLASS_RECSYN},
3622 {"resform",CLASS_RESFORM},
3623 {"accform",CLASS_ACCFORM},
3624 {"extserv",CLASS_EXTSERV},
3625 {"userinfo",CLASS_USERINFO},
3626 {"elemspec",CLASS_ELEMSPEC},
3627 {"varset",CLASS_VARSET},
3628 {"schema",CLASS_SCHEMA},
3629 {"tagset",CLASS_TAGSET},
3630 {"general",CLASS_GENERAL},
3631 {0,(enum oid_class) 0}
3633 char oname_str[101], oclass_str[101], oid_str[101];
3635 int oidclass = CLASS_GENERAL;
3638 if (sscanf (args, "%100[^ ] %100[^ ] %100s",
3639 oname_str,oclass_str, oid_str) < 1) {
3640 printf("Error in register command \n");
3644 for (i = 0; oid_classes[i].className; i++) {
3645 if (!strcmp(oid_classes[i].className, oclass_str))
3647 oidclass=oid_classes[i].oclass;
3652 if(!(oid_classes[i].className)) {
3653 printf("Unknown oid class %s\n",oclass_str);
3657 oid_dotstring_to_oid(oid_str, oid);
3659 if (yaz_oid_add(yaz_oid_std(), oidclass, oname_str, oid))
3661 printf("oid %s already exists, registration failed\n",
3667 int cmd_push_command(const char* arg)
3669 #if HAVE_READLINE_HISTORY_H
3673 fprintf(stderr,"Not compiled with the readline/history module\n");
3678 void source_rcfile(void)
3680 /* Look for a $HOME/.yazclientrc and source it if it exists */
3681 struct stat statbuf;
3683 char* homedir = getenv("HOME");
3685 sprintf(fname, "%.500s%s%s", homedir ? homedir : "",
3689 if (stat(fname,&statbuf)==0)
3690 cmd_source(fname, 0 );
3693 void add_to_readline_history(void *client_data, const char *line)
3695 #if HAVE_READLINE_HISTORY_H
3701 static void initialize(void)
3706 if (!(out = odr_createmem(ODR_ENCODE)) ||
3707 !(in = odr_createmem(ODR_DECODE)) ||
3708 !(print = odr_createmem(ODR_PRINT)))
3710 fprintf(stderr, "failed to allocate ODR streams\n");
3714 setvbuf(stdout, 0, _IONBF, 0);
3716 odr_setprint(print, apdu_file);
3718 bibset = ccl_qual_mk ();
3719 inf = fopen (ccl_fields, "r");
3722 ccl_qual_file (bibset, inf);
3726 cqltrans = cql_transform_open_fname(cql_fields);
3727 /* If this fails, no problem: we detect cqltrans == 0 later */
3729 #if HAVE_READLINE_READLINE_H
3730 rl_attempted_completion_function = (CPPFunction*)readline_completer;
3732 for(i = 0; i < maxOtherInfosSupported; ++i) {
3733 extraOtherInfos[i].oid[0] = -1;
3734 extraOtherInfos[i].value = 0;
3737 cmd_format("usmarc");
3741 file_history = file_history_new();
3742 file_history_load(file_history);
3743 file_history_trav(file_history, 0, add_to_readline_history);
3747 #if HAVE_GETTIMEOFDAY
3748 struct timeval tv_start;
3752 static void handle_srw_record(Z_SRW_record *rec)
3754 if (rec->recordPosition)
3756 printf ("pos=%d", *rec->recordPosition);
3757 setno = *rec->recordPosition + 1;
3759 if (rec->recordSchema)
3760 printf (" schema=%s", rec->recordSchema);
3762 if (rec->recordData_buf && rec->recordData_len)
3764 fwrite(rec->recordData_buf, 1, rec->recordData_len, stdout);
3766 fwrite (rec->recordData_buf, 1, rec->recordData_len, marc_file);
3769 printf ("No data!");
3773 static void handle_srw_explain_response(Z_SRW_explainResponse *res)
3775 handle_srw_record(&res->record);
3778 static void handle_srw_response(Z_SRW_searchRetrieveResponse *res)
3782 printf ("Received SRW SearchRetrieve Response\n");
3784 for (i = 0; i<res->num_diagnostics; i++)
3786 if (res->diagnostics[i].uri)
3787 printf ("SRW diagnostic %s\n",
3788 res->diagnostics[i].uri);
3790 printf ("SRW diagnostic missing or could not be decoded\n");
3791 if (res->diagnostics[i].message)
3792 printf ("Message: %s\n", res->diagnostics[i].message);
3793 if (res->diagnostics[i].details)
3794 printf ("Details: %s\n", res->diagnostics[i].details);
3796 if (res->numberOfRecords)
3797 printf ("Number of hits: %d\n", *res->numberOfRecords);
3798 for (i = 0; i<res->num_records; i++)
3799 handle_srw_record(res->records + i);
3802 static void handle_srw_scan_term(Z_SRW_scanTerm *term)
3804 if (term->displayTerm)
3805 printf("%s:", term->displayTerm);
3806 else if (term->value)
3807 printf("%s:", term->value);
3809 printf("No value:");
3810 if (term->numberOfRecords)
3811 printf(" %d", *term->numberOfRecords);
3812 if (term->whereInList)
3813 printf(" %s", term->whereInList);
3814 if (term->value && term->displayTerm)
3815 printf(" %s", term->value);
3817 strcpy(last_scan_line, term->value);
3821 static void handle_srw_scan_response(Z_SRW_scanResponse *res)
3825 printf ("Received SRW Scan Response\n");
3827 for (i = 0; i<res->num_diagnostics; i++)
3829 if (res->diagnostics[i].uri)
3830 printf ("SRW diagnostic %s\n",
3831 res->diagnostics[i].uri);
3833 printf ("SRW diagnostic missing or could not be decoded\n");
3834 if (res->diagnostics[i].message)
3835 printf ("Message: %s\n", res->diagnostics[i].message);
3836 if (res->diagnostics[i].details)
3837 printf ("Details: %s\n", res->diagnostics[i].details);
3840 for (i = 0; i<res->num_terms; i++)
3841 handle_srw_scan_term(res->terms + i);
3844 static void http_response(Z_HTTP_Response *hres)
3847 const char *content_type = z_HTTP_header_lookup(hres->headers,
3849 const char *connection_head = z_HTTP_header_lookup(hres->headers,
3851 if (content_type && !yaz_strcmp_del("text/xml", content_type, "; "))
3853 Z_SOAP *soap_package = 0;
3854 ODR o = odr_createmem(ODR_DECODE);
3855 Z_SOAP_Handler soap_handlers[3] = {
3856 {YAZ_XMLNS_SRU_v1_1, 0, (Z_SOAP_fun) yaz_srw_codec},
3857 {YAZ_XMLNS_UPDATE_v0_9, 0, (Z_SOAP_fun) yaz_ucp_codec},
3860 ret = z_soap_codec(o, &soap_package,
3861 &hres->content_buf, &hres->content_len,
3863 if (!ret && soap_package->which == Z_SOAP_generic)
3865 Z_SRW_PDU *sr = soap_package->u.generic->p;
3866 if (sr->which == Z_SRW_searchRetrieve_response)
3867 handle_srw_response(sr->u.response);
3868 else if (sr->which == Z_SRW_explain_response)
3869 handle_srw_explain_response(sr->u.explain_response);
3870 else if (sr->which == Z_SRW_scan_response)
3871 handle_srw_scan_response(sr->u.scan_response);
3872 else if (sr->which == Z_SRW_update_response)
3873 printf("Got update response. Status: %s\n",
3874 sr->u.update_response->operationStatus);
3878 else if (soap_package && (soap_package->which == Z_SOAP_fault
3879 || soap_package->which == Z_SOAP_error))
3881 printf ("HTTP Error Status=%d\n", hres->code);
3882 printf ("SOAP Fault code %s\n",
3883 soap_package->u.fault->fault_code);
3884 printf ("SOAP Fault string %s\n",
3885 soap_package->u.fault->fault_string);
3886 if (soap_package->u.fault->details)
3887 printf ("SOAP Details %s\n",
3888 soap_package->u.fault->details);
3892 printf("z_soap_codec failed. (no SOAP error)\n");
3899 if (hres->code != 200)
3901 printf ("HTTP Error Status=%d\n", hres->code);
3905 printf ("Decoding of SRW package failed\n");
3911 if (!strcmp(hres->version, "1.0"))
3913 /* HTTP 1.0: only if Keep-Alive we stay alive.. */
3914 if (!connection_head || strcmp(connection_head, "Keep-Alive"))
3919 /* HTTP 1.1: only if no close we stay alive .. */
3920 if (connection_head && !strcmp(connection_head, "close"))
3927 void wait_and_handle_response(int one_response_only)
3929 int reconnect_ok = 1;
3932 int netbufferlen = 0;
3933 #if HAVE_GETTIMEOFDAY
3935 struct timeval tv_end;
3941 res = cs_get(conn, &netbuffer, &netbufferlen);
3942 if (reconnect_ok && res <= 0 && protocol == PROTO_HTTP)
3953 buf_out = odr_getbuf(out, &len_out, 0);
3955 do_hex_dump(buf_out, len_out);
3957 cs_put(conn, buf_out, len_out);
3965 printf("Target closed connection\n");
3969 #if HAVE_GETTIMEOFDAY
3970 if (got_tv_end == 0)
3971 gettimeofday (&tv_end, 0); /* count first one only */
3975 odr_reset(in); /* release APDU from last round */
3977 do_hex_dump(netbuffer, res);
3978 odr_setbuf(in, netbuffer, res, 0);
3980 if (!z_GDU(in, &gdu, 0, 0))
3982 FILE *f = ber_file ? ber_file : stdout;
3983 odr_perror(in, "Decoding incoming APDU");
3984 fprintf(f, "[Near %ld]\n", (long) odr_offset(in));
3985 fprintf(f, "Packet dump:\n---------\n");
3986 odr_dumpBER(f, netbuffer, res);
3987 fprintf(f, "---------\n");
3990 z_GDU(print, &gdu, 0, 0);
3993 if (conn && cs_more(conn))
3998 odr_dumpBER(ber_file, netbuffer, res);
3999 if (apdu_file && !z_GDU(print, &gdu, 0, 0))
4001 odr_perror(print, "Failed to print incoming APDU");
4005 if (gdu->which == Z_GDU_Z3950)
4007 Z_APDU *apdu = gdu->u.z3950;
4010 case Z_APDU_initResponse:
4011 process_initResponse(apdu->u.initResponse);
4013 case Z_APDU_searchResponse:
4014 process_searchResponse(apdu->u.searchResponse);
4016 case Z_APDU_scanResponse:
4017 process_scanResponse(apdu->u.scanResponse);
4019 case Z_APDU_presentResponse:
4020 print_refid (apdu->u.presentResponse->referenceId);
4022 *apdu->u.presentResponse->numberOfRecordsReturned;
4023 if (apdu->u.presentResponse->records)
4024 display_records(apdu->u.presentResponse->records);
4026 printf("No records.\n");
4027 printf ("nextResultSetPosition = %d\n",
4028 *apdu->u.presentResponse->nextResultSetPosition);
4030 case Z_APDU_sortResponse:
4031 process_sortResponse(apdu->u.sortResponse);
4033 case Z_APDU_extendedServicesResponse:
4034 printf("Got extended services response\n");
4035 process_ESResponse(apdu->u.extendedServicesResponse);
4038 printf("Target has closed the association.\n");
4039 process_close(apdu->u.close);
4041 case Z_APDU_resourceControlRequest:
4042 process_resourceControlRequest
4043 (apdu->u.resourceControlRequest);
4045 case Z_APDU_deleteResultSetResponse:
4046 process_deleteResultSetResponse(apdu->u.
4047 deleteResultSetResponse);
4050 printf("Received unknown APDU type (%d).\n",
4056 else if (gdu->which == Z_GDU_HTTP_Response)
4058 http_response(gdu->u.HTTP_Response);
4061 if (one_response_only)
4063 if (conn && !cs_more(conn))
4066 #if HAVE_GETTIMEOFDAY
4070 printf ("S/U S/U=%ld/%ld %ld/%ld",
4071 (long) tv_start.tv_sec,
4072 (long) tv_start.tv_usec,
4073 (long) tv_end.tv_sec,
4074 (long) tv_end.tv_usec);
4076 printf ("Elapsed: %.6f\n",
4077 (double) tv_end.tv_usec / 1e6 + tv_end.tv_sec -
4078 ((double) tv_start.tv_usec / 1e6 + tv_start.tv_sec));
4085 int cmd_cclparse(const char* arg)
4088 struct ccl_rpn_node *rpn=NULL;
4091 rpn = ccl_find_str (bibset, arg, &error, &pos);
4094 int ioff = 3+strlen(last_cmd)+1+pos;
4095 printf ("%*s^ - ", ioff, " ");
4096 printf ("%s\n", ccl_err_msg (error));
4102 ccl_pr_tree(rpn, stdout);
4106 ccl_rpn_delete(rpn);
4114 int cmd_set_otherinfo(const char* args)
4116 char oidstr[101], otherinfoString[101];
4120 sscan_res = sscanf (args, "%d %100[^ ] %100s",
4121 &otherinfoNo, oidstr, otherinfoString);
4123 if (sscan_res > 0 && otherinfoNo >= maxOtherInfosSupported) {
4124 printf("Error otherinfo index too large (%d>=%d)\n",
4125 otherinfoNo,maxOtherInfosSupported);
4132 /* reset this otherinfo */
4133 extraOtherInfos[otherinfoNo].oid[0] = -1;
4134 xfree(extraOtherInfos[otherinfoNo].value);
4135 extraOtherInfos[otherinfoNo].value = 0;
4138 if (sscan_res != 3) {
4139 printf("Error in set_otherinfo command \n");
4144 NMEM oid_tmp = nmem_create();
4146 yaz_string_to_oid_nmem(yaz_oid_std(),
4147 CLASS_GENERAL, oidstr, oid_tmp);
4148 oid_oidcpy(extraOtherInfos[otherinfoNo].oid, oid);
4150 xfree(extraOtherInfos[otherinfoNo].value);
4151 extraOtherInfos[otherinfoNo].value = xstrdup(otherinfoString);
4153 nmem_destroy(oid_tmp);
4159 int cmd_sleep(const char* args )
4168 printf("Done sleeping %d seconds\n", sec);
4173 int cmd_list_otherinfo(const char* args)
4180 if (i >= maxOtherInfosSupported)
4182 printf("Error otherinfo index to large (%d>%d)\n",i,maxOtherInfosSupported);
4185 if (extraOtherInfos[i].value)
4187 char name_oid[OID_STR_MAX];
4190 yaz_oid_to_string_buf(extraOtherInfos[i].oid, &oclass,
4192 printf(" otherinfo %d %s %s\n",
4193 i, name ? name : "null",
4194 extraOtherInfos[i].value);
4200 for(i = 0; i < maxOtherInfosSupported; ++i)
4202 if (extraOtherInfos[i].value)
4204 char name_oid[OID_STR_MAX];
4207 yaz_oid_to_string_buf(extraOtherInfos[i].oid, &oclass,
4209 printf(" otherinfo %d %s %s\n",
4210 i, name ? name : "null",
4211 extraOtherInfos[i].value);
4220 int cmd_list_all(const char* args) {
4223 /* connection options */
4225 printf("Connected to : %s\n",last_open_command);
4227 if(last_open_command)
4228 printf("Not connected to : %s\n",last_open_command);
4230 printf("Not connected : \n");
4233 if(yazProxy) printf("using proxy : %s\n",yazProxy);
4235 printf("auto_reconnect : %s\n",auto_reconnect?"on":"off");
4236 printf("auto_wait : %s\n",auto_wait?"on":"off");
4239 printf("Authentication : none\n");
4241 switch(auth->which) {
4242 case Z_IdAuthentication_idPass:
4243 printf("Authentication : IdPass\n");
4244 printf(" Login User : %s\n",auth->u.idPass->userId?auth->u.idPass->userId:"");
4245 printf(" Login Group : %s\n",auth->u.idPass->groupId?auth->u.idPass->groupId:"");
4246 printf(" Password : %s\n",auth->u.idPass->password?auth->u.idPass->password:"");
4248 case Z_IdAuthentication_open:
4249 printf("Authentication : psOpen\n");
4250 printf(" Open string : %s\n",auth->u.open);
4253 printf("Authentication : Unknown\n");
4256 if (negotiationCharset)
4257 printf("Neg. Character set : `%s'\n", negotiationCharset);
4261 for (i = 0; i<num_databaseNames; i++) printf("%s ",databaseNames[i]);
4265 printf("CCL file : %s\n",ccl_fields);
4266 printf("CQL file : %s\n",cql_fields);
4267 printf("Query type : %s\n",query_type_as_string(queryType));
4269 printf("Named Result Sets : %s\n",setnumber==-1?"off":"on");
4271 /* piggy back options */
4272 printf("ssub/lslb/mspn : %d/%d/%d\n",smallSetUpperBound,largeSetLowerBound,mediumSetPresentNumber);
4274 /* print present related options */
4275 if (recordsyntax_size > 0)
4277 printf("Format : %s\n", recordsyntax_list[0]);
4279 printf("Schema : %s\n",record_schema ? record_schema : "not set");
4280 printf("Elements : %s\n",elementSetNames?elementSetNames->u.generic:"");
4282 /* loging options */
4283 printf("APDU log : %s\n",apdu_file?"on":"off");
4284 printf("Record log : %s\n",marc_file?"on":"off");
4287 printf("Other Info: \n");
4288 cmd_list_otherinfo("");
4293 int cmd_clear_otherinfo(const char* args)
4295 if(strlen(args)>0) {
4296 int otherinfoNo = atoi(args);
4297 if (otherinfoNo >= maxOtherInfosSupported) {
4298 printf("Error otherinfo index too large (%d>=%d)\n",
4299 otherinfoNo, maxOtherInfosSupported);
4302 if (extraOtherInfos[otherinfoNo].value)
4304 /* only clear if set. */
4305 extraOtherInfos[otherinfoNo].oid[0] = -1;
4306 xfree(extraOtherInfos[otherinfoNo].value);
4307 extraOtherInfos[otherinfoNo].value = 0;
4311 for(i = 0; i < maxOtherInfosSupported; ++i)
4313 if (extraOtherInfos[i].value)
4315 extraOtherInfos[i].oid[0] = -1;
4316 xfree(extraOtherInfos[i].value);
4317 extraOtherInfos[i].value = 0;
4324 int cmd_wait_response(const char *arg)
4326 int wait_for = atoi(arg);
4328 if( wait_for < 1 ) {
4332 for( i=0 ; i < wait_for ; ++i ) {
4333 wait_and_handle_response(1);
4338 static int cmd_help (const char *line);
4340 typedef char *(*completerFunctionType)(const char *text, int state);
4344 int (*fun)(const char *arg);
4346 completerFunctionType rl_completerfunction;
4347 int complete_filenames;
4348 const char **local_tabcompletes;
4350 {"open", cmd_open, "('tcp'|'ssl')':<host>[':'<port>][/<db>]",NULL,0,NULL},
4351 {"quit", cmd_quit, "",NULL,0,NULL},
4352 {"find", cmd_find, "<query>",NULL,0,NULL},
4353 {"delete", cmd_delete, "<setname>",NULL,0,NULL},
4354 {"base", cmd_base, "<base-name>",NULL,0,NULL},
4355 {"show", cmd_show, "<rec#>['+'<#recs>['+'<setname>]]",NULL,0,NULL},
4356 {"scan", cmd_scan, "<term>",NULL,0,NULL},
4357 {"scanstep", cmd_scanstep, "<size>",NULL,0,NULL},
4358 {"scanpos", cmd_scanpos, "<size>",NULL,0,NULL},
4359 {"scansize", cmd_scansize, "<size>",NULL,0,NULL},
4360 {"sort", cmd_sort, "<sortkey> <flag> <sortkey> <flag> ...",NULL,0,NULL},
4361 {"sort+", cmd_sort_newset, "<sortkey> <flag> <sortkey> <flag> ...",NULL,0,NULL},
4362 {"authentication", cmd_authentication, "<acctstring>",NULL,0,NULL},
4363 {"lslb", cmd_lslb, "<largeSetLowerBound>",NULL,0,NULL},
4364 {"ssub", cmd_ssub, "<smallSetUpperBound>",NULL,0,NULL},
4365 {"mspn", cmd_mspn, "<mediumSetPresentNumber>",NULL,0,NULL},
4366 {"status", cmd_status, "",NULL,0,NULL},
4367 {"setnames", cmd_setnames, "",NULL,0,NULL},
4368 {"cancel", cmd_cancel, "",NULL,0,NULL},
4369 {"cancel_find", cmd_cancel_find, "<query>",NULL,0,NULL},
4370 {"format", cmd_format, "<recordsyntax>",complete_format,0,NULL},
4371 {"schema", cmd_schema, "<schema>",complete_schema,0,NULL},
4372 {"elements", cmd_elements, "<elementSetName>",NULL,0,NULL},
4373 {"close", cmd_close, "",NULL,0,NULL},
4374 {"querytype", cmd_querytype, "<type>",complete_querytype,0,NULL},
4375 {"refid", cmd_refid, "<id>",NULL,0,NULL},
4376 {"itemorder", cmd_itemorder, "ill|item|xml <itemno>",NULL,0,NULL},
4377 {"update", cmd_update, "<action> <recid> [<doc>]",NULL,0,NULL},
4378 {"update0", cmd_update0, "<action> <recid> [<doc>]",NULL,0,NULL},
4379 {"xmles", cmd_xmles, "<OID> <doc>",NULL,0,NULL},
4380 {"packagename", cmd_packagename, "<packagename>",NULL,0,NULL},
4381 {"proxy", cmd_proxy, "[('tcp'|'ssl')]<host>[':'<port>]",NULL,0,NULL},
4382 {"charset", cmd_charset, "<nego_charset> <output_charset>",NULL,0,NULL},
4383 {"negcharset", cmd_negcharset, "<nego_charset>",NULL,0,NULL},
4384 {"displaycharset", cmd_displaycharset, "<output_charset>",NULL,0,NULL},
4385 {"marccharset", cmd_marccharset, "<charset_name>",NULL,0,NULL},
4386 {"lang", cmd_lang, "<language_code>",NULL,0,NULL},
4387 {"source", cmd_source_echo, "<filename>",NULL,1,NULL},
4388 {".", cmd_source_echo, "<filename>",NULL,1,NULL},
4389 {"!", cmd_subshell, "Subshell command",NULL,1,NULL},
4390 {"set_apdufile", cmd_set_apdufile, "<filename>",NULL,1,NULL},
4391 {"set_berfile", cmd_set_berfile, "<filename>",NULL,1,NULL},
4392 {"set_marcdump", cmd_set_marcdump," <filename>",NULL,1,NULL},
4393 {"set_cclfile", cmd_set_cclfile," <filename>",NULL,1,NULL},
4394 {"set_cqlfile", cmd_set_cqlfile," <filename>",NULL,1,NULL},
4395 {"set_auto_reconnect", cmd_set_auto_reconnect," on|off",complete_auto_reconnect,1,NULL},
4396 {"set_auto_wait", cmd_set_auto_wait," on|off",complete_auto_reconnect,1,NULL},
4397 {"set_otherinfo", cmd_set_otherinfo,"<otherinfoinddex> <oid> <string>",NULL,0,NULL},
4398 {"sleep", cmd_sleep,"<seconds>",NULL,0,NULL},
4399 {"register_oid", cmd_register_oid,"<name> <class> <oid>",NULL,0,NULL},
4400 {"push_command", cmd_push_command,"<command>",command_generator,0,NULL},
4401 {"register_tab", cmd_register_tab,"<commandname> <tab>",command_generator,0,NULL},
4402 {"cclparse", cmd_cclparse,"<ccl find command>",NULL,0,NULL},
4403 {"list_otherinfo",cmd_list_otherinfo,"[otherinfoinddex]",NULL,0,NULL},
4404 {"list_all",cmd_list_all,"",NULL,0,NULL},
4405 {"clear_otherinfo",cmd_clear_otherinfo,"",NULL,0,NULL},
4406 {"wait_response",cmd_wait_response,"<number>",NULL,0,NULL},
4407 /* Server Admin Functions */
4408 {"adm-reindex", cmd_adm_reindex, "<database-name>",NULL,0,NULL},
4409 {"adm-truncate", cmd_adm_truncate, "('database'|'index')<object-name>",NULL,0,NULL},
4410 {"adm-create", cmd_adm_create, "",NULL,0,NULL},
4411 {"adm-drop", cmd_adm_drop, "('database'|'index')<object-name>",NULL,0,NULL},
4412 {"adm-import", cmd_adm_import, "<record-type> <dir> <pattern>",NULL,0,NULL},
4413 {"adm-refresh", cmd_adm_refresh, "",NULL,0,NULL},
4414 {"adm-commit", cmd_adm_commit, "",NULL,0,NULL},
4415 {"adm-shutdown", cmd_adm_shutdown, "",NULL,0,NULL},
4416 {"adm-startup", cmd_adm_startup, "",NULL,0,NULL},
4417 {"explain", cmd_explain, "", NULL, 0, NULL},
4418 {"options", cmd_options, "", NULL, 0, NULL},
4419 {"zversion", cmd_zversion, "", NULL, 0, NULL},
4420 {"help", cmd_help, "", NULL,0,NULL},
4421 {"init", cmd_init, "", NULL,0,NULL},
4422 {"sru", cmd_sru, "", NULL,0,NULL},
4423 {"exit", cmd_quit, "",NULL,0,NULL},
4427 static int cmd_help (const char *line)
4433 sscanf (line, "%20s", topic);
4436 printf("Commands:\n");
4437 for (i = 0; cmd_array[i].cmd; i++)
4438 if (*topic == 0 || strcmp (topic, cmd_array[i].cmd) == 0)
4439 printf(" %s %s\n", cmd_array[i].cmd, cmd_array[i].ad);
4440 if (!strcmp(topic, "find"))
4443 printf(" \"term\" Simple Term\n");
4444 printf(" @attr [attset] type=value op Attribute\n");
4445 printf(" @and opl opr And\n");
4446 printf(" @or opl opr Or\n");
4447 printf(" @not opl opr And-Not\n");
4448 printf(" @set set Result set\n");
4449 printf(" @prox exl dist ord rel uc ut Proximity. Use help prox\n");
4451 printf("Bib-1 attribute types\n");
4453 printf("4=Title 7=ISBN 8=ISSN 30=Date 62=Abstract 1003=Author 1016=Any\n");
4454 printf("2=Relation: ");
4455 printf("1< 2<= 3= 4>= 5> 6!= 102=Relevance\n");
4456 printf("3=Position: ");
4457 printf("1=First in Field 2=First in subfield 3=Any position\n");
4458 printf("4=Structure: ");
4459 printf("1=Phrase 2=Word 3=Key 4=Year 5=Date 6=WordList\n");
4460 printf("5=Truncation: ");
4461 printf("1=Right 2=Left 3=L&R 100=No 101=# 102=Re-1 103=Re-2\n");
4462 printf("6=Completeness:");
4463 printf("1=Incomplete subfield 2=Complete subfield 3=Complete field\n");
4465 if (!strcmp(topic, "prox"))
4467 printf("Proximity:\n");
4468 printf(" @prox exl dist ord rel uc ut\n");
4469 printf(" exl: exclude flag . 0=include, 1=exclude.\n");
4470 printf(" dist: distance integer.\n");
4471 printf(" ord: order flag. 0=unordered, 1=ordered.\n");
4472 printf(" rel: relation integer. 1< 2<= 3= 4>= 5> 6!= .\n");
4473 printf(" uc: unit class. k=known, p=private.\n");
4474 printf(" ut: unit type. 1=character, 2=word, 3=sentence,\n");
4475 printf(" 4=paragraph, 5=section, 6=chapter, 7=document,\n");
4476 printf(" 8=element, 9=subelement, 10=elementType, 11=byte.\n");
4477 printf("\nExamples:\n");
4478 printf(" Search for a and b in-order at most 3 words apart:\n");
4479 printf(" @prox 0 3 1 2 k 2 a b\n");
4480 printf(" Search for any order of a and b next to each other:\n");
4481 printf(" @prox 0 1 0 3 k 2 a b\n");
4486 int cmd_register_tab(const char* arg)
4488 #if HAVE_READLINE_READLINE_H
4489 char command[101], tabargument[101];
4492 const char** tabslist;
4494 if (sscanf (arg, "%100s %100s", command, tabargument) < 1) {
4498 /* locate the amdn in the list */
4499 for (i = 0; cmd_array[i].cmd; i++) {
4500 if (!strncmp(cmd_array[i].cmd, command, strlen(command))) {
4505 if (!cmd_array[i].cmd) {
4506 fprintf(stderr,"Unknown command %s\n",command);
4511 if (!cmd_array[i].local_tabcompletes)
4512 cmd_array[i].local_tabcompletes = (const char **) calloc(1,sizeof(char**));
4516 tabslist = cmd_array[i].local_tabcompletes;
4517 for(; tabslist && *tabslist; tabslist++) {
4521 cmd_array[i].local_tabcompletes = (const char **)
4522 realloc(cmd_array[i].local_tabcompletes,
4523 (num_of_tabs+2)*sizeof(char**));
4524 tabslist = cmd_array[i].local_tabcompletes;
4525 tabslist[num_of_tabs] = strdup(tabargument);
4526 tabslist[num_of_tabs+1] = NULL;
4532 void process_cmd_line(char* line)
4535 char word[32], arg[10240];
4537 #if HAVE_GETTIMEOFDAY
4538 gettimeofday (&tv_start, 0);
4541 if ((res = sscanf(line, "%31s %10239[^;]", word, arg)) <= 0)
4543 strcpy(word, last_cmd);
4548 strcpy(last_cmd, word);
4550 /* removed tailing spaces from the arg command */
4553 char* lastnonspace=NULL;
4556 if(!isspace(*(unsigned char *) p)) {
4561 *(++lastnonspace) = 0;
4564 for (i = 0; cmd_array[i].cmd; i++)
4565 if (!strncmp(cmd_array[i].cmd, word, strlen(word)))
4567 res = (*cmd_array[i].fun)(arg);
4571 if (!cmd_array[i].cmd) /* dump our help-screen */
4573 printf("Unknown command: %s.\n", word);
4574 printf("Type 'help' for list of commands\n");
4578 if(apdu_file) fflush(apdu_file);
4580 if (res >= 2 && auto_wait)
4581 wait_and_handle_response(0);
4589 static char *command_generator(const char *text, int state)
4591 #if HAVE_READLINE_READLINE_H
4596 for( ; cmd_array[idx].cmd; ++idx) {
4597 if (!strncmp(cmd_array[idx].cmd, text, strlen(text))) {
4598 ++idx; /* skip this entry on the next run */
4599 return strdup(cmd_array[idx-1].cmd);
4606 #if HAVE_READLINE_READLINE_H
4607 static const char** default_completer_list = NULL;
4609 static char* default_completer(const char* text, int state)
4611 return complete_from_list(default_completer_list, text, state);
4615 #if HAVE_READLINE_READLINE_H
4618 This function only known how to complete on the first word
4620 char **readline_completer(char *text, int start, int end)
4622 completerFunctionType completerToUse;
4625 #if HAVE_READLINE_RL_COMPLETION_MATCHES
4626 char** res = rl_completion_matches(text, command_generator);
4628 char** res = completion_matches(text,
4629 (CPFunction*)command_generator);
4631 rl_attempted_completion_over = 1;
4634 char arg[10240],word[32];
4636 if ((res = sscanf(rl_line_buffer, "%31s %10239[^;]", word, arg)) <= 0) {
4637 rl_attempted_completion_over = 1;
4641 for (i = 0; cmd_array[i].cmd; i++)
4642 if (!strncmp(cmd_array[i].cmd, word, strlen(word)))
4645 if(!cmd_array[i].cmd)
4648 default_completer_list = cmd_array[i].local_tabcompletes;
4650 completerToUse = cmd_array[i].rl_completerfunction;
4651 if (!completerToUse)
4652 { /* if command completer is not defined use the default completer */
4653 completerToUse = default_completer;
4655 if (completerToUse) {
4656 #ifdef HAVE_READLINE_RL_COMPLETION_MATCHES
4658 rl_completion_matches(text, completerToUse);
4661 completion_matches(text, (CPFunction*)completerToUse);
4663 if (!cmd_array[i].complete_filenames)
4664 rl_attempted_completion_over = 1;
4667 if (!cmd_array[i].complete_filenames)
4668 rl_attempted_completion_over = 1;
4676 void ctrl_c_handler(int x)
4682 static void client(void)
4689 signal(SIGINT, ctrl_c_handler);
4692 #if HAVE_GETTIMEOFDAY
4693 gettimeofday (&tv_start, 0);
4698 char *line_in = NULL;
4699 #if HAVE_READLINE_READLINE_H
4702 line_in=readline(C_PROMPT);
4705 #if HAVE_READLINE_HISTORY_H
4707 add_history(line_in);
4709 strncpy(line, line_in, sizeof(line)-1);
4718 if (!fgets(line, sizeof(line)-1, stdin))
4720 if ((end_p = strchr (line, '\n')))
4724 file_history_add_line(file_history, line);
4725 process_cmd_line(line);
4729 static void show_version(void)
4733 yaz_version(vstr, 0);
4734 printf ("YAZ version: %s\n", YAZ_VERSION);
4735 if (strcmp(vstr, YAZ_VERSION))
4736 printf ("YAZ DLL/SO: %s\n", vstr);
4740 int main(int argc, char **argv)
4743 char *open_command = 0;
4744 char *auth_command = 0;
4749 if (!setlocale(LC_CTYPE, ""))
4750 fprintf (stderr, "setlocale failed\n");
4754 codeset = nl_langinfo(CODESET);
4758 outputCharset = xstrdup(codeset);
4760 ODR_MASK_SET(&z3950_options, Z_Options_search);
4761 ODR_MASK_SET(&z3950_options, Z_Options_present);
4762 ODR_MASK_SET(&z3950_options, Z_Options_namedResultSets);
4763 ODR_MASK_SET(&z3950_options, Z_Options_triggerResourceCtrl);
4764 ODR_MASK_SET(&z3950_options, Z_Options_scan);
4765 ODR_MASK_SET(&z3950_options, Z_Options_sort);
4766 ODR_MASK_SET(&z3950_options, Z_Options_extendedServices);
4767 ODR_MASK_SET(&z3950_options, Z_Options_delSet);
4769 while ((ret = options("k:c:q:a:b:m:v:p:u:t:Vxd:", argv, argc, &arg)) != -2)
4776 open_command = (char *) xmalloc (strlen(arg)+6);
4777 strcpy (open_command, "open ");
4778 strcat (open_command, arg);
4782 fprintf(stderr, "%s: Specify at most one server address\n",
4788 dump_file_prefix = arg;
4791 kilobytes = atoi(arg);
4794 if (!(marc_file = fopen (arg, "a")))
4801 outputCharset = xstrdup(arg);
4804 strncpy (ccl_fields, arg, sizeof(ccl_fields)-1);
4805 ccl_fields[sizeof(ccl_fields)-1] = '\0';
4808 strncpy (cql_fields, arg, sizeof(cql_fields)-1);
4809 cql_fields[sizeof(cql_fields)-1] = '\0';
4812 if (!strcmp(arg, "-"))
4815 ber_file=fopen(arg, "a");
4818 if (!strcmp(arg, "-"))
4821 apdu_file=fopen(arg, "a");
4827 yazProxy = xstrdup(arg);
4832 auth_command = (char *) xmalloc (strlen(arg)+6);
4833 strcpy (auth_command, "auth ");
4834 strcat (auth_command, arg);
4838 yaz_log_init(yaz_log_mask_str(arg), "", 0);
4844 fprintf (stderr, "Usage: %s "
4851 " [-p <proxy-addr>]"
4855 " [<server-addr>]\n",
4863 #ifdef HAVE_GETTIMEOFDAY
4864 gettimeofday (&tv_start, 0);
4866 process_cmd_line (auth_command);
4867 #if HAVE_READLINE_HISTORY_H
4868 add_history(auth_command);
4870 xfree(auth_command);
4874 #ifdef HAVE_GETTIMEOFDAY
4875 gettimeofday (&tv_start, 0);
4877 process_cmd_line (open_command);
4878 #if HAVE_READLINE_HISTORY_H
4879 add_history(open_command);
4881 xfree(open_command);
4890 * indent-tabs-mode: nil
4892 * vim: shiftwidth=4 tabstop=8 expandtab