1 /* This file is part of the YAZ toolkit.
2 * Copyright (C) 1995-2013 Index Data
3 * See the file LICENSE for details.
6 * \brief yaz-client program
20 #include <sys/types.h>
42 #define S_ISREG(x) (x & _S_IFREG)
43 #define S_ISDIR(x) (x & _S_IFDIR)
46 #include <yaz/yaz-util.h>
48 #include <yaz/comstack.h>
50 #include <yaz/oid_db.h>
51 #include <yaz/proto.h>
52 #include <yaz/marcdisp.h>
53 #include <yaz/diagbib1.h>
54 #include <yaz/otherinfo.h>
55 #include <yaz/charneg.h>
56 #include <yaz/query-charset.h>
58 #include <yaz/pquery.h>
59 #include <yaz/sortspec.h>
63 #include <yaz/yaz-ccl.h>
66 #include <yaz/facet.h>
68 #if HAVE_READLINE_READLINE_H
69 #include <readline/readline.h>
71 #if HAVE_READLINE_HISTORY_H
72 #include <readline/history.h>
77 #include "tabcomplete.h"
80 #define C_PROMPT "Z> "
82 static file_history_t file_history = 0;
84 static char sru_method[10] = "soap";
85 static char sru_version[10] = "1.2";
86 static char sru_recordPacking[10] = "";
87 static char *codeset = 0; /* character set for output */
88 static int hex_dump = 0;
89 static char *dump_file_prefix = 0;
90 static ODR out, in, print; /* encoding and decoding streams */
92 static ODR srw_sr_odr_out = 0;
93 static Z_SRW_PDU *srw_sr = 0;
95 static FILE *apdu_file = 0;
96 static FILE *ber_file = 0;
97 static COMSTACK conn = 0; /* our z-association */
99 static Z_IdAuthentication *auth = 0; /* our current auth definition */
100 static NMEM nmem_auth = NULL;
102 char *databaseNames[128];
103 int num_databaseNames = 0;
104 static Z_External *record_last = 0;
105 static int setnumber = -1; /* current result set number */
106 static int smallSetUpperBound = 0;
107 static int largeSetLowerBound = 1;
108 static int mediumSetPresentNumber = 0;
109 static Z_ElementSetNames *elementSetNames = 0;
110 static Z_FacetList *facet_list = 0;
111 static ODR facet_odr = 0;
112 static Odr_int setno = 1; /* current set offset */
113 static enum oid_proto protocol = PROTO_Z3950; /* current app protocol */
114 #define RECORDSYNTAX_MAX 20
115 static char *recordsyntax_list[RECORDSYNTAX_MAX];
116 static int recordsyntax_size = 0;
118 static char *record_schema = 0;
119 static int sent_close = 0;
120 static NMEM session_mem = NULL; /* memory handle for init-response */
121 static Z_InitResponse *session_initResponse = 0; /* session parameters */
122 static char last_scan_line[512] = "0";
123 static char last_scan_query[512] = "0";
124 static char ccl_fields[512] = "default.bib";
125 /* ### How can I set this path to use wherever YAZ is installed? */
126 static char cql_fields[512] = "/usr/local/share/yaz/etc/pqf.properties";
127 static char *esPackageName = 0;
128 static char *yazProxy = 0;
129 static int kilobytes = 64 * 1024;
130 static char *negotiationCharset = 0;
131 static int negotiationCharsetRecords = 1;
132 static int negotiationCharsetVersion = 3;
133 static char *outputCharset = 0;
134 static char *marcCharset = 0;
135 static char *queryCharset = 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 int auto_reconnect = 0;
142 static int auto_wait = 1;
143 static Odr_bitmask z3950_options;
144 static int z3950_version = 3;
145 static int scan_stepSize = 0;
146 static char scan_position[64];
147 static int scan_size = 20;
148 static char cur_host[200];
149 static Odr_int last_hit_count = 0;
150 static int pretty_xml = 0;
151 static Odr_int sru_maximumRecords = 0;
161 static QueryType queryType = QueryType_Prefix;
163 static CCL_bibset bibset; /* CCL bibset handle */
164 static cql_transform_t cqltrans = 0; /* CQL context-set handle */
166 #if HAVE_READLINE_COMPLETION_OVER
169 /* readline doesn't have this var. Define it ourselves. */
170 int rl_attempted_completion_over = 0;
173 #define maxOtherInfosSupported 10
175 Odr_oid oid[OID_SIZE];
177 } extraOtherInfos[maxOtherInfosSupported];
179 static void process_cmd_line(char* line);
180 #if HAVE_READLINE_READLINE_H
181 static char **readline_completer(char *text, int start, int end);
183 static char *command_generator(const char *text, int state);
184 static int cmd_register_tab(const char* arg);
185 static int cmd_querycharset(const char *arg);
187 static void close_session(void);
189 static void marc_file_write(const char *buf, size_t sz);
191 static void wait_and_handle_response(int one_response_only);
192 static Z_GDU *get_HTTP_Request_url(ODR odr, const char *url);
194 ODR getODROutputStream(void)
199 static const char* query_type_as_string(QueryType q)
203 case QueryType_Prefix: return "prefix (RPN sent to server)";
204 case QueryType_CCL: return "CCL (CCL sent to server) ";
205 case QueryType_CCL2RPN: return "CCL -> RPN (RPN sent to server)";
206 case QueryType_CQL: return "CQL (CQL sent to server)";
207 case QueryType_CQL2RPN: return "CQL -> RPN (RPN sent to server)";
209 return "unknown Query type internal yaz-client error";
213 static void do_hex_dump(const char* buf, size_t len)
219 for (i = 0; i < len ; i = i+16 )
221 printf(" %4.4ld ", (long) i);
222 for (x = 0 ; i+x < len && x < 16; ++x)
224 printf("%2.2X ",(unsigned int)((unsigned char)buf[i+x]));
229 if (dump_file_prefix)
232 if (++no < 1000 && strlen(dump_file_prefix) < 500)
236 sprintf(fname, "%s.%03d.raw", dump_file_prefix, no);
237 of = fopen(fname, "wb");
239 if (fwrite(buf, 1, len, of) != len)
241 printf("write failed for %s", fname);
245 printf("close failed for %s", fname);
251 static void add_otherInfos(Z_APDU *a)
253 Z_OtherInformation **oi;
256 if (facet_list && a->which == Z_APDU_searchRequest)
258 oi = &a->u.searchRequest->additionalSearchInfo;
259 yaz_oi_set_facetlist(oi, out, facet_list);
262 for (i = 0; i < maxOtherInfosSupported; ++i)
264 if (oid_oidlen(extraOtherInfos[i].oid) > 0)
265 yaz_oi_set_string_oid(oi, out, extraOtherInfos[i].oid,
266 1, extraOtherInfos[i].value);
270 int send_apdu(Z_APDU *a)
279 z_APDU(print, &a, 0, 0);
282 if (!z_APDU(out, &a, 0, 0))
284 odr_perror(out, "Encoding APDU");
288 buf = odr_getbuf(out, &len, 0);
290 odr_dumpBER(ber_file, buf, len);
291 do_hex_dump(buf, len);
292 if (cs_put(conn, buf, len) < 0)
294 fprintf(stderr, "cs_put: %s\n", cs_errmsg(cs_errno(conn)));
298 odr_reset(out); /* release the APDU structure */
302 static void print_stringn(const char *buf, size_t len)
305 for (i = 0; i < len; i++)
306 if ((buf[i] <= 126 && buf[i] >= 32) || strchr("\n\r\t\f", buf[i]))
307 printf("%c", buf[i]);
309 printf("\\X%02X", ((const unsigned char *)buf)[i]);
312 static void print_refid(Z_ReferenceId *id)
316 printf("Reference Id: ");
317 print_stringn((const char *) id->buf, id->len);
322 static Z_ReferenceId *set_refid(ODR out)
326 return odr_create_Odr_oct(out, refid, strlen(refid));
329 /* INIT SERVICE ------------------------------- */
331 static void send_Z3950_initRequest(const char* type_and_host)
333 Z_APDU *apdu = zget_APDU(out, Z_APDU_initRequest);
334 Z_InitRequest *req = apdu->u.initRequest;
337 req->options = &z3950_options;
339 ODR_MASK_ZERO(req->protocolVersion);
340 for (i = 0; i<z3950_version; i++)
341 ODR_MASK_SET(req->protocolVersion, i);
343 *req->maximumRecordSize = 1024*kilobytes;
344 *req->preferredMessageSize = 1024*kilobytes;
346 req->idAuthentication = auth;
348 req->referenceId = set_refid(out);
350 if (yazProxy && type_and_host)
352 yaz_oi_set_string_oid(&req->otherInfo, out, yaz_oid_userinfo_proxy,
356 if (negotiationCharset || yazLang)
358 Z_OtherInformation **p;
359 Z_OtherInformationUnit *p0;
361 yaz_oi_APDU(apdu, &p);
363 if ((p0=yaz_oi_update(p, out, NULL, 0, 0)))
365 ODR_MASK_SET(req->options, Z_Options_negotiationModel);
367 p0->which = Z_OtherInfo_externallyDefinedInfo;
368 p0->information.externallyDefinedInfo =
369 yaz_set_proposal_charneg_list(out, ",",
372 negotiationCharsetRecords);
376 printf("Sent initrequest.\n");
380 static void render_initUserInfo(Z_OtherInformation *ui1);
381 static void render_diag(Z_DiagnosticFormat *diag);
383 static void pr_opt(const char *opt, void *clientData)
388 static int process_Z3950_initResponse(Z_InitResponse *res)
391 /* save session parameters for later use */
392 session_mem = odr_extract_mem(in);
393 session_initResponse = res;
395 for (ver = 0; ver < 8; ver++)
396 if (!ODR_MASK_GET(res->protocolVersion, ver))
400 printf("Connection rejected by v%d target.\n", ver);
402 printf("Connection accepted by v%d target.\n", ver);
403 if (res->implementationId)
404 printf("ID : %s\n", res->implementationId);
405 if (res->implementationName)
406 printf("Name : %s\n", res->implementationName);
407 if (res->implementationVersion)
408 printf("Version: %s\n", res->implementationVersion);
409 if (res->userInformationField)
411 Z_External *uif = res->userInformationField;
412 if (uif->which == Z_External_userInfo1)
413 render_initUserInfo(uif->u.userInfo1);
416 printf("UserInformationfield:\n");
417 if (!z_External(print, (Z_External**)&uif, 0, 0))
419 odr_perror(print, "Printing userinfo\n");
422 if (uif->which == Z_External_octet)
424 printf("Guessing visiblestring:\n");
425 printf("'%.*s'\n", uif->u.octet_aligned->len,
426 uif->u.octet_aligned->buf);
428 else if (uif->which == Z_External_single)
430 Odr_any *sat = uif->u.single_ASN1_type;
431 if (!oid_oidcmp(uif->direct_reference,
432 yaz_oid_userinfo_oclc_userinfo))
434 Z_OCLC_UserInformation *oclc_ui;
435 ODR decode = odr_createmem(ODR_DECODE);
436 odr_setbuf(decode, (char *) sat->buf, sat->len, 0);
437 if (!z_OCLC_UserInformation(decode, &oclc_ui, 0, 0))
438 printf("Bad OCLC UserInformation:\n");
440 printf("OCLC UserInformation:\n");
441 if (!z_OCLC_UserInformation(print, &oclc_ui, 0, 0))
442 printf("Bad OCLC UserInformation spec\n");
447 /* Peek at any private Init-diagnostic APDUs */
448 printf("yaz-client ignoring unrecognised userInformationField: %d-octet External '%.*s'\n",
449 (int) sat->len, sat->len, sat->buf);
456 yaz_init_opt_decode(res->options, pr_opt, 0);
459 if (ODR_MASK_GET(res->options, Z_Options_namedResultSets))
462 if (ODR_MASK_GET(res->options, Z_Options_negotiationModel))
464 Z_CharSetandLanguageNegotiation *p =
465 yaz_get_charneg_record(res->otherInfo);
469 char *charset=NULL, *lang=NULL;
472 yaz_get_response_charneg(session_mem, p, &charset, &lang,
475 printf("Accepted character set : %s\n", charset ? charset:"none");
476 printf("Accepted code language : %s\n", lang ? lang:"none");
477 printf("Accepted records in ...: %d\n", selected );
479 if (outputCharset && charset)
481 printf("Converting between %s and %s\n",
482 outputCharset, charset);
483 odr_set_charset(out, charset, outputCharset);
484 odr_set_charset(in, outputCharset, charset);
485 cmd_querycharset(charset);
489 odr_set_charset(out, 0, 0);
490 odr_set_charset(in, 0, 0);
499 static void render_initUserInfo(Z_OtherInformation *ui1)
502 printf("Init response contains %d otherInfo unit%s:\n",
503 ui1->num_elements, ui1->num_elements == 1 ? "" : "s");
505 for (i = 0; i < ui1->num_elements; i++)
507 Z_OtherInformationUnit *unit = ui1->list[i];
508 printf(" %d: otherInfo unit contains ", i+1);
509 if (unit->which == Z_OtherInfo_externallyDefinedInfo &&
510 unit->information.externallyDefinedInfo &&
511 unit->information.externallyDefinedInfo->which ==
514 render_diag(unit->information.externallyDefinedInfo->u.diag1);
516 else if (unit->which != Z_OtherInfo_externallyDefinedInfo)
518 printf("unsupported otherInfo unit->which = %d\n", unit->which);
522 printf("unsupported otherInfo unit external %d\n",
523 unit->information.externallyDefinedInfo ?
524 unit->information.externallyDefinedInfo->which : -2);
530 /* ### should this share code with display_diagrecs()? */
531 static void render_diag(Z_DiagnosticFormat *diag)
535 printf("%d diagnostic%s:\n", diag->num, diag->num == 1 ? "" : "s");
536 for (i = 0; i < diag->num; i++)
538 Z_DiagnosticFormat_s *ds = diag->elements[i];
539 printf(" %d: ", i+1);
542 case Z_DiagnosticFormat_s_defaultDiagRec: {
543 Z_DefaultDiagFormat *dd = ds->u.defaultDiagRec;
544 /* ### should check `dd->diagnosticSetId' */
545 printf("code=" ODR_INT_PRINTF " (%s)", *dd->condition,
546 diagbib1_str(*dd->condition));
547 /* Both types of addinfo are the same, so use type-pun */
548 if (dd->u.v2Addinfo != 0)
549 printf(",\n\taddinfo='%s'", dd->u.v2Addinfo);
552 case Z_DiagnosticFormat_s_explicitDiagnostic:
553 printf("Explicit diagnostic (not supported)");
556 printf("Unrecognised diagnostic type %d", ds->which);
560 if (ds->message != 0)
561 printf(", message='%s'", ds->message);
567 static int set_base(const char *arg)
572 for (i = 0; i<num_databaseNames; i++)
573 xfree(databaseNames[i]);
574 num_databaseNames = 0;
578 if (!(cp = strchr(arg, ' ')))
579 cp = arg + strlen(arg);
582 databaseNames[num_databaseNames] = (char *)xmalloc(1 + cp - arg);
583 memcpy(databaseNames[num_databaseNames], arg, cp - arg);
584 databaseNames[num_databaseNames][cp - arg] = '\0';
586 for (cp1 = databaseNames[num_databaseNames]; *cp1 ; cp1++)
595 if (num_databaseNames == 0)
597 num_databaseNames = 1;
598 databaseNames[0] = xstrdup("");
603 static int parse_cmd_doc(const char **arg, ODR out, char **buf, int *len)
606 while (**arg && strchr(" \t\n\r\f", **arg))
612 else if ((*arg)[0] == '<')
617 const char *arg_start = ++(*arg);
619 while (**arg != '\0' && **arg != ' ')
622 fname = odr_strdupn(out, arg_start, *arg - arg_start);
624 inf = fopen(fname, "rb");
627 printf("Couldn't open %s\n", fname);
630 if (fseek(inf, 0L, SEEK_END) == -1)
632 printf("Couldn't seek in %s\n", fname);
637 if (fseek(inf, 0L, SEEK_SET) == -1)
639 printf("Couldn't seek in %s\n", fname);
644 *buf = (char *) odr_malloc(out, fsize+1);
645 (*buf)[fsize] = '\0';
646 if (fread(*buf, 1, fsize, inf) != fsize)
648 printf("Unable to read %s\n", fname);
654 else if ((*arg)[0] == '\"' && (sep=strchr(*arg+1, '"')))
658 *buf = odr_strdupn(out, *arg, *len);
663 const char *arg_start = *arg;
665 while (**arg != '\0' && **arg != ' ')
668 *len = *arg - arg_start;
669 *buf = odr_strdupn(out, arg_start, *len);
674 static int cmd_base(const char *arg)
678 printf("Usage: base <database> <database> ...\n");
681 return set_base(arg);
684 static int session_connect_base(const char *arg, const char **basep)
687 char type_and_host[101];
695 nmem_destroy(session_mem);
697 session_initResponse = 0;
699 cs_get_host_args(arg, basep);
701 strncpy(type_and_host, arg, sizeof(type_and_host)-1);
702 type_and_host[sizeof(type_and_host)-1] = '\0';
704 conn = cs_create_host_proxy(arg, 1, &add, yazProxy);
707 printf("Could not resolve address %s\n", arg);
712 if (conn->protocol == PROTO_HTTP)
714 printf("SRW/HTTP not enabled in this YAZ\n");
720 protocol = conn->protocol;
721 printf("Connecting...");
723 if (cs_connect(conn, add) < 0)
725 printf("error = %s\n", cs_strerror(conn));
731 cs_print_session_info(conn);
732 if (protocol == PROTO_Z3950)
734 send_Z3950_initRequest(type_and_host);
740 static int session_connect(const char *arg)
743 const char *basep = 0;
745 r = session_connect_base(arg, &basep);
748 else if (protocol == PROTO_Z3950)
753 static int cmd_open(const char *arg)
758 strncpy(cur_host, arg, sizeof(cur_host)-1);
759 cur_host[sizeof(cur_host)-1] = 0;
762 r = session_connect(cur_host);
763 if (conn && conn->protocol == PROTO_HTTP)
764 queryType = QueryType_CQL;
770 static int cmd_authentication(const char *arg)
775 nmem_reset(nmem_auth);
776 nmem_strsplit_blank(nmem_auth, arg, &args, &r);
780 printf("Authentication set to null\n");
785 auth = (Z_IdAuthentication *) nmem_malloc(nmem_auth, sizeof(*auth));
786 if (!strcmp(args[0], "-"))
788 auth->which = Z_IdAuthentication_anonymous;
789 auth->u.anonymous = odr_nullval();
790 printf("Authentication set to Anonymous\n");
794 auth->which = Z_IdAuthentication_open;
795 auth->u.open = args[0];
796 printf("Authentication set to Open (%s)\n", args[0]);
801 auth = (Z_IdAuthentication *) nmem_malloc(nmem_auth, sizeof(*auth));
802 auth->which = Z_IdAuthentication_idPass;
803 auth->u.idPass = (Z_IdPass *)
804 nmem_malloc(nmem_auth, sizeof(*auth->u.idPass));
805 auth->u.idPass->groupId = NULL;
806 auth->u.idPass->userId = !strcmp(args[0], "-") ? 0 : args[0];
807 auth->u.idPass->password = !strcmp(args[1], "-") ? 0 : args[1];
808 printf("Authentication set to User (%s), Pass (%s)\n",
813 auth = (Z_IdAuthentication*) nmem_malloc(nmem_auth, sizeof(*auth));
814 auth->which = Z_IdAuthentication_idPass;
815 auth->u.idPass = (Z_IdPass *)
816 nmem_malloc(nmem_auth, sizeof(*auth->u.idPass));
817 auth->u.idPass->groupId = args[1];
818 auth->u.idPass->userId = args[0];
819 auth->u.idPass->password = args[2];
820 printf("Authentication set to User (%s), Group (%s), Pass (%s)\n",
821 args[0], args[1], args[2]);
825 printf("Bad number of args to auth\n");
832 /* SEARCH SERVICE ------------------------------ */
833 static void display_record(Z_External *r);
835 static void print_record(const char *buf, size_t len)
838 print_stringn(buf, len);
839 /* add newline if not already added ... */
840 if (i <= 0 || buf[i-1] != '\n')
844 static void print_xml_record(const char *buf, size_t len)
851 xmlKeepBlanksDefault(0); /* get get xmlDocFormatMemory to work! */
852 doc = xmlParseMemory(buf, len);
857 xmlDocDumpFormatMemory(doc, &xml_mem, &xml_size, 1);
858 fwrite(xml_mem, 1, xml_size, stdout);
866 fwrite(buf, 1, len, stdout);
869 static void display_record(Z_External *r)
871 const Odr_oid *oid = r->direct_reference;
875 * Tell the user what we got.
880 char oid_name_buf[OID_STR_MAX];
882 = yaz_oid_to_string_buf(oid, &oclass, oid_name_buf);
883 printf("Record type: ");
885 printf("%s\n", oid_name);
887 /* Check if this is a known, ASN.1 type tucked away in an octet string */
888 if (r->which == Z_External_octet)
890 Z_ext_typeent *type = z_ext_getentbyref(r->direct_reference);
896 * Call the given decoder to process the record.
898 odr_setbuf(in, (char*)r->u.octet_aligned->buf,
899 r->u.octet_aligned->len, 0);
900 if (!(*type->fun)(in, &rr, 0, 0))
902 odr_perror(in, "Decoding constructed record.");
903 fprintf(stdout, "[Near %ld]\n", (long) odr_offset(in));
904 fprintf(stdout, "Packet dump:\n---------\n");
905 odr_dumpBER(stdout, (char*)r->u.octet_aligned->buf,
906 r->u.octet_aligned->len);
907 fprintf(stdout, "---------\n");
909 /* note just ignores the error ant print the bytes form the octet_aligned later */
912 * Note: we throw away the original, BER-encoded record here.
913 * Do something else with it if you want to keep it.
915 r->u.sutrs = (Z_SUTRS *) rr; /* we don't actually check the type here. */
916 r->which = type->what;
920 if (oid && r->which == Z_External_octet)
922 const char *octet_buf = (const char*)r->u.octet_aligned->buf;
923 size_t octet_len = r->u.octet_aligned->len;
924 if (!oid_oidcmp(oid, yaz_oid_recsyn_xml)
925 || !oid_oidcmp(oid, yaz_oid_recsyn_application_xml)
926 || !oid_oidcmp(oid, yaz_oid_recsyn_html))
928 print_xml_record(octet_buf, octet_len);
930 else if (!oid_oidcmp(oid, yaz_oid_recsyn_mab))
932 print_record(octet_buf, octet_len);
939 yaz_marc_t mt = yaz_marc_create();
940 const char *from = 0;
942 if (marcCharset && !strcmp(marcCharset, "auto"))
944 if (!oid_oidcmp(oid, yaz_oid_recsyn_usmarc))
946 if (octet_buf[9] == 'a')
954 else if (marcCharset)
956 if (outputCharset && from)
958 cd = yaz_iconv_open(outputCharset, from);
959 printf("convert from %s to %s", from,
962 printf(" unsupported\n");
965 yaz_marc_iconv(mt, cd);
970 if (yaz_marc_decode_buf(mt, octet_buf, octet_len,
973 if (fwrite(result, rlen, 1, stdout) != 1)
975 printf("write to stdout failed\n");
980 if (yaz_oid_is_iso2709(oid))
981 printf("bad MARC. Dumping as it is:\n");
982 print_record(octet_buf, octet_len);
984 yaz_marc_destroy(mt);
988 marc_file_write(octet_buf, r->u.octet_aligned->len);
990 else if (oid && !oid_oidcmp(oid, yaz_oid_recsyn_sutrs))
992 if (r->which != Z_External_sutrs)
994 printf("Expecting single SUTRS type for SUTRS.\n");
997 print_record((const char *) r->u.sutrs->buf, r->u.sutrs->len);
998 marc_file_write((const char *) r->u.sutrs->buf, r->u.sutrs->len);
1000 else if (oid && !oid_oidcmp(oid, yaz_oid_recsyn_grs_1))
1003 if (r->which != Z_External_grs1)
1005 printf("Expecting single GRS type for GRS.\n");
1009 yaz_display_grs1(w, r->u.grs1, 0);
1010 puts(wrbuf_cstr(w));
1013 else if (oid && !oid_oidcmp(oid, yaz_oid_recsyn_opac))
1016 if (r->u.opac->bibliographicRecord)
1017 display_record(r->u.opac->bibliographicRecord);
1018 for (i = 0; i<r->u.opac->num_holdingsData; i++)
1020 Z_HoldingsRecord *h = r->u.opac->holdingsData[i];
1021 if (h->which == Z_HoldingsRecord_marcHoldingsRecord)
1023 printf("MARC holdings %d\n", i);
1024 display_record(h->u.marcHoldingsRecord);
1026 else if (h->which == Z_HoldingsRecord_holdingsAndCirc)
1030 Z_HoldingsAndCircData *data = h->u.holdingsAndCirc;
1032 printf("Data holdings %d\n", i);
1033 if (data->typeOfRecord)
1034 printf("typeOfRecord: %s\n", data->typeOfRecord);
1035 if (data->encodingLevel)
1036 printf("encodingLevel: %s\n", data->encodingLevel);
1037 if (data->receiptAcqStatus)
1038 printf("receiptAcqStatus: %s\n", data->receiptAcqStatus);
1039 if (data->generalRetention)
1040 printf("generalRetention: %s\n", data->generalRetention);
1041 if (data->completeness)
1042 printf("completeness: %s\n", data->completeness);
1043 if (data->dateOfReport)
1044 printf("dateOfReport: %s\n", data->dateOfReport);
1046 printf("nucCode: %s\n", data->nucCode);
1047 if (data->localLocation)
1048 printf("localLocation: %s\n", data->localLocation);
1049 if (data->shelvingLocation)
1050 printf("shelvingLocation: %s\n", data->shelvingLocation);
1051 if (data->callNumber)
1052 printf("callNumber: %s\n", data->callNumber);
1053 if (data->shelvingData)
1054 printf("shelvingData: %s\n", data->shelvingData);
1055 if (data->copyNumber)
1056 printf("copyNumber: %s\n", data->copyNumber);
1057 if (data->publicNote)
1058 printf("publicNote: %s\n", data->publicNote);
1059 if (data->reproductionNote)
1060 printf("reproductionNote: %s\n", data->reproductionNote);
1061 if (data->termsUseRepro)
1062 printf("termsUseRepro: %s\n", data->termsUseRepro);
1063 if (data->enumAndChron)
1064 printf("enumAndChron: %s\n", data->enumAndChron);
1065 for (j = 0; j<data->num_volumes; j++)
1067 printf("volume %d\n", j);
1068 if (data->volumes[j]->enumeration)
1069 printf(" enumeration: %s\n",
1070 data->volumes[j]->enumeration);
1071 if (data->volumes[j]->chronology)
1072 printf(" chronology: %s\n",
1073 data->volumes[j]->chronology);
1074 if (data->volumes[j]->enumAndChron)
1075 printf(" enumAndChron: %s\n",
1076 data->volumes[j]->enumAndChron);
1078 for (j = 0; j<data->num_circulationData; j++)
1080 printf("circulation %d\n", j);
1081 if (data->circulationData[j]->availableNow)
1082 printf(" availableNow: %d\n",
1083 *data->circulationData[j]->availableNow);
1084 if (data->circulationData[j]->availablityDate)
1085 printf(" availabiltyDate: %s\n",
1086 data->circulationData[j]->availablityDate);
1087 if (data->circulationData[j]->availableThru)
1088 printf(" availableThru: %s\n",
1089 data->circulationData[j]->availableThru);
1090 if (data->circulationData[j]->restrictions)
1091 printf(" restrictions: %s\n",
1092 data->circulationData[j]->restrictions);
1093 if (data->circulationData[j]->itemId)
1094 printf(" itemId: %s\n",
1095 data->circulationData[j]->itemId);
1096 if (data->circulationData[j]->renewable)
1097 printf(" renewable: %d\n",
1098 *data->circulationData[j]->renewable);
1099 if (data->circulationData[j]->onHold)
1100 printf(" onHold: %d\n",
1101 *data->circulationData[j]->onHold);
1102 if (data->circulationData[j]->enumAndChron)
1103 printf(" enumAndChron: %s\n",
1104 data->circulationData[j]->enumAndChron);
1105 if (data->circulationData[j]->midspine)
1106 printf(" midspine: %s\n",
1107 data->circulationData[j]->midspine);
1108 if (data->circulationData[j]->temporaryLocation)
1109 printf(" temporaryLocation: %s\n",
1110 data->circulationData[j]->temporaryLocation);
1117 printf("Unknown record representation.\n");
1118 if (!z_External(print, &r, 0, 0))
1120 odr_perror(print, "Printing external");
1126 static void display_diagrecs(Z_DiagRec **pp, int num)
1129 Z_DefaultDiagFormat *r;
1131 printf("Diagnostic message(s) from database:\n");
1132 for (i = 0; i<num; i++)
1134 Z_DiagRec *p = pp[i];
1135 if (p->which != Z_DiagRec_defaultFormat)
1137 printf("Diagnostic record not in default format.\n");
1141 r = p->u.defaultFormat;
1143 if (!r->diagnosticSetId)
1144 printf("Missing diagset\n");
1148 char diag_name_buf[OID_STR_MAX];
1149 const char *diag_name = 0;
1150 diag_name = yaz_oid_to_string_buf
1151 (r->diagnosticSetId, &oclass, diag_name_buf);
1152 if (oid_oidcmp(r->diagnosticSetId, yaz_oid_diagset_bib_1))
1153 printf("Unknown diagset: %s\n", diag_name);
1155 printf(" [" ODR_INT_PRINTF "] %s",
1156 *r->condition, diagbib1_str(*r->condition));
1159 case Z_DefaultDiagFormat_v2Addinfo:
1160 printf(" -- v2 addinfo '%s'\n", r->u.v2Addinfo);
1162 case Z_DefaultDiagFormat_v3Addinfo:
1163 printf(" -- v3 addinfo '%s'\n", r->u.v3Addinfo);
1170 static void display_nameplusrecord(Z_NamePlusRecord *p)
1172 if (p->databaseName)
1173 printf("[%s]", p->databaseName);
1174 if (p->which == Z_NamePlusRecord_surrogateDiagnostic)
1175 display_diagrecs(&p->u.surrogateDiagnostic, 1);
1176 else if (p->which == Z_NamePlusRecord_databaseRecord)
1177 display_record(p->u.databaseRecord);
1180 static void display_records(Z_Records *p)
1184 if (p->which == Z_Records_NSD)
1186 Z_DiagRec dr, *dr_p = &dr;
1187 dr.which = Z_DiagRec_defaultFormat;
1188 dr.u.defaultFormat = p->u.nonSurrogateDiagnostic;
1189 display_diagrecs(&dr_p, 1);
1191 else if (p->which == Z_Records_multipleNSD)
1192 display_diagrecs(p->u.multipleNonSurDiagnostics->diagRecs,
1193 p->u.multipleNonSurDiagnostics->num_diagRecs);
1196 printf("Records: %d\n", p->u.databaseOrSurDiagnostics->num_records);
1197 for (i = 0; i < p->u.databaseOrSurDiagnostics->num_records; i++)
1198 display_nameplusrecord(p->u.databaseOrSurDiagnostics->records[i]);
1202 static int send_Z3950_deleteResultSetRequest(const char *arg)
1207 Z_APDU *apdu = zget_APDU(out, Z_APDU_deleteResultSetRequest);
1208 Z_DeleteResultSetRequest *req = apdu->u.deleteResultSetRequest;
1210 req->referenceId = set_refid(out);
1212 req->num_resultSetList =
1213 sscanf(arg, "%30s %30s %30s %30s %30s %30s %30s %30s",
1214 names[0], names[1], names[2], names[3],
1215 names[4], names[5], names[6], names[7]);
1217 req->deleteFunction = odr_intdup(out, 0);
1218 if (req->num_resultSetList > 0)
1220 *req->deleteFunction = Z_DeleteResultSetRequest_list;
1221 req->resultSetList = (char **)
1222 odr_malloc(out, sizeof(*req->resultSetList)*
1223 req->num_resultSetList);
1224 for (i = 0; i<req->num_resultSetList; i++)
1225 req->resultSetList[i] = names[i];
1229 *req->deleteFunction = Z_DeleteResultSetRequest_all;
1230 req->resultSetList = 0;
1234 printf("Sent deleteResultSetRequest.\n");
1239 static int send_gdu(Z_GDU *gdu)
1241 if (z_GDU(out, &gdu, 0, 0))
1249 if (!z_GDU(print, &gdu, 0, 0))
1250 printf("Failed to print outgoing SRU package\n");
1253 buf_out = odr_getbuf(out, &len_out, 0);
1255 /* we don't odr_reset(out), since we may need the buffer again */
1257 do_hex_dump(buf_out, len_out);
1259 r = cs_put(conn, buf_out, len_out);
1267 static int send_srw_host_path(Z_SRW_PDU *sr, const char *host_port,
1270 const char *charset = negotiationCharset;
1273 gdu = z_get_HTTP_Request_host_path(out, host_port, path);
1277 if (auth->which == Z_IdAuthentication_open)
1281 nmem_strsplit(out->mem, "/", auth->u.open, &darray, &num);
1283 sr->username = darray[0];
1285 sr->password = darray[1];
1287 else if (auth->which == Z_IdAuthentication_idPass)
1289 sr->username = auth->u.idPass->userId;
1290 sr->password = auth->u.idPass->password;
1294 if (!yaz_matchstr(sru_method, "get"))
1296 yaz_sru_get_encode(gdu->u.HTTP_Request, sr, out, charset);
1298 else if (!yaz_matchstr(sru_method, "post"))
1300 yaz_sru_post_encode(gdu->u.HTTP_Request, sr, out, charset);
1302 else if (!yaz_matchstr(sru_method, "soap"))
1304 yaz_sru_soap_encode(gdu->u.HTTP_Request, sr, out, charset);
1306 else if (!yaz_matchstr(sru_method, "solr"))
1308 yaz_solr_encode_request(gdu->u.HTTP_Request, sr, out, charset);
1311 return send_gdu(gdu);
1314 static int send_srw(Z_SRW_PDU *sr)
1316 char *path = yaz_encode_sru_dbpath_odr(out, databaseNames[0]);
1317 return send_srw_host_path(sr, cur_host, path);
1320 static int send_SRW_redirect(const char *uri, Z_HTTP_Response *cookie_hres)
1322 const char *username = 0;
1323 const char *password = 0;
1324 struct Z_HTTP_Header *h;
1325 char *combined_cookies = 0;
1326 int combined_cookies_len = 0;
1327 Z_GDU *gdu = get_HTTP_Request_url(out, uri);
1329 gdu->u.HTTP_Request->method = odr_strdup(out, "GET");
1330 z_HTTP_header_add(out, &gdu->u.HTTP_Request->headers, "Accept",
1333 for (h = cookie_hres->headers; h; h = h->next)
1335 if (!strcmp(h->name, "Set-Cookie"))
1339 if (!(cp = strchr(h->value, ';')))
1340 cp = h->value + strlen(h->value);
1341 if (cp - h->value >= 1)
1343 combined_cookies = xrealloc(combined_cookies, combined_cookies_len + cp - h->value + 3);
1344 memcpy(combined_cookies+combined_cookies_len, h->value, cp - h->value);
1345 combined_cookies[combined_cookies_len + cp - h->value] = '\0';
1346 strcat(combined_cookies,"; ");
1347 combined_cookies_len = strlen(combined_cookies);
1351 if (combined_cookies_len)
1353 z_HTTP_header_add(out, &gdu->u.HTTP_Request->headers, "Cookie", combined_cookies);
1354 xfree(combined_cookies);
1359 if (auth->which == Z_IdAuthentication_open)
1363 nmem_strsplit(out->mem, "/", auth->u.open, &darray, &num);
1365 username = darray[0];
1367 password = darray[1];
1369 else if (auth->which == Z_IdAuthentication_idPass)
1371 username = auth->u.idPass->userId;
1372 password = auth->u.idPass->password;
1376 if (username && password)
1378 z_HTTP_header_add_basic_auth(out, &gdu->u.HTTP_Request->headers,
1379 username, password);
1382 return send_gdu(gdu);
1387 static char *encode_SRW_term(ODR o, const char *q)
1389 const char *in_charset = "ISO-8859-1";
1390 WRBUF w = wrbuf_alloc();
1394 in_charset = outputCharset;
1395 cd = yaz_iconv_open("UTF-8", in_charset);
1399 return odr_strdup(o, q);
1401 wrbuf_iconv_write(w, cd, q, strlen(q));
1403 res = odr_strdup(o, wrbuf_cstr(w));
1405 res = odr_strdup(o, q);
1406 yaz_iconv_close(cd);
1412 static int send_SRW_scanRequest(const char *arg, Odr_int *pos, int num)
1416 /* regular requestse .. */
1417 sr = yaz_srw_get_pdu(out, Z_SRW_scan_request, sru_version);
1422 sr->u.scan_request->queryType = "cql";
1423 sr->u.scan_request->scanClause = encode_SRW_term(out, arg);
1425 case QueryType_Prefix:
1426 sr->u.scan_request->queryType = "pqf";
1427 sr->u.scan_request->scanClause = encode_SRW_term(out, arg);
1430 printf("Only CQL and PQF supported in SRW\n");
1433 sr->u.scan_request->responsePosition = pos;
1434 sr->u.scan_request->maximumTerms = odr_intdup(out, num);
1435 return send_srw(sr);
1438 static int send_SRW_searchRequest(const char *arg)
1444 assert(srw_sr_odr_out == 0);
1445 srw_sr_odr_out = odr_createmem(ODR_ENCODE);
1447 odr_reset(srw_sr_odr_out);
1451 /* save this for later .. when fetching individual records */
1452 srw_sr = yaz_srw_get_pdu(srw_sr_odr_out, Z_SRW_searchRetrieve_request,
1455 /* regular request .. */
1456 sr = yaz_srw_get_pdu(out, Z_SRW_searchRetrieve_request, sru_version);
1461 srw_sr->u.request->queryType = "cql";
1462 srw_sr->u.request->query = encode_SRW_term(srw_sr_odr_out, arg);
1464 sr->u.request->queryType = "cql";
1465 sr->u.request->query = encode_SRW_term(srw_sr_odr_out, arg);
1467 case QueryType_Prefix:
1468 srw_sr->u.request->queryType = "pqf";
1469 srw_sr->u.request->query = encode_SRW_term(srw_sr_odr_out, arg);
1471 sr->u.request->queryType = "pqf";
1472 sr->u.request->query = encode_SRW_term(srw_sr_odr_out, arg);
1475 printf("Only CQL and PQF supported in SRW\n");
1478 if (*sru_recordPacking)
1479 sr->u.request->recordPacking = sru_recordPacking;
1480 sru_maximumRecords = 0;
1481 sr->u.request->maximumRecords = odr_intdup(out, 0);
1482 sr->u.request->facetList = facet_list;
1484 sr->u.request->recordSchema = record_schema;
1485 if (recordsyntax_size == 1 && !yaz_matchstr(recordsyntax_list[0], "xml"))
1486 sr->u.request->recordPacking = "xml";
1487 return send_srw(sr);
1491 static void query_charset_convert(Z_RPNQuery *q)
1493 if (queryCharset && outputCharset)
1495 yaz_iconv_t cd = yaz_iconv_open(queryCharset, outputCharset);
1498 printf("Conversion from %s to %s unsupported\n",
1499 outputCharset, queryCharset);
1502 yaz_query_charset_convert_rpnquery(q, out, cd);
1503 yaz_iconv_close(cd);
1507 static int send_Z3950_searchRequest(const char *arg)
1509 Z_APDU *apdu = zget_APDU(out, Z_APDU_searchRequest);
1510 Z_SearchRequest *req = apdu->u.searchRequest;
1512 struct ccl_rpn_node *rpn = NULL;
1514 char setstring[100];
1515 Z_RPNQuery *RPNquery;
1517 YAZ_PQF_Parser pqf_parser;
1519 QueryType myQueryType = queryType;
1522 if (myQueryType == QueryType_CCL2RPN)
1524 rpn = ccl_find_str(bibset, arg, &error, &pos);
1527 printf("CCL ERROR: %s\n", ccl_err_msg(error));
1531 else if (myQueryType == QueryType_CQL2RPN)
1533 /* ### All this code should be wrapped in a utility function */
1535 struct cql_node *node;
1536 const char *addinfo;
1539 printf("Can't use CQL: no translation file. Try set_cqlfile\n");
1542 parser = cql_parser_create();
1543 if ((error = cql_parser_string(parser, arg)) != 0)
1545 printf("Can't parse CQL: must be a syntax error\n");
1548 node = cql_parser_result(parser);
1549 if ((error = cql_transform_buf(cqltrans, node, pqfbuf,
1550 sizeof pqfbuf)) != 0)
1552 error = cql_transform_error(cqltrans, &addinfo);
1553 printf("Can't convert CQL to PQF: %s (addinfo=%s)\n",
1554 cql_strerror(error), addinfo);
1558 myQueryType = QueryType_Prefix;
1561 req->referenceId = set_refid(out);
1562 if (!strcmp(arg, "@big")) /* strictly for troublemaking */
1564 static char big[2100];
1565 static Odr_oct bigo;
1567 /* send a very big referenceid to test transport stack etc. */
1568 memset(big, 'A', 2100);
1571 req->referenceId = &bigo;
1576 sprintf(setstring, "%d", ++setnumber);
1577 req->resultSetName = setstring;
1579 *req->smallSetUpperBound = smallSetUpperBound;
1580 *req->largeSetLowerBound = largeSetLowerBound;
1581 *req->mediumSetPresentNumber = mediumSetPresentNumber;
1582 if (smallSetUpperBound > 0 || (largeSetLowerBound > 1 &&
1583 mediumSetPresentNumber > 0))
1585 if (recordsyntax_size)
1586 req->preferredRecordSyntax =
1587 yaz_string_to_oid_odr(yaz_oid_std(),
1588 CLASS_RECSYN, recordsyntax_list[0], out);
1590 req->smallSetElementSetNames =
1591 req->mediumSetElementSetNames = elementSetNames;
1593 req->num_databaseNames = num_databaseNames;
1594 req->databaseNames = databaseNames;
1596 req->query = &query;
1598 switch (myQueryType)
1600 case QueryType_Prefix:
1601 query.which = Z_Query_type_1;
1602 pqf_parser = yaz_pqf_create();
1603 RPNquery = yaz_pqf_parse(pqf_parser, out, arg);
1606 const char *pqf_msg;
1608 int code = yaz_pqf_error(pqf_parser, &pqf_msg, &off);
1610 printf("%*s^\n", ioff+4, "");
1611 printf("Prefix query error: %s (code %d)\n", pqf_msg, code);
1613 yaz_pqf_destroy(pqf_parser);
1616 yaz_pqf_destroy(pqf_parser);
1617 query_charset_convert(RPNquery);
1618 query.u.type_1 = RPNquery;
1621 query.which = Z_Query_type_2;
1622 query.u.type_2 = &ccl_query;
1623 ccl_query.buf = (char *) arg;
1624 ccl_query.len = strlen(arg);
1626 case QueryType_CCL2RPN:
1627 query.which = Z_Query_type_1;
1628 RPNquery = ccl_rpn_query(out, rpn);
1631 printf("Couldn't convert from CCL to RPN\n");
1634 query_charset_convert(RPNquery);
1635 query.u.type_1 = RPNquery;
1636 ccl_rpn_delete(rpn);
1639 query.which = Z_Query_type_104;
1640 ext = (Z_External *) odr_malloc(out, sizeof(*ext));
1641 ext->direct_reference = odr_getoidbystr(out, "1.2.840.10003.16.2");
1642 ext->indirect_reference = 0;
1643 ext->descriptor = 0;
1644 ext->which = Z_External_CQL;
1645 ext->u.cql = odr_strdup(out, arg);
1646 query.u.type_104 = ext;
1649 printf("Unsupported query type\n");
1652 if (send_apdu(apdu))
1653 printf("Sent searchRequest.\n");
1658 static void display_term(Z_Term *term)
1660 switch (term->which)
1662 case Z_Term_general:
1663 printf("%.*s", term->u.general->len, term->u.general->buf);
1665 case Z_Term_characterString:
1666 printf("%s", term->u.characterString);
1668 case Z_Term_numeric:
1669 printf(ODR_INT_PRINTF, *term->u.numeric);
1677 /* display Query Expression as part of searchResult-1 */
1678 static void display_queryExpression(const char *lead, Z_QueryExpression *qe)
1682 printf(" %s=", lead);
1683 if (qe->which == Z_QueryExpression_term)
1685 if (qe->u.term->queryTerm)
1687 Z_Term *term = qe->u.term->queryTerm;
1693 static void display_facet(Z_FacetField *facet)
1695 if (facet->attributes)
1697 Z_AttributeList *al = facet->attributes;
1698 struct yaz_facet_attr attr_values;
1699 yaz_facet_attr_init(&attr_values);
1700 yaz_facet_attr_get_z_attributes(al, &attr_values);
1701 if (!attr_values.errcode)
1704 printf(" %s (%d): \n", attr_values.useattr, facet->num_terms);
1705 for (term_index = 0 ; term_index < facet->num_terms; term_index++)
1707 Z_FacetTerm *facetTerm = facet->terms[term_index];
1709 display_term(facetTerm->term);
1710 printf(" (" NMEM_INT_PRINTF ")\n", *facetTerm->count);
1717 static void* display_facets(Z_FacetList *fl)
1720 printf("Facets(%d): \n", fl->num);
1722 for (index = 0; index < fl->num ; index++)
1724 display_facet(fl->elements[index]);
1729 void display_searchResult1(Z_SearchInfoReport *sr)
1732 printf("SearchResult-1:");
1733 for (j = 0; j < sr->num; j++)
1737 if (!sr->elements[j]->subqueryExpression)
1739 display_queryExpression("term",
1740 sr->elements[j]->subqueryExpression);
1741 display_queryExpression("interpretation",
1742 sr->elements[j]->subqueryInterpretation);
1743 display_queryExpression("recommendation",
1744 sr->elements[j]->subqueryRecommendation);
1745 if (sr->elements[j]->subqueryCount)
1746 printf(" cnt=" ODR_INT_PRINTF,
1747 *sr->elements[j]->subqueryCount);
1748 if (sr->elements[j]->subqueryId)
1749 printf(" id=%s ", sr->elements[j]->subqueryId);
1756 /* see if we can find USR:SearchResult-1 */
1757 static void display_searchResult(Z_OtherInformation *o)
1762 for (i = 0; i < o->num_elements; i++)
1764 if (o->list[i]->which == Z_OtherInfo_externallyDefinedInfo)
1766 Z_External *ext = o->list[i]->information.externallyDefinedInfo;
1768 if (ext->which == Z_External_searchResult1)
1769 display_searchResult1(ext->u.searchResult1);
1770 else if (ext->which == Z_External_userFacets)
1771 display_facets(ext->u.facetList);
1776 static int process_Z3950_searchResponse(Z_SearchResponse *res)
1778 printf("Received SearchResponse.\n");
1779 print_refid(res->referenceId);
1780 if (*res->searchStatus)
1781 printf("Search was a success.\n");
1783 printf("Search was a bloomin' failure.\n");
1784 printf("Number of hits: " ODR_INT_PRINTF, *res->resultCount);
1785 last_hit_count = *res->resultCount;
1787 printf(", setno %d", setnumber);
1789 if (res->resultSetStatus)
1791 printf("Result Set Status: ");
1792 switch (*res->resultSetStatus)
1794 case Z_SearchResponse_subset:
1795 printf("subset"); break;
1796 case Z_SearchResponse_interim:
1797 printf("interim"); break;
1798 case Z_SearchResponse_none:
1799 printf("none"); break;
1800 case Z_SearchResponse_estimate:
1801 printf("estimate"); break;
1803 printf(ODR_INT_PRINTF, *res->resultSetStatus);
1807 display_searchResult(res->additionalSearchInfo);
1808 printf("records returned: " ODR_INT_PRINTF "\n",
1809 *res->numberOfRecordsReturned);
1810 setno += *res->numberOfRecordsReturned;
1812 display_records(res->records);
1816 static void print_level(int iLevel)
1819 for (i = 0; i < iLevel * 4; i++)
1823 static void print_int(int iLevel, const char *pTag, Odr_int *pInt)
1827 print_level(iLevel);
1828 printf("%s: " ODR_INT_PRINTF "\n", pTag, *pInt);
1832 static void print_bool(int iLevel, const char *pTag, Odr_bool *pInt)
1836 print_level(iLevel);
1837 printf("%s: %d\n", pTag, *pInt);
1841 static void print_string(int iLevel, const char *pTag, const char *pString)
1843 if (pString != NULL)
1845 print_level(iLevel);
1846 printf("%s: %s\n", pTag, pString);
1850 static void print_oid(int iLevel, const char *pTag, Odr_oid *pOid)
1854 Odr_oid *pInt = pOid;
1856 print_level(iLevel);
1857 printf("%s:", pTag);
1858 for (; *pInt != -1; pInt++)
1859 printf(" %d", *pInt);
1864 static void print_referenceId(int iLevel, Z_ReferenceId *referenceId)
1866 if (referenceId != NULL)
1870 print_level(iLevel);
1871 printf("Ref Id (%d): ", referenceId->len);
1872 for (i = 0; i < referenceId->len; i++)
1873 printf("%c", referenceId->buf[i]);
1878 static void print_string_or_numeric(int iLevel, const char *pTag, Z_StringOrNumeric *pStringNumeric)
1880 if (pStringNumeric != NULL)
1882 switch (pStringNumeric->which)
1884 case Z_StringOrNumeric_string:
1885 print_string(iLevel, pTag, pStringNumeric->u.string);
1888 case Z_StringOrNumeric_numeric:
1889 print_int(iLevel, pTag, pStringNumeric->u.numeric);
1893 print_level(iLevel);
1894 printf("%s: valid type for Z_StringOrNumeric\n", pTag);
1900 static void print_universe_report_duplicate(
1902 Z_UniverseReportDuplicate *pUniverseReportDuplicate)
1904 if (pUniverseReportDuplicate != NULL)
1906 print_level(iLevel);
1907 printf("Universe Report Duplicate: \n");
1909 print_string_or_numeric(iLevel, "Hit No",
1910 pUniverseReportDuplicate->hitno);
1914 static void print_universe_report_hits(
1916 Z_UniverseReportHits *pUniverseReportHits)
1918 if (pUniverseReportHits != NULL)
1920 print_level(iLevel);
1921 printf("Universe Report Hits: \n");
1923 print_string_or_numeric(iLevel, "Database",
1924 pUniverseReportHits->database);
1925 print_string_or_numeric(iLevel, "Hits", pUniverseReportHits->hits);
1929 static void print_universe_report(int iLevel, Z_UniverseReport *pUniverseReport)
1931 if (pUniverseReport != NULL)
1933 print_level(iLevel);
1934 printf("Universe Report: \n");
1936 print_int(iLevel, "Total Hits", pUniverseReport->totalHits);
1937 switch (pUniverseReport->which)
1939 case Z_UniverseReport_databaseHits:
1940 print_universe_report_hits(iLevel,
1941 pUniverseReport->u.databaseHits);
1944 case Z_UniverseReport_duplicate:
1945 print_universe_report_duplicate(iLevel,
1946 pUniverseReport->u.duplicate);
1950 print_level(iLevel);
1951 printf("Type: %d\n", pUniverseReport->which);
1957 static void print_external(int iLevel, Z_External *pExternal)
1959 if (pExternal != NULL)
1961 print_level(iLevel);
1962 printf("External: \n");
1964 print_oid(iLevel, "Direct Reference", pExternal->direct_reference);
1965 print_int(iLevel, "InDirect Reference", pExternal->indirect_reference);
1966 print_string(iLevel, "Descriptor", pExternal->descriptor);
1967 switch (pExternal->which)
1969 case Z_External_universeReport:
1970 print_universe_report(iLevel, pExternal->u.universeReport);
1974 print_level(iLevel);
1975 printf("Type: %d\n", pExternal->which);
1981 static int process_Z3950_resourceControlRequest(Z_ResourceControlRequest *req)
1983 printf("Received ResourceControlRequest.\n");
1984 print_referenceId(1, req->referenceId);
1985 print_bool(1, "Suspended Flag", req->suspendedFlag);
1986 print_int(1, "Partial Results Available", req->partialResultsAvailable);
1987 print_bool(1, "Response Required", req->responseRequired);
1988 print_bool(1, "Triggered Request Flag", req->triggeredRequestFlag);
1989 print_external(1, req->resourceReport);
1993 static void process_Z3950_ESResponse(Z_ExtendedServicesResponse *res)
1996 switch (*res->operationStatus)
1998 case Z_ExtendedServicesResponse_done:
2001 case Z_ExtendedServicesResponse_accepted:
2002 printf("accepted\n");
2004 case Z_ExtendedServicesResponse_failure:
2005 printf("failure\n");
2006 display_diagrecs(res->diagnostics, res->num_diagnostics);
2009 printf("unknown\n");
2011 if ( (*res->operationStatus != Z_ExtendedServicesResponse_failure) &&
2012 (res->num_diagnostics != 0) )
2014 display_diagrecs(res->diagnostics, res->num_diagnostics);
2016 print_refid (res->referenceId);
2017 if (res->taskPackage &&
2018 res->taskPackage->which == Z_External_extendedService)
2020 Z_TaskPackage *taskPackage = res->taskPackage->u.extendedService;
2021 Odr_oct *id = taskPackage->targetReference;
2022 Z_External *ext = taskPackage->taskSpecificParameters;
2026 printf("Target Reference: ");
2027 print_stringn((const char *) id->buf, id->len);
2030 if (ext->which == Z_External_update)
2032 Z_IUUpdateTaskPackage *utp = ext->u.update->u.taskPackage;
2033 if (utp && utp->targetPart)
2035 Z_IUTargetPart *targetPart = utp->targetPart;
2038 for (i = 0; i<targetPart->num_taskPackageRecords; i++)
2041 Z_IUTaskPackageRecordStructure *tpr =
2042 targetPart->taskPackageRecords[i];
2043 printf("task package record %d\n", i+1);
2044 if (tpr->which == Z_IUTaskPackageRecordStructure_record)
2046 display_record (tpr->u.record);
2050 printf("other type\n");
2055 if (ext->which == Z_External_itemOrder)
2057 Z_IOTaskPackage *otp = ext->u.itemOrder->u.taskPackage;
2059 if (otp && otp->targetPart)
2061 if (otp->targetPart->itemRequest)
2063 Z_External *ext = otp->targetPart->itemRequest;
2064 if (ext->which == Z_External_octet)
2066 Odr_oct *doc = ext->u.octet_aligned;
2067 printf("Got itemRequest doc %.*s\n",
2068 doc->len, doc->buf);
2071 else if (otp->targetPart->statusOrErrorReport)
2073 Z_External *ext = otp->targetPart->statusOrErrorReport;
2074 if (ext->which == Z_External_octet)
2076 Odr_oct *doc = ext->u.octet_aligned;
2077 printf("Got Status or Error Report doc %.*s\n",
2078 doc->len, doc->buf);
2084 if (res->taskPackage && res->taskPackage->which == Z_External_octet)
2086 Odr_oct *doc = res->taskPackage->u.octet_aligned;
2087 printf("%.*s\n", doc->len, doc->buf);
2091 static const char *get_ill_element(void *clientData, const char *element)
2096 static Z_External *create_external_itemRequest(void)
2098 struct ill_get_ctl ctl;
2099 ILL_ItemRequest *req;
2101 int item_request_size = 0;
2102 char *item_request_buf = 0;
2106 ctl.f = get_ill_element;
2108 req = ill_get_ItemRequest(&ctl, "ill", 0);
2110 printf("ill_get_ItemRequest failed\n");
2112 if (!ill_ItemRequest(out, &req, 0, 0))
2116 ill_ItemRequest(print, &req, 0, 0);
2119 item_request_buf = odr_getbuf (out, &item_request_size, 0);
2120 if (item_request_buf)
2121 odr_setbuf (out, item_request_buf, item_request_size, 1);
2122 printf("Couldn't encode ItemRequest, size %d\n", item_request_size);
2127 item_request_buf = odr_getbuf (out, &item_request_size, 0);
2128 r = (Z_External *) odr_malloc(out, sizeof(*r));
2129 r->direct_reference = odr_oiddup(out, yaz_oid_general_isoill_1);
2130 r->indirect_reference = 0;
2132 r->which = Z_External_single;
2133 r->u.single_ASN1_type =
2134 odr_create_Odr_oct(out, item_request_buf, item_request_size);
2135 do_hex_dump(item_request_buf,item_request_size);
2140 static Z_External *create_external_ILL_APDU(void)
2142 struct ill_get_ctl ctl;
2145 int ill_request_size = 0;
2146 char *ill_request_buf = 0;
2150 ctl.f = get_ill_element;
2152 ill_apdu = ill_get_APDU(&ctl, "ill", 0);
2154 if (!ill_APDU (out, &ill_apdu, 0, 0))
2158 printf("-------------------\n");
2159 ill_APDU(print, &ill_apdu, 0, 0);
2161 printf("-------------------\n");
2163 ill_request_buf = odr_getbuf (out, &ill_request_size, 0);
2164 if (ill_request_buf)
2165 odr_setbuf (out, ill_request_buf, ill_request_size, 1);
2166 printf("Couldn't encode ILL-Request, size %d\n", ill_request_size);
2171 ill_request_buf = odr_getbuf (out, &ill_request_size, 0);
2173 r = (Z_External *) odr_malloc(out, sizeof(*r));
2174 r->direct_reference = odr_oiddup(out, yaz_oid_general_isoill_1);
2175 r->indirect_reference = 0;
2177 r->which = Z_External_single;
2178 r->u.single_ASN1_type = odr_create_Odr_oct(out, ill_request_buf,
2185 static Z_External *create_ItemOrderExternal(const char *type, int itemno,
2186 const char *xml_buf,
2189 Z_External *r = (Z_External *) odr_malloc(out, sizeof(Z_External));
2190 r->direct_reference = odr_oiddup(out, yaz_oid_extserv_item_order);
2191 r->indirect_reference = 0;
2194 r->which = Z_External_itemOrder;
2196 r->u.itemOrder = (Z_ItemOrder *) odr_malloc(out,sizeof(Z_ItemOrder));
2197 memset(r->u.itemOrder, 0, sizeof(Z_ItemOrder));
2198 r->u.itemOrder->which=Z_IOItemOrder_esRequest;
2200 r->u.itemOrder->u.esRequest = (Z_IORequest *)
2201 odr_malloc(out,sizeof(Z_IORequest));
2202 memset(r->u.itemOrder->u.esRequest, 0, sizeof(Z_IORequest));
2204 r->u.itemOrder->u.esRequest->toKeep = (Z_IOOriginPartToKeep *)
2205 odr_malloc(out,sizeof(Z_IOOriginPartToKeep));
2206 memset(r->u.itemOrder->u.esRequest->toKeep, 0, sizeof(Z_IOOriginPartToKeep));
2207 r->u.itemOrder->u.esRequest->notToKeep = (Z_IOOriginPartNotToKeep *)
2208 odr_malloc(out,sizeof(Z_IOOriginPartNotToKeep));
2209 memset(r->u.itemOrder->u.esRequest->notToKeep, 0, sizeof(Z_IOOriginPartNotToKeep));
2211 r->u.itemOrder->u.esRequest->toKeep->supplDescription = NULL;
2212 r->u.itemOrder->u.esRequest->toKeep->contact = NULL;
2213 r->u.itemOrder->u.esRequest->toKeep->addlBilling = NULL;
2215 r->u.itemOrder->u.esRequest->notToKeep->resultSetItem =
2216 (Z_IOResultSetItem *) odr_malloc(out, sizeof(Z_IOResultSetItem));
2217 memset(r->u.itemOrder->u.esRequest->notToKeep->resultSetItem, 0, sizeof(Z_IOResultSetItem));
2218 r->u.itemOrder->u.esRequest->notToKeep->resultSetItem->resultSetId = "1";
2220 r->u.itemOrder->u.esRequest->notToKeep->resultSetItem->item =
2221 odr_intdup(out, itemno);
2222 if (!strcmp (type, "item") || !strcmp(type, "2"))
2224 printf("using item-request\n");
2225 r->u.itemOrder->u.esRequest->notToKeep->itemRequest =
2226 create_external_itemRequest();
2228 else if (!strcmp(type, "ill") || !strcmp(type, "1"))
2230 printf("using ILL-request\n");
2231 r->u.itemOrder->u.esRequest->notToKeep->itemRequest =
2232 create_external_ILL_APDU();
2234 else if (!strcmp(type, "xml") || !strcmp(type, "3"))
2236 printf("using XML ILL-request\n");
2240 printf("no docoument added\n");
2241 r->u.itemOrder->u.esRequest->notToKeep->itemRequest = 0;
2245 r->u.itemOrder->u.esRequest->notToKeep->itemRequest =
2246 z_ext_record_oid(out, yaz_oid_recsyn_xml, xml_buf, xml_len);
2250 r->u.itemOrder->u.esRequest->notToKeep->itemRequest = 0;
2255 static int send_Z3950_itemorder(const char *type, int itemno,
2256 const char *xml_buf, int xml_len)
2258 Z_APDU *apdu = zget_APDU(out, Z_APDU_extendedServicesRequest);
2259 Z_ExtendedServicesRequest *req = apdu->u.extendedServicesRequest;
2261 req->referenceId = set_refid (out);
2263 req->packageType = odr_oiddup(out, yaz_oid_extserv_item_order);
2264 req->packageName = esPackageName;
2266 req->taskSpecificParameters = create_ItemOrderExternal(type, itemno,
2272 static int only_z3950(void)
2276 printf("Not connected yet\n");
2279 if (protocol == PROTO_HTTP)
2281 printf("Not supported by SRW\n");
2287 static int cmd_update_common(const char *arg, int version);
2289 static int cmd_update(const char *arg)
2291 return cmd_update_common(arg, 1);
2294 static int cmd_update0(const char *arg)
2296 return cmd_update_common(arg, 0);
2299 static int send_Z3950_update(int version, int action_no, const char *recid,
2300 char *rec_buf, int rec_len);
2303 static int send_SRW_update(int action_no, const char *recid,
2304 char *rec_buf, int rec_len);
2307 static int cmd_update_common(const char *arg, int version)
2313 const char *recid = 0;
2319 if (parse_cmd_doc(&arg, out, &action_buf, &action_len) == 0)
2321 printf("Use: update action recid [fname]\n");
2322 printf(" where action is one of insert,replace,delete.update\n");
2323 printf(" recid is some record ID. Use none for no ID\n");
2324 printf(" fname is file of record to be updated\n");
2328 if (parse_cmd_doc(&arg, out, &recid_buf, &recid_len) == 0)
2330 printf("Missing recid\n");
2334 if (!strcmp(action_buf, "insert"))
2335 action_no = Z_IUOriginPartToKeep_recordInsert;
2336 else if (!strcmp(action_buf, "replace"))
2337 action_no = Z_IUOriginPartToKeep_recordReplace;
2338 else if (!strcmp(action_buf, "delete"))
2339 action_no = Z_IUOriginPartToKeep_recordDelete;
2340 else if (!strcmp(action_buf, "update"))
2341 action_no = Z_IUOriginPartToKeep_specialUpdate;
2344 printf("Bad action: %s\n", action_buf);
2345 printf("Possible values: insert, replace, delete, update\n");
2349 if (strcmp(recid_buf, "none")) /* none means no record ID */
2353 if (parse_cmd_doc(&arg, out, &rec_buf, &rec_len) == 0)
2357 if (protocol == PROTO_HTTP)
2358 return send_SRW_update(action_no, recid, rec_buf, rec_len);
2360 return send_Z3950_update(version, action_no, recid, rec_buf, rec_len);
2364 static int send_SRW_update(int action_no, const char *recid,
2365 char *rec_buf, int rec_len)
2368 session_connect(cur_host);
2373 Z_SRW_PDU *srw = yaz_srw_get(out, Z_SRW_update_request);
2374 Z_SRW_updateRequest *sr = srw->u.update_request;
2378 case Z_IUOriginPartToKeep_recordInsert:
2379 sr->operation = "info:srw/action/1/create";
2381 case Z_IUOriginPartToKeep_recordReplace:
2382 sr->operation = "info:srw/action/1/replace";
2384 case Z_IUOriginPartToKeep_recordDelete:
2385 sr->operation = "info:srw/action/1/delete";
2390 sr->record = yaz_srw_get_record(out);
2391 sr->record->recordData_buf = rec_buf;
2392 sr->record->recordData_len = rec_len;
2393 sr->record->recordSchema = record_schema;
2396 sr->recordId = odr_strdup(out, recid);
2397 return send_srw(srw);
2402 static int send_Z3950_update(int version, int action_no, const char *recid,
2403 char *rec_buf, int rec_len)
2405 Z_APDU *apdu = zget_APDU(out, Z_APDU_extendedServicesRequest );
2406 Z_ExtendedServicesRequest *req = apdu->u.extendedServicesRequest;
2408 Z_External *record_this = 0;
2410 record_this = z_ext_record_oid(out, yaz_oid_recsyn_xml,
2416 printf("No last record (update ignored)\n");
2419 record_this = record_last;
2422 req->packageType = odr_oiddup(out, (version == 0 ?
2423 yaz_oid_extserv_database_update_first_version :
2424 yaz_oid_extserv_database_update));
2426 req->packageName = esPackageName;
2428 req->referenceId = set_refid (out);
2430 r = req->taskSpecificParameters = (Z_External *)
2431 odr_malloc(out, sizeof(*r));
2432 r->direct_reference = req->packageType;
2433 r->indirect_reference = 0;
2437 Z_IU0OriginPartToKeep *toKeep;
2438 Z_IU0SuppliedRecords *notToKeep;
2440 r->which = Z_External_update0;
2441 r->u.update0 = (Z_IU0Update *) odr_malloc(out, sizeof(*r->u.update0));
2442 r->u.update0->which = Z_IUUpdate_esRequest;
2443 r->u.update0->u.esRequest = (Z_IU0UpdateEsRequest *)
2444 odr_malloc(out, sizeof(*r->u.update0->u.esRequest));
2445 toKeep = r->u.update0->u.esRequest->toKeep = (Z_IU0OriginPartToKeep *)
2446 odr_malloc(out, sizeof(*r->u.update0->u.esRequest->toKeep));
2448 toKeep->databaseName = databaseNames[0];
2452 toKeep->schema = yaz_string_to_oid_odr(yaz_oid_std(),
2454 record_schema, out);
2456 toKeep->elementSetName = 0;
2458 toKeep->action = odr_intdup(out, action_no);
2460 notToKeep = r->u.update0->u.esRequest->notToKeep = (Z_IU0SuppliedRecords *)
2461 odr_malloc(out, sizeof(*r->u.update0->u.esRequest->notToKeep));
2463 notToKeep->elements = (Z_IU0SuppliedRecords_elem **)
2464 odr_malloc(out, sizeof(*notToKeep->elements));
2465 notToKeep->elements[0] = (Z_IU0SuppliedRecords_elem *)
2466 odr_malloc(out, sizeof(**notToKeep->elements));
2467 notToKeep->elements[0]->which = Z_IUSuppliedRecords_elem_opaque;
2468 notToKeep->elements[0]->u.opaque = recid ?
2469 odr_create_Odr_oct(out, recid, strlen(recid)) : 0;
2470 notToKeep->elements[0]->supplementalId = 0;
2471 notToKeep->elements[0]->correlationInfo = 0;
2472 notToKeep->elements[0]->record = record_this;
2476 Z_IUOriginPartToKeep *toKeep;
2477 Z_IUSuppliedRecords *notToKeep;
2479 r->which = Z_External_update;
2480 r->u.update = (Z_IUUpdate *) odr_malloc(out, sizeof(*r->u.update));
2481 r->u.update->which = Z_IUUpdate_esRequest;
2482 r->u.update->u.esRequest = (Z_IUUpdateEsRequest *)
2483 odr_malloc(out, sizeof(*r->u.update->u.esRequest));
2484 toKeep = r->u.update->u.esRequest->toKeep = (Z_IUOriginPartToKeep *)
2485 odr_malloc(out, sizeof(*r->u.update->u.esRequest->toKeep));
2487 toKeep->databaseName = databaseNames[0];
2491 toKeep->schema = yaz_string_to_oid_odr(yaz_oid_std(),
2493 record_schema, out);
2495 toKeep->elementSetName = 0;
2496 toKeep->actionQualifier = 0;
2497 toKeep->action = odr_intdup(out, action_no);
2499 notToKeep = r->u.update->u.esRequest->notToKeep = (Z_IUSuppliedRecords *)
2500 odr_malloc(out, sizeof(*r->u.update->u.esRequest->notToKeep));
2502 notToKeep->elements = (Z_IUSuppliedRecords_elem **)
2503 odr_malloc(out, sizeof(*notToKeep->elements));
2504 notToKeep->elements[0] = (Z_IUSuppliedRecords_elem *)
2505 odr_malloc(out, sizeof(**notToKeep->elements));
2506 notToKeep->elements[0]->which = Z_IUSuppliedRecords_elem_opaque;
2507 notToKeep->elements[0]->u.opaque = recid ?
2508 odr_create_Odr_oct(out, recid, strlen(recid)) : 0;
2509 notToKeep->elements[0]->supplementalId = 0;
2510 notToKeep->elements[0]->correlationInfo = 0;
2511 notToKeep->elements[0]->record = record_this;
2519 static int cmd_xmles(const char *arg)
2529 Z_APDU *apdu = zget_APDU(out, Z_APDU_extendedServicesRequest);
2530 Z_ExtendedServicesRequest *req = apdu->u.extendedServicesRequest;
2533 Z_External *ext = (Z_External *) odr_malloc(out, sizeof(*ext));
2535 req->referenceId = set_refid (out);
2536 req->taskSpecificParameters = ext;
2537 ext->indirect_reference = 0;
2538 ext->descriptor = 0;
2539 ext->which = Z_External_octet;
2540 ext->u.single_ASN1_type = (Odr_oct *) odr_malloc(out, sizeof(Odr_oct));
2541 sscanf(arg, "%50s%n", oid_str, &noread);
2544 printf("Missing OID for xmles\n");
2548 if (parse_cmd_doc(&arg, out, &asn_buf,
2549 &ext->u.single_ASN1_type->len) == 0)
2552 ext->u.single_ASN1_type->buf = asn_buf;
2554 oid = yaz_string_to_oid_odr(yaz_oid_std(),
2555 CLASS_EXTSERV, oid_str, out);
2558 printf("Bad OID: %s\n", oid_str);
2562 req->packageType = oid;
2564 ext->direct_reference = oid;
2572 static int cmd_itemorder(const char *arg)
2582 if (sscanf(arg, "%10s %d%n", type, &itemno, &no_read) < 2)
2585 parse_cmd_doc(&arg, out, &xml_buf, &xml_len);
2588 send_Z3950_itemorder(type, itemno, xml_buf, xml_len);
2592 static void show_opt(const char *arg, void *clientData)
2597 static int cmd_zversion(const char *arg)
2600 z3950_version = atoi(arg);
2602 printf("version is %d\n", z3950_version);
2606 static int cmd_options(const char *arg)
2612 r = yaz_init_opt_encode(&z3950_options, arg, &pos);
2614 printf("Unknown option(s) near %s\n", arg+pos);
2618 yaz_init_opt_decode(&z3950_options, show_opt, 0);
2624 static int cmd_explain(const char *arg)
2626 if (protocol != PROTO_HTTP)
2630 session_connect(cur_host);
2637 /* save this for later .. when fetching individual records */
2638 sr = yaz_srw_get(out, Z_SRW_explain_request);
2639 if (recordsyntax_size == 1
2640 && !yaz_matchstr(recordsyntax_list[0], "xml"))
2641 sr->u.explain_request->recordPacking = "xml";
2649 static int cmd_init(const char *arg)
2653 strncpy(cur_host, arg, sizeof(cur_host)-1);
2654 cur_host[sizeof(cur_host)-1] = 0;
2658 send_Z3950_initRequest(cur_host);
2662 static Z_GDU *get_HTTP_Request_url(ODR odr, const char *url)
2664 Z_GDU *p = z_get_HTTP_Request(odr);
2665 const char *host = url;
2666 const char *cp0 = strstr(host, "://");
2667 const char *cp1 = 0;
2673 cp1 = strchr(cp0, '/');
2675 cp1 = cp0 + strlen(cp0);
2679 char *h = (char*) odr_malloc(odr, cp1 - cp0 + 1);
2680 memcpy (h, cp0, cp1 - cp0);
2682 z_HTTP_header_add(odr, &p->u.HTTP_Request->headers, "Host", h);
2684 p->u.HTTP_Request->path = odr_strdup(odr, *cp1 ? cp1 : "/");
2688 static WRBUF get_url(const char *uri, WRBUF username, WRBUF password,
2689 int *code, int show_headers)
2692 ODR out = odr_createmem(ODR_ENCODE);
2693 ODR in = odr_createmem(ODR_DECODE);
2694 Z_GDU *gdu = get_HTTP_Request_url(out, uri);
2696 gdu->u.HTTP_Request->method = odr_strdup(out, "GET");
2697 if (username && password)
2699 z_HTTP_header_add_basic_auth(out, &gdu->u.HTTP_Request->headers,
2700 wrbuf_cstr(username),
2701 wrbuf_cstr(password));
2703 z_HTTP_header_add(out, &gdu->u.HTTP_Request->headers, "Accept",
2705 if (!z_GDU(out, &gdu, 0, 0))
2707 yaz_log(YLOG_WARN, "Can not encode HTTP request URL:%s", uri);
2712 COMSTACK conn = cs_create_host(uri, 1, &add);
2713 if (cs_connect(conn, add) < 0)
2714 yaz_log(YLOG_WARN, "Can not connect to URL:%s", uri);
2718 char *buf = odr_getbuf(out, &len, 0);
2720 if (cs_put(conn, buf, len) < 0)
2721 yaz_log(YLOG_WARN, "cs_put failed URL:%s", uri);
2724 char *netbuffer = 0;
2726 int res = cs_get(conn, &netbuffer, &netlen);
2729 yaz_log(YLOG_WARN, "cs_get failed URL:%s", uri);
2734 odr_setbuf(in, netbuffer, res, 0);
2735 if (!z_GDU(in, &gdu, 0, 0)
2736 || gdu->which != Z_GDU_HTTP_Response)
2738 yaz_log(YLOG_WARN, "decode failed URL: %s", uri);
2742 Z_HTTP_Response *res = gdu->u.HTTP_Response;
2743 struct Z_HTTP_Header *h;
2744 result = wrbuf_alloc();
2748 wrbuf_printf(result, "HTTP %d\n", res->code);
2749 for (h = res->headers; h; h = h->next)
2750 wrbuf_printf(result, "%s: %s\n",
2754 wrbuf_write(result, res->content_buf, res->content_len);
2768 static int cmd_url(const char *arg)
2771 WRBUF res = get_url(arg, 0, 0, &code, 1);
2774 if (wrbuf_len(res) > 1200)
2776 fwrite(wrbuf_buf(res), 1, 1200, stdout);
2777 printf(".. out of %lld\n", (long long) wrbuf_len(res));
2780 puts(wrbuf_cstr(res));
2786 static int cmd_sru(const char *arg)
2790 printf("SRU method is: %s\n", sru_method);
2791 printf("SRU version is: %s\n", sru_version);
2795 int r = sscanf(arg, "%9s %9s %9s", sru_method, sru_version,
2799 if (!yaz_matchstr(sru_method, "post"))
2801 else if (!yaz_matchstr(sru_method, "get"))
2803 else if (!yaz_matchstr(sru_method, "soap"))
2805 else if (!yaz_matchstr(sru_method, "solr"))
2809 strcpy(sru_method, "soap");
2810 printf("Unknown SRU method: %s\n", arg);
2811 printf("Specify one of POST, GET, SOAP, SOLR\n");
2818 static int cmd_find(const char *arg)
2822 printf("Find what?\n");
2825 if (protocol == PROTO_HTTP)
2829 session_connect(cur_host);
2832 if (!send_SRW_searchRequest(arg))
2840 if (*cur_host && auto_reconnect)
2847 if (!send_Z3950_searchRequest(arg))
2849 wait_and_handle_response(0);
2855 printf("Unable to reconnect\n");
2858 session_connect(cur_host);
2859 wait_and_handle_response(0);
2865 if (!send_Z3950_searchRequest(arg))
2870 printf("Not connected yet\n");
2877 static int cmd_facets(const char *arg)
2880 facet_odr = odr_createmem(ODR_ENCODE);
2881 odr_reset(facet_odr);
2886 printf("Facets cleared.\n");
2889 facet_list = yaz_pqf_parse_facet_list(facet_odr, arg);
2892 printf("Invalid facet list: %s", arg);
2898 static int cmd_delete(const char *arg)
2902 if (!send_Z3950_deleteResultSetRequest(arg))
2907 static int cmd_ssub(const char *arg)
2909 if (!(smallSetUpperBound = atoi(arg)))
2914 static int cmd_lslb(const char *arg)
2916 if (!(largeSetLowerBound = atoi(arg)))
2921 static int cmd_mspn(const char *arg)
2923 if (!(mediumSetPresentNumber = atoi(arg)))
2928 static int cmd_status(const char *arg)
2930 printf("smallSetUpperBound: %d\n", smallSetUpperBound);
2931 printf("largeSetLowerBound: %d\n", largeSetLowerBound);
2932 printf("mediumSetPresentNumber: %d\n", mediumSetPresentNumber);
2936 static int cmd_setnames(const char *arg)
2938 if (*arg == '1') /* enable ? */
2940 else if (*arg == '0') /* disable ? */
2942 else if (setnumber < 0) /* no args, toggle .. */
2948 printf("Set numbering enabled.\n");
2950 printf("Set numbering disabled.\n");
2954 /* PRESENT SERVICE ----------------------------- */
2956 size_t check_token(const char *haystack, const char *token)
2958 size_t len = strlen(token);
2960 if (strncmp(haystack, token, len))
2962 for (extra = 0; haystack[extra + len] != '\0'; extra++)
2963 if (!strchr(" \r\n\t", haystack[extra + len]))
2968 return 0; /* no whitespace after token */
2973 static int parse_show_args(const char *arg_c, char *setstring,
2974 Odr_int *start, Odr_int *number)
2977 Odr_int start_position;
2981 sprintf(setstring, "%d", setnumber);
2985 token_len = check_token(arg_c, "format");
2994 token_len = check_token(arg_c, "all");
2997 *number = last_hit_count;
3001 start_position = odr_strtol(arg_c, &end_ptr, 10);
3002 if (end_ptr == arg_c)
3004 *start = start_position;
3005 if (*end_ptr == '\0')
3007 while (yaz_isspace(*end_ptr))
3009 if (*end_ptr != '+')
3011 printf("Bad show arg: expected +. Got %s\n", end_ptr);
3016 *number = odr_strtol(arg_c, &end_ptr, 10);
3017 if (end_ptr == arg_c)
3019 printf("Bad show arg: expected number after +\n");
3022 if (*end_ptr == '\0')
3024 while (yaz_isspace(*end_ptr))
3026 if (*end_ptr != '+')
3028 printf("Bad show arg: + expected. Got %s\n", end_ptr);
3031 strcpy(setstring, end_ptr+1);
3035 static int send_Z3950_presentRequest(const char *arg)
3037 Z_APDU *apdu = zget_APDU(out, Z_APDU_presentRequest);
3038 Z_PresentRequest *req = apdu->u.presentRequest;
3039 Z_RecordComposition compo;
3041 char setstring[100];
3043 req->referenceId = set_refid(out);
3045 if (!parse_show_args(arg, setstring, &setno, &nos))
3048 req->resultSetId = setstring;
3050 req->resultSetStartPoint = &setno;
3051 req->numberOfRecordsRequested = &nos;
3053 if (recordsyntax_size)
3054 req->preferredRecordSyntax =
3055 yaz_string_to_oid_odr(yaz_oid_std(),
3056 CLASS_RECSYN, recordsyntax_list[0], out);
3058 if (record_schema || recordsyntax_size >= 2)
3060 req->recordComposition = &compo;
3061 compo.which = Z_RecordComp_complex;
3062 compo.u.complex = (Z_CompSpec *)
3063 odr_malloc(out, sizeof(*compo.u.complex));
3064 compo.u.complex->selectAlternativeSyntax = (bool_t *)
3065 odr_malloc(out, sizeof(bool_t));
3066 *compo.u.complex->selectAlternativeSyntax = 0;
3068 compo.u.complex->generic = (Z_Specification *)
3069 odr_malloc(out, sizeof(*compo.u.complex->generic));
3071 compo.u.complex->generic->which = Z_Schema_oid;
3073 compo.u.complex->generic->schema.oid = 0;
3076 compo.u.complex->generic->schema.oid =
3077 yaz_string_to_oid_odr(yaz_oid_std(),
3078 CLASS_SCHEMA, record_schema, out);
3080 if (!compo.u.complex->generic->schema.oid)
3082 /* OID wasn't a schema! Try record syntax instead. */
3083 compo.u.complex->generic->schema.oid = (Odr_oid *)
3084 yaz_string_to_oid_odr(yaz_oid_std(),
3085 CLASS_RECSYN, record_schema, out);
3088 if (!elementSetNames)
3089 compo.u.complex->generic->elementSpec = 0;
3092 compo.u.complex->generic->elementSpec = (Z_ElementSpec *)
3093 odr_malloc(out, sizeof(Z_ElementSpec));
3094 compo.u.complex->generic->elementSpec->which =
3095 Z_ElementSpec_elementSetName;
3096 compo.u.complex->generic->elementSpec->u.elementSetName =
3097 elementSetNames->u.generic;
3099 compo.u.complex->num_dbSpecific = 0;
3100 compo.u.complex->dbSpecific = 0;
3102 compo.u.complex->num_recordSyntax = 0;
3103 compo.u.complex->recordSyntax = 0;
3104 if (recordsyntax_size >= 2)
3107 compo.u.complex->num_recordSyntax = recordsyntax_size;
3108 compo.u.complex->recordSyntax = (Odr_oid **)
3109 odr_malloc(out, recordsyntax_size * sizeof(Odr_oid*));
3110 for (i = 0; i < recordsyntax_size; i++)
3111 compo.u.complex->recordSyntax[i] =
3112 yaz_string_to_oid_odr(yaz_oid_std(),
3113 CLASS_RECSYN, recordsyntax_list[i], out);
3116 else if (elementSetNames)
3118 req->recordComposition = &compo;
3119 compo.which = Z_RecordComp_simple;
3120 compo.u.simple = elementSetNames;
3123 printf("Sent presentRequest (" ODR_INT_PRINTF "+" ODR_INT_PRINTF ").\n",
3129 static int send_SRW_presentRequest(const char *arg)
3131 char setstring[100];
3133 Z_SRW_PDU *sr = srw_sr;
3137 if (!parse_show_args(arg, setstring, &setno, &nos))
3139 if (*sru_recordPacking)
3140 sr->u.request->recordPacking = sru_recordPacking;
3141 sr->u.request->startRecord = odr_intdup(out, setno);
3142 sru_maximumRecords = nos;
3143 sr->u.request->maximumRecords = odr_intdup(out, nos);
3145 sr->u.request->recordSchema = record_schema;
3146 if (recordsyntax_size == 1 && !yaz_matchstr(recordsyntax_list[0], "xml"))
3147 sr->u.request->recordPacking = "xml";
3148 return send_srw(sr);
3152 static void close_session(void)
3164 static void process_Z3950_close(Z_Close *req)
3166 Z_APDU *apdu = zget_APDU(out, Z_APDU_close);
3167 Z_Close *res = apdu->u.close;
3169 static char *reasons[] =
3174 "cost limit reached",
3176 "security violation",
3183 printf("Reason: %s, message: %s\n", reasons[*req->closeReason],
3184 req->diagnosticInformation ? req->diagnosticInformation : "NULL");
3189 *res->closeReason = Z_Close_finished;
3191 printf("Sent response.\n");
3196 static int cmd_show(const char *arg)
3198 if (protocol == PROTO_HTTP)
3202 session_connect(cur_host);
3205 if (!send_SRW_presentRequest(arg))
3215 printf("Not connected yet\n");
3218 if (!send_Z3950_presentRequest(arg))
3224 static void exit_client(int code)
3226 file_history_save(file_history);
3227 file_history_destroy(&file_history);
3228 nmem_destroy(nmem_auth);
3232 static int cmd_quit(const char *arg)
3234 printf("See you later, alligator.\n");
3240 static int cmd_cancel(const char *arg)
3246 Z_APDU *apdu = zget_APDU(out, Z_APDU_triggerResourceControlRequest);
3247 Z_TriggerResourceControlRequest *req =
3248 apdu->u.triggerResourceControlRequest;
3253 sscanf(arg, "%15s", command);
3257 if (session_initResponse &&
3258 !ODR_MASK_GET(session_initResponse->options,
3259 Z_Options_triggerResourceCtrl))
3261 printf("Target doesn't support cancel (trigger resource ctrl)\n");
3264 *req->requestedAction = Z_TriggerResourceControlRequest_cancel;
3265 req->resultSetWanted = &rfalse;
3266 req->referenceId = set_refid(out);
3269 printf("Sent cancel request\n");
3270 if (!strcmp(command, "wait"))
3276 static int cmd_cancel_find(const char *arg)
3281 fres = cmd_find(arg);
3284 return cmd_cancel("");
3289 static int send_Z3950_scanrequest(const char *set, const char *query,
3290 Odr_int *pos, Odr_int num, const char *term)
3292 Z_APDU *apdu = zget_APDU(out, Z_APDU_scanRequest);
3293 Z_ScanRequest *req = apdu->u.scanRequest;
3297 printf("query: %s\n", query);
3298 if (queryType == QueryType_CCL2RPN)
3301 struct ccl_rpn_node *rpn;
3303 rpn = ccl_find_str(bibset, query, &error, &pos);
3306 printf("CCL ERROR: %s\n", ccl_err_msg(error));
3310 yaz_string_to_oid_odr(yaz_oid_std(),
3311 CLASS_ATTSET, "Bib-1", out);
3312 if (!(req->termListAndStartPoint = ccl_scan_query(out, rpn)))
3314 printf("Couldn't convert CCL to Scan term\n");
3317 ccl_rpn_delete(rpn);
3321 YAZ_PQF_Parser pqf_parser = yaz_pqf_create();
3324 if (!(req->termListAndStartPoint =
3325 yaz_pqf_scan(pqf_parser, out, &req->attributeSet, query)))
3327 const char *pqf_msg;
3329 int code = yaz_pqf_error(pqf_parser, &pqf_msg, &off);
3331 printf("%*s^\n", ioff+7, "");
3332 printf("Prefix query error: %s (code %d)\n", pqf_msg, code);
3333 yaz_pqf_destroy(pqf_parser);
3336 yaz_pqf_destroy(pqf_parser);
3338 if (queryCharset && outputCharset)
3340 yaz_iconv_t cd = yaz_iconv_open(queryCharset, outputCharset);
3343 printf("Conversion from %s to %s unsupported\n",
3344 outputCharset, queryCharset);
3347 yaz_query_charset_convert_apt(req->termListAndStartPoint, out, cd);
3348 yaz_iconv_close(cd);
3352 if (req->termListAndStartPoint->term &&
3353 req->termListAndStartPoint->term->which == Z_Term_general &&
3354 req->termListAndStartPoint->term->u.general)
3356 req->termListAndStartPoint->term->u.general->buf =
3357 odr_strdup(out, term);
3358 req->termListAndStartPoint->term->u.general->len = strlen(term);
3361 req->referenceId = set_refid(out);
3362 req->num_databaseNames = num_databaseNames;
3363 req->databaseNames = databaseNames;
3364 req->numberOfTermsRequested = #
3365 req->preferredPositionInResponse = pos;
3366 req->stepSize = odr_intdup(out, scan_stepSize);
3369 yaz_oi_set_string_oid(&req->otherInfo, out,
3370 yaz_oid_userinfo_scan_set, 1, set);
3376 static int send_sortrequest(const char *arg, int newset)
3378 Z_APDU *apdu = zget_APDU(out, Z_APDU_sortRequest);
3379 Z_SortRequest *req = apdu->u.sortRequest;
3380 Z_SortKeySpecList *sksl = (Z_SortKeySpecList *)
3381 odr_malloc(out, sizeof(*sksl));
3387 sprintf(setstring, "%d", setnumber);
3389 sprintf(setstring, "default");
3391 req->referenceId = set_refid(out);
3393 req->num_inputResultSetNames = 1;
3394 req->inputResultSetNames = (Z_InternationalString **)
3395 odr_malloc(out, sizeof(*req->inputResultSetNames));
3396 req->inputResultSetNames[0] = odr_strdup(out, setstring);
3398 if (newset && setnumber >= 0)
3399 sprintf(setstring, "%d", ++setnumber);
3401 req->sortedResultSetName = odr_strdup(out, setstring);
3403 req->sortSequence = yaz_sort_spec(out, arg);
3404 if (!req->sortSequence)
3406 printf("Missing sort specifications\n");
3413 static void display_term_info(Z_TermInfo *t)
3416 printf("%s", t->displayTerm);
3417 else if (t->term->which == Z_Term_general)
3418 printf("%.*s", t->term->u.general->len, t->term->u.general->buf);
3420 printf("Term (not general)");
3421 if (t->term->which == Z_Term_general)
3422 sprintf(last_scan_line, "%.*s", t->term->u.general->len,
3423 t->term->u.general->buf);
3425 if (t->globalOccurrences)
3426 printf(" (" ODR_INT_PRINTF ")\n", *t->globalOccurrences);
3431 static void process_Z3950_scanResponse(Z_ScanResponse *res)
3434 Z_Entry **entries = NULL;
3435 int num_entries = 0;
3437 printf("Received ScanResponse\n");
3438 print_refid(res->referenceId);
3439 printf(ODR_INT_PRINTF " entries", *res->numberOfEntriesReturned);
3440 if (res->positionOfTerm)
3441 printf(", position=" ODR_INT_PRINTF, *res->positionOfTerm);
3443 if (*res->scanStatus != Z_Scan_success)
3444 printf("Scan returned code " ODR_INT_PRINTF "\n", *res->scanStatus);
3447 if ((entries = res->entries->entries))
3448 num_entries = res->entries->num_entries;
3449 for (i = 0; i < num_entries; i++)
3451 int pos_term = res->positionOfTerm ? *res->positionOfTerm : -1;
3452 if (entries[i]->which == Z_Entry_termInfo)
3454 printf("%c ", i + 1 == pos_term ? '*' : ' ');
3455 display_term_info(entries[i]->u.termInfo);
3458 display_diagrecs(&entries[i]->u.surrogateDiagnostic, 1);
3460 if (res->entries->nonsurrogateDiagnostics)
3461 display_diagrecs(res->entries->nonsurrogateDiagnostics,
3462 res->entries->num_nonsurrogateDiagnostics);
3465 static void process_Z3950_sortResponse(Z_SortResponse *res)
3467 printf("Received SortResponse: status=");
3468 switch (*res->sortStatus)
3470 case Z_SortResponse_success:
3471 printf("success"); break;
3472 case Z_SortResponse_partial_1:
3473 printf("partial"); break;
3474 case Z_SortResponse_failure:
3475 printf("failure"); break;
3477 printf("unknown (" ODR_INT_PRINTF ")", *res->sortStatus);
3480 print_refid (res->referenceId);
3481 if (res->diagnostics)
3482 display_diagrecs(res->diagnostics,
3483 res->num_diagnostics);
3486 static void process_Z3950_deleteResultSetResponse(
3487 Z_DeleteResultSetResponse *res)
3489 printf("Got deleteResultSetResponse status=" ODR_INT_PRINTF "\n",
3490 *res->deleteOperationStatus);
3491 if (res->deleteListStatuses)
3494 for (i = 0; i < res->deleteListStatuses->num; i++)
3496 printf("%s status=" ODR_INT_PRINTF "\n",
3497 res->deleteListStatuses->elements[i]->id,
3498 *res->deleteListStatuses->elements[i]->status);
3503 static int cmd_sort_generic(const char *arg, int newset)
3507 if (session_initResponse &&
3508 !ODR_MASK_GET(session_initResponse->options, Z_Options_sort))
3510 printf("Target doesn't support sort\n");
3515 if (send_sortrequest(arg, newset) < 0)
3522 static int cmd_sort(const char *arg)
3524 return cmd_sort_generic(arg, 0);
3527 static int cmd_sort_newset(const char *arg)
3529 return cmd_sort_generic(arg, 1);
3532 static int cmd_scanstep(const char *arg)
3534 scan_stepSize = atoi(arg);
3538 static int cmd_scanpos(const char *arg)
3540 if (!strcmp(arg, "none"))
3541 strcpy(scan_position, "none");
3545 int r = sscanf(arg, "%d", &dummy);
3546 if (r == 1 && strlen(arg) < sizeof(scan_position)-1)
3547 strcpy(scan_position, arg);
3549 printf("specify number of none for scanpos\n");
3554 static int cmd_scansize(const char *arg)
3556 int r = sscanf(arg, "%d", &scan_size);
3562 static int cmd_scan_common(const char *set, const char *arg)
3564 Odr_int pos, *pos_p = 0;
3565 const char *scan_term = 0;
3566 const char *scan_query = 0;
3572 scan_query = last_scan_query;
3573 scan_term = last_scan_line;
3577 strcpy(last_scan_query, arg);
3579 if (strcmp(scan_position, "none"))
3581 pos = odr_atoi(scan_position);
3586 if (protocol == PROTO_HTTP)
3590 session_connect(cur_host);
3593 if (send_SRW_scanRequest(scan_query, pos_p, scan_size) < 0)
3602 if (*cur_host && !conn && auto_reconnect)
3604 session_connect(cur_host);
3605 wait_and_handle_response(0);
3609 if (session_initResponse &&
3610 !ODR_MASK_GET(session_initResponse->options, Z_Options_scan))
3612 printf("Target doesn't support scan\n");
3615 if (send_Z3950_scanrequest(set, scan_query, pos_p,
3616 scan_size, scan_term) < 0)
3622 static int cmd_scan(const char *arg)
3624 return cmd_scan_common(0, arg);
3627 static int cmd_setscan(const char *arg)
3629 char setstring[100];
3631 if (sscanf(arg, "%99s%n", setstring, &nor) < 1)
3633 printf("missing set for setscan\n");
3636 return cmd_scan_common(setstring, arg + nor);
3639 static int cmd_schema(const char *arg)
3641 xfree(record_schema);
3644 record_schema = xstrdup(arg);
3648 static int cmd_format(const char *arg)
3650 const char *cp = arg;
3657 printf("Usage: format <recordsyntax>\n");
3660 while (sscanf(cp, "%40s%n", form_str, &nor) >= 1 && nor > 0
3661 && idx < RECORDSYNTAX_MAX)
3663 if (strcmp(form_str, "none") &&
3664 !yaz_string_to_oid_odr(yaz_oid_std(), CLASS_RECSYN, form_str, out))
3666 printf("Bad format: %s\n", form_str);
3671 for (i = 0; i < recordsyntax_size; i++)
3673 xfree(recordsyntax_list[i]);
3674 recordsyntax_list[i] = 0;
3678 while (sscanf(cp, "%40s%n", form_str, &nor) >= 1 && nor > 0
3679 && idx < RECORDSYNTAX_MAX)
3681 if (!strcmp(form_str, "none"))
3683 recordsyntax_list[idx] = xstrdup(form_str);
3687 recordsyntax_size = idx;
3691 static int cmd_elements(const char *arg)
3693 static Z_ElementSetNames esn;
3694 static char what[100];
3698 elementSetNames = 0;
3702 esn.which = Z_ElementSetNames_generic;
3703 esn.u.generic = what;
3704 elementSetNames = &esn;
3708 static int cmd_querytype(const char *arg)
3710 if (!strcmp(arg, "ccl"))
3711 queryType = QueryType_CCL;
3712 else if (!strcmp(arg, "prefix") || !strcmp(arg, "rpn"))
3713 queryType = QueryType_Prefix;
3714 else if (!strcmp(arg, "ccl2rpn") || !strcmp(arg, "cclrpn"))
3715 queryType = QueryType_CCL2RPN;
3716 else if (!strcmp(arg, "cql"))
3717 queryType = QueryType_CQL;
3718 else if (!strcmp(arg, "cql2rpn") || !strcmp(arg, "cqlrpn"))
3719 queryType = QueryType_CQL2RPN;
3722 printf("Querytype must be one of:\n");
3723 printf(" prefix - Prefix query\n");
3724 printf(" ccl - CCL query\n");
3725 printf(" ccl2rpn - CCL query converted to RPN\n");
3726 printf(" cql - CQL\n");
3727 printf(" cql2rpn - CQL query converted to RPN\n");
3733 static int cmd_refid(const char *arg)
3738 refid = xstrdup(arg);
3742 static int cmd_close(const char *arg)
3748 apdu = zget_APDU(out, Z_APDU_close);
3749 req = apdu->u.close;
3750 *req->closeReason = Z_Close_finished;
3752 printf("Sent close request.\n");
3757 int cmd_packagename(const char* arg)
3759 xfree(esPackageName);
3760 esPackageName = NULL;
3762 esPackageName = xstrdup(arg);
3766 static int cmd_proxy(const char* arg)
3771 yazProxy = xstrdup(arg);
3775 static int cmd_marccharset(const char *arg)
3780 if (sscanf(arg, "%29s", l1) < 1)
3782 printf("MARC character set is `%s'\n",
3783 marcCharset ? marcCharset: "none");
3788 if (strcmp(l1, "-") && strcmp(l1, "none"))
3789 marcCharset = xstrdup(l1);
3793 static int cmd_querycharset(const char *arg)
3798 if (sscanf(arg, "%29s", l1) < 1)
3800 printf("Query character set is `%s'\n",
3801 queryCharset ? queryCharset: "none");
3804 xfree(queryCharset);
3806 if (strcmp(l1, "-") && strcmp(l1, "none"))
3807 queryCharset = xstrdup(l1);
3811 static int cmd_displaycharset(const char *arg)
3816 if (sscanf(arg, "%29s", l1) < 1)
3818 printf("Display character set is `%s'\n",
3819 outputCharset ? outputCharset: "none");
3823 xfree(outputCharset);
3825 if (!strcmp(l1, "auto") && codeset)
3829 printf("Display character set: %s\n", codeset);
3830 outputCharset = xstrdup(codeset);
3833 printf("No codeset found on this system\n");
3835 else if (strcmp(l1, "-") && strcmp(l1, "none"))
3836 outputCharset = xstrdup(l1);
3841 static int cmd_negcharset(const char *arg)
3846 if (sscanf(arg, "%29s %d %d", l1, &negotiationCharsetRecords,
3847 &negotiationCharsetVersion) < 1)
3849 printf("Negotiation character set `%s'\n",
3850 negotiationCharset ? negotiationCharset: "none");
3851 if (negotiationCharset)
3853 printf("Records in charset %s\n", negotiationCharsetRecords ?
3855 printf("Charneg version %d\n", negotiationCharsetVersion);
3860 xfree(negotiationCharset);
3861 negotiationCharset = NULL;
3862 if (*l1 && strcmp(l1, "-") && strcmp(l1, "none"))
3864 negotiationCharset = xstrdup(l1);
3865 printf("Character set negotiation : %s\n", negotiationCharset);
3871 static int cmd_charset(const char* arg)
3873 char l1[30], l2[30], l3[30], l4[30];
3875 *l1 = *l2 = *l3 = *l4 = '\0';
3876 if (sscanf(arg, "%29s %29s %29s %29s", l1, l2, l3, l4) < 1)
3879 cmd_displaycharset("");
3880 cmd_marccharset("");
3881 cmd_querycharset("");
3887 cmd_displaycharset(l2);
3889 cmd_marccharset(l3);
3891 cmd_querycharset(l4);
3896 static int cmd_lang(const char* arg)
3900 printf("Current language is `%s'\n", yazLang ? yazLang : "none");
3906 yazLang = xstrdup(arg);
3910 static int cmd_source(const char* arg, int echo )
3912 /* first should open the file and read one line at a time.. */
3914 char line[102400], *cp;
3916 if (strlen(arg) < 1)
3918 fprintf(stderr, "Error in source command use a filename\n");
3922 includeFile = fopen(arg, "r");
3926 fprintf(stderr, "Unable to open file %s for reading\n",arg);
3930 while (fgets(line, sizeof(line), includeFile))
3932 if (strlen(line) < 2)
3937 if ((cp = strrchr(line, '\n')))
3941 printf("processing line: %s\n", line);
3942 process_cmd_line(line);
3945 if (fclose(includeFile))
3947 perror("unable to close include file");
3953 static int cmd_source_echo(const char* arg)
3959 static int cmd_subshell(const char* args)
3961 int ret = system(strlen(args) ? args : getenv("SHELL"));
3965 printf("Exit %d\n", ret);
3970 static int cmd_set_berfile(const char *arg)
3972 if (ber_file && ber_file != stdout && ber_file != stderr)
3974 if (!strcmp(arg, ""))
3976 else if (!strcmp(arg, "-"))
3979 ber_file = fopen(arg, "a");
3983 static int cmd_set_apdufile(const char *arg)
3985 if (apdu_file && apdu_file != stderr && apdu_file != stderr)
3987 if (!strcmp(arg, ""))
3989 else if (!strcmp(arg, "-"))
3993 apdu_file = fopen(arg, "a");
3995 perror("unable to open apdu log file");
3998 odr_setprint(print, apdu_file);
4002 static int cmd_set_cclfile(const char* arg)
4006 bibset = ccl_qual_mk();
4007 inf = fopen(arg, "r");
4009 perror("unable to open CCL file");
4012 ccl_qual_file(bibset, inf);
4015 strcpy(ccl_fields,arg);
4019 static int cmd_set_cqlfile(const char* arg)
4021 cql_transform_t newcqltrans;
4023 if ((newcqltrans = cql_transform_open_fname(arg)) == 0)
4025 perror("unable to open CQL file");
4029 cql_transform_close(cqltrans);
4031 cqltrans = newcqltrans;
4032 strcpy(cql_fields, arg);
4036 static int cmd_set_auto_reconnect(const char* arg)
4039 auto_reconnect = ! auto_reconnect;
4040 else if (strcmp(arg,"on")==0)
4042 else if (strcmp(arg,"off")==0)
4046 printf("Error use on or off\n");
4051 printf("Set auto reconnect enabled.\n");
4053 printf("Set auto reconnect disabled.\n");
4058 static int cmd_set_auto_wait(const char* arg)
4061 auto_wait = ! auto_wait;
4062 else if (strcmp(arg,"on")==0)
4064 else if (strcmp(arg,"off")==0)
4068 printf("Error use on or off\n");
4073 printf("Set auto wait enabled.\n");
4075 printf("Set auto wait disabled.\n");
4080 static int cmd_set_marcdump(const char* arg)
4082 if (marc_file && marc_file != stderr)
4083 { /* don't close stdout*/
4087 if (!strcmp(arg, ""))
4089 else if (!strcmp(arg, "-"))
4093 marc_file = fopen(arg, "a");
4095 perror("unable to open marc log file");
4100 static void marc_file_write(const char *buf, size_t sz)
4104 if (fwrite(buf, 1, sz, marc_file) != sz)
4106 perror("marcfile write");
4111 this command takes 3 arge {name class oid}
4113 static int cmd_register_oid(const char* args)
4119 {"appctx",CLASS_APPCTX},
4120 {"absyn",CLASS_ABSYN},
4121 {"attset",CLASS_ATTSET},
4122 {"transyn",CLASS_TRANSYN},
4123 {"diagset",CLASS_DIAGSET},
4124 {"recsyn",CLASS_RECSYN},
4125 {"resform",CLASS_RESFORM},
4126 {"accform",CLASS_ACCFORM},
4127 {"extserv",CLASS_EXTSERV},
4128 {"userinfo",CLASS_USERINFO},
4129 {"elemspec",CLASS_ELEMSPEC},
4130 {"varset",CLASS_VARSET},
4131 {"schema",CLASS_SCHEMA},
4132 {"tagset",CLASS_TAGSET},
4133 {"general",CLASS_GENERAL},
4134 {0,(enum oid_class) 0}
4136 char oname_str[101], oclass_str[101], oid_str[101];
4138 oid_class oidclass = CLASS_GENERAL;
4139 Odr_oid oid[OID_SIZE];
4141 if (sscanf(args, "%100[^ ] %100[^ ] %100s",
4142 oname_str,oclass_str, oid_str) < 1)
4144 printf("Error in register command \n");
4148 for (i = 0; oid_classes[i].className; i++)
4150 if (!strcmp(oid_classes[i].className, oclass_str))
4152 oidclass=oid_classes[i].oclass;
4157 if (!(oid_classes[i].className))
4159 printf("Unknown oid class %s\n",oclass_str);
4163 oid_dotstring_to_oid(oid_str, oid);
4165 if (yaz_oid_add(yaz_oid_std(), oidclass, oname_str, oid))
4167 printf("oid %s already exists, registration failed\n",
4173 static int cmd_push_command(const char* arg)
4175 #if HAVE_READLINE_HISTORY_H
4176 if (strlen(arg) > 1)
4179 fprintf(stderr,"Not compiled with the readline/history module\n");
4184 void source_rc_file(const char *rc_file)
4186 /* If rc_file != NULL, source that. Else
4187 Look for .yazclientrc and read it if it exists.
4188 If it does not exist, read $HOME/.yazclientrc instead */
4189 struct stat statbuf;
4193 if (stat(rc_file, &statbuf) == 0)
4194 cmd_source(rc_file, 0);
4197 fprintf(stderr, "yaz_client: cannot source '%s'\n", rc_file);
4204 strcpy(fname, ".yazclientrc");
4205 if (stat(fname, &statbuf)==0)
4207 cmd_source(fname, 0);
4211 const char* homedir = getenv("HOME");
4214 sprintf(fname, "%.800s/%s", homedir, ".yazclientrc");
4215 if (stat(fname, &statbuf)==0)
4216 cmd_source(fname, 0);
4222 static void add_to_readline_history(void *client_data, const char *line)
4224 #if HAVE_READLINE_HISTORY_H
4230 static void initialize(const char *rc_file)
4235 if (!(out = odr_createmem(ODR_ENCODE)) ||
4236 !(in = odr_createmem(ODR_DECODE)) ||
4237 !(print = odr_createmem(ODR_PRINT)))
4239 fprintf(stderr, "failed to allocate ODR streams\n");
4243 strcpy(scan_position, "1");
4245 setvbuf(stdout, 0, _IONBF, 0);
4247 odr_setprint(print, apdu_file);
4249 bibset = ccl_qual_mk();
4250 inf = fopen(ccl_fields, "r");
4253 ccl_qual_file(bibset, inf);
4257 cqltrans = cql_transform_open_fname(cql_fields);
4258 /* If this fails, no problem: we detect cqltrans == 0 later */
4260 #if HAVE_READLINE_READLINE_H
4261 rl_attempted_completion_function =
4262 (char **(*)(const char *, int, int)) readline_completer;
4264 for (i = 0; i < maxOtherInfosSupported; ++i)
4266 extraOtherInfos[i].oid[0] = -1;
4267 extraOtherInfos[i].value = 0;
4270 cmd_format("usmarc");
4272 file_history = file_history_new();
4274 source_rc_file(rc_file);
4276 file_history_load(file_history);
4277 file_history_trav(file_history, 0, add_to_readline_history);
4281 #if HAVE_GETTIMEOFDAY
4282 struct timeval tv_start;
4286 static void handle_srw_record(Z_SRW_record *rec)
4288 if (rec->recordPosition)
4290 printf("pos=" ODR_INT_PRINTF, *rec->recordPosition);
4291 setno = *rec->recordPosition + 1;
4293 if (rec->recordSchema)
4294 printf(" schema=%s", rec->recordSchema);
4296 if (rec->recordData_buf && rec->recordData_len)
4298 print_xml_record(rec->recordData_buf, rec->recordData_len);
4299 marc_file_write(rec->recordData_buf, rec->recordData_len);
4306 static void handle_srw_explain_response(Z_SRW_explainResponse *res)
4308 handle_srw_record(&res->record);
4311 static void handle_srw_response(Z_SRW_searchRetrieveResponse *res)
4315 printf("Received SRW SearchRetrieve Response\n");
4317 for (i = 0; i<res->num_diagnostics; i++)
4319 if (res->diagnostics[i].uri)
4320 printf("SRW diagnostic %s\n",
4321 res->diagnostics[i].uri);
4323 printf("SRW diagnostic missing or could not be decoded\n");
4324 if (res->diagnostics[i].message)
4325 printf("Message: %s\n", res->diagnostics[i].message);
4326 if (res->diagnostics[i].details)
4327 printf("Details: %s\n", res->diagnostics[i].details);
4329 if (res->numberOfRecords)
4330 printf("Number of hits: " ODR_INT_PRINTF "\n", *res->numberOfRecords);
4332 display_facets(res->facetList);
4333 if (res->suggestions)
4334 printf("Suggestions:\n%s\n", res->suggestions);
4335 for (i = 0; i < res->num_records; i++)
4337 if (i >= sru_maximumRecords)
4339 printf("SRU server returns extra records. Skipping "
4340 ODR_INT_PRINTF " records.\n",
4341 res->num_records - sru_maximumRecords);
4344 handle_srw_record(res->records + i);
4348 static void handle_srw_scan_term(Z_SRW_scanTerm *term)
4350 if (term->displayTerm)
4351 printf("%s:", term->displayTerm);
4352 else if (term->value)
4353 printf("%s:", term->value);
4355 printf("No value:");
4356 if (term->numberOfRecords)
4357 printf(" " ODR_INT_PRINTF, *term->numberOfRecords);
4358 if (term->whereInList)
4359 printf(" %s", term->whereInList);
4360 if (term->value && term->displayTerm)
4361 printf(" %s", term->value);
4363 strcpy(last_scan_line, term->value);
4367 static void handle_srw_scan_response(Z_SRW_scanResponse *res)
4371 printf("Received SRW Scan Response\n");
4373 for (i = 0; i<res->num_diagnostics; i++)
4375 if (res->diagnostics[i].uri)
4376 printf("SRW diagnostic %s\n",
4377 res->diagnostics[i].uri);
4379 printf("SRW diagnostic missing or could not be decoded\n");
4380 if (res->diagnostics[i].message)
4381 printf("Message: %s\n", res->diagnostics[i].message);
4382 if (res->diagnostics[i].details)
4383 printf("Details: %s\n", res->diagnostics[i].details);
4386 for (i = 0; i<res->num_terms; i++)
4387 handle_srw_scan_term(res->terms + i);
4390 static void http_response(Z_HTTP_Response *hres)
4393 const char *connection_head = z_HTTP_header_lookup(hres->headers,
4395 if (hres->code != 200)
4397 printf("HTTP Error Status=%d\n", hres->code);
4400 if (!yaz_srw_check_content_type(hres))
4401 printf("Content type does not appear to be XML\n");
4404 if (!yaz_matchstr(sru_method, "solr"))
4407 ODR o = odr_createmem(ODR_DECODE);
4408 ret = yaz_solr_decode_response(o, hres, &sr);
4410 if (ret == 0 && sr->which == Z_SRW_searchRetrieve_response)
4411 handle_srw_response(sr->u.response);
4412 else if (ret == 0 && sr->which == Z_SRW_scan_response)
4413 handle_srw_scan_response(sr->u.scan_response);
4416 printf("Decoding of Solr package failed\n");
4423 Z_SOAP *soap_package = 0;
4424 ODR o = odr_createmem(ODR_DECODE);
4425 Z_SOAP_Handler soap_handlers[] = {
4426 {YAZ_XMLNS_SRU_v2_mask, 0, (Z_SOAP_fun) yaz_srw_codec},
4427 {YAZ_XMLNS_UPDATE_v0_9, 0, (Z_SOAP_fun) yaz_ucp_codec},
4428 {YAZ_XMLNS_SRU_v1_response, 0, (Z_SOAP_fun) yaz_srw_codec},
4431 ret = z_soap_codec(o, &soap_package,
4432 &hres->content_buf, &hres->content_len,
4434 if (!ret && soap_package->which == Z_SOAP_generic)
4436 Z_SRW_PDU *sr = (Z_SRW_PDU *) soap_package->u.generic->p;
4437 if (sr->which == Z_SRW_searchRetrieve_response)
4438 handle_srw_response(sr->u.response);
4439 else if (sr->which == Z_SRW_explain_response)
4440 handle_srw_explain_response(sr->u.explain_response);
4441 else if (sr->which == Z_SRW_scan_response)
4442 handle_srw_scan_response(sr->u.scan_response);
4443 else if (sr->which == Z_SRW_update_response)
4444 printf("Got update response. Status: %s\n",
4445 sr->u.update_response->operationStatus);
4448 printf("Decoding of SRW package failed\n");
4452 else if (soap_package && (soap_package->which == Z_SOAP_fault
4453 || soap_package->which == Z_SOAP_error))
4455 printf("SOAP Fault code %s\n",
4456 soap_package->u.fault->fault_code);
4457 printf("SOAP Fault string %s\n",
4458 soap_package->u.fault->fault_string);
4459 if (soap_package->u.fault->details)
4460 printf("SOAP Details %s\n",
4461 soap_package->u.fault->details);
4465 printf("z_soap_codec failed. (no SOAP error)\n");
4472 close_session(); /* close session on error */
4475 if (!strcmp(hres->version, "1.0"))
4477 /* HTTP 1.0: only if Keep-Alive we stay alive.. */
4478 if (!connection_head || strcmp(connection_head, "Keep-Alive"))
4483 /* HTTP 1.1: only if no close we stay alive .. */
4484 if (connection_head && !strcmp(connection_head, "close"))
4491 #define max_HTTP_redirects 2
4493 static void wait_and_handle_response(int one_response_only)
4495 int reconnect_ok = 1;
4496 int no_redirects = 0;
4499 int netbufferlen = 0;
4500 #if HAVE_GETTIMEOFDAY
4502 struct timeval tv_end;
4508 res = cs_get(conn, &netbuffer, &netbufferlen);
4509 if (reconnect_ok && res <= 0 && protocol == PROTO_HTTP)
4513 session_connect(cur_host);
4520 buf_out = odr_getbuf(out, &len_out, 0);
4522 do_hex_dump(buf_out, len_out);
4524 cs_put(conn, buf_out, len_out);
4532 printf("Target closed connection\n");
4536 #if HAVE_GETTIMEOFDAY
4537 if (got_tv_end == 0)
4538 gettimeofday(&tv_end, 0); /* count first one only */
4542 odr_reset(in); /* release APDU from last round */
4544 do_hex_dump(netbuffer, res);
4545 odr_setbuf(in, netbuffer, res, 0);
4547 if (!z_GDU(in, &gdu, 0, 0))
4549 FILE *f = ber_file ? ber_file : stdout;
4550 odr_perror(in, "Decoding incoming APDU");
4551 fprintf(f, "[Near %ld]\n", (long) odr_offset(in));
4552 fprintf(f, "Packet dump:\n---------\n");
4553 odr_dumpBER(f, netbuffer, res);
4554 fprintf(f, "---------\n");
4557 z_GDU(print, &gdu, 0, 0);
4560 if (conn && cs_more(conn))
4565 odr_dumpBER(ber_file, netbuffer, res);
4566 if (apdu_file && !z_GDU(print, &gdu, 0, 0))
4568 odr_perror(print, "Failed to print incoming APDU");
4572 if (gdu->which == Z_GDU_Z3950)
4574 Z_APDU *apdu = gdu->u.z3950;
4575 switch (apdu->which)
4577 case Z_APDU_initResponse:
4578 process_Z3950_initResponse(apdu->u.initResponse);
4580 case Z_APDU_searchResponse:
4581 process_Z3950_searchResponse(apdu->u.searchResponse);
4583 case Z_APDU_scanResponse:
4584 process_Z3950_scanResponse(apdu->u.scanResponse);
4586 case Z_APDU_presentResponse:
4587 print_refid(apdu->u.presentResponse->referenceId);
4589 *apdu->u.presentResponse->numberOfRecordsReturned;
4590 if (apdu->u.presentResponse->records)
4591 display_records(apdu->u.presentResponse->records);
4593 printf("No records.\n");
4594 printf("nextResultSetPosition = " ODR_INT_PRINTF "\n",
4595 *apdu->u.presentResponse->nextResultSetPosition);
4597 case Z_APDU_sortResponse:
4598 process_Z3950_sortResponse(apdu->u.sortResponse);
4600 case Z_APDU_extendedServicesResponse:
4601 printf("Got extended services response\n");
4602 process_Z3950_ESResponse(apdu->u.extendedServicesResponse);
4605 printf("Target has closed the association.\n");
4606 process_Z3950_close(apdu->u.close);
4608 case Z_APDU_resourceControlRequest:
4609 process_Z3950_resourceControlRequest(
4610 apdu->u.resourceControlRequest);
4612 case Z_APDU_deleteResultSetResponse:
4613 process_Z3950_deleteResultSetResponse(
4614 apdu->u.deleteResultSetResponse);
4617 printf("Received unknown APDU type (%d).\n",
4623 else if (gdu->which == Z_GDU_HTTP_Response)
4625 Z_HTTP_Response *hres = gdu->u.HTTP_Response;
4626 int code = hres->code;
4627 const char *location = 0;
4628 if ((code == 301 || code == 302)
4629 && no_redirects < max_HTTP_redirects
4630 && !yaz_matchstr(sru_method, "get")
4631 && (location = z_HTTP_header_lookup(hres->headers, "Location")))
4633 const char *base_tmp;
4634 session_connect_base(location, &base_tmp);
4638 if (send_SRW_redirect(location, hres) == 2)
4641 printf("Redirect failed\n");
4644 http_response(gdu->u.HTTP_Response);
4647 if (one_response_only)
4649 if (conn && !cs_more(conn))
4652 #if HAVE_GETTIMEOFDAY
4656 printf("S/U S/U=%ld/%ld %ld/%ld",
4657 (long) tv_start.tv_sec,
4658 (long) tv_start.tv_usec,
4659 (long) tv_end.tv_sec,
4660 (long) tv_end.tv_usec);
4662 printf("Elapsed: %.6f\n",
4663 (double) tv_end.tv_usec / 1e6 + tv_end.tv_sec -
4664 ((double) tv_start.tv_usec / 1e6 + tv_start.tv_sec));
4670 static int cmd_cclparse(const char* arg)
4673 struct ccl_rpn_node *rpn=NULL;
4676 rpn = ccl_find_str(bibset, arg, &error, &pos);
4680 int ioff = 3+strlen(last_cmd)+1+pos;
4681 printf("%*s^ - ", ioff, " ");
4682 printf("%s\n", ccl_err_msg(error));
4688 ccl_pr_tree(rpn, stdout);
4692 ccl_rpn_delete(rpn);
4699 static int cmd_set_otherinfo(const char* args)
4701 char oidstr[101], otherinfoString[101];
4705 sscan_res = sscanf(args, "%d %100[^ ] %100s",
4706 &otherinfoNo, oidstr, otherinfoString);
4708 if (sscan_res > 0 && otherinfoNo >= maxOtherInfosSupported)
4710 printf("Error otherinfo index too large (%d>=%d)\n",
4711 otherinfoNo,maxOtherInfosSupported);
4718 /* reset this otherinfo */
4719 extraOtherInfos[otherinfoNo].oid[0] = -1;
4720 xfree(extraOtherInfos[otherinfoNo].value);
4721 extraOtherInfos[otherinfoNo].value = 0;
4726 printf("Error in set_otherinfo command \n");
4731 NMEM oid_tmp = nmem_create();
4732 const Odr_oid *oid =
4733 yaz_string_to_oid_nmem(yaz_oid_std(),
4734 CLASS_GENERAL, oidstr, oid_tmp);
4735 oid_oidcpy(extraOtherInfos[otherinfoNo].oid, oid);
4737 xfree(extraOtherInfos[otherinfoNo].value);
4738 extraOtherInfos[otherinfoNo].value = xstrdup(otherinfoString);
4740 nmem_destroy(oid_tmp);
4746 static int cmd_sleep(const char* args )
4748 int sec = atoi(args);
4756 printf("Done sleeping %d seconds\n", sec);
4761 static int cmd_list_otherinfo(const char* args)
4768 if (i >= maxOtherInfosSupported)
4770 printf("Error otherinfo index to large (%d>%d)\n",i,maxOtherInfosSupported);
4773 if (extraOtherInfos[i].value)
4775 char name_oid[OID_STR_MAX];
4778 yaz_oid_to_string_buf(extraOtherInfos[i].oid, &oclass,
4780 printf(" otherinfo %d %s %s\n",
4781 i, name ? name : "null",
4782 extraOtherInfos[i].value);
4788 for (i = 0; i < maxOtherInfosSupported; ++i)
4790 if (extraOtherInfos[i].value)
4792 char name_oid[OID_STR_MAX];
4795 yaz_oid_to_string_buf(extraOtherInfos[i].oid, &oclass,
4797 printf(" otherinfo %d %s %s\n",
4798 i, name ? name : "null",
4799 extraOtherInfos[i].value);
4806 static int cmd_list_all(const char* args)
4810 /* connection options */
4812 printf("Connected to : %s\n", cur_host);
4814 printf("Not connected to : %s\n", cur_host);
4816 printf("Not connected : \n");
4817 if (yazProxy) printf("using proxy : %s\n",yazProxy);
4819 printf("auto_reconnect : %s\n",auto_reconnect?"on":"off");
4820 printf("auto_wait : %s\n",auto_wait?"on":"off");
4823 printf("Authentication : none\n");
4826 switch (auth->which)
4828 case Z_IdAuthentication_idPass:
4829 printf("Authentication : IdPass\n");
4830 printf(" Login User : %s\n",auth->u.idPass->userId?auth->u.idPass->userId:"");
4831 printf(" Login Group : %s\n",auth->u.idPass->groupId?auth->u.idPass->groupId:"");
4832 printf(" Password : %s\n",auth->u.idPass->password?auth->u.idPass->password:"");
4834 case Z_IdAuthentication_open:
4835 printf("Authentication : psOpen\n");
4836 printf(" Open string : %s\n",auth->u.open);
4839 printf("Authentication : Unknown\n");
4842 if (negotiationCharset)
4843 printf("Neg. Character set : `%s'\n", negotiationCharset);
4847 for (i = 0; i<num_databaseNames; i++) printf("%s ",databaseNames[i]);
4851 printf("CCL file : %s\n",ccl_fields);
4852 printf("CQL file : %s\n",cql_fields);
4853 printf("Query type : %s\n",query_type_as_string(queryType));
4855 printf("Named Result Sets : %s\n",setnumber==-1?"off":"on");
4857 /* piggy back options */
4858 printf("ssub/lslb/mspn : %d/%d/%d\n",smallSetUpperBound,largeSetLowerBound,mediumSetPresentNumber);
4860 /* print present related options */
4861 if (recordsyntax_size > 0)
4863 printf("Format : %s\n", recordsyntax_list[0]);
4865 printf("Schema : %s\n",record_schema ? record_schema : "not set");
4866 printf("Elements : %s\n",elementSetNames?elementSetNames->u.generic:"");
4868 /* loging options */
4869 printf("APDU log : %s\n",apdu_file?"on":"off");
4870 printf("Record log : %s\n",marc_file?"on":"off");
4873 printf("Other Info: \n");
4874 cmd_list_otherinfo("");
4879 static int cmd_clear_otherinfo(const char* args)
4881 if (strlen(args) > 0)
4883 int otherinfoNo = atoi(args);
4884 if (otherinfoNo >= maxOtherInfosSupported)
4886 printf("Error otherinfo index too large (%d>=%d)\n",
4887 otherinfoNo, maxOtherInfosSupported);
4890 if (extraOtherInfos[otherinfoNo].value)
4892 /* only clear if set. */
4893 extraOtherInfos[otherinfoNo].oid[0] = -1;
4894 xfree(extraOtherInfos[otherinfoNo].value);
4895 extraOtherInfos[otherinfoNo].value = 0;
4901 for (i = 0; i < maxOtherInfosSupported; ++i)
4903 if (extraOtherInfos[i].value)
4905 extraOtherInfos[i].oid[0] = -1;
4906 xfree(extraOtherInfos[i].value);
4907 extraOtherInfos[i].value = 0;
4914 static int cmd_wait_response(const char *arg)
4917 int wait_for = atoi(arg);
4921 for (i = 0 ; i < wait_for; ++i )
4922 wait_and_handle_response(1);
4926 static int cmd_help(const char *line);
4928 typedef char *(*completerFunctionType)(const char *text, int state);
4932 int (*fun)(const char *arg);
4934 completerFunctionType rl_completerfunction;
4935 int complete_filenames;
4936 const char **local_tabcompletes;
4938 {"open", cmd_open, "('tcp'|'ssl')':<host>[':'<port>][/<db>]",NULL,0,NULL},
4939 {"quit", cmd_quit, "",NULL,0,NULL},
4940 {"find", cmd_find, "<query>",NULL,0,NULL},
4941 {"facets", cmd_facets, "<query>",NULL,0,NULL},
4942 {"delete", cmd_delete, "<setname>",NULL,0,NULL},
4943 {"base", cmd_base, "<base-name>",NULL,0,NULL},
4944 {"show", cmd_show, "<rec#>['+'<#recs>['+'<setname>]]",NULL,0,NULL},
4945 {"setscan", cmd_setscan, "<term>",NULL,0,NULL},
4946 {"scan", cmd_scan, "<term>",NULL,0,NULL},
4947 {"scanstep", cmd_scanstep, "<size>",NULL,0,NULL},
4948 {"scanpos", cmd_scanpos, "<size>",NULL,0,NULL},
4949 {"scansize", cmd_scansize, "<size>",NULL,0,NULL},
4950 {"sort", cmd_sort, "<sortkey> <flag> <sortkey> <flag> ...",NULL,0,NULL},
4951 {"sort+", cmd_sort_newset, "<sortkey> <flag> <sortkey> <flag> ...",NULL,0,NULL},
4952 {"authentication", cmd_authentication, "<acctstring>",NULL,0,NULL},
4953 {"lslb", cmd_lslb, "<largeSetLowerBound>",NULL,0,NULL},
4954 {"ssub", cmd_ssub, "<smallSetUpperBound>",NULL,0,NULL},
4955 {"mspn", cmd_mspn, "<mediumSetPresentNumber>",NULL,0,NULL},
4956 {"status", cmd_status, "",NULL,0,NULL},
4957 {"setnames", cmd_setnames, "",NULL,0,NULL},
4958 {"cancel", cmd_cancel, "",NULL,0,NULL},
4959 {"cancel_find", cmd_cancel_find, "<query>",NULL,0,NULL},
4960 {"format", cmd_format, "<recordsyntax>",complete_format,0,NULL},
4961 {"schema", cmd_schema, "<schema>",complete_schema,0,NULL},
4962 {"elements", cmd_elements, "<elementSetName>",NULL,0,NULL},
4963 {"close", cmd_close, "",NULL,0,NULL},
4964 {"querytype", cmd_querytype, "<type>",complete_querytype,0,NULL},
4965 {"refid", cmd_refid, "<id>",NULL,0,NULL},
4966 {"itemorder", cmd_itemorder, "ill|item|xml <itemno>",NULL,0,NULL},
4967 {"update", cmd_update, "<action> <recid> [<doc>]",NULL,0,NULL},
4968 {"update0", cmd_update0, "<action> <recid> [<doc>]",NULL,0,NULL},
4969 {"xmles", cmd_xmles, "<OID> <doc>",NULL,0,NULL},
4970 {"packagename", cmd_packagename, "<packagename>",NULL,0,NULL},
4971 {"proxy", cmd_proxy, "[('tcp'|'ssl')]<host>[':'<port>]",NULL,0,NULL},
4972 {"charset", cmd_charset, "<nego_charset> <output_charset>",NULL,0,NULL},
4973 {"negcharset", cmd_negcharset, "<nego_charset>",NULL,0,NULL},
4974 {"displaycharset", cmd_displaycharset, "<output_charset>",NULL,0,NULL},
4975 {"marccharset", cmd_marccharset, "<charset_name>",NULL,0,NULL},
4976 {"querycharset", cmd_querycharset, "<charset_name>",NULL,0,NULL},
4977 {"lang", cmd_lang, "<language_code>",NULL,0,NULL},
4978 {"source", cmd_source_echo, "<filename>",NULL,1,NULL},
4979 {".", cmd_source_echo, "<filename>",NULL,1,NULL},
4980 {"!", cmd_subshell, "Subshell command",NULL,1,NULL},
4981 {"set_apdufile", cmd_set_apdufile, "<filename>",NULL,1,NULL},
4982 {"set_berfile", cmd_set_berfile, "<filename>",NULL,1,NULL},
4983 {"set_marcdump", cmd_set_marcdump," <filename>",NULL,1,NULL},
4984 {"set_cclfile", cmd_set_cclfile," <filename>",NULL,1,NULL},
4985 {"set_cqlfile", cmd_set_cqlfile," <filename>",NULL,1,NULL},
4986 {"set_auto_reconnect", cmd_set_auto_reconnect," on|off",complete_auto_reconnect,1,NULL},
4987 {"set_auto_wait", cmd_set_auto_wait," on|off",complete_auto_reconnect,1,NULL},
4988 {"set_otherinfo", cmd_set_otherinfo,"<otherinfoinddex> <oid> <string>",NULL,0,NULL},
4989 {"sleep", cmd_sleep,"<seconds>",NULL,0,NULL},
4990 {"register_oid", cmd_register_oid,"<name> <class> <oid>",NULL,0,NULL},
4991 {"push_command", cmd_push_command,"<command>",command_generator,0,NULL},
4992 {"register_tab", cmd_register_tab,"<commandname> <tab>",command_generator,0,NULL},
4993 {"cclparse", cmd_cclparse,"<ccl find command>",NULL,0,NULL},
4994 {"list_otherinfo",cmd_list_otherinfo,"[otherinfoinddex]",NULL,0,NULL},
4995 {"list_all",cmd_list_all,"",NULL,0,NULL},
4996 {"clear_otherinfo",cmd_clear_otherinfo,"",NULL,0,NULL},
4997 {"wait_response",cmd_wait_response,"<number>",NULL,0,NULL},
4998 /* Server Admin Functions */
4999 {"adm-reindex", cmd_adm_reindex, "<database-name>",NULL,0,NULL},
5000 {"adm-truncate", cmd_adm_truncate, "('database'|'index')<object-name>",NULL,0,NULL},
5001 {"adm-create", cmd_adm_create, "",NULL,0,NULL},
5002 {"adm-drop", cmd_adm_drop, "('database'|'index')<object-name>",NULL,0,NULL},
5003 {"adm-import", cmd_adm_import, "<record-type> <dir> <pattern>",NULL,0,NULL},
5004 {"adm-refresh", cmd_adm_refresh, "",NULL,0,NULL},
5005 {"adm-commit", cmd_adm_commit, "",NULL,0,NULL},
5006 {"adm-shutdown", cmd_adm_shutdown, "",NULL,0,NULL},
5007 {"adm-startup", cmd_adm_startup, "",NULL,0,NULL},
5008 {"explain", cmd_explain, "", NULL, 0, NULL},
5009 {"options", cmd_options, "", NULL, 0, NULL},
5010 {"zversion", cmd_zversion, "", NULL, 0, NULL},
5011 {"help", cmd_help, "", NULL,0,NULL},
5012 {"init", cmd_init, "", NULL,0,NULL},
5013 {"sru", cmd_sru, "<method> <version>", NULL,0,NULL},
5014 {"url", cmd_url, "<url>", NULL,0,NULL},
5015 {"exit", cmd_quit, "",NULL,0,NULL},
5019 static int cmd_help(const char *line)
5025 sscanf(line, "%20s", topic);
5028 printf("Commands:\n");
5029 for (i = 0; cmd_array[i].cmd; i++)
5030 if (*topic == 0 || strcmp(topic, cmd_array[i].cmd) == 0)
5031 printf(" %s %s\n", cmd_array[i].cmd, cmd_array[i].ad);
5032 if (!strcmp(topic, "find"))
5035 printf(" \"term\" Simple Term\n");
5036 printf(" @attr [attset] type=value op Attribute\n");
5037 printf(" @and opl opr And\n");
5038 printf(" @or opl opr Or\n");
5039 printf(" @not opl opr And-Not\n");
5040 printf(" @set set Result set\n");
5041 printf(" @prox exl dist ord rel uc ut Proximity. Use help prox\n");
5043 printf("Bib-1 attribute types\n");
5045 printf("4=Title 7=ISBN 8=ISSN 30=Date 62=Abstract 1003=Author 1016=Any\n");
5046 printf("2=Relation: ");
5047 printf("1< 2<= 3= 4>= 5> 6!= 102=Relevance\n");
5048 printf("3=Position: ");
5049 printf("1=First in Field 2=First in subfield 3=Any position\n");
5050 printf("4=Structure: ");
5051 printf("1=Phrase 2=Word 3=Key 4=Year 5=Date 6=WordList\n");
5052 printf("5=Truncation: ");
5053 printf("1=Right 2=Left 3=L&R 100=No 101=# 102=Re-1 103=Re-2\n");
5054 printf("6=Completeness:");
5055 printf("1=Incomplete subfield 2=Complete subfield 3=Complete field\n");
5057 if (!strcmp(topic, "prox"))
5059 printf("Proximity:\n");
5060 printf(" @prox exl dist ord rel uc ut\n");
5061 printf(" exl: exclude flag . 0=include, 1=exclude.\n");
5062 printf(" dist: distance integer.\n");
5063 printf(" ord: order flag. 0=unordered, 1=ordered.\n");
5064 printf(" rel: relation integer. 1< 2<= 3= 4>= 5> 6!= .\n");
5065 printf(" uc: unit class. k=known, p=private.\n");
5066 printf(" ut: unit type. 1=character, 2=word, 3=sentence,\n");
5067 printf(" 4=paragraph, 5=section, 6=chapter, 7=document,\n");
5068 printf(" 8=element, 9=subelement, 10=elementType, 11=byte.\n");
5069 printf("\nExamples:\n");
5070 printf(" Search for a and b in-order at most 3 words apart:\n");
5071 printf(" @prox 0 3 1 2 k 2 a b\n");
5072 printf(" Search for any order of a and b next to each other:\n");
5073 printf(" @prox 0 1 0 3 k 2 a b\n");
5078 static int cmd_register_tab(const char* arg)
5080 #if HAVE_READLINE_READLINE_H
5081 char command[101], tabargument[101];
5084 const char** tabslist;
5086 if (sscanf(arg, "%100s %100s", command, tabargument) < 1)
5091 /* locate the amdn in the list */
5092 for (i = 0; cmd_array[i].cmd; i++)
5094 if (!strncmp(cmd_array[i].cmd, command, strlen(command)))
5098 if (!cmd_array[i].cmd)
5100 fprintf(stderr,"Unknown command %s\n",command);
5105 if (!cmd_array[i].local_tabcompletes)
5106 cmd_array[i].local_tabcompletes = (const char **) calloc(1,sizeof(char**));
5110 tabslist = cmd_array[i].local_tabcompletes;
5111 for (; tabslist && *tabslist; tabslist++)
5114 cmd_array[i].local_tabcompletes = (const char **)
5115 realloc(cmd_array[i].local_tabcompletes,
5116 (num_of_tabs+2)*sizeof(char**));
5117 tabslist = cmd_array[i].local_tabcompletes;
5118 tabslist[num_of_tabs] = strdup(tabargument);
5119 tabslist[num_of_tabs+1] = NULL;
5124 static void process_cmd_line(char* line)
5127 char word[32], arg[10240];
5129 #if HAVE_GETTIMEOFDAY
5130 gettimeofday(&tv_start, 0);
5133 if ((res = sscanf(line, "%31s %10239[^;]", word, arg)) <= 0)
5135 strcpy(word, last_cmd);
5140 strcpy(last_cmd, word);
5142 /* removed tailing spaces from the arg command */
5145 char* lastnonspace=NULL;
5149 if (!yaz_isspace(*p))
5153 *(++lastnonspace) = 0;
5156 for (i = 0; cmd_array[i].cmd; i++)
5157 if (!strncmp(cmd_array[i].cmd, word, strlen(word)))
5159 res = (*cmd_array[i].fun)(arg);
5163 if (!cmd_array[i].cmd) /* dump our help-screen */
5165 printf("Unknown command: %s.\n", word);
5166 printf("Type 'help' for list of commands\n");
5173 if (res >= 2 && auto_wait)
5174 wait_and_handle_response(0);
5182 static char *command_generator(const char *text, int state)
5184 #if HAVE_READLINE_READLINE_H
5188 for (; cmd_array[idx].cmd; ++idx)
5190 if (!strncmp(cmd_array[idx].cmd, text, strlen(text)))
5192 ++idx; /* skip this entry on the next run */
5193 return strdup(cmd_array[idx-1].cmd);
5200 #if HAVE_READLINE_READLINE_H
5201 static const char** default_completer_list = NULL;
5203 static char* default_completer(const char* text, int state)
5205 return complete_from_list(default_completer_list, text, state);
5209 #if HAVE_READLINE_READLINE_H
5212 This function only known how to complete on the first word
5214 static char **readline_completer(char *text, int start, int end)
5216 completerFunctionType completerToUse;
5220 #if HAVE_READLINE_RL_COMPLETION_MATCHES
5221 char** res = rl_completion_matches(text, command_generator);
5223 char** res = completion_matches(text,
5224 (CPFunction*)command_generator);
5226 rl_attempted_completion_over = 1;
5231 char arg[10240],word[32];
5233 if ((res = sscanf(rl_line_buffer, "%31s %10239[^;]", word, arg)) <= 0)
5235 rl_attempted_completion_over = 1;
5239 for (i = 0; cmd_array[i].cmd; i++)
5240 if (!strncmp(cmd_array[i].cmd, word, strlen(word)))
5243 if (!cmd_array[i].cmd)
5246 default_completer_list = cmd_array[i].local_tabcompletes;
5248 completerToUse = cmd_array[i].rl_completerfunction;
5249 if (!completerToUse)
5250 { /* if command completer is not defined use the default completer */
5251 completerToUse = default_completer;
5255 #ifdef HAVE_READLINE_RL_COMPLETION_MATCHES
5257 rl_completion_matches(text, completerToUse);
5260 completion_matches(text, (CPFunction*)completerToUse);
5262 if (!cmd_array[i].complete_filenames)
5263 rl_attempted_completion_over = 1;
5268 if (!cmd_array[i].complete_filenames)
5269 rl_attempted_completion_over = 1;
5277 static void ctrl_c_handler(int x)
5283 static void client(void)
5290 signal(SIGINT, ctrl_c_handler);
5293 #if HAVE_GETTIMEOFDAY
5294 gettimeofday(&tv_start, 0);
5299 char *line_in = NULL;
5300 #if HAVE_READLINE_READLINE_H
5303 line_in=readline(C_PROMPT);
5309 #if HAVE_READLINE_HISTORY_H
5311 add_history(line_in);
5313 strncpy(line, line_in, sizeof(line)-1);
5322 if (!fgets(line, sizeof(line)-1, stdin))
5324 if ((end_p = strchr(line, '\n')))
5328 file_history_add_line(file_history, line);
5329 process_cmd_line(line);
5333 static void show_version(void)
5335 char vstr[20], sha1_str[41];
5337 yaz_version(vstr, sha1_str);
5338 printf("YAZ version: %s %s\n", YAZ_VERSION, YAZ_VERSION_SHA1);
5339 if (strcmp(sha1_str, YAZ_VERSION_SHA1))
5340 printf("YAZ DLL/SO: %s %s\n", vstr, sha1_str);
5344 int main(int argc, char **argv)
5347 char *open_command = 0;
5348 char *auth_command = 0;
5350 const char *rc_file = 0;
5354 if (!setlocale(LC_CTYPE, ""))
5355 fprintf(stderr, "setlocale failed\n");
5359 codeset = nl_langinfo(CODESET);
5363 outputCharset = xstrdup(codeset);
5365 ODR_MASK_SET(&z3950_options, Z_Options_search);
5366 ODR_MASK_SET(&z3950_options, Z_Options_present);
5367 ODR_MASK_SET(&z3950_options, Z_Options_namedResultSets);
5368 ODR_MASK_SET(&z3950_options, Z_Options_triggerResourceCtrl);
5369 ODR_MASK_SET(&z3950_options, Z_Options_scan);
5370 ODR_MASK_SET(&z3950_options, Z_Options_sort);
5371 ODR_MASK_SET(&z3950_options, Z_Options_extendedServices);
5372 ODR_MASK_SET(&z3950_options, Z_Options_delSet);
5374 nmem_auth = nmem_create();
5376 while ((ret = options("k:c:q:a:b:m:v:p:u:t:Vxd:f:", argv, argc, &arg)) != -2)
5383 open_command = (char *) xmalloc(strlen(arg)+6);
5384 strcpy(open_command, "open ");
5385 strcat(open_command, arg);
5389 fprintf(stderr, "%s: Specify at most one server address\n",
5395 if (!strcmp(arg, "-"))
5398 apdu_file=fopen(arg, "a");
5401 if (!strcmp(arg, "-"))
5404 ber_file=fopen(arg, "a");
5407 strncpy(ccl_fields, arg, sizeof(ccl_fields)-1);
5408 ccl_fields[sizeof(ccl_fields)-1] = '\0';
5411 dump_file_prefix = arg;
5417 kilobytes = atoi(arg);
5420 if (!(marc_file = fopen(arg, "a")))
5427 yazProxy = xstrdup(arg);
5430 strncpy(cql_fields, arg, sizeof(cql_fields)-1);
5431 cql_fields[sizeof(cql_fields)-1] = '\0';
5434 outputCharset = xstrdup(arg);
5439 auth_command = (char *) xmalloc(strlen(arg)+6);
5440 strcpy(auth_command, "auth ");
5441 strcat(auth_command, arg);
5445 yaz_log_init(yaz_log_mask_str(arg), "", 0);
5454 fprintf(stderr, "Usage: %s "
5474 initialize(rc_file);
5477 #ifdef HAVE_GETTIMEOFDAY
5478 gettimeofday(&tv_start, 0);
5480 process_cmd_line(auth_command);
5481 #if HAVE_READLINE_HISTORY_H
5482 add_history(auth_command);
5484 xfree(auth_command);
5488 #ifdef HAVE_GETTIMEOFDAY
5489 gettimeofday(&tv_start, 0);
5491 process_cmd_line(open_command);
5492 #if HAVE_READLINE_HISTORY_H
5493 add_history(open_command);
5495 xfree(open_command);
5504 * c-file-style: "Stroustrup"
5505 * indent-tabs-mode: nil
5507 * vim: shiftwidth=4 tabstop=8 expandtab