2 * Copyright (C) 1995-2005, Index Data ApS
3 * See the file LICENSE for details.
5 * $Id: client.c,v 1.304 2006-04-21 10:28:06 adam Exp $
14 #include <sys/types.h>
32 #if HAVE_OPENSSL_SSL_H
33 #include <openssl/bio.h>
34 #include <openssl/crypto.h>
35 #include <openssl/x509.h>
36 #include <openssl/pem.h>
37 #include <openssl/ssl.h>
38 #include <openssl/err.h>
45 #define S_ISREG(x) (x & _S_IFREG)
46 #define S_ISDIR(x) (x & _S_IFDIR)
49 #include <yaz/yaz-util.h>
51 #include <yaz/comstack.h>
53 #include <yaz/proto.h>
54 #include <yaz/marcdisp.h>
55 #include <yaz/diagbib1.h>
56 #include <yaz/otherinfo.h>
57 #include <yaz/charneg.h>
59 #include <yaz/pquery.h>
60 #include <yaz/sortspec.h>
64 #include <yaz/yaz-ccl.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"
79 #define C_PROMPT "Z> "
81 static char *codeset = 0; /* character set for output */
82 static int hex_dump = 0;
83 static char *dump_file_prefix = 0;
84 static ODR out, in, print; /* encoding and decoding streams */
86 static ODR srw_sr_odr_out = 0;
87 static Z_SRW_PDU *srw_sr = 0;
89 static FILE *apdu_file = 0;
90 static FILE *ber_file = 0;
91 static COMSTACK conn = 0; /* our z-association */
92 static Z_IdAuthentication *auth = 0; /* our current auth definition */
93 char *databaseNames[128];
94 int num_databaseNames = 0;
95 static Z_External *record_last = 0;
96 static int setnumber = -1; /* current result set number */
97 static int smallSetUpperBound = 0;
98 static int largeSetLowerBound = 1;
99 static int mediumSetPresentNumber = 0;
100 static Z_ElementSetNames *elementSetNames = 0;
101 static int setno = 1; /* current set offset */
102 static enum oid_proto protocol = PROTO_Z3950; /* current app protocol */
103 #define RECORDSYNTAX_MAX 20
104 static enum oid_value recordsyntax_list[RECORDSYNTAX_MAX] = { VAL_USMARC };
105 static int recordsyntax_size = 1;
107 static char *record_schema = 0;
108 static int sent_close = 0;
109 static NMEM session_mem = NULL; /* memory handle for init-response */
110 static Z_InitResponse *session_initResponse = 0; /* session parameters */
111 static char last_scan_line[512] = "0";
112 static char last_scan_query[512] = "0";
113 static char ccl_fields[512] = "default.bib";
114 /* ### How can I set this path to use wherever YAZ is installed? */
115 static char cql_fields[512] = "/usr/local/share/yaz/etc/pqf.properties";
116 static char *esPackageName = 0;
117 static char *yazProxy = 0;
118 static int kilobytes = 1024;
119 static char *negotiationCharset = 0;
120 static int negotiationCharsetRecords = 1;
121 static int negotiationCharsetVersion = 3;
122 static char *outputCharset = 0;
123 static char *marcCharset = 0;
124 static char* yazLang = 0;
125 static char* http_version = "1.1";
127 static char last_cmd[32] = "?";
128 static FILE *marc_file = 0;
129 static char *refid = NULL;
130 static char *last_open_command = NULL;
131 static int auto_reconnect = 0;
132 static int auto_wait = 1;
133 static Odr_bitmask z3950_options;
134 static int z3950_version = 3;
135 static int scan_stepSize = 0;
136 static int scan_position = 1;
137 static int scan_size = 20;
138 static char cur_host[200];
139 static int last_hit_count = 0;
149 static QueryType queryType = QueryType_Prefix;
151 static CCL_bibset bibset; /* CCL bibset handle */
152 static cql_transform_t cqltrans; /* CQL context-set handle */
154 #if HAVE_READLINE_COMPLETION_OVER
157 /* readline doesn't have this var. Define it ourselves. */
158 int rl_attempted_completion_over = 0;
161 /* set this one to 1, to avoid decode of unknown MARCs */
162 #define AVOID_MARC_DECODE 1
164 #define maxOtherInfosSupported 10
168 } extraOtherInfos[maxOtherInfosSupported];
171 void process_cmd_line(char* line);
172 char ** readline_completer(char *text, int start, int end);
173 char *command_generator(const char *text, int state);
174 char** curret_global_list=NULL;
175 int cmd_register_tab(const char* arg);
177 static void close_session (void);
179 ODR getODROutputStream()
184 const char* query_type_as_string(QueryType q)
187 case QueryType_Prefix: return "prefix (RPN sent to server)";
188 case QueryType_CCL: return "CCL (CCL sent to server) ";
189 case QueryType_CCL2RPN: return "CCL -> RPN (RPN sent to server)";
190 case QueryType_CQL: return "CQL (CQL sent to server)";
191 case QueryType_CQL2RPN: return "CQL -> RPN (RPN sent to server)";
193 return "unknown Query type internal yaz-client error";
197 static void do_hex_dump(const char* buf, int len)
202 for( i=0; i<len ; i=i+16 )
205 for(x=0 ; i+x<len && x<16; ++x)
207 printf("%2.2X ",(unsigned int)((unsigned char)buf[i+x]));
212 if (dump_file_prefix)
215 if (++no < 1000 && strlen(dump_file_prefix) < 500)
219 sprintf (fname, "%s.%03d.raw", dump_file_prefix, no);
220 of = fopen(fname, "wb");
222 fwrite (buf, 1, len, of);
229 void add_otherInfos(Z_APDU *a)
231 Z_OtherInformation **oi;
235 for(i=0; i<maxOtherInfosSupported; ++i)
237 if(extraOtherInfos[i].oidval != -1)
238 yaz_oi_set_string_oidval(oi, out, extraOtherInfos[i].oidval,
239 1, extraOtherInfos[i].value);
243 int send_apdu(Z_APDU *a)
252 z_APDU(print, &a, 0, 0);
255 if (!z_APDU(out, &a, 0, 0))
257 odr_perror(out, "Encoding APDU");
261 buf = odr_getbuf(out, &len, 0);
263 odr_dumpBER(ber_file, buf, len);
264 /* printf ("sending APDU of size %d\n", len); */
265 do_hex_dump(buf, len);
266 if (cs_put(conn, buf, len) < 0)
268 fprintf(stderr, "cs_put: %s", cs_errmsg(cs_errno(conn)));
272 odr_reset(out); /* release the APDU structure */
276 static void print_stringn(const unsigned char *buf, size_t len)
279 for (i = 0; i<len; i++)
280 if ((buf[i] <= 126 && buf[i] >= 32) || strchr ("\n\r\t\f", buf[i]))
281 printf ("%c", buf[i]);
283 printf ("\\X%02X", buf[i]);
286 static void print_refid (Z_ReferenceId *id)
290 printf ("Reference Id: ");
291 print_stringn (id->buf, id->len);
296 static Z_ReferenceId *set_refid (ODR out)
301 id = (Z_ReferenceId *) odr_malloc (out, sizeof(*id));
302 id->size = id->len = strlen(refid);
303 id->buf = (unsigned char *) odr_malloc (out, id->len);
304 memcpy (id->buf, refid, id->len);
308 /* INIT SERVICE ------------------------------- */
310 static void send_initRequest(const char* type_and_host)
312 Z_APDU *apdu = zget_APDU(out, Z_APDU_initRequest);
313 Z_InitRequest *req = apdu->u.initRequest;
316 req->options = &z3950_options;
318 ODR_MASK_ZERO(req->protocolVersion);
319 for (i = 0; i<z3950_version; i++)
320 ODR_MASK_SET(req->protocolVersion, i);
322 *req->maximumRecordSize = 1024*kilobytes;
323 *req->preferredMessageSize = 1024*kilobytes;
325 req->idAuthentication = auth;
327 req->referenceId = set_refid (out);
329 if (yazProxy && type_and_host)
330 yaz_oi_set_string_oidval(&req->otherInfo, out, VAL_PROXY,
333 if (negotiationCharset || yazLang) {
334 Z_OtherInformation **p;
335 Z_OtherInformationUnit *p0;
337 yaz_oi_APDU(apdu, &p);
339 if ((p0=yaz_oi_update(p, out, NULL, 0, 0))) {
340 ODR_MASK_SET(req->options, Z_Options_negotiationModel);
342 p0->which = Z_OtherInfo_externallyDefinedInfo;
343 p0->information.externallyDefinedInfo =
344 yaz_set_proposal_charneg_list(out, ",",
347 negotiationCharsetRecords);
352 printf("Sent initrequest.\n");
356 /* These two are used only from process_initResponse() */
357 static void render_initUserInfo(Z_OtherInformation *ui1);
358 static void render_diag(Z_DiagnosticFormat *diag);
360 static void pr_opt(const char *opt, void *clientData)
365 static int process_initResponse(Z_InitResponse *res)
368 /* save session parameters for later use */
369 session_mem = odr_extract_mem(in);
370 session_initResponse = res;
372 for (ver = 0; ver < 8; ver++)
373 if (!ODR_MASK_GET(res->protocolVersion, ver))
377 printf("Connection rejected by v%d target.\n", ver);
379 printf("Connection accepted by v%d target.\n", ver);
380 if (res->implementationId)
381 printf("ID : %s\n", res->implementationId);
382 if (res->implementationName)
383 printf("Name : %s\n", res->implementationName);
384 if (res->implementationVersion)
385 printf("Version: %s\n", res->implementationVersion);
386 if (res->userInformationField)
388 Z_External *uif = res->userInformationField;
389 if (uif->which == Z_External_userInfo1) {
390 render_initUserInfo(uif->u.userInfo1);
392 printf("UserInformationfield:\n");
393 if (!z_External(print, (Z_External**)&uif, 0, 0))
395 odr_perror(print, "Printing userinfo\n");
398 if (uif->which == Z_External_octet) {
399 printf("Guessing visiblestring:\n");
400 printf("'%.*s'\n", uif->u.octet_aligned->len,
401 uif->u.octet_aligned->buf);
403 else if (uif->which == Z_External_single)
405 Odr_any *sat = uif->u.single_ASN1_type;
406 oident *oid = oid_getentbyoid(uif->direct_reference);
407 if (oid->value == VAL_OCLCUI) {
408 Z_OCLC_UserInformation *oclc_ui;
409 ODR decode = odr_createmem(ODR_DECODE);
410 odr_setbuf(decode, (char *) sat->buf, sat->len, 0);
411 if (!z_OCLC_UserInformation(decode, &oclc_ui, 0, 0))
412 printf ("Bad OCLC UserInformation:\n");
414 printf ("OCLC UserInformation:\n");
415 if (!z_OCLC_UserInformation(print, &oclc_ui, 0, 0))
416 printf ("Bad OCLC UserInformation spec\n");
421 /* Peek at any private Init-diagnostic APDUs */
422 printf("### NAUGHTY: External is '%.*s'\n",
430 yaz_init_opt_decode(res->options, pr_opt, 0);
433 if (ODR_MASK_GET(res->options, Z_Options_namedResultSets))
436 if (ODR_MASK_GET(res->options, Z_Options_negotiationModel)) {
438 Z_CharSetandLanguageNegotiation *p =
439 yaz_get_charneg_record(res->otherInfo);
443 char *charset=NULL, *lang=NULL;
446 yaz_get_response_charneg(session_mem, p, &charset, &lang,
449 if (outputCharset && negotiationCharset) {
450 odr_set_charset (out, charset, outputCharset);
451 odr_set_charset (in, outputCharset, charset);
454 odr_set_charset (out, 0, 0);
455 odr_set_charset (in, 0, 0);
458 printf("Accepted character set : %s\n", charset);
459 printf("Accepted code language : %s\n", lang ? lang : "none");
460 printf("Accepted records in ...: %d\n", selected );
468 static void render_initUserInfo(Z_OtherInformation *ui1) {
470 printf("Init response contains %d otherInfo unit%s:\n",
471 ui1->num_elements, ui1->num_elements == 1 ? "" : "s");
473 for (i = 0; i < ui1->num_elements; i++) {
474 Z_OtherInformationUnit *unit = ui1->list[i];
475 printf(" %d: otherInfo unit contains ", i+1);
476 if (unit->which == Z_OtherInfo_externallyDefinedInfo &&
477 unit->information.externallyDefinedInfo &&
478 unit->information.externallyDefinedInfo->which ==
480 render_diag(unit->information.externallyDefinedInfo->u.diag1);
482 else if (unit->which != Z_OtherInfo_externallyDefinedInfo)
484 printf("unsupported otherInfo unit->which = %d\n", unit->which);
488 printf("unsupported otherInfo unit external %d\n",
489 unit->information.externallyDefinedInfo ?
490 unit->information.externallyDefinedInfo->which : -2);
496 /* ### should this share code with display_diagrecs()? */
497 static void render_diag(Z_DiagnosticFormat *diag) {
500 printf("%d diagnostic%s:\n", diag->num, diag->num == 1 ? "" : "s");
501 for (i = 0; i < diag->num; i++) {
502 Z_DiagnosticFormat_s *ds = diag->elements[i];
503 printf(" %d: ", i+1);
505 case Z_DiagnosticFormat_s_defaultDiagRec: {
506 Z_DefaultDiagFormat *dd = ds->u.defaultDiagRec;
507 /* ### should check `dd->diagnosticSetId' */
508 printf("code=%d (%s)", *dd->condition,
509 diagbib1_str(*dd->condition));
510 /* Both types of addinfo are the same, so use type-pun */
511 if (dd->u.v2Addinfo != 0)
512 printf(",\n\taddinfo='%s'", dd->u.v2Addinfo);
515 case Z_DiagnosticFormat_s_explicitDiagnostic:
516 printf("Explicit diagnostic (not supported)");
519 printf("Unrecognised diagnostic type %d", ds->which);
523 if (ds->message != 0)
524 printf(", message='%s'", ds->message);
530 static int set_base(const char *arg)
535 for (i = 0; i<num_databaseNames; i++)
536 xfree (databaseNames[i]);
537 num_databaseNames = 0;
541 if (!(cp = strchr(arg, ' ')))
542 cp = arg + strlen(arg);
545 databaseNames[num_databaseNames] = (char *)xmalloc (1 + cp - arg);
546 memcpy (databaseNames[num_databaseNames], arg, cp - arg);
547 databaseNames[num_databaseNames][cp - arg] = '\0';
549 for (cp1 = databaseNames[num_databaseNames]; *cp1 ; cp1++)
558 if (num_databaseNames == 0)
560 num_databaseNames = 1;
561 databaseNames[0] = xstrdup("");
566 static int parse_cmd_doc(const char **arg, ODR out, char **buf,
570 while (**arg && strchr(" \t\n\r\f", **arg))
572 if ((*arg)[0] == '\"' && (sep=strchr(*arg+1, '"')))
576 *buf = odr_strdupn(out, *arg, *len);
580 else if ((*arg)[0] && (*arg)[0] != '\"')
584 const char *fname = *arg;
586 while (**arg != '\0' && **arg != ' ')
589 inf = fopen(fname, "rb");
592 printf("Couldn't open %s\n", fname);
595 if (fseek(inf, 0L, SEEK_END) == -1)
597 printf("Couldn't seek in %s\n", fname);
602 if (fseek(inf, 0L, SEEK_SET) == -1)
604 printf("Couldn't seek in %s\n", fname);
609 *buf = odr_malloc(out, fsize);
610 if (fread(*buf, 1, fsize, inf) != fsize)
612 printf("Unable to read %s\n", fname);
619 else if (**arg == '\0')
627 printf("Missing doc argument\n");
630 printf("Bad doc argument %s\n", *arg);
634 static int cmd_base(const char *arg)
638 printf("Usage: base <database> <database> ...\n");
641 return set_base(arg);
644 void cmd_open_remember_last_open_command(const char* arg, char* new_open_command)
646 if(last_open_command != arg)
648 if(last_open_command) xfree(last_open_command);
649 last_open_command = xstrdup(new_open_command);
653 int session_connect(const char *arg)
656 char type_and_host[101];
657 const char *basep = 0;
658 #if HAVE_OPENSSL_SSL_H
668 nmem_destroy (session_mem);
670 session_initResponse = 0;
672 cs_get_host_args(arg, &basep);
674 strncpy(type_and_host, arg, sizeof(type_and_host)-1);
675 type_and_host[sizeof(type_and_host)-1] = '\0';
677 cmd_open_remember_last_open_command(arg, type_and_host);
680 conn = cs_create_host(yazProxy, 1, &add);
682 conn = cs_create_host(arg, 1, &add);
685 printf ("Couldn't create comstack\n");
689 if (conn->protocol == PROTO_HTTP)
690 queryType = QueryType_CQL;
692 if (conn->protocol == PROTO_HTTP)
694 printf ("SRW/HTTP not enabled in this YAZ\n");
700 protocol = conn->protocol;
701 if (conn->protocol == PROTO_HTTP)
705 printf("Connecting...");
707 if (cs_connect(conn, add) < 0)
709 printf ("error = %s\n", cs_strerror(conn));
710 if (conn->cerrno == CSYSERR)
713 yaz_strerror(msg, sizeof(msg));
714 printf ("%s\n", msg);
721 #if HAVE_OPENSSL_SSL_H
722 if ((ssl = (SSL *) cs_get_ssl(conn)))
724 X509 *server_cert = SSL_get_peer_certificate (ssl);
730 BIO *bio = BIO_new(BIO_s_mem());
732 /* get PEM buffer in memory */
733 PEM_write_bio_X509(bio, server_cert);
734 pem_len = BIO_get_mem_data(bio, &pem_buf);
735 fwrite(pem_buf, pem_len, 1, stdout);
737 /* print all info on screen .. */
738 X509_print_fp(stdout, server_cert);
741 X509_free (server_cert);
747 if (protocol == PROTO_Z3950)
749 send_initRequest(type_and_host);
755 int cmd_open(const char *arg)
759 strncpy (cur_host, arg, sizeof(cur_host)-1);
760 cur_host[sizeof(cur_host)-1] = 0;
762 return session_connect(cur_host);
769 if(!( auto_reconnect && last_open_command) ) return ;
771 open_command = (char *) xmalloc (strlen(last_open_command)+6);
772 strcpy (open_command, "open ");
774 strcat (open_command, last_open_command);
776 process_cmd_line(open_command);
781 int cmd_authentication(const char *arg)
783 static Z_IdAuthentication au;
784 static char user[40], group[40], pass[40];
785 static Z_IdPass idPass;
790 printf("Auth field set to null\n");
794 r = sscanf (arg, "%39s %39s %39s", user, group, pass);
797 printf("Authentication set to null\n");
803 if (!strcmp(user, "-")) {
804 au.which = Z_IdAuthentication_anonymous;
805 printf("Authentication set to Anonymous\n");
807 au.which = Z_IdAuthentication_open;
809 printf("Authentication set to Open (%s)\n", user);
815 au.which = Z_IdAuthentication_idPass;
816 au.u.idPass = &idPass;
817 idPass.groupId = NULL;
818 idPass.userId = user;
819 idPass.password = group;
820 printf("Authentication set to User (%s), Pass (%s)\n", user, group);
825 au.which = Z_IdAuthentication_idPass;
826 au.u.idPass = &idPass;
827 idPass.groupId = group;
828 idPass.userId = user;
829 idPass.password = pass;
830 printf("Authentication set to User (%s), Group (%s), Pass (%s)\n",
836 /* SEARCH SERVICE ------------------------------ */
837 static void display_record(Z_External *r);
839 static void print_record(const unsigned char *buf, size_t len)
842 print_stringn (buf, len);
843 /* add newline if not already added ... */
844 if (i <= 0 || buf[i-1] != '\n')
848 static void display_record(Z_External *r)
850 oident *ent = oid_getentbyoid(r->direct_reference);
854 * Tell the user what we got.
856 if (r->direct_reference)
858 printf("Record type: ");
860 printf("%s\n", ent->desc);
861 else if (!odr_oid(print, &r->direct_reference, 0, 0))
863 odr_perror(print, "print oid");
867 /* Check if this is a known, ASN.1 type tucked away in an octet string */
868 if (ent && r->which == Z_External_octet)
870 Z_ext_typeent *type = z_ext_getentbyref(ent->value);
876 * Call the given decoder to process the record.
878 odr_setbuf(in, (char*)r->u.octet_aligned->buf,
879 r->u.octet_aligned->len, 0);
880 if (!(*type->fun)(in, &rr, 0, 0))
882 odr_perror(in, "Decoding constructed record.");
883 fprintf(stdout, "[Near %ld]\n", (long) odr_offset(in));
884 fprintf(stdout, "Packet dump:\n---------\n");
885 odr_dumpBER(stdout, (char*)r->u.octet_aligned->buf,
886 r->u.octet_aligned->len);
887 fprintf(stdout, "---------\n");
889 /* note just ignores the error ant print the bytes form the octet_aligned later */
892 * Note: we throw away the original, BER-encoded record here.
893 * Do something else with it if you want to keep it.
895 r->u.sutrs = (Z_SUTRS *) rr; /* we don't actually check the type here. */
896 r->which = type->what;
900 if (ent && ent->value == VAL_SOIF)
902 print_record((const unsigned char *) r->u.octet_aligned->buf,
903 r->u.octet_aligned->len);
905 fwrite (r->u.octet_aligned->buf, 1, r->u.octet_aligned->len, marc_file);
907 else if (r->which == Z_External_octet)
909 const char *octet_buf = (char*)r->u.octet_aligned->buf;
910 if (ent->oclass == CLASS_RECSYN &&
911 (ent->value == VAL_TEXT_XML ||
912 ent->value == VAL_APPLICATION_XML ||
913 ent->value == VAL_HTML))
915 print_record((const unsigned char *) octet_buf,
916 r->u.octet_aligned->len);
918 else if (ent->value == VAL_POSTSCRIPT)
920 int size = r->u.octet_aligned->len;
923 print_record((const unsigned char *) octet_buf, size);
928 #if AVOID_MARC_DECODE
929 /* primitive check for a marc OID 5.1-29 except 16 */
930 ent->oidsuffix[0] == 5 && ent->oidsuffix[1] < 30 &&
931 ent->oidsuffix[1] != 16
940 yaz_marc_t mt = yaz_marc_create();
942 if (yaz_marc_decode_buf(mt, octet_buf,r->u.octet_aligned->len,
946 if (marcCharset && !strcmp(marcCharset, "auto"))
948 if (ent->value == VAL_USMARC)
950 if (octet_buf[9] == 'a')
958 else if (marcCharset)
960 if (outputCharset && from)
962 cd = yaz_iconv_open(outputCharset, from);
963 printf ("convert from %s to %s", from,
966 printf (" unsupported\n");
971 fwrite (result, 1, rlen, stdout);
975 size_t inbytesleft = rlen;
976 const char *inp = result;
980 size_t outbytesleft = sizeof(outbuf);
984 r = yaz_iconv (cd, (char**) &inp,
986 &outp, &outbytesleft);
987 if (r == (size_t) (-1))
989 int e = yaz_iconv_error(cd);
990 if (e != YAZ_ICONV_E2BIG)
993 fwrite (outbuf, outp - outbuf, 1, stdout);
999 printf ("bad MARC. Dumping as it is:\n");
1000 print_record((const unsigned char*) octet_buf,
1001 r->u.octet_aligned->len);
1003 yaz_marc_destroy(mt);
1005 yaz_iconv_close(cd);
1009 print_record((const unsigned char*) octet_buf,
1010 r->u.octet_aligned->len);
1014 fwrite (octet_buf, 1, r->u.octet_aligned->len, marc_file);
1016 else if (ent && ent->value == VAL_SUTRS)
1018 if (r->which != Z_External_sutrs)
1020 printf("Expecting single SUTRS type for SUTRS.\n");
1023 print_record(r->u.sutrs->buf, r->u.sutrs->len);
1025 fwrite (r->u.sutrs->buf, 1, r->u.sutrs->len, marc_file);
1027 else if (ent && ent->value == VAL_GRS1)
1030 if (r->which != Z_External_grs1)
1032 printf("Expecting single GRS type for GRS.\n");
1036 yaz_display_grs1(w, r->u.grs1, 0);
1037 puts (wrbuf_buf(w));
1040 else if (ent && ent->value == VAL_OPAC)
1043 if (r->u.opac->bibliographicRecord)
1044 display_record(r->u.opac->bibliographicRecord);
1045 for (i = 0; i<r->u.opac->num_holdingsData; i++)
1047 Z_HoldingsRecord *h = r->u.opac->holdingsData[i];
1048 if (h->which == Z_HoldingsRecord_marcHoldingsRecord)
1050 printf ("MARC holdings %d\n", i);
1051 display_record(h->u.marcHoldingsRecord);
1053 else if (h->which == Z_HoldingsRecord_holdingsAndCirc)
1057 Z_HoldingsAndCircData *data = h->u.holdingsAndCirc;
1059 printf ("Data holdings %d\n", i);
1060 if (data->typeOfRecord)
1061 printf ("typeOfRecord: %s\n", data->typeOfRecord);
1062 if (data->encodingLevel)
1063 printf ("encodingLevel: %s\n", data->encodingLevel);
1064 if (data->receiptAcqStatus)
1065 printf ("receiptAcqStatus: %s\n", data->receiptAcqStatus);
1066 if (data->generalRetention)
1067 printf ("generalRetention: %s\n", data->generalRetention);
1068 if (data->completeness)
1069 printf ("completeness: %s\n", data->completeness);
1070 if (data->dateOfReport)
1071 printf ("dateOfReport: %s\n", data->dateOfReport);
1073 printf ("nucCode: %s\n", data->nucCode);
1074 if (data->localLocation)
1075 printf ("localLocation: %s\n", data->localLocation);
1076 if (data->shelvingLocation)
1077 printf ("shelvingLocation: %s\n", data->shelvingLocation);
1078 if (data->callNumber)
1079 printf ("callNumber: %s\n", data->callNumber);
1080 if (data->shelvingData)
1081 printf ("shelvingData: %s\n", data->shelvingData);
1082 if (data->copyNumber)
1083 printf ("copyNumber: %s\n", data->copyNumber);
1084 if (data->publicNote)
1085 printf ("publicNote: %s\n", data->publicNote);
1086 if (data->reproductionNote)
1087 printf ("reproductionNote: %s\n", data->reproductionNote);
1088 if (data->termsUseRepro)
1089 printf ("termsUseRepro: %s\n", data->termsUseRepro);
1090 if (data->enumAndChron)
1091 printf ("enumAndChron: %s\n", data->enumAndChron);
1092 for (j = 0; j<data->num_volumes; j++)
1094 printf ("volume %d\n", j);
1095 if (data->volumes[j]->enumeration)
1096 printf (" enumeration: %s\n",
1097 data->volumes[j]->enumeration);
1098 if (data->volumes[j]->chronology)
1099 printf (" chronology: %s\n",
1100 data->volumes[j]->chronology);
1101 if (data->volumes[j]->enumAndChron)
1102 printf (" enumAndChron: %s\n",
1103 data->volumes[j]->enumAndChron);
1105 for (j = 0; j<data->num_circulationData; j++)
1107 printf ("circulation %d\n", j);
1108 if (data->circulationData[j]->availableNow)
1109 printf (" availableNow: %d\n",
1110 *data->circulationData[j]->availableNow);
1111 if (data->circulationData[j]->availablityDate)
1112 printf (" availabiltyDate: %s\n",
1113 data->circulationData[j]->availablityDate);
1114 if (data->circulationData[j]->availableThru)
1115 printf (" availableThru: %s\n",
1116 data->circulationData[j]->availableThru);
1117 if (data->circulationData[j]->restrictions)
1118 printf (" restrictions: %s\n",
1119 data->circulationData[j]->restrictions);
1120 if (data->circulationData[j]->itemId)
1121 printf (" itemId: %s\n",
1122 data->circulationData[j]->itemId);
1123 if (data->circulationData[j]->renewable)
1124 printf (" renewable: %d\n",
1125 *data->circulationData[j]->renewable);
1126 if (data->circulationData[j]->onHold)
1127 printf (" onHold: %d\n",
1128 *data->circulationData[j]->onHold);
1129 if (data->circulationData[j]->enumAndChron)
1130 printf (" enumAndChron: %s\n",
1131 data->circulationData[j]->enumAndChron);
1132 if (data->circulationData[j]->midspine)
1133 printf (" midspine: %s\n",
1134 data->circulationData[j]->midspine);
1135 if (data->circulationData[j]->temporaryLocation)
1136 printf (" temporaryLocation: %s\n",
1137 data->circulationData[j]->temporaryLocation);
1144 printf("Unknown record representation.\n");
1145 if (!z_External(print, &r, 0, 0))
1147 odr_perror(print, "Printing external");
1153 static void display_diagrecs(Z_DiagRec **pp, int num)
1157 Z_DefaultDiagFormat *r;
1159 printf("Diagnostic message(s) from database:\n");
1160 for (i = 0; i<num; i++)
1162 Z_DiagRec *p = pp[i];
1163 if (p->which != Z_DiagRec_defaultFormat)
1165 printf("Diagnostic record not in default format.\n");
1169 r = p->u.defaultFormat;
1170 if (!(ent = oid_getentbyoid(r->diagnosticSetId)) ||
1171 ent->oclass != CLASS_DIAGSET || ent->value != VAL_BIB1)
1172 printf("Missing or unknown diagset\n");
1173 printf(" [%d] %s", *r->condition, diagbib1_str(*r->condition));
1176 case Z_DefaultDiagFormat_v2Addinfo:
1177 printf (" -- v2 addinfo '%s'\n", r->u.v2Addinfo);
1179 case Z_DefaultDiagFormat_v3Addinfo:
1180 printf (" -- v3 addinfo '%s'\n", r->u.v3Addinfo);
1187 static void display_nameplusrecord(Z_NamePlusRecord *p)
1189 if (p->databaseName)
1190 printf("[%s]", p->databaseName);
1191 if (p->which == Z_NamePlusRecord_surrogateDiagnostic)
1192 display_diagrecs(&p->u.surrogateDiagnostic, 1);
1193 else if (p->which == Z_NamePlusRecord_databaseRecord)
1194 display_record(p->u.databaseRecord);
1197 static void display_records(Z_Records *p)
1201 if (p->which == Z_Records_NSD)
1203 Z_DiagRec dr, *dr_p = &dr;
1204 dr.which = Z_DiagRec_defaultFormat;
1205 dr.u.defaultFormat = p->u.nonSurrogateDiagnostic;
1206 display_diagrecs (&dr_p, 1);
1208 else if (p->which == Z_Records_multipleNSD)
1209 display_diagrecs (p->u.multipleNonSurDiagnostics->diagRecs,
1210 p->u.multipleNonSurDiagnostics->num_diagRecs);
1213 printf("Records: %d\n", p->u.databaseOrSurDiagnostics->num_records);
1214 for (i = 0; i < p->u.databaseOrSurDiagnostics->num_records; i++)
1215 display_nameplusrecord(p->u.databaseOrSurDiagnostics->records[i]);
1219 static int send_deleteResultSetRequest(const char *arg)
1224 Z_APDU *apdu = zget_APDU(out, Z_APDU_deleteResultSetRequest);
1225 Z_DeleteResultSetRequest *req = apdu->u.deleteResultSetRequest;
1227 req->referenceId = set_refid (out);
1229 req->num_resultSetList =
1230 sscanf (arg, "%30s %30s %30s %30s %30s %30s %30s %30s",
1231 names[0], names[1], names[2], names[3],
1232 names[4], names[5], names[6], names[7]);
1234 req->deleteFunction = (int *)
1235 odr_malloc (out, sizeof(*req->deleteFunction));
1236 if (req->num_resultSetList > 0)
1238 *req->deleteFunction = Z_DeleteResultSetRequest_list;
1239 req->resultSetList = (char **)
1240 odr_malloc (out, sizeof(*req->resultSetList)*
1241 req->num_resultSetList);
1242 for (i = 0; i<req->num_resultSetList; i++)
1243 req->resultSetList[i] = names[i];
1247 *req->deleteFunction = Z_DeleteResultSetRequest_all;
1248 req->resultSetList = 0;
1252 printf("Sent deleteResultSetRequest.\n");
1257 static int send_srw(Z_SRW_PDU *sr)
1259 const char *charset = negotiationCharset;
1260 const char *host_port = cur_host;
1263 Z_SOAP_Handler h[2] = {
1264 {"http://www.loc.gov/zing/srw/", 0, (Z_SOAP_fun) yaz_srw_codec},
1267 ODR o = odr_createmem(ODR_ENCODE);
1269 Z_SOAP *p = odr_malloc(o, sizeof(*p));
1272 path = odr_malloc(out, strlen(databaseNames[0])+2);
1274 strcpy(path+1, databaseNames[0]);
1276 gdu = z_get_HTTP_Request(out);
1277 gdu->u.HTTP_Request->version = http_version;
1278 gdu->u.HTTP_Request->path = odr_strdup(out, path);
1282 const char *cp0 = strstr(host_port, "://");
1283 const char *cp1 = 0;
1289 cp1 = strchr(cp0, '/');
1291 cp1 = cp0+strlen(cp0);
1295 char *h = odr_malloc(out, cp1 - cp0 + 1);
1296 memcpy (h, cp0, cp1 - cp0);
1298 z_HTTP_header_add(out, &gdu->u.HTTP_Request->headers,
1303 strcpy(ctype, "text/xml");
1304 if (charset && strlen(charset) < 20)
1306 strcat(ctype, "; charset=");
1307 strcat(ctype, charset);
1309 z_HTTP_header_add(out, &gdu->u.HTTP_Request->headers,
1310 "Content-Type", ctype);
1311 z_HTTP_header_add(out, &gdu->u.HTTP_Request->headers,
1312 "SOAPAction", "\"\"");
1313 p->which = Z_SOAP_generic;
1314 p->u.generic = odr_malloc(o, sizeof(*p->u.generic));
1315 p->u.generic->no = 0;
1316 p->u.generic->ns = 0;
1317 p->u.generic->p = sr;
1318 p->ns = "http://schemas.xmlsoap.org/soap/envelope/";
1320 ret = z_soap_codec_enc(o, &p,
1321 &gdu->u.HTTP_Request->content_buf,
1322 &gdu->u.HTTP_Request->content_len, h,
1325 if (z_GDU(out, &gdu, 0, 0))
1333 if (!z_GDU(print, &gdu, 0, 0))
1334 printf ("Failed to print outgoing APDU\n");
1337 buf_out = odr_getbuf(out, &len_out, 0);
1339 /* we don't odr_reset(out), since we may need the buffer again */
1341 do_hex_dump(buf_out, len_out);
1343 r = cs_put(conn, buf_out, len_out);
1355 static char *encode_SRW_term(ODR o, const char *q)
1357 const char *in_charset = "ISO-8859-1";
1358 WRBUF w = wrbuf_alloc();
1362 in_charset = outputCharset;
1363 cd = yaz_iconv_open("UTF-8", in_charset);
1367 return odr_strdup(o, q);
1369 wrbuf_iconv_write(w, cd, q, strlen(q));
1372 int len = wrbuf_len(w);
1373 res = odr_strdupn(o, wrbuf_buf(w), len);
1376 res = odr_strdup(o, q);
1377 yaz_iconv_close(cd);
1383 static int send_SRW_scanRequest(const char *arg, int pos, int num)
1387 /* regular requestse .. */
1388 sr = yaz_srw_get(out, Z_SRW_scan_request);
1393 sr->u.scan_request->query_type = Z_SRW_query_type_cql;
1394 sr->u.scan_request->scanClause.cql = encode_SRW_term(out, arg);
1396 case QueryType_Prefix:
1397 sr->u.scan_request->query_type = Z_SRW_query_type_pqf;
1398 sr->u.scan_request->scanClause.pqf = encode_SRW_term(out, arg);
1401 printf ("Only CQL and PQF supported in SRW\n");
1404 sr->u.scan_request->responsePosition = odr_intdup(out, pos);
1405 sr->u.scan_request->maximumTerms = odr_intdup(out, num);
1406 return send_srw(sr);
1409 static int send_SRW_searchRequest(const char *arg)
1415 assert(srw_sr_odr_out == 0);
1416 srw_sr_odr_out = odr_createmem(ODR_ENCODE);
1418 odr_reset(srw_sr_odr_out);
1422 /* save this for later .. when fetching individual records */
1423 srw_sr = yaz_srw_get(srw_sr_odr_out, Z_SRW_searchRetrieve_request);
1425 /* regular request .. */
1426 sr = yaz_srw_get(out, Z_SRW_searchRetrieve_request);
1431 srw_sr->u.request->query_type = Z_SRW_query_type_cql;
1432 srw_sr->u.request->query.cql = encode_SRW_term(srw_sr_odr_out, arg);
1434 sr->u.request->query_type = Z_SRW_query_type_cql;
1435 sr->u.request->query.cql = encode_SRW_term(srw_sr_odr_out, arg);
1437 case QueryType_Prefix:
1438 srw_sr->u.request->query_type = Z_SRW_query_type_pqf;
1439 srw_sr->u.request->query.pqf = encode_SRW_term(srw_sr_odr_out, arg);
1441 sr->u.request->query_type = Z_SRW_query_type_pqf;
1442 sr->u.request->query.pqf = encode_SRW_term(srw_sr_odr_out, arg);
1445 printf ("Only CQL and PQF supported in SRW\n");
1448 sr->u.request->maximumRecords = odr_intdup(out, 0);
1451 sr->u.request->recordSchema = record_schema;
1452 if (recordsyntax_size == 1 && recordsyntax_list[0] == VAL_TEXT_XML)
1453 sr->u.explain_request->recordPacking = "xml";
1454 return send_srw(sr);
1458 static int send_searchRequest(const char *arg)
1460 Z_APDU *apdu = zget_APDU(out, Z_APDU_searchRequest);
1461 Z_SearchRequest *req = apdu->u.searchRequest;
1463 struct ccl_rpn_node *rpn = NULL;
1465 char setstring[100];
1466 Z_RPNQuery *RPNquery;
1468 YAZ_PQF_Parser pqf_parser;
1470 QueryType myQueryType = queryType;
1473 if (myQueryType == QueryType_CCL2RPN)
1475 rpn = ccl_find_str(bibset, arg, &error, &pos);
1478 printf("CCL ERROR: %s\n", ccl_err_msg(error));
1481 } else if (myQueryType == QueryType_CQL2RPN) {
1482 /* ### All this code should be wrapped in a utility function */
1484 struct cql_node *node;
1485 const char *addinfo;
1486 if (cqltrans == 0) {
1487 printf("Can't use CQL: no translation file. Try set_cqlfile\n");
1490 parser = cql_parser_create();
1491 if ((error = cql_parser_string(parser, arg)) != 0) {
1492 printf("Can't parse CQL: must be a syntax error\n");
1495 node = cql_parser_result(parser);
1496 if ((error = cql_transform_buf(cqltrans, node, pqfbuf,
1497 sizeof pqfbuf)) != 0) {
1498 error = cql_transform_error(cqltrans, &addinfo);
1499 printf ("Can't convert CQL to PQF: %s (addinfo=%s)\n",
1500 cql_strerror(error), addinfo);
1504 myQueryType = QueryType_Prefix;
1507 req->referenceId = set_refid (out);
1508 if (!strcmp(arg, "@big")) /* strictly for troublemaking */
1510 static unsigned char big[2100];
1511 static Odr_oct bigo;
1513 /* send a very big referenceid to test transport stack etc. */
1514 memset(big, 'A', 2100);
1515 bigo.len = bigo.size = 2100;
1517 req->referenceId = &bigo;
1522 sprintf(setstring, "%d", ++setnumber);
1523 req->resultSetName = setstring;
1525 *req->smallSetUpperBound = smallSetUpperBound;
1526 *req->largeSetLowerBound = largeSetLowerBound;
1527 *req->mediumSetPresentNumber = mediumSetPresentNumber;
1528 if (smallSetUpperBound > 0 || (largeSetLowerBound > 1 &&
1529 mediumSetPresentNumber > 0))
1531 if (recordsyntax_size > 0)
1532 req->preferredRecordSyntax =
1533 yaz_oidval_to_z3950oid(out, CLASS_RECSYN, recordsyntax_list[0]);
1534 req->smallSetElementSetNames =
1535 req->mediumSetElementSetNames = elementSetNames;
1537 req->num_databaseNames = num_databaseNames;
1538 req->databaseNames = databaseNames;
1540 req->query = &query;
1542 switch (myQueryType)
1544 case QueryType_Prefix:
1545 query.which = Z_Query_type_1;
1546 pqf_parser = yaz_pqf_create ();
1547 RPNquery = yaz_pqf_parse (pqf_parser, out, arg);
1550 const char *pqf_msg;
1552 int code = yaz_pqf_error (pqf_parser, &pqf_msg, &off);
1554 printf("%*s^\n", ioff+4, "");
1555 printf("Prefix query error: %s (code %d)\n", pqf_msg, code);
1557 yaz_pqf_destroy (pqf_parser);
1560 yaz_pqf_destroy (pqf_parser);
1561 query.u.type_1 = RPNquery;
1564 query.which = Z_Query_type_2;
1565 query.u.type_2 = &ccl_query;
1566 ccl_query.buf = (unsigned char*) arg;
1567 ccl_query.len = strlen(arg);
1569 case QueryType_CCL2RPN:
1570 query.which = Z_Query_type_1;
1571 RPNquery = ccl_rpn_query(out, rpn);
1574 printf ("Couldn't convert from CCL to RPN\n");
1577 query.u.type_1 = RPNquery;
1578 ccl_rpn_delete (rpn);
1581 query.which = Z_Query_type_104;
1582 ext = (Z_External *) odr_malloc(out, sizeof(*ext));
1583 ext->direct_reference = odr_getoidbystr(out, "1.2.840.10003.16.2");
1584 ext->indirect_reference = 0;
1585 ext->descriptor = 0;
1586 ext->which = Z_External_CQL;
1587 ext->u.cql = odr_strdup(out, arg);
1588 query.u.type_104 = ext;
1591 printf ("Unsupported query type\n");
1594 if (send_apdu(apdu))
1595 printf("Sent searchRequest.\n");
1600 /* display Query Expression as part of searchResult-1 */
1601 static void display_queryExpression (const char *lead, Z_QueryExpression *qe)
1605 printf(" %s=", lead);
1606 if (qe->which == Z_QueryExpression_term)
1608 if (qe->u.term->queryTerm)
1610 Z_Term *term = qe->u.term->queryTerm;
1611 switch (term->which)
1613 case Z_Term_general:
1614 printf ("%.*s", term->u.general->len, term->u.general->buf);
1616 case Z_Term_characterString:
1617 printf ("%s", term->u.characterString);
1619 case Z_Term_numeric:
1620 printf ("%d", *term->u.numeric);
1630 /* see if we can find USR:SearchResult-1 */
1631 static void display_searchResult (Z_OtherInformation *o)
1636 for (i = 0; i < o->num_elements; i++)
1638 if (o->list[i]->which == Z_OtherInfo_externallyDefinedInfo)
1640 Z_External *ext = o->list[i]->information.externallyDefinedInfo;
1642 if (ext->which == Z_External_searchResult1)
1645 Z_SearchInfoReport *sr = ext->u.searchResult1;
1646 printf ("SearchResult-1:");
1647 for (j = 0; j < sr->num; j++)
1651 if (!sr->elements[j]->subqueryExpression)
1653 display_queryExpression("term",
1654 sr->elements[j]->subqueryExpression);
1655 display_queryExpression("interpretation",
1656 sr->elements[j]->subqueryInterpretation);
1657 display_queryExpression("recommendation",
1658 sr->elements[j]->subqueryRecommendation);
1659 if (sr->elements[j]->subqueryCount)
1660 printf(" cnt=%d", *sr->elements[j]->subqueryCount);
1661 if (sr->elements[j]->subqueryId)
1662 printf(" id=%s ", sr->elements[j]->subqueryId);
1670 static int process_searchResponse(Z_SearchResponse *res)
1672 printf ("Received SearchResponse.\n");
1673 print_refid (res->referenceId);
1674 if (*res->searchStatus)
1675 printf("Search was a success.\n");
1677 printf("Search was a bloomin' failure.\n");
1678 printf("Number of hits: %d", *res->resultCount);
1679 last_hit_count = *res->resultCount;
1681 printf (", setno %d", setnumber);
1683 display_searchResult (res->additionalSearchInfo);
1684 printf("records returned: %d\n",
1685 *res->numberOfRecordsReturned);
1686 setno += *res->numberOfRecordsReturned;
1688 display_records(res->records);
1692 static void print_level(int iLevel)
1695 for (i = 0; i < iLevel * 4; i++)
1699 static void print_int(int iLevel, const char *pTag, int *pInt)
1703 print_level(iLevel);
1704 printf("%s: %d\n", pTag, *pInt);
1708 static void print_string(int iLevel, const char *pTag, const char *pString)
1710 if (pString != NULL)
1712 print_level(iLevel);
1713 printf("%s: %s\n", pTag, pString);
1717 static void print_oid(int iLevel, const char *pTag, Odr_oid *pOid)
1723 print_level(iLevel);
1724 printf("%s:", pTag);
1725 for (; *pInt != -1; pInt++)
1726 printf(" %d", *pInt);
1731 static void print_referenceId(int iLevel, Z_ReferenceId *referenceId)
1733 if (referenceId != NULL)
1737 print_level(iLevel);
1738 printf("Ref Id (%d, %d): ", referenceId->len, referenceId->size);
1739 for (i = 0; i < referenceId->len; i++)
1740 printf("%c", referenceId->buf[i]);
1745 static void print_string_or_numeric(int iLevel, const char *pTag, Z_StringOrNumeric *pStringNumeric)
1747 if (pStringNumeric != NULL)
1749 switch (pStringNumeric->which)
1751 case Z_StringOrNumeric_string:
1752 print_string(iLevel, pTag, pStringNumeric->u.string);
1755 case Z_StringOrNumeric_numeric:
1756 print_int(iLevel, pTag, pStringNumeric->u.numeric);
1760 print_level(iLevel);
1761 printf("%s: valid type for Z_StringOrNumeric\n", pTag);
1767 static void print_universe_report_duplicate(
1769 Z_UniverseReportDuplicate *pUniverseReportDuplicate)
1771 if (pUniverseReportDuplicate != NULL)
1773 print_level(iLevel);
1774 printf("Universe Report Duplicate: \n");
1776 print_string_or_numeric(iLevel, "Hit No",
1777 pUniverseReportDuplicate->hitno);
1781 static void print_universe_report_hits(
1783 Z_UniverseReportHits *pUniverseReportHits)
1785 if (pUniverseReportHits != NULL)
1787 print_level(iLevel);
1788 printf("Universe Report Hits: \n");
1790 print_string_or_numeric(iLevel, "Database",
1791 pUniverseReportHits->database);
1792 print_string_or_numeric(iLevel, "Hits", pUniverseReportHits->hits);
1796 static void print_universe_report(int iLevel, Z_UniverseReport *pUniverseReport)
1798 if (pUniverseReport != NULL)
1800 print_level(iLevel);
1801 printf("Universe Report: \n");
1803 print_int(iLevel, "Total Hits", pUniverseReport->totalHits);
1804 switch (pUniverseReport->which)
1806 case Z_UniverseReport_databaseHits:
1807 print_universe_report_hits(iLevel,
1808 pUniverseReport->u.databaseHits);
1811 case Z_UniverseReport_duplicate:
1812 print_universe_report_duplicate(iLevel,
1813 pUniverseReport->u.duplicate);
1817 print_level(iLevel);
1818 printf("Type: %d\n", pUniverseReport->which);
1824 static void print_external(int iLevel, Z_External *pExternal)
1826 if (pExternal != NULL)
1828 print_level(iLevel);
1829 printf("External: \n");
1831 print_oid(iLevel, "Direct Reference", pExternal->direct_reference);
1832 print_int(iLevel, "InDirect Reference", pExternal->indirect_reference);
1833 print_string(iLevel, "Descriptor", pExternal->descriptor);
1834 switch (pExternal->which)
1836 case Z_External_universeReport:
1837 print_universe_report(iLevel, pExternal->u.universeReport);
1841 print_level(iLevel);
1842 printf("Type: %d\n", pExternal->which);
1848 static int process_resourceControlRequest (Z_ResourceControlRequest *req)
1850 printf ("Received ResourceControlRequest.\n");
1851 print_referenceId(1, req->referenceId);
1852 print_int(1, "Suspended Flag", req->suspendedFlag);
1853 print_int(1, "Partial Results Available", req->partialResultsAvailable);
1854 print_int(1, "Response Required", req->responseRequired);
1855 print_int(1, "Triggered Request Flag", req->triggeredRequestFlag);
1856 print_external(1, req->resourceReport);
1860 void process_ESResponse(Z_ExtendedServicesResponse *res)
1863 switch (*res->operationStatus)
1865 case Z_ExtendedServicesResponse_done:
1868 case Z_ExtendedServicesResponse_accepted:
1869 printf ("accepted\n");
1871 case Z_ExtendedServicesResponse_failure:
1872 printf ("failure\n");
1873 display_diagrecs(res->diagnostics, res->num_diagnostics);
1876 printf ("unknown\n");
1878 if ( (*res->operationStatus != Z_ExtendedServicesResponse_failure) &&
1879 (res->num_diagnostics != 0) ) {
1880 display_diagrecs(res->diagnostics, res->num_diagnostics);
1882 print_refid (res->referenceId);
1883 if (res->taskPackage &&
1884 res->taskPackage->which == Z_External_extendedService)
1886 Z_TaskPackage *taskPackage = res->taskPackage->u.extendedService;
1887 Odr_oct *id = taskPackage->targetReference;
1888 Z_External *ext = taskPackage->taskSpecificParameters;
1892 printf ("Target Reference: ");
1893 print_stringn (id->buf, id->len);
1896 if (ext->which == Z_External_update)
1898 Z_IUUpdateTaskPackage *utp = ext->u.update->u.taskPackage;
1899 if (utp && utp->targetPart)
1901 Z_IUTargetPart *targetPart = utp->targetPart;
1904 for (i = 0; i<targetPart->num_taskPackageRecords; i++)
1907 Z_IUTaskPackageRecordStructure *tpr =
1908 targetPart->taskPackageRecords[i];
1909 printf ("task package record %d\n", i+1);
1910 if (tpr->which == Z_IUTaskPackageRecordStructure_record)
1912 display_record (tpr->u.record);
1916 printf ("other type\n");
1922 if (res->taskPackage && res->taskPackage->which == Z_External_octet)
1924 Odr_oct *doc = res->taskPackage->u.octet_aligned;
1925 printf("%.*s\n", doc->len, doc->buf);
1929 const char *get_ill_element (void *clientData, const char *element)
1934 static Z_External *create_external_itemRequest()
1936 struct ill_get_ctl ctl;
1937 ILL_ItemRequest *req;
1939 int item_request_size = 0;
1940 char *item_request_buf = 0;
1944 ctl.f = get_ill_element;
1946 req = ill_get_ItemRequest(&ctl, "ill", 0);
1948 printf ("ill_get_ItemRequest failed\n");
1950 if (!ill_ItemRequest (out, &req, 0, 0))
1954 ill_ItemRequest(print, &req, 0, 0);
1957 item_request_buf = odr_getbuf (out, &item_request_size, 0);
1958 if (item_request_buf)
1959 odr_setbuf (out, item_request_buf, item_request_size, 1);
1960 printf ("Couldn't encode ItemRequest, size %d\n", item_request_size);
1967 item_request_buf = odr_getbuf (out, &item_request_size, 0);
1968 oid.proto = PROTO_GENERAL;
1969 oid.oclass = CLASS_GENERAL;
1970 oid.value = VAL_ISO_ILL_1;
1972 r = (Z_External *) odr_malloc (out, sizeof(*r));
1973 r->direct_reference = odr_oiddup(out,oid_getoidbyent(&oid));
1974 r->indirect_reference = 0;
1976 r->which = Z_External_single;
1978 r->u.single_ASN1_type = (Odr_oct *)
1979 odr_malloc (out, sizeof(*r->u.single_ASN1_type));
1980 r->u.single_ASN1_type->buf = (unsigned char *)
1981 odr_malloc (out, item_request_size);
1982 r->u.single_ASN1_type->len = item_request_size;
1983 r->u.single_ASN1_type->size = item_request_size;
1984 memcpy (r->u.single_ASN1_type->buf, item_request_buf,
1987 do_hex_dump(item_request_buf,item_request_size);
1992 static Z_External *create_external_ILL_APDU(int which)
1994 struct ill_get_ctl ctl;
1997 int ill_request_size = 0;
1998 char *ill_request_buf = 0;
2002 ctl.f = get_ill_element;
2004 ill_apdu = ill_get_APDU(&ctl, "ill", 0);
2006 if (!ill_APDU (out, &ill_apdu, 0, 0))
2010 printf ("-------------------\n");
2011 ill_APDU(print, &ill_apdu, 0, 0);
2013 printf ("-------------------\n");
2015 ill_request_buf = odr_getbuf (out, &ill_request_size, 0);
2016 if (ill_request_buf)
2017 odr_setbuf (out, ill_request_buf, ill_request_size, 1);
2018 printf ("Couldn't encode ILL-Request, size %d\n", ill_request_size);
2024 ill_request_buf = odr_getbuf (out, &ill_request_size, 0);
2026 oid.proto = PROTO_GENERAL;
2027 oid.oclass = CLASS_GENERAL;
2028 oid.value = VAL_ISO_ILL_1;
2030 r = (Z_External *) odr_malloc (out, sizeof(*r));
2031 r->direct_reference = odr_oiddup(out,oid_getoidbyent(&oid));
2032 r->indirect_reference = 0;
2034 r->which = Z_External_single;
2036 r->u.single_ASN1_type = (Odr_oct *)
2037 odr_malloc (out, sizeof(*r->u.single_ASN1_type));
2038 r->u.single_ASN1_type->buf = (unsigned char *)
2039 odr_malloc (out, ill_request_size);
2040 r->u.single_ASN1_type->len = ill_request_size;
2041 r->u.single_ASN1_type->size = ill_request_size;
2042 memcpy (r->u.single_ASN1_type->buf, ill_request_buf, ill_request_size);
2043 /* printf ("len = %d\n", ill_request_size); */
2044 /* do_hex_dump(ill_request_buf,ill_request_size); */
2045 /* printf("--- end of extenal\n"); */
2052 static Z_External *create_ItemOrderExternal(const char *type, int itemno)
2054 Z_External *r = (Z_External *) odr_malloc(out, sizeof(Z_External));
2055 oident ItemOrderRequest;
2057 ItemOrderRequest.proto = PROTO_Z3950;
2058 ItemOrderRequest.oclass = CLASS_EXTSERV;
2059 ItemOrderRequest.value = VAL_ITEMORDER;
2061 r->direct_reference = odr_oiddup(out,oid_getoidbyent(&ItemOrderRequest));
2062 r->indirect_reference = 0;
2065 r->which = Z_External_itemOrder;
2067 r->u.itemOrder = (Z_ItemOrder *) odr_malloc(out,sizeof(Z_ItemOrder));
2068 memset(r->u.itemOrder, 0, sizeof(Z_ItemOrder));
2069 r->u.itemOrder->which=Z_IOItemOrder_esRequest;
2071 r->u.itemOrder->u.esRequest = (Z_IORequest *)
2072 odr_malloc(out,sizeof(Z_IORequest));
2073 memset(r->u.itemOrder->u.esRequest, 0, sizeof(Z_IORequest));
2075 r->u.itemOrder->u.esRequest->toKeep = (Z_IOOriginPartToKeep *)
2076 odr_malloc(out,sizeof(Z_IOOriginPartToKeep));
2077 memset(r->u.itemOrder->u.esRequest->toKeep, 0, sizeof(Z_IOOriginPartToKeep));
2078 r->u.itemOrder->u.esRequest->notToKeep = (Z_IOOriginPartNotToKeep *)
2079 odr_malloc(out,sizeof(Z_IOOriginPartNotToKeep));
2080 memset(r->u.itemOrder->u.esRequest->notToKeep, 0, sizeof(Z_IOOriginPartNotToKeep));
2082 r->u.itemOrder->u.esRequest->toKeep->supplDescription = NULL;
2083 r->u.itemOrder->u.esRequest->toKeep->contact = NULL;
2084 r->u.itemOrder->u.esRequest->toKeep->addlBilling = NULL;
2086 r->u.itemOrder->u.esRequest->notToKeep->resultSetItem =
2087 (Z_IOResultSetItem *) odr_malloc(out, sizeof(Z_IOResultSetItem));
2088 memset(r->u.itemOrder->u.esRequest->notToKeep->resultSetItem, 0, sizeof(Z_IOResultSetItem));
2089 r->u.itemOrder->u.esRequest->notToKeep->resultSetItem->resultSetId = "1";
2091 r->u.itemOrder->u.esRequest->notToKeep->resultSetItem->item =
2092 (int *) odr_malloc(out, sizeof(int));
2093 *r->u.itemOrder->u.esRequest->notToKeep->resultSetItem->item = itemno;
2095 if (!strcmp (type, "item") || !strcmp(type, "2"))
2097 printf ("using item-request\n");
2098 r->u.itemOrder->u.esRequest->notToKeep->itemRequest =
2099 create_external_itemRequest();
2101 else if (!strcmp(type, "ill") || !strcmp(type, "1"))
2103 printf ("using ILL-request\n");
2104 r->u.itemOrder->u.esRequest->notToKeep->itemRequest =
2105 create_external_ILL_APDU(ILL_APDU_ILL_Request);
2107 else if (!strcmp(type, "xml") || !strcmp(type, "3"))
2109 const char *xml_buf =
2111 " <type>request</type>\n"
2112 " <libraryNo>000200</libraryNo>\n"
2113 " <borrowerTicketNo> 1212 </borrowerTicketNo>\n"
2115 r->u.itemOrder->u.esRequest->notToKeep->itemRequest =
2116 z_ext_record (out, VAL_TEXT_XML, xml_buf, strlen(xml_buf));
2119 r->u.itemOrder->u.esRequest->notToKeep->itemRequest = 0;
2124 static int send_itemorder(const char *type, int itemno)
2126 Z_APDU *apdu = zget_APDU(out, Z_APDU_extendedServicesRequest);
2127 Z_ExtendedServicesRequest *req = apdu->u.extendedServicesRequest;
2128 oident ItemOrderRequest;
2130 ItemOrderRequest.proto = PROTO_Z3950;
2131 ItemOrderRequest.oclass = CLASS_EXTSERV;
2132 ItemOrderRequest.value = VAL_ITEMORDER;
2133 req->packageType = odr_oiddup(out,oid_getoidbyent(&ItemOrderRequest));
2134 req->packageName = esPackageName;
2136 req->taskSpecificParameters = create_ItemOrderExternal(type, itemno);
2142 static int only_z3950()
2146 printf ("Not connected yet\n");
2149 if (protocol == PROTO_HTTP)
2151 printf ("Not supported by SRW\n");
2157 static int cmd_update_common(const char *arg, int version);
2159 static int cmd_update(const char *arg)
2161 return cmd_update_common(arg, 1);
2164 static int cmd_update0(const char *arg)
2166 return cmd_update_common(arg, 0);
2169 static int cmd_update_common(const char *arg, int version)
2171 Z_APDU *apdu = zget_APDU(out, Z_APDU_extendedServicesRequest );
2172 Z_ExtendedServicesRequest *req = apdu->u.extendedServicesRequest;
2174 char action[20], recid[20];
2179 Z_External *record_this = 0;
2185 sscanf (arg, "%19s %19s%n", action, recid, &noread);
2188 printf("Update must be followed by action and recid\n");
2189 printf(" where action is one of insert,replace,delete.update\n");
2190 printf(" recid is some record ID (any string)\n");
2194 if (!strcmp (action, "insert"))
2195 action_no = Z_IUOriginPartToKeep_recordInsert;
2196 else if (!strcmp (action, "replace"))
2197 action_no = Z_IUOriginPartToKeep_recordReplace;
2198 else if (!strcmp (action, "delete"))
2199 action_no = Z_IUOriginPartToKeep_recordDelete;
2200 else if (!strcmp (action, "update"))
2201 action_no = Z_IUOriginPartToKeep_specialUpdate;
2204 printf ("Bad action: %s\n", action);
2205 printf ("Possible values: insert, replace, delete, update\n");
2210 if (parse_cmd_doc(&arg, out, &rec_buf, &rec_len, 1) == 0)
2214 record_this = z_ext_record (out, VAL_TEXT_XML, rec_buf, rec_len);
2219 printf ("No last record (update ignored)\n");
2222 record_this = record_last;
2226 yaz_oidval_to_z3950oid(out, CLASS_EXTSERV,
2227 version == 0 ? VAL_DBUPDATE0 : VAL_DBUPDATE);
2229 req->packageName = esPackageName;
2231 req->referenceId = set_refid (out);
2233 r = req->taskSpecificParameters = (Z_External *)
2234 odr_malloc (out, sizeof(*r));
2235 r->direct_reference = req->packageType;
2236 r->indirect_reference = 0;
2240 Z_IU0OriginPartToKeep *toKeep;
2241 Z_IU0SuppliedRecords *notToKeep;
2243 r->which = Z_External_update0;
2244 r->u.update0 = (Z_IU0Update *) odr_malloc(out, sizeof(*r->u.update0));
2245 r->u.update0->which = Z_IUUpdate_esRequest;
2246 r->u.update0->u.esRequest = (Z_IU0UpdateEsRequest *)
2247 odr_malloc(out, sizeof(*r->u.update0->u.esRequest));
2248 toKeep = r->u.update0->u.esRequest->toKeep = (Z_IU0OriginPartToKeep *)
2249 odr_malloc(out, sizeof(*r->u.update0->u.esRequest->toKeep));
2251 toKeep->databaseName = databaseNames[0];
2253 toKeep->elementSetName = 0;
2255 toKeep->action = (int *) odr_malloc(out, sizeof(*toKeep->action));
2256 *toKeep->action = action_no;
2258 notToKeep = r->u.update0->u.esRequest->notToKeep = (Z_IU0SuppliedRecords *)
2259 odr_malloc(out, sizeof(*r->u.update0->u.esRequest->notToKeep));
2261 notToKeep->elements = (Z_IU0SuppliedRecords_elem **)
2262 odr_malloc(out, sizeof(*notToKeep->elements));
2263 notToKeep->elements[0] = (Z_IU0SuppliedRecords_elem *)
2264 odr_malloc(out, sizeof(**notToKeep->elements));
2265 notToKeep->elements[0]->which = Z_IUSuppliedRecords_elem_opaque;
2268 notToKeep->elements[0]->u.opaque = (Odr_oct *)
2269 odr_malloc (out, sizeof(Odr_oct));
2270 notToKeep->elements[0]->u.opaque->buf = (unsigned char *) recid;
2271 notToKeep->elements[0]->u.opaque->size = strlen(recid);
2272 notToKeep->elements[0]->u.opaque->len = strlen(recid);
2275 notToKeep->elements[0]->u.opaque = 0;
2276 notToKeep->elements[0]->supplementalId = 0;
2277 notToKeep->elements[0]->correlationInfo = 0;
2278 notToKeep->elements[0]->record = record_this;
2282 Z_IUOriginPartToKeep *toKeep;
2283 Z_IUSuppliedRecords *notToKeep;
2285 r->which = Z_External_update;
2286 r->u.update = (Z_IUUpdate *) odr_malloc(out, sizeof(*r->u.update));
2287 r->u.update->which = Z_IUUpdate_esRequest;
2288 r->u.update->u.esRequest = (Z_IUUpdateEsRequest *)
2289 odr_malloc(out, sizeof(*r->u.update->u.esRequest));
2290 toKeep = r->u.update->u.esRequest->toKeep = (Z_IUOriginPartToKeep *)
2291 odr_malloc(out, sizeof(*r->u.update->u.esRequest->toKeep));
2293 toKeep->databaseName = databaseNames[0];
2295 toKeep->elementSetName = 0;
2296 toKeep->actionQualifier = 0;
2297 toKeep->action = (int *) odr_malloc(out, sizeof(*toKeep->action));
2298 *toKeep->action = action_no;
2300 notToKeep = r->u.update->u.esRequest->notToKeep = (Z_IUSuppliedRecords *)
2301 odr_malloc(out, sizeof(*r->u.update->u.esRequest->notToKeep));
2303 notToKeep->elements = (Z_IUSuppliedRecords_elem **)
2304 odr_malloc(out, sizeof(*notToKeep->elements));
2305 notToKeep->elements[0] = (Z_IUSuppliedRecords_elem *)
2306 odr_malloc(out, sizeof(**notToKeep->elements));
2307 notToKeep->elements[0]->which = Z_IUSuppliedRecords_elem_opaque;
2310 notToKeep->elements[0]->u.opaque = (Odr_oct *)
2311 odr_malloc (out, sizeof(Odr_oct));
2312 notToKeep->elements[0]->u.opaque->buf = (unsigned char *) recid;
2313 notToKeep->elements[0]->u.opaque->size = strlen(recid);
2314 notToKeep->elements[0]->u.opaque->len = strlen(recid);
2317 notToKeep->elements[0]->u.opaque = 0;
2318 notToKeep->elements[0]->supplementalId = 0;
2319 notToKeep->elements[0]->correlationInfo = 0;
2320 notToKeep->elements[0]->record = record_this;
2328 static int cmd_xmles(const char *arg)
2336 int oid_value_xmles = VAL_XMLES;
2337 Z_APDU *apdu = zget_APDU(out, Z_APDU_extendedServicesRequest);
2338 Z_ExtendedServicesRequest *req = apdu->u.extendedServicesRequest;
2340 Z_External *ext = (Z_External *) odr_malloc(out, sizeof(*ext));
2342 req->taskSpecificParameters = ext;
2343 ext->indirect_reference = 0;
2344 ext->descriptor = 0;
2345 ext->which = Z_External_octet;
2346 ext->u.single_ASN1_type = (Odr_oct *) odr_malloc (out, sizeof(Odr_oct));
2347 sscanf(arg, "%50s%n", oid_str, &noread);
2350 printf("Missing OID for xmles\n");
2354 oid_value_xmles = oid_getvalbyname(oid_str);
2355 if (oid_value_xmles == VAL_NONE)
2357 printf("Bad OID: %s\n", oid_str);
2361 if (parse_cmd_doc(&arg, out, (char **) &ext->u.single_ASN1_type->buf,
2362 &ext->u.single_ASN1_type->len, 0) == 0)
2364 req->packageType = yaz_oidval_to_z3950oid(out, CLASS_EXTSERV,
2367 ext->direct_reference = yaz_oidval_to_z3950oid(out, CLASS_EXTSERV,
2375 static int cmd_itemorder(const char *arg)
2382 if (sscanf (arg, "%10s %d", type, &itemno) != 2)
2385 printf("Item order request\n");
2387 send_itemorder(type, itemno);
2391 static void show_opt(const char *arg, void *clientData)
2393 printf ("%s ", arg);
2396 static int cmd_zversion(const char *arg)
2399 z3950_version = atoi(arg);
2401 printf ("version is %d\n", z3950_version);
2405 static int cmd_options(const char *arg)
2411 r = yaz_init_opt_encode(&z3950_options, arg, &pos);
2413 printf("Unknown option(s) near %s\n", arg+pos);
2417 yaz_init_opt_decode(&z3950_options, show_opt, 0);
2423 static int cmd_explain(const char *arg)
2425 if (protocol != PROTO_HTTP)
2436 /* save this for later .. when fetching individual records */
2437 sr = yaz_srw_get(out, Z_SRW_explain_request);
2438 if (recordsyntax_size > 0 && recordsyntax_list[0] == VAL_TEXT_XML)
2439 sr->u.explain_request->recordPacking = "xml";
2447 static int cmd_init(const char *arg)
2451 strncpy (cur_host, arg, sizeof(cur_host)-1);
2452 cur_host[sizeof(cur_host)-1] = 0;
2456 send_initRequest(cur_host);
2460 static int cmd_find(const char *arg)
2464 printf("Find what?\n");
2467 if (protocol == PROTO_HTTP)
2474 if (!send_SRW_searchRequest(arg))
2487 printf("Not connected yet\n");
2491 if (!send_searchRequest(arg))
2497 static int cmd_delete(const char *arg)
2501 if (!send_deleteResultSetRequest(arg))
2506 static int cmd_ssub(const char *arg)
2508 if (!(smallSetUpperBound = atoi(arg)))
2513 static int cmd_lslb(const char *arg)
2515 if (!(largeSetLowerBound = atoi(arg)))
2520 static int cmd_mspn(const char *arg)
2522 if (!(mediumSetPresentNumber = atoi(arg)))
2527 static int cmd_status(const char *arg)
2529 printf("smallSetUpperBound: %d\n", smallSetUpperBound);
2530 printf("largeSetLowerBound: %d\n", largeSetLowerBound);
2531 printf("mediumSetPresentNumber: %d\n", mediumSetPresentNumber);
2535 static int cmd_setnames(const char *arg)
2537 if (*arg == '1') /* enable ? */
2539 else if (*arg == '0') /* disable ? */
2541 else if (setnumber < 0) /* no args, toggle .. */
2547 printf("Set numbering enabled.\n");
2549 printf("Set numbering disabled.\n");
2553 /* PRESENT SERVICE ----------------------------- */
2555 static void parse_show_args(const char *arg_c, char *setstring,
2556 int *start, int *number)
2561 strncpy(arg, arg_c, sizeof(arg)-1);
2562 arg[sizeof(arg)-1] = '\0';
2564 if ((p = strchr(arg, '+')))
2566 *number = atoi(p + 1);
2571 if (!strcmp(arg, "all"))
2573 *number = last_hit_count;
2579 if (p && (p=strchr(p+1, '+')))
2580 strcpy (setstring, p+1);
2581 else if (setnumber >= 0)
2582 sprintf(setstring, "%d", setnumber);
2587 static int send_presentRequest(const char *arg)
2589 Z_APDU *apdu = zget_APDU(out, Z_APDU_presentRequest);
2590 Z_PresentRequest *req = apdu->u.presentRequest;
2591 Z_RecordComposition compo;
2593 char setstring[100];
2595 req->referenceId = set_refid (out);
2597 parse_show_args(arg, setstring, &setno, &nos);
2599 req->resultSetId = setstring;
2601 req->resultSetStartPoint = &setno;
2602 req->numberOfRecordsRequested = &nos;
2604 if (recordsyntax_size == 1)
2605 req->preferredRecordSyntax =
2606 yaz_oidval_to_z3950oid(out, CLASS_RECSYN, recordsyntax_list[0]);
2608 if (record_schema || recordsyntax_size >= 2)
2610 req->recordComposition = &compo;
2611 compo.which = Z_RecordComp_complex;
2612 compo.u.complex = (Z_CompSpec *)
2613 odr_malloc(out, sizeof(*compo.u.complex));
2614 compo.u.complex->selectAlternativeSyntax = (bool_t *)
2615 odr_malloc(out, sizeof(bool_t));
2616 *compo.u.complex->selectAlternativeSyntax = 0;
2618 compo.u.complex->generic = (Z_Specification *)
2619 odr_malloc(out, sizeof(*compo.u.complex->generic));
2621 compo.u.complex->generic->which = Z_Schema_oid;
2623 compo.u.complex->generic->schema.oid = 0;
2626 compo.u.complex->generic->schema.oid =
2627 yaz_str_to_z3950oid(out, CLASS_SCHEMA, record_schema);
2629 if (!compo.u.complex->generic->schema.oid)
2631 /* OID wasn't a schema! Try record syntax instead. */
2632 compo.u.complex->generic->schema.oid = (Odr_oid *)
2633 yaz_str_to_z3950oid(out, CLASS_RECSYN, record_schema);
2636 if (!elementSetNames)
2637 compo.u.complex->generic->elementSpec = 0;
2640 compo.u.complex->generic->elementSpec = (Z_ElementSpec *)
2641 odr_malloc(out, sizeof(Z_ElementSpec));
2642 compo.u.complex->generic->elementSpec->which =
2643 Z_ElementSpec_elementSetName;
2644 compo.u.complex->generic->elementSpec->u.elementSetName =
2645 elementSetNames->u.generic;
2647 compo.u.complex->num_dbSpecific = 0;
2648 compo.u.complex->dbSpecific = 0;
2649 if (recordsyntax_size >= 2)
2652 compo.u.complex->num_recordSyntax = recordsyntax_size;
2653 compo.u.complex->recordSyntax = (Odr_oid **)
2654 odr_malloc(out, recordsyntax_size * sizeof(Odr_oid*));
2655 for (i = 0; i < recordsyntax_size; i++)
2656 compo.u.complex->recordSyntax[i] =
2657 yaz_oidval_to_z3950oid(out, CLASS_RECSYN,
2658 recordsyntax_list[i]);
2662 compo.u.complex->num_recordSyntax = 0;
2663 compo.u.complex->recordSyntax = 0;
2666 else if (elementSetNames)
2668 req->recordComposition = &compo;
2669 compo.which = Z_RecordComp_simple;
2670 compo.u.simple = elementSetNames;
2673 printf("Sent presentRequest (%d+%d).\n", setno, nos);
2678 static int send_SRW_presentRequest(const char *arg)
2680 char setstring[100];
2682 Z_SRW_PDU *sr = srw_sr;
2686 parse_show_args(arg, setstring, &setno, &nos);
2687 sr->u.request->startRecord = odr_intdup(out, setno);
2688 sr->u.request->maximumRecords = odr_intdup(out, nos);
2690 sr->u.request->recordSchema = record_schema;
2691 if (recordsyntax_size == 1 && recordsyntax_list[0] == VAL_TEXT_XML)
2692 sr->u.request->recordPacking = "xml";
2693 return send_srw(sr);
2697 static void close_session (void)
2709 void process_close(Z_Close *req)
2711 Z_APDU *apdu = zget_APDU(out, Z_APDU_close);
2712 Z_Close *res = apdu->u.close;
2714 static char *reasons[] =
2719 "cost limit reached",
2721 "security violation",
2728 printf("Reason: %s, message: %s\n", reasons[*req->closeReason],
2729 req->diagnosticInformation ? req->diagnosticInformation : "NULL");
2734 *res->closeReason = Z_Close_finished;
2736 printf("Sent response.\n");
2741 static int cmd_show(const char *arg)
2743 if (protocol == PROTO_HTTP)
2750 if (!send_SRW_presentRequest(arg))
2760 printf("Not connected yet\n");
2763 if (!send_presentRequest(arg))
2769 int cmd_quit(const char *arg)
2771 printf("See you later, alligator.\n");
2777 int cmd_cancel(const char *arg)
2779 Z_APDU *apdu = zget_APDU(out, Z_APDU_triggerResourceControlRequest);
2780 Z_TriggerResourceControlRequest *req =
2781 apdu->u.triggerResourceControlRequest;
2786 sscanf(arg, "%15s", command);
2790 if (session_initResponse &&
2791 !ODR_MASK_GET(session_initResponse->options,
2792 Z_Options_triggerResourceCtrl))
2794 printf("Target doesn't support cancel (trigger resource ctrl)\n");
2797 *req->requestedAction = Z_TriggerResourceControlRequest_cancel;
2798 req->resultSetWanted = &rfalse;
2799 req->referenceId = set_refid (out);
2802 printf("Sent cancel request\n");
2803 if (!strcmp(command, "wait"))
2809 int cmd_cancel_find(const char *arg) {
2813 return cmd_cancel("");
2818 int send_scanrequest(const char *query, int pp, int num, const char *term)
2820 Z_APDU *apdu = zget_APDU(out, Z_APDU_scanRequest);
2821 Z_ScanRequest *req = apdu->u.scanRequest;
2825 if (queryType == QueryType_CCL2RPN)
2828 struct ccl_rpn_node *rpn;
2830 rpn = ccl_find_str (bibset, query, &error, &pos);
2833 printf("CCL ERROR: %s\n", ccl_err_msg(error));
2837 yaz_oidval_to_z3950oid(out, CLASS_ATTSET, VAL_BIB1);
2838 if (!(req->termListAndStartPoint = ccl_scan_query (out, rpn)))
2840 printf("Couldn't convert CCL to Scan term\n");
2843 ccl_rpn_delete (rpn);
2847 YAZ_PQF_Parser pqf_parser = yaz_pqf_create ();
2849 if (!(req->termListAndStartPoint =
2850 yaz_pqf_scan(pqf_parser, out, &req->attributeSet, query)))
2852 const char *pqf_msg;
2854 int code = yaz_pqf_error (pqf_parser, &pqf_msg, &off);
2856 printf("%*s^\n", ioff+7, "");
2857 printf("Prefix query error: %s (code %d)\n", pqf_msg, code);
2858 yaz_pqf_destroy (pqf_parser);
2861 yaz_pqf_destroy (pqf_parser);
2865 if (req->termListAndStartPoint->term &&
2866 req->termListAndStartPoint->term->which == Z_Term_general &&
2867 req->termListAndStartPoint->term->u.general)
2869 req->termListAndStartPoint->term->u.general->buf =
2870 (unsigned char *) odr_strdup(out, term);
2871 req->termListAndStartPoint->term->u.general->len =
2872 req->termListAndStartPoint->term->u.general->size =
2876 req->referenceId = set_refid (out);
2877 req->num_databaseNames = num_databaseNames;
2878 req->databaseNames = databaseNames;
2879 req->numberOfTermsRequested = #
2880 req->preferredPositionInResponse = &pp;
2881 req->stepSize = odr_intdup(out, scan_stepSize);
2886 int send_sortrequest(const char *arg, int newset)
2888 Z_APDU *apdu = zget_APDU(out, Z_APDU_sortRequest);
2889 Z_SortRequest *req = apdu->u.sortRequest;
2890 Z_SortKeySpecList *sksl = (Z_SortKeySpecList *)
2891 odr_malloc (out, sizeof(*sksl));
2897 sprintf (setstring, "%d", setnumber);
2899 sprintf (setstring, "default");
2901 req->referenceId = set_refid (out);
2903 req->num_inputResultSetNames = 1;
2904 req->inputResultSetNames = (Z_InternationalString **)
2905 odr_malloc (out, sizeof(*req->inputResultSetNames));
2906 req->inputResultSetNames[0] = odr_strdup (out, setstring);
2908 if (newset && setnumber >= 0)
2909 sprintf (setstring, "%d", ++setnumber);
2911 req->sortedResultSetName = odr_strdup (out, setstring);
2913 req->sortSequence = yaz_sort_spec (out, arg);
2914 if (!req->sortSequence)
2916 printf ("Missing sort specifications\n");
2923 void display_term(Z_TermInfo *t)
2926 printf("%s", t->displayTerm);
2927 else if (t->term->which == Z_Term_general)
2929 printf("%.*s", t->term->u.general->len, t->term->u.general->buf);
2930 sprintf(last_scan_line, "%.*s", t->term->u.general->len,
2931 t->term->u.general->buf);
2934 printf("Term (not general)");
2935 if (t->globalOccurrences)
2936 printf (" (%d)\n", *t->globalOccurrences);
2941 void process_scanResponse(Z_ScanResponse *res)
2944 Z_Entry **entries = NULL;
2945 int num_entries = 0;
2947 printf("Received ScanResponse\n");
2948 print_refid (res->referenceId);
2949 printf("%d entries", *res->numberOfEntriesReturned);
2950 if (res->positionOfTerm)
2951 printf (", position=%d", *res->positionOfTerm);
2953 if (*res->scanStatus != Z_Scan_success)
2954 printf("Scan returned code %d\n", *res->scanStatus);
2957 if ((entries = res->entries->entries))
2958 num_entries = res->entries->num_entries;
2959 for (i = 0; i < num_entries; i++)
2961 int pos_term = res->positionOfTerm ? *res->positionOfTerm : -1;
2962 if (entries[i]->which == Z_Entry_termInfo)
2964 printf("%c ", i + 1 == pos_term ? '*' : ' ');
2965 display_term(entries[i]->u.termInfo);
2968 display_diagrecs(&entries[i]->u.surrogateDiagnostic, 1);
2970 if (res->entries->nonsurrogateDiagnostics)
2971 display_diagrecs (res->entries->nonsurrogateDiagnostics,
2972 res->entries->num_nonsurrogateDiagnostics);
2975 void process_sortResponse(Z_SortResponse *res)
2977 printf("Received SortResponse: status=");
2978 switch (*res->sortStatus)
2980 case Z_SortResponse_success:
2981 printf ("success"); break;
2982 case Z_SortResponse_partial_1:
2983 printf ("partial"); break;
2984 case Z_SortResponse_failure:
2985 printf ("failure"); break;
2987 printf ("unknown (%d)", *res->sortStatus);
2990 print_refid (res->referenceId);
2991 if (res->diagnostics)
2992 display_diagrecs(res->diagnostics,
2993 res->num_diagnostics);
2996 void process_deleteResultSetResponse (Z_DeleteResultSetResponse *res)
2998 printf("Got deleteResultSetResponse status=%d\n",
2999 *res->deleteOperationStatus);
3000 if (res->deleteListStatuses)
3003 for (i = 0; i < res->deleteListStatuses->num; i++)
3005 printf ("%s status=%d\n", res->deleteListStatuses->elements[i]->id,
3006 *res->deleteListStatuses->elements[i]->status);
3011 int cmd_sort_generic(const char *arg, int newset)
3015 if (session_initResponse &&
3016 !ODR_MASK_GET(session_initResponse->options, Z_Options_sort))
3018 printf("Target doesn't support sort\n");
3023 if (send_sortrequest(arg, newset) < 0)
3030 int cmd_sort(const char *arg)
3032 return cmd_sort_generic (arg, 0);
3035 int cmd_sort_newset (const char *arg)
3037 return cmd_sort_generic (arg, 1);
3040 int cmd_scanstep(const char *arg)
3042 scan_stepSize = atoi(arg);
3046 int cmd_scanpos(const char *arg)
3048 int r = sscanf(arg, "%d", &scan_position);
3054 int cmd_scansize(const char *arg)
3056 int r = sscanf(arg, "%d", &scan_size);
3062 int cmd_scan(const char *arg)
3064 if (protocol == PROTO_HTTP)
3073 if (send_SRW_scanRequest(arg, scan_position, scan_size) < 0)
3078 if (send_SRW_scanRequest(last_scan_line, 1, scan_size) < 0)
3093 printf("Session not initialized yet\n");
3097 if (session_initResponse &&
3098 !ODR_MASK_GET(session_initResponse->options, Z_Options_scan))
3100 printf("Target doesn't support scan\n");
3105 strcpy (last_scan_query, arg);
3106 if (send_scanrequest(arg, scan_position, scan_size, 0) < 0)
3111 if (send_scanrequest(last_scan_query, 1, scan_size, last_scan_line) < 0)
3118 int cmd_schema(const char *arg)
3120 xfree(record_schema);
3123 record_schema = xstrdup(arg);
3127 int cmd_format(const char *arg)
3129 const char *cp = arg;
3132 oid_value nsyntax[RECORDSYNTAX_MAX];
3136 printf("Usage: format <recordsyntax>\n");
3139 while (sscanf(cp, "%40s%n", form_str, &nor) >= 1 && nor > 0
3140 && idx < RECORDSYNTAX_MAX)
3142 nsyntax[idx] = oid_getvalbyname(form_str);
3143 if (!strcmp(form_str, "none"))
3145 if (nsyntax[idx] == VAL_NONE)
3147 printf ("unknown record syntax: %s\n", form_str);
3153 recordsyntax_size = idx;
3154 memcpy(recordsyntax_list, nsyntax, idx * sizeof(*nsyntax));
3158 int cmd_elements(const char *arg)
3160 static Z_ElementSetNames esn;
3161 static char what[100];
3165 elementSetNames = 0;
3169 esn.which = Z_ElementSetNames_generic;
3170 esn.u.generic = what;
3171 elementSetNames = &esn;
3175 int cmd_attributeset(const char *arg)
3181 printf("Usage: attributeset <setname>\n");
3184 sscanf(arg, "%s", what);
3185 if (p_query_attset (what))
3187 printf("Unknown attribute set name\n");
3193 int cmd_querytype (const char *arg)
3195 if (!strcmp (arg, "ccl"))
3196 queryType = QueryType_CCL;
3197 else if (!strcmp (arg, "prefix") || !strcmp(arg, "rpn"))
3198 queryType = QueryType_Prefix;
3199 else if (!strcmp (arg, "ccl2rpn") || !strcmp (arg, "cclrpn"))
3200 queryType = QueryType_CCL2RPN;
3201 else if (!strcmp(arg, "cql"))
3202 queryType = QueryType_CQL;
3203 else if (!strcmp (arg, "cql2rpn") || !strcmp (arg, "cqlrpn"))
3204 queryType = QueryType_CQL2RPN;
3207 printf ("Querytype must be one of:\n");
3208 printf (" prefix - Prefix query\n");
3209 printf (" ccl - CCL query\n");
3210 printf (" ccl2rpn - CCL query converted to RPN\n");
3211 printf (" cql - CQL\n");
3212 printf (" cql2rpn - CQL query converted to RPN\n");
3218 int cmd_refid (const char *arg)
3223 refid = xstrdup (arg);
3227 int cmd_close(const char *arg)
3233 apdu = zget_APDU(out, Z_APDU_close);
3234 req = apdu->u.close;
3235 *req->closeReason = Z_Close_finished;
3237 printf("Sent close request.\n");
3242 int cmd_packagename(const char* arg)
3244 xfree (esPackageName);
3245 esPackageName = NULL;
3247 esPackageName = xstrdup(arg);
3251 int cmd_proxy(const char* arg)
3256 yazProxy = xstrdup (arg);
3260 int cmd_marccharset(const char *arg)
3265 if (sscanf(arg, "%29s", l1) < 1)
3267 printf("MARC character set is `%s'\n",
3268 marcCharset ? marcCharset: "none");
3271 xfree (marcCharset);
3273 if (strcmp(l1, "-"))
3274 marcCharset = xstrdup(l1);
3278 int cmd_displaycharset(const char *arg)
3283 if (sscanf(arg, "%29s", l1) < 1)
3285 printf("Display character set is `%s'\n",
3286 outputCharset ? outputCharset: "none");
3290 xfree (outputCharset);
3292 if (!strcmp(l1, "auto") && codeset)
3296 printf ("Display character set: %s\n", codeset);
3297 outputCharset = xstrdup(codeset);
3300 printf ("No codeset found on this system\n");
3302 else if (strcmp(l1, "-") && strcmp(l1, "none"))
3303 outputCharset = xstrdup(l1);
3308 int cmd_negcharset(const char *arg)
3313 if (sscanf(arg, "%29s %d %d", l1, &negotiationCharsetRecords,
3314 &negotiationCharsetVersion) < 1)
3316 printf("Current negotiation character set is `%s'\n",
3317 negotiationCharset ? negotiationCharset: "none");
3318 printf("Records in charset %s\n", negotiationCharsetRecords ?
3320 printf("Charneg version %d\n", negotiationCharsetVersion);
3324 xfree (negotiationCharset);
3325 negotiationCharset = NULL;
3326 if (*l1 && strcmp(l1, "-") && strcmp(l1, "none"))
3328 negotiationCharset = xstrdup(l1);
3329 printf ("Character set negotiation : %s\n", negotiationCharset);
3335 int cmd_charset(const char* arg)
3337 char l1[30], l2[30], l3[30];
3339 *l1 = *l2 = *l3 = 0;
3340 if (sscanf(arg, "%29s %29s %29s", l1, l2, l3) < 1)
3343 cmd_displaycharset("");
3344 cmd_marccharset("");
3350 cmd_displaycharset(l2);
3352 cmd_marccharset(l3);
3357 int cmd_lang(const char* arg)
3360 printf("Current language is `%s'\n", (yazLang)?yazLang:NULL);
3366 yazLang = xstrdup(arg);
3370 int cmd_source(const char* arg, int echo )
3372 /* first should open the file and read one line at a time.. */
3374 char line[102400], *cp;
3377 fprintf(stderr,"Error in source command use a filename\n");
3381 includeFile = fopen (arg, "r");
3384 fprintf(stderr,"Unable to open file %s for reading\n",arg);
3388 while(!feof(includeFile)) {
3389 memset(line,0,sizeof(line));
3390 fgets(line,sizeof(line),includeFile);
3392 if(strlen(line) < 2) continue;
3393 if(line[0] == '#') continue;
3395 if ((cp = strrchr (line, '\n')))
3399 printf( "processing line: %s\n",line );
3401 process_cmd_line(line);
3404 if(fclose(includeFile)<0) {
3405 perror("unable to close include file");
3411 int cmd_source_echo(const char* arg)
3417 int cmd_source_noecho(const char* arg)
3424 int cmd_subshell(const char* args)
3429 system(getenv("SHELL"));
3435 int cmd_set_berfile(const char *arg)
3437 if (ber_file && ber_file != stdout && ber_file != stderr)
3439 if (!strcmp(arg, ""))
3441 else if (!strcmp(arg, "-"))
3444 ber_file = fopen(arg, "a");
3448 int cmd_set_apdufile(const char *arg)
3450 if(apdu_file && apdu_file != stderr && apdu_file != stderr)
3452 if (!strcmp(arg, ""))
3454 else if (!strcmp(arg, "-"))
3458 apdu_file = fopen(arg, "a");
3460 perror("unable to open apdu log file");
3463 odr_setprint(print, apdu_file);
3467 int cmd_set_cclfile(const char* arg)
3471 bibset = ccl_qual_mk ();
3472 inf = fopen (arg, "r");
3474 perror("unable to open CCL file");
3477 ccl_qual_file (bibset, inf);
3480 strcpy(ccl_fields,arg);
3484 int cmd_set_cqlfile(const char* arg)
3486 cql_transform_t newcqltrans;
3488 if ((newcqltrans = cql_transform_open_fname(arg)) == 0) {
3489 perror("unable to open CQL file");
3493 cql_transform_close(cqltrans);
3495 cqltrans = newcqltrans;
3496 strcpy(cql_fields, arg);
3500 int cmd_set_auto_reconnect(const char* arg)
3502 if(strlen(arg)==0) {
3503 auto_reconnect = ! auto_reconnect;
3504 } else if(strcmp(arg,"on")==0) {
3506 } else if(strcmp(arg,"off")==0) {
3509 printf("Error use on or off\n");
3514 printf("Set auto reconnect enabled.\n");
3516 printf("Set auto reconnect disabled.\n");
3522 int cmd_set_auto_wait(const char* arg)
3524 if(strlen(arg)==0) {
3525 auto_wait = ! auto_wait;
3526 } else if(strcmp(arg,"on")==0) {
3528 } else if(strcmp(arg,"off")==0) {
3531 printf("Error use on or off\n");
3536 printf("Set auto wait enabled.\n");
3538 printf("Set auto wait disabled.\n");
3543 int cmd_set_marcdump(const char* arg)
3545 if(marc_file && marc_file != stderr) { /* don't close stdout*/
3549 if (!strcmp(arg, ""))
3551 else if (!strcmp(arg, "-"))
3555 marc_file = fopen(arg, "a");
3557 perror("unable to open marc log file");
3563 this command takes 3 arge {name class oid}
3565 int cmd_register_oid(const char* args) {
3570 {"appctx",CLASS_APPCTX},
3571 {"absyn",CLASS_ABSYN},
3572 {"attset",CLASS_ATTSET},
3573 {"transyn",CLASS_TRANSYN},
3574 {"diagset",CLASS_DIAGSET},
3575 {"recsyn",CLASS_RECSYN},
3576 {"resform",CLASS_RESFORM},
3577 {"accform",CLASS_ACCFORM},
3578 {"extserv",CLASS_EXTSERV},
3579 {"userinfo",CLASS_USERINFO},
3580 {"elemspec",CLASS_ELEMSPEC},
3581 {"varset",CLASS_VARSET},
3582 {"schema",CLASS_SCHEMA},
3583 {"tagset",CLASS_TAGSET},
3584 {"general",CLASS_GENERAL},
3585 {0,(enum oid_class) 0}
3587 char oname_str[101], oclass_str[101], oid_str[101];
3590 oid_class oidclass = CLASS_GENERAL;
3591 int val = 0, oid[OID_SIZE];
3592 struct oident * new_oident=NULL;
3594 if (sscanf (args, "%100[^ ] %100[^ ] %100s",
3595 oname_str,oclass_str, oid_str) < 1) {
3596 printf("Error in register command \n");
3600 for (i = 0; oid_classes[i].className; i++) {
3601 if (!strcmp(oid_classes[i].className, oclass_str))
3603 oidclass=oid_classes[i].oclass;
3608 if(!(oid_classes[i].className)) {
3609 printf("Unknown oid class %s\n",oclass_str);
3617 while (isdigit (*(unsigned char *) name))
3619 val = val*10 + (*name - '0');
3632 new_oident = oid_addent (oid, PROTO_GENERAL, oidclass, oname_str,
3634 if(strcmp(new_oident->desc,oname_str))
3636 fprintf(stderr,"oid is already named as %s, registration failed\n",
3642 int cmd_push_command(const char* arg)
3644 #if HAVE_READLINE_HISTORY_H
3648 fprintf(stderr,"Not compiled with the readline/history module\n");
3653 void source_rcfile()
3655 /* Look for a $HOME/.yazclientrc and source it if it exists */
3656 struct stat statbuf;
3658 char* homedir=getenv("HOME");
3662 sprintf(buffer,"%s/.yazclientrc",homedir);
3664 if(stat(buffer,&statbuf)==0) {
3665 cmd_source(buffer, 0 );
3670 if(stat(".yazclientrc",&statbuf)==0) {
3671 cmd_source(".yazclientrc", 0 );
3676 static void initialize(void)
3681 if (!(out = odr_createmem(ODR_ENCODE)) ||
3682 !(in = odr_createmem(ODR_DECODE)) ||
3683 !(print = odr_createmem(ODR_PRINT)))
3685 fprintf(stderr, "failed to allocate ODR streams\n");
3690 setvbuf(stdout, 0, _IONBF, 0);
3692 odr_setprint(print, apdu_file);
3694 bibset = ccl_qual_mk ();
3695 inf = fopen (ccl_fields, "r");
3698 ccl_qual_file (bibset, inf);
3702 cqltrans = cql_transform_open_fname(cql_fields);
3703 /* If this fails, no problem: we detect cqltrans == 0 later */
3705 #if HAVE_READLINE_READLINE_H
3706 rl_attempted_completion_function = (CPPFunction*)readline_completer;
3710 for(i=0; i<maxOtherInfosSupported; ++i) {
3711 extraOtherInfos[i].oidval = -1;
3718 #if HAVE_GETTIMEOFDAY
3719 struct timeval tv_start;
3723 static void handle_srw_record(Z_SRW_record *rec)
3725 if (rec->recordPosition)
3727 printf ("pos=%d", *rec->recordPosition);
3728 setno = *rec->recordPosition + 1;
3730 if (rec->recordSchema)
3731 printf (" schema=%s", rec->recordSchema);
3733 if (rec->recordData_buf && rec->recordData_len)
3735 fwrite(rec->recordData_buf, 1, rec->recordData_len, stdout);
3737 fwrite (rec->recordData_buf, 1, rec->recordData_len, marc_file);
3740 printf ("No data!");
3744 static void handle_srw_explain_response(Z_SRW_explainResponse *res)
3746 handle_srw_record(&res->record);
3749 static void handle_srw_response(Z_SRW_searchRetrieveResponse *res)
3753 printf ("Received SRW SearchRetrieve Response\n");
3755 for (i = 0; i<res->num_diagnostics; i++)
3757 if (res->diagnostics[i].uri)
3758 printf ("SRW diagnostic %s\n",
3759 res->diagnostics[i].uri);
3761 printf ("SRW diagnostic missing or could not be decoded\n");
3762 if (res->diagnostics[i].message)
3763 printf ("Message: %s\n", res->diagnostics[i].message);
3764 if (res->diagnostics[i].details)
3765 printf ("Details: %s\n", res->diagnostics[i].details);
3767 if (res->numberOfRecords)
3768 printf ("Number of hits: %d\n", *res->numberOfRecords);
3769 for (i = 0; i<res->num_records; i++)
3770 handle_srw_record(res->records + i);
3773 static void handle_srw_scan_term(Z_SRW_scanTerm *term)
3775 if (term->displayTerm)
3776 printf("%s:", term->displayTerm);
3777 else if (term->value)
3778 printf("%s:", term->value);
3780 printf("No value:");
3781 if (term->numberOfRecords)
3782 printf(" %d", *term->numberOfRecords);
3783 if (term->whereInList)
3784 printf(" %s", term->whereInList);
3785 if (term->value && term->displayTerm)
3786 printf(" %s", term->value);
3788 strcpy(last_scan_line, term->value);
3792 static void handle_srw_scan_response(Z_SRW_scanResponse *res)
3796 printf ("Received SRW Scan Response\n");
3798 for (i = 0; i<res->num_diagnostics; i++)
3800 if (res->diagnostics[i].uri)
3801 printf ("SRW diagnostic %s\n",
3802 res->diagnostics[i].uri);
3804 printf ("SRW diagnostic missing or could not be decoded\n");
3805 if (res->diagnostics[i].message)
3806 printf ("Message: %s\n", res->diagnostics[i].message);
3807 if (res->diagnostics[i].details)
3808 printf ("Details: %s\n", res->diagnostics[i].details);
3811 for (i = 0; i<res->num_terms; i++)
3812 handle_srw_scan_term(res->terms + i);
3815 static void http_response(Z_HTTP_Response *hres)
3818 const char *content_type = z_HTTP_header_lookup(hres->headers,
3820 const char *connection_head = z_HTTP_header_lookup(hres->headers,
3822 if (content_type && !yaz_strcmp_del("text/xml", content_type, "; "))
3824 Z_SOAP *soap_package = 0;
3825 ODR o = odr_createmem(ODR_DECODE);
3826 Z_SOAP_Handler soap_handlers[2] = {
3827 {"http://www.loc.gov/zing/srw/", 0,
3828 (Z_SOAP_fun) yaz_srw_codec},
3831 ret = z_soap_codec(o, &soap_package,
3832 &hres->content_buf, &hres->content_len,
3834 if (!ret && soap_package->which == Z_SOAP_generic &&
3835 soap_package->u.generic->no == 0)
3837 Z_SRW_PDU *sr = soap_package->u.generic->p;
3838 if (sr->which == Z_SRW_searchRetrieve_response)
3839 handle_srw_response(sr->u.response);
3840 else if (sr->which == Z_SRW_explain_response)
3841 handle_srw_explain_response(sr->u.explain_response);
3842 else if (sr->which == Z_SRW_scan_response)
3843 handle_srw_scan_response(sr->u.scan_response);
3847 else if (soap_package && (soap_package->which == Z_SOAP_fault
3848 || soap_package->which == Z_SOAP_error))
3850 printf ("HTTP Error Status=%d\n", hres->code);
3851 printf ("SOAP Fault code %s\n",
3852 soap_package->u.fault->fault_code);
3853 printf ("SOAP Fault string %s\n",
3854 soap_package->u.fault->fault_string);
3855 if (soap_package->u.fault->details)
3856 printf ("SOAP Details %s\n",
3857 soap_package->u.fault->details);
3865 if (hres->code != 200)
3867 printf ("HTTP Error Status=%d\n", hres->code);
3871 printf ("Decoding of SRW package failed\n");
3877 if (!strcmp(hres->version, "1.0"))
3879 /* HTTP 1.0: only if Keep-Alive we stay alive.. */
3880 if (!connection_head || strcmp(connection_head, "Keep-Alive"))
3885 /* HTTP 1.1: only if no close we stay alive .. */
3886 if (connection_head && !strcmp(connection_head, "close"))
3893 void wait_and_handle_response(int one_response_only)
3895 int reconnect_ok = 1;
3898 int netbufferlen = 0;
3899 #if HAVE_GETTIMEOFDAY
3901 struct timeval tv_end;
3907 res = cs_get(conn, &netbuffer, &netbufferlen);
3908 if (reconnect_ok && res <= 0 && protocol == PROTO_HTTP)
3919 buf_out = odr_getbuf(out, &len_out, 0);
3921 do_hex_dump(buf_out, len_out);
3923 cs_put(conn, buf_out, len_out);
3931 printf("Target closed connection\n");
3935 #if HAVE_GETTIMEOFDAY
3936 if (got_tv_end == 0)
3937 gettimeofday (&tv_end, 0); /* count first one only */
3941 odr_reset(in); /* release APDU from last round */
3943 do_hex_dump(netbuffer, res);
3944 odr_setbuf(in, netbuffer, res, 0);
3946 if (!z_GDU(in, &gdu, 0, 0))
3948 FILE *f = ber_file ? ber_file : stdout;
3949 odr_perror(in, "Decoding incoming APDU");
3950 fprintf(f, "[Near %ld]\n", (long) odr_offset(in));
3951 fprintf(f, "Packet dump:\n---------\n");
3952 odr_dumpBER(f, netbuffer, res);
3953 fprintf(f, "---------\n");
3956 z_GDU(print, &gdu, 0, 0);
3959 if (conn && cs_more(conn))
3964 odr_dumpBER(ber_file, netbuffer, res);
3965 if (apdu_file && !z_GDU(print, &gdu, 0, 0))
3967 odr_perror(print, "Failed to print incoming APDU");
3971 if (gdu->which == Z_GDU_Z3950)
3973 Z_APDU *apdu = gdu->u.z3950;
3976 case Z_APDU_initResponse:
3977 process_initResponse(apdu->u.initResponse);
3979 case Z_APDU_searchResponse:
3980 process_searchResponse(apdu->u.searchResponse);
3982 case Z_APDU_scanResponse:
3983 process_scanResponse(apdu->u.scanResponse);
3985 case Z_APDU_presentResponse:
3986 print_refid (apdu->u.presentResponse->referenceId);
3988 *apdu->u.presentResponse->numberOfRecordsReturned;
3989 if (apdu->u.presentResponse->records)
3990 display_records(apdu->u.presentResponse->records);
3992 printf("No records.\n");
3993 printf ("nextResultSetPosition = %d\n",
3994 *apdu->u.presentResponse->nextResultSetPosition);
3996 case Z_APDU_sortResponse:
3997 process_sortResponse(apdu->u.sortResponse);
3999 case Z_APDU_extendedServicesResponse:
4000 printf("Got extended services response\n");
4001 process_ESResponse(apdu->u.extendedServicesResponse);
4004 printf("Target has closed the association.\n");
4005 process_close(apdu->u.close);
4007 case Z_APDU_resourceControlRequest:
4008 process_resourceControlRequest
4009 (apdu->u.resourceControlRequest);
4011 case Z_APDU_deleteResultSetResponse:
4012 process_deleteResultSetResponse(apdu->u.
4013 deleteResultSetResponse);
4016 printf("Received unknown APDU type (%d).\n",
4022 else if (gdu->which == Z_GDU_HTTP_Response)
4024 http_response(gdu->u.HTTP_Response);
4027 if (one_response_only)
4029 if (conn && !cs_more(conn))
4032 #if HAVE_GETTIMEOFDAY
4036 printf ("S/U S/U=%ld/%ld %ld/%ld",
4037 (long) tv_start.tv_sec,
4038 (long) tv_start.tv_usec,
4039 (long) tv_end.tv_sec,
4040 (long) tv_end.tv_usec);
4042 printf ("Elapsed: %.6f\n",
4043 (double) tv_end.tv_usec / 1e6 + tv_end.tv_sec -
4044 ((double) tv_start.tv_usec / 1e6 + tv_start.tv_sec));
4051 int cmd_cclparse(const char* arg)
4054 struct ccl_rpn_node *rpn=NULL;
4057 rpn = ccl_find_str (bibset, arg, &error, &pos);
4060 int ioff = 3+strlen(last_cmd)+1+pos;
4061 printf ("%*s^ - ", ioff, " ");
4062 printf ("%s\n", ccl_err_msg (error));
4068 ccl_pr_tree(rpn, stdout);
4072 ccl_rpn_delete(rpn);
4080 int cmd_set_otherinfo(const char* args)
4082 char oidstr[101], otherinfoString[101];
4087 sscan_res = sscanf (args, "%d %100[^ ] %100s", &otherinfoNo, oidstr, otherinfoString);
4089 /* reset this otherinfo */
4090 if(otherinfoNo>=maxOtherInfosSupported) {
4091 printf("Error otherinfo index to large (%d>%d)\n",
4092 otherinfoNo,maxOtherInfosSupported);
4094 extraOtherInfos[otherinfoNo].oidval = -1;
4095 if (extraOtherInfos[otherinfoNo].value)
4096 free(extraOtherInfos[otherinfoNo].value);
4097 extraOtherInfos[otherinfoNo].value = 0;
4101 printf("Error in set_otherinfo command \n");
4105 if (otherinfoNo>=maxOtherInfosSupported) {
4106 printf("Error otherinfo index to large (%d>%d)\n",
4107 otherinfoNo,maxOtherInfosSupported);
4110 oidval = oid_getvalbyname (oidstr);
4111 if (oidval == -1 ) {
4112 printf("Error in set_otherinfo command unknown oid %s \n",oidstr);
4115 extraOtherInfos[otherinfoNo].oidval = oidval;
4116 if(extraOtherInfos[otherinfoNo].value) free(extraOtherInfos[otherinfoNo].value);
4117 extraOtherInfos[otherinfoNo].value = strdup(otherinfoString);
4122 int cmd_sleep(const char* args )
4131 printf("Done sleeping %d seconds\n", sec);
4136 int cmd_list_otherinfo(const char* args)
4140 if(strlen(args)>0) {
4142 if( i >= maxOtherInfosSupported ) {
4143 printf("Error otherinfo index to large (%d>%d)\n",i,maxOtherInfosSupported);
4147 if(extraOtherInfos[i].oidval != -1)
4148 printf(" otherinfo %d %s %s\n",
4150 yaz_z3950_oid_value_to_str(
4151 (enum oid_value) extraOtherInfos[i].oidval,
4153 extraOtherInfos[i].value);
4156 for(i=0; i<maxOtherInfosSupported; ++i) {
4157 if(extraOtherInfos[i].oidval != -1)
4158 printf(" otherinfo %d %s %s\n",
4160 yaz_z3950_oid_value_to_str(
4161 (enum oid_value) extraOtherInfos[i].oidval,
4163 extraOtherInfos[i].value);
4171 int cmd_list_all(const char* args) {
4174 /* connection options */
4176 printf("Connected to : %s\n",last_open_command);
4178 if(last_open_command)
4179 printf("Not connected to : %s\n",last_open_command);
4181 printf("Not connected : \n");
4184 if(yazProxy) printf("using proxy : %s\n",yazProxy);
4186 printf("auto_reconnect : %s\n",auto_reconnect?"on":"off");
4187 printf("auto_wait : %s\n",auto_wait?"on":"off");
4190 printf("Authentication : none\n");
4192 switch(auth->which) {
4193 case Z_IdAuthentication_idPass:
4194 printf("Authentication : IdPass\n");
4195 printf(" Login User : %s\n",auth->u.idPass->userId?auth->u.idPass->userId:"");
4196 printf(" Login Group : %s\n",auth->u.idPass->groupId?auth->u.idPass->groupId:"");
4197 printf(" Password : %s\n",auth->u.idPass->password?auth->u.idPass->password:"");
4199 case Z_IdAuthentication_open:
4200 printf("Authentication : psOpen\n");
4201 printf(" Open string : %s\n",auth->u.open);
4204 printf("Authentication : Unknown\n");
4207 if (negotiationCharset)
4208 printf("Neg. Character set : `%s'\n", negotiationCharset);
4212 for (i = 0; i<num_databaseNames; i++) printf("%s ",databaseNames[i]);
4216 printf("CCL file : %s\n",ccl_fields);
4217 printf("CQL file : %s\n",cql_fields);
4218 printf("Query type : %s\n",query_type_as_string(queryType));
4220 printf("Named Result Sets : %s\n",setnumber==-1?"off":"on");
4222 /* piggy back options */
4223 printf("ssub/lslb/mspn : %d/%d/%d\n",smallSetUpperBound,largeSetLowerBound,mediumSetPresentNumber);
4225 /* print present related options */
4226 printf("Format : %s\n",
4227 (recordsyntax_size > 0) ?
4228 yaz_z3950_oid_value_to_str(recordsyntax_list[0], CLASS_RECSYN) :
4230 printf("Schema : %s\n",record_schema ? record_schema : "not set");
4231 printf("Elements : %s\n",elementSetNames?elementSetNames->u.generic:"");
4233 /* loging options */
4234 printf("APDU log : %s\n",apdu_file?"on":"off");
4235 printf("Record log : %s\n",marc_file?"on":"off");
4238 printf("Other Info: \n");
4239 cmd_list_otherinfo("");
4244 int cmd_clear_otherinfo(const char* args)
4246 if(strlen(args)>0) {
4248 otherinfoNo = atoi(args);
4249 if( otherinfoNo >= maxOtherInfosSupported ) {
4250 printf("Error otherinfo index to large (%d>%d)\n",otherinfoNo,maxOtherInfosSupported);
4254 if(extraOtherInfos[otherinfoNo].oidval != -1) {
4255 /* only clear if set. */
4256 extraOtherInfos[otherinfoNo].oidval=-1;
4257 free(extraOtherInfos[otherinfoNo].value);
4262 for(i=0; i<maxOtherInfosSupported; ++i) {
4263 if (extraOtherInfos[i].oidval!=-1 ) {
4264 extraOtherInfos[i].oidval=-1;
4265 free(extraOtherInfos[i].value);
4272 int cmd_wait_response(const char *arg)
4274 int wait_for = atoi(arg);
4276 if( wait_for < 1 ) {
4280 for( i=0 ; i < wait_for ; ++i ) {
4281 wait_and_handle_response(1);
4286 static int cmd_help (const char *line);
4288 typedef char *(*completerFunctionType)(const char *text, int state);
4292 int (*fun)(const char *arg);
4294 completerFunctionType rl_completerfunction;
4295 int complete_filenames;
4296 char **local_tabcompletes;
4298 {"open", cmd_open, "('tcp'|'ssl')':<host>[':'<port>][/<db>]",NULL,0,NULL},
4299 {"quit", cmd_quit, "",NULL,0,NULL},
4300 {"find", cmd_find, "<query>",NULL,0,NULL},
4301 {"delete", cmd_delete, "<setname>",NULL,0,NULL},
4302 {"base", cmd_base, "<base-name>",NULL,0,NULL},
4303 {"show", cmd_show, "<rec#>['+'<#recs>['+'<setname>]]",NULL,0,NULL},
4304 {"scan", cmd_scan, "<term>",NULL,0,NULL},
4305 {"scanstep", cmd_scanstep, "<size>",NULL,0,NULL},
4306 {"scanpos", cmd_scanpos, "<size>",NULL,0,NULL},
4307 {"scansize", cmd_scansize, "<size>",NULL,0,NULL},
4308 {"sort", cmd_sort, "<sortkey> <flag> <sortkey> <flag> ...",NULL,0,NULL},
4309 {"sort+", cmd_sort_newset, "<sortkey> <flag> <sortkey> <flag> ...",NULL,0,NULL},
4310 {"authentication", cmd_authentication, "<acctstring>",NULL,0,NULL},
4311 {"lslb", cmd_lslb, "<largeSetLowerBound>",NULL,0,NULL},
4312 {"ssub", cmd_ssub, "<smallSetUpperBound>",NULL,0,NULL},
4313 {"mspn", cmd_mspn, "<mediumSetPresentNumber>",NULL,0,NULL},
4314 {"status", cmd_status, "",NULL,0,NULL},
4315 {"setnames", cmd_setnames, "",NULL,0,NULL},
4316 {"cancel", cmd_cancel, "",NULL,0,NULL},
4317 {"cancel_find", cmd_cancel_find, "<query>",NULL,0,NULL},
4318 {"format", cmd_format, "<recordsyntax>",complete_format,0,NULL},
4319 {"schema", cmd_schema, "<schema>",complete_schema,0,NULL},
4320 {"elements", cmd_elements, "<elementSetName>",NULL,0,NULL},
4321 {"close", cmd_close, "",NULL,0,NULL},
4322 {"attributeset", cmd_attributeset, "<attrset>",complete_attributeset,0,NULL},
4323 {"querytype", cmd_querytype, "<type>",complete_querytype,0,NULL},
4324 {"refid", cmd_refid, "<id>",NULL,0,NULL},
4325 {"itemorder", cmd_itemorder, "ill|item <itemno>",NULL,0,NULL},
4326 {"update", cmd_update, "<action> <recid> [<doc>]",NULL,0,NULL},
4327 {"update0", cmd_update0, "<action> <recid> [<doc>]",NULL,0,NULL},
4328 {"xmles", cmd_xmles, "<OID> <doc>",NULL,0,NULL},
4329 {"packagename", cmd_packagename, "<packagename>",NULL,0,NULL},
4330 {"proxy", cmd_proxy, "[('tcp'|'ssl')]<host>[':'<port>]",NULL,0,NULL},
4331 {"charset", cmd_charset, "<nego_charset> <output_charset>",NULL,0,NULL},
4332 {"negcharset", cmd_negcharset, "<nego_charset>",NULL,0,NULL},
4333 {"displaycharset", cmd_displaycharset, "<output_charset>",NULL,0,NULL},
4334 {"marccharset", cmd_marccharset, "<charset_name>",NULL,0,NULL},
4335 {"lang", cmd_lang, "<language_code>",NULL,0,NULL},
4336 {".", cmd_source_echo, "<filename>",NULL,1,NULL},
4337 {"!", cmd_subshell, "Subshell command",NULL,1,NULL},
4338 {"set_apdufile", cmd_set_apdufile, "<filename>",NULL,1,NULL},
4339 {"set_berfile", cmd_set_berfile, "<filename>",NULL,1,NULL},
4340 {"set_marcdump", cmd_set_marcdump," <filename>",NULL,1,NULL},
4341 {"set_cclfile", cmd_set_cclfile," <filename>",NULL,1,NULL},
4342 {"set_cqlfile", cmd_set_cqlfile," <filename>",NULL,1,NULL},
4343 {"set_auto_reconnect", cmd_set_auto_reconnect," on|off",complete_auto_reconnect,1,NULL},
4344 {"set_auto_wait", cmd_set_auto_wait," on|off",complete_auto_reconnect,1,NULL},
4345 {"set_otherinfo", cmd_set_otherinfo,"<otherinfoinddex> <oid> <string>",NULL,0,NULL},
4346 {"sleep", cmd_sleep,"<seconds>",NULL,0,NULL},
4347 {"register_oid", cmd_register_oid,"<name> <class> <oid>",NULL,0,NULL},
4348 {"push_command", cmd_push_command,"<command>",command_generator,0,NULL},
4349 {"register_tab", cmd_register_tab,"<commandname> <tab>",command_generator,0,NULL},
4350 {"cclparse", cmd_cclparse,"<ccl find command>",NULL,0,NULL},
4351 {"list_otherinfo",cmd_list_otherinfo,"[otherinfoinddex]",NULL,0,NULL},
4352 {"list_all",cmd_list_all,"",NULL,0,NULL},
4353 {"clear_otherinfo",cmd_clear_otherinfo,"",NULL,0,NULL},
4354 {"wait_response",cmd_wait_response,"<number>",NULL,0,NULL},
4355 /* Server Admin Functions */
4356 {"adm-reindex", cmd_adm_reindex, "<database-name>",NULL,0,NULL},
4357 {"adm-truncate", cmd_adm_truncate, "('database'|'index')<object-name>",NULL,0,NULL},
4358 {"adm-create", cmd_adm_create, "",NULL,0,NULL},
4359 {"adm-drop", cmd_adm_drop, "('database'|'index')<object-name>",NULL,0,NULL},
4360 {"adm-import", cmd_adm_import, "<record-type> <dir> <pattern>",NULL,0,NULL},
4361 {"adm-refresh", cmd_adm_refresh, "",NULL,0,NULL},
4362 {"adm-commit", cmd_adm_commit, "",NULL,0,NULL},
4363 {"adm-shutdown", cmd_adm_shutdown, "",NULL,0,NULL},
4364 {"adm-startup", cmd_adm_startup, "",NULL,0,NULL},
4365 {"explain", cmd_explain, "", NULL, 0, NULL},
4366 {"options", cmd_options, "", NULL, 0, NULL},
4367 {"zversion", cmd_zversion, "", NULL, 0, NULL},
4368 {"help", cmd_help, "", NULL,0,NULL},
4369 {"init", cmd_init, "", NULL,0,NULL},
4370 {"exit", cmd_quit, "",NULL,0,NULL},
4374 static int cmd_help (const char *line)
4380 sscanf (line, "%20s", topic);
4383 printf("Commands:\n");
4384 for (i = 0; cmd_array[i].cmd; i++)
4385 if (*topic == 0 || strcmp (topic, cmd_array[i].cmd) == 0)
4386 printf(" %s %s\n", cmd_array[i].cmd, cmd_array[i].ad);
4387 if (!strcmp(topic, "find"))
4390 printf(" \"term\" Simple Term\n");
4391 printf(" @attr [attset] type=value op Attribute\n");
4392 printf(" @and opl opr And\n");
4393 printf(" @or opl opr Or\n");
4394 printf(" @not opl opr And-Not\n");
4395 printf(" @set set Result set\n");
4396 printf(" @prox exl dist ord rel uc ut Proximity. Use help prox\n");
4398 printf("Bib-1 attribute types\n");
4400 printf("4=Title 7=ISBN 8=ISSN 30=Date 62=Abstract 1003=Author 1016=Any\n");
4401 printf("2=Relation: ");
4402 printf("1< 2<= 3= 4>= 5> 6!= 102=Relevance\n");
4403 printf("3=Position: ");
4404 printf("1=First in Field 2=First in subfield 3=Any position\n");
4405 printf("4=Structure: ");
4406 printf("1=Phrase 2=Word 3=Key 4=Year 5=Date 6=WordList\n");
4407 printf("5=Truncation: ");
4408 printf("1=Right 2=Left 3=L&R 100=No 101=# 102=Re-1 103=Re-2\n");
4409 printf("6=Completeness:");
4410 printf("1=Incomplete subfield 2=Complete subfield 3=Complete field\n");
4412 if (!strcmp(topic, "prox"))
4414 printf("Proximity:\n");
4415 printf(" @prox exl dist ord rel uc ut\n");
4416 printf(" exl: exclude flag . 0=include, 1=exclude.\n");
4417 printf(" dist: distance integer.\n");
4418 printf(" ord: order flag. 0=unordered, 1=ordered.\n");
4419 printf(" rel: relation integer. 1< 2<= 3= 4>= 5> 6!= .\n");
4420 printf(" uc: unit class. k=known, p=private.\n");
4421 printf(" ut: unit type. 1=character, 2=word, 3=sentence,\n");
4422 printf(" 4=paragraph, 5=section, 6=chapter, 7=document,\n");
4423 printf(" 8=element, 9=subelement, 10=elementType, 11=byte.\n");
4424 printf("\nExamples:\n");
4425 printf(" Search for a and b in-order at most 3 words apart:\n");
4426 printf(" @prox 0 3 1 2 k 2 a b\n");
4427 printf(" Search for any order of a and b next to each other:\n");
4428 printf(" @prox 0 1 0 3 k 2 a b\n");
4433 int cmd_register_tab(const char* arg) {
4435 char command[101], tabargument[101];
4440 if (sscanf (arg, "%100s %100s", command, tabargument) < 1) {
4444 /* locate the amdn in the list */
4445 for (i = 0; cmd_array[i].cmd; i++) {
4446 if (!strncmp(cmd_array[i].cmd, command, strlen(command))) {
4451 if(!cmd_array[i].cmd) {
4452 fprintf(stderr,"Unknown command %s\n",command);
4457 if(!cmd_array[i].local_tabcompletes)
4458 cmd_array[i].local_tabcompletes = (char **) calloc(1,sizeof(char**));
4462 tabslist = cmd_array[i].local_tabcompletes;
4463 for(;tabslist && *tabslist;tabslist++) {
4467 cmd_array[i].local_tabcompletes = (char **)
4468 realloc(cmd_array[i].local_tabcompletes,(num_of_tabs+2)*sizeof(char**));
4469 tabslist=cmd_array[i].local_tabcompletes;
4470 tabslist[num_of_tabs]=strdup(tabargument);
4471 tabslist[num_of_tabs+1]=NULL;
4476 void process_cmd_line(char* line)
4479 char word[32], arg[10240];
4481 #if HAVE_GETTIMEOFDAY
4482 gettimeofday (&tv_start, 0);
4485 if ((res = sscanf(line, "%31s %10239[^;]", word, arg)) <= 0)
4487 strcpy(word, last_cmd);
4492 strcpy(last_cmd, word);
4494 /* removed tailing spaces from the arg command */
4497 char* lastnonspace=NULL;
4500 if(!isspace(*(unsigned char *) p)) {
4505 *(++lastnonspace) = 0;
4508 for (i = 0; cmd_array[i].cmd; i++)
4509 if (!strncmp(cmd_array[i].cmd, word, strlen(word)))
4511 res = (*cmd_array[i].fun)(arg);
4515 if (!cmd_array[i].cmd) /* dump our help-screen */
4517 printf("Unknown command: %s.\n", word);
4518 printf("Type 'help' for list of commands\n");
4522 if(apdu_file) fflush(apdu_file);
4524 if (res >= 2 && auto_wait)
4525 wait_and_handle_response(0);
4534 char *command_generator(const char *text, int state)
4540 for( ; cmd_array[idx].cmd; ++idx) {
4541 if (!strncmp(cmd_array[idx].cmd,text,strlen(text))) {
4542 ++idx; /* skip this entry on the next run */
4543 return strdup(cmd_array[idx-1].cmd);
4551 This function only known how to complete on the first word
4553 char ** readline_completer(char *text, int start, int end) {
4554 #if HAVE_READLINE_READLINE_H
4556 completerFunctionType completerToUse;
4559 #if HAVE_READLINE_RL_COMPLETION_MATCHES
4560 char** res=rl_completion_matches(text,
4563 char** res=completion_matches(text,
4564 (CPFunction*)command_generator);
4566 rl_attempted_completion_over = 1;
4569 char arg[10240],word[32];
4571 if ((res = sscanf(rl_line_buffer, "%31s %10239[^;]", word, arg)) <= 0) {
4572 rl_attempted_completion_over = 1;
4576 for (i = 0; cmd_array[i].cmd; i++) {
4577 if (!strncmp(cmd_array[i].cmd, word, strlen(word))) {
4582 if(!cmd_array[i].cmd) return NULL;
4584 curret_global_list = cmd_array[i].local_tabcompletes;
4586 completerToUse = cmd_array[i].rl_completerfunction;
4587 if(completerToUse==NULL) /* if no pr. command completer is defined use the default completer */
4588 completerToUse = default_completer;
4590 if(completerToUse) {
4591 #ifdef HAVE_READLINE_RL_COMPLETION_MATCHES
4593 rl_completion_matches(text,
4597 completion_matches(text,
4598 (CPFunction*)completerToUse);
4600 if(!cmd_array[i].complete_filenames)
4601 rl_attempted_completion_over = 1;
4604 if(!cmd_array[i].complete_filenames)
4605 rl_attempted_completion_over = 1;
4615 static void client(void)
4621 #if HAVE_GETTIMEOFDAY
4622 gettimeofday (&tv_start, 0);
4627 char *line_in = NULL;
4628 #if HAVE_READLINE_READLINE_H
4631 line_in=readline(C_PROMPT);
4634 #if HAVE_READLINE_HISTORY_H
4636 add_history(line_in);
4638 strncpy(line, line_in, 10239);
4647 if (!fgets(line, 10239, stdin))
4649 if ((end_p = strchr (line, '\n')))
4652 process_cmd_line(line);
4656 static void show_version(void)
4660 yaz_version(vstr, 0);
4661 printf ("YAZ version: %s\n", YAZ_VERSION);
4662 if (strcmp(vstr, YAZ_VERSION))
4663 printf ("YAZ DLL/SO: %s\n", vstr);
4667 int main(int argc, char **argv)
4670 char *open_command = 0;
4671 char *auth_command = 0;
4676 if (!setlocale(LC_CTYPE, ""))
4677 fprintf (stderr, "setlocale failed\n");
4681 codeset = nl_langinfo(CODESET);
4685 outputCharset = xstrdup(codeset);
4687 ODR_MASK_SET(&z3950_options, Z_Options_search);
4688 ODR_MASK_SET(&z3950_options, Z_Options_present);
4689 ODR_MASK_SET(&z3950_options, Z_Options_namedResultSets);
4690 ODR_MASK_SET(&z3950_options, Z_Options_triggerResourceCtrl);
4691 ODR_MASK_SET(&z3950_options, Z_Options_scan);
4692 ODR_MASK_SET(&z3950_options, Z_Options_sort);
4693 ODR_MASK_SET(&z3950_options, Z_Options_extendedServices);
4694 ODR_MASK_SET(&z3950_options, Z_Options_delSet);
4696 while ((ret = options("k:c:q:a:b:m:v:p:u:t:Vxd:", argv, argc, &arg)) != -2)
4703 open_command = (char *) xmalloc (strlen(arg)+6);
4704 strcpy (open_command, "open ");
4705 strcat (open_command, arg);
4709 fprintf(stderr, "%s: Specify at most one server address\n",
4715 dump_file_prefix = arg;
4718 kilobytes = atoi(arg);
4721 if (!(marc_file = fopen (arg, "a")))
4728 outputCharset = xstrdup(arg);
4731 strncpy (ccl_fields, arg, sizeof(ccl_fields)-1);
4732 ccl_fields[sizeof(ccl_fields)-1] = '\0';
4735 strncpy (cql_fields, arg, sizeof(cql_fields)-1);
4736 cql_fields[sizeof(cql_fields)-1] = '\0';
4739 if (!strcmp(arg, "-"))
4742 ber_file=fopen(arg, "a");
4745 if (!strcmp(arg, "-"))
4748 apdu_file=fopen(arg, "a");
4754 yazProxy = xstrdup(arg);
4759 auth_command = (char *) xmalloc (strlen(arg)+6);
4760 strcpy (auth_command, "auth ");
4761 strcat (auth_command, arg);
4765 yaz_log_init(yaz_log_mask_str(arg), "", 0);
4771 fprintf (stderr, "Usage: %s "
4778 " [-p <proxy-addr>]"
4782 " [<server-addr>]\n",
4790 #ifdef HAVE_GETTIMEOFDAY
4791 gettimeofday (&tv_start, 0);
4793 process_cmd_line (auth_command);
4794 #if HAVE_READLINE_HISTORY_H
4795 add_history(auth_command);
4797 xfree(auth_command);
4801 #ifdef HAVE_GETTIMEOFDAY
4802 gettimeofday (&tv_start, 0);
4804 process_cmd_line (open_command);
4805 #if HAVE_READLINE_HISTORY_H
4806 add_history(open_command);
4808 xfree(open_command);
4816 * indent-tabs-mode: nil
4818 * vim: shiftwidth=4 tabstop=8 expandtab