2 * Copyright (C) 1995-2007, Index Data ApS
3 * See the file LICENSE for details.
5 * $Id: client.c,v 1.328 2007-03-14 11:46:37 adam Exp $
8 * \brief yaz-client program
20 #include <sys/types.h>
38 #if HAVE_OPENSSL_SSL_H
39 #include <openssl/bio.h>
40 #include <openssl/crypto.h>
41 #include <openssl/x509.h>
42 #include <openssl/pem.h>
43 #include <openssl/ssl.h>
44 #include <openssl/err.h>
51 #define S_ISREG(x) (x & _S_IFREG)
52 #define S_ISDIR(x) (x & _S_IFDIR)
55 #include <yaz/yaz-util.h>
57 #include <yaz/comstack.h>
59 #include <yaz/proto.h>
60 #include <yaz/marcdisp.h>
61 #include <yaz/diagbib1.h>
62 #include <yaz/otherinfo.h>
63 #include <yaz/charneg.h>
65 #include <yaz/pquery.h>
66 #include <yaz/sortspec.h>
70 #include <yaz/yaz-ccl.h>
74 #if HAVE_READLINE_READLINE_H
75 #include <readline/readline.h>
77 #if HAVE_READLINE_HISTORY_H
78 #include <readline/history.h>
83 #include "tabcomplete.h"
86 #define C_PROMPT "Z> "
88 static file_history_t file_history = 0;
90 static char *sru_method = "soap";
91 static char *codeset = 0; /* character set for output */
92 static int hex_dump = 0;
93 static char *dump_file_prefix = 0;
94 static ODR out, in, print; /* encoding and decoding streams */
96 static ODR srw_sr_odr_out = 0;
97 static Z_SRW_PDU *srw_sr = 0;
99 static FILE *apdu_file = 0;
100 static FILE *ber_file = 0;
101 static COMSTACK conn = 0; /* our z-association */
102 static Z_IdAuthentication *auth = 0; /* our current auth definition */
103 char *databaseNames[128];
104 int num_databaseNames = 0;
105 static Z_External *record_last = 0;
106 static int setnumber = -1; /* current result set number */
107 static int smallSetUpperBound = 0;
108 static int largeSetLowerBound = 1;
109 static int mediumSetPresentNumber = 0;
110 static Z_ElementSetNames *elementSetNames = 0;
111 static int setno = 1; /* current set offset */
112 static enum oid_proto protocol = PROTO_Z3950; /* current app protocol */
113 #define RECORDSYNTAX_MAX 20
114 static enum oid_value recordsyntax_list[RECORDSYNTAX_MAX] = { VAL_USMARC };
115 static int recordsyntax_size = 1;
117 static char *record_schema = 0;
118 static int sent_close = 0;
119 static NMEM session_mem = NULL; /* memory handle for init-response */
120 static Z_InitResponse *session_initResponse = 0; /* session parameters */
121 static char last_scan_line[512] = "0";
122 static char last_scan_query[512] = "0";
123 static char ccl_fields[512] = "default.bib";
124 /* ### How can I set this path to use wherever YAZ is installed? */
125 static char cql_fields[512] = "/usr/local/share/yaz/etc/pqf.properties";
126 static char *esPackageName = 0;
127 static char *yazProxy = 0;
128 static int kilobytes = 1024;
129 static char *negotiationCharset = 0;
130 static int negotiationCharsetRecords = 1;
131 static int negotiationCharsetVersion = 3;
132 static char *outputCharset = 0;
133 static char *marcCharset = 0;
134 static char* yazLang = 0;
136 static char last_cmd[32] = "?";
137 static FILE *marc_file = 0;
138 static char *refid = NULL;
139 static char *last_open_command = NULL;
140 static int auto_reconnect = 0;
141 static int auto_wait = 1;
142 static Odr_bitmask z3950_options;
143 static int z3950_version = 3;
144 static int scan_stepSize = 0;
145 static int scan_position = 1;
146 static int scan_size = 20;
147 static char cur_host[200];
148 static int last_hit_count = 0;
158 static QueryType queryType = QueryType_Prefix;
160 static CCL_bibset bibset; /* CCL bibset handle */
161 static cql_transform_t cqltrans; /* CQL context-set handle */
163 #if HAVE_READLINE_COMPLETION_OVER
166 /* readline doesn't have this var. Define it ourselves. */
167 int rl_attempted_completion_over = 0;
170 /* set this one to 1, to avoid decode of unknown MARCs */
171 #define AVOID_MARC_DECODE 1
173 #define maxOtherInfosSupported 10
177 } extraOtherInfos[maxOtherInfosSupported];
180 void process_cmd_line(char* line);
181 #if HAVE_READLINE_READLINE_H
182 char **readline_completer(char *text, int start, int end);
184 static char *command_generator(const char *text, int state);
185 int cmd_register_tab(const char* arg);
187 static void close_session (void);
189 ODR getODROutputStream(void)
194 const char* query_type_as_string(QueryType q)
197 case QueryType_Prefix: return "prefix (RPN sent to server)";
198 case QueryType_CCL: return "CCL (CCL sent to server) ";
199 case QueryType_CCL2RPN: return "CCL -> RPN (RPN sent to server)";
200 case QueryType_CQL: return "CQL (CQL sent to server)";
201 case QueryType_CQL2RPN: return "CQL -> RPN (RPN sent to server)";
203 return "unknown Query type internal yaz-client error";
207 static void do_hex_dump(const char* buf, int len)
212 for( i=0; i<len ; i=i+16 )
215 for(x=0 ; i+x<len && x<16; ++x)
217 printf("%2.2X ",(unsigned int)((unsigned char)buf[i+x]));
222 if (dump_file_prefix)
225 if (++no < 1000 && strlen(dump_file_prefix) < 500)
229 sprintf (fname, "%s.%03d.raw", dump_file_prefix, no);
230 of = fopen(fname, "wb");
232 fwrite (buf, 1, len, of);
239 void add_otherInfos(Z_APDU *a)
241 Z_OtherInformation **oi;
245 for(i=0; i<maxOtherInfosSupported; ++i)
247 if(extraOtherInfos[i].oidval != -1)
248 yaz_oi_set_string_oidval(oi, out, extraOtherInfos[i].oidval,
249 1, extraOtherInfos[i].value);
253 int send_apdu(Z_APDU *a)
262 z_APDU(print, &a, 0, 0);
265 if (!z_APDU(out, &a, 0, 0))
267 odr_perror(out, "Encoding APDU");
271 buf = odr_getbuf(out, &len, 0);
273 odr_dumpBER(ber_file, buf, len);
274 /* printf ("sending APDU of size %d\n", len); */
275 do_hex_dump(buf, len);
276 if (cs_put(conn, buf, len) < 0)
278 fprintf(stderr, "cs_put: %s", cs_errmsg(cs_errno(conn)));
282 odr_reset(out); /* release the APDU structure */
286 static void print_stringn(const unsigned char *buf, size_t len)
289 for (i = 0; i<len; i++)
290 if ((buf[i] <= 126 && buf[i] >= 32) || strchr ("\n\r\t\f", buf[i]))
291 printf ("%c", buf[i]);
293 printf ("\\X%02X", buf[i]);
296 static void print_refid (Z_ReferenceId *id)
300 printf ("Reference Id: ");
301 print_stringn (id->buf, id->len);
306 static Z_ReferenceId *set_refid (ODR out)
311 id = (Z_ReferenceId *) odr_malloc (out, sizeof(*id));
312 id->size = id->len = strlen(refid);
313 id->buf = (unsigned char *) odr_malloc (out, id->len);
314 memcpy (id->buf, refid, id->len);
318 /* INIT SERVICE ------------------------------- */
320 static void send_initRequest(const char* type_and_host)
322 Z_APDU *apdu = zget_APDU(out, Z_APDU_initRequest);
323 Z_InitRequest *req = apdu->u.initRequest;
326 req->options = &z3950_options;
328 ODR_MASK_ZERO(req->protocolVersion);
329 for (i = 0; i<z3950_version; i++)
330 ODR_MASK_SET(req->protocolVersion, i);
332 *req->maximumRecordSize = 1024*kilobytes;
333 *req->preferredMessageSize = 1024*kilobytes;
335 req->idAuthentication = auth;
337 req->referenceId = set_refid (out);
339 if (yazProxy && type_and_host)
340 yaz_oi_set_string_oidval(&req->otherInfo, out, VAL_PROXY,
343 if (negotiationCharset || yazLang) {
344 Z_OtherInformation **p;
345 Z_OtherInformationUnit *p0;
347 yaz_oi_APDU(apdu, &p);
349 if ((p0=yaz_oi_update(p, out, NULL, 0, 0))) {
350 ODR_MASK_SET(req->options, Z_Options_negotiationModel);
352 p0->which = Z_OtherInfo_externallyDefinedInfo;
353 p0->information.externallyDefinedInfo =
354 yaz_set_proposal_charneg_list(out, ",",
357 negotiationCharsetRecords);
362 printf("Sent initrequest.\n");
366 /* These two are used only from process_initResponse() */
367 static void render_initUserInfo(Z_OtherInformation *ui1);
368 static void render_diag(Z_DiagnosticFormat *diag);
370 static void pr_opt(const char *opt, void *clientData)
375 static int process_initResponse(Z_InitResponse *res)
378 /* save session parameters for later use */
379 session_mem = odr_extract_mem(in);
380 session_initResponse = res;
382 for (ver = 0; ver < 8; ver++)
383 if (!ODR_MASK_GET(res->protocolVersion, ver))
387 printf("Connection rejected by v%d target.\n", ver);
389 printf("Connection accepted by v%d target.\n", ver);
390 if (res->implementationId)
391 printf("ID : %s\n", res->implementationId);
392 if (res->implementationName)
393 printf("Name : %s\n", res->implementationName);
394 if (res->implementationVersion)
395 printf("Version: %s\n", res->implementationVersion);
396 if (res->userInformationField)
398 Z_External *uif = res->userInformationField;
399 if (uif->which == Z_External_userInfo1) {
400 render_initUserInfo(uif->u.userInfo1);
402 printf("UserInformationfield:\n");
403 if (!z_External(print, (Z_External**)&uif, 0, 0))
405 odr_perror(print, "Printing userinfo\n");
408 if (uif->which == Z_External_octet) {
409 printf("Guessing visiblestring:\n");
410 printf("'%.*s'\n", uif->u.octet_aligned->len,
411 uif->u.octet_aligned->buf);
413 else if (uif->which == Z_External_single)
415 Odr_any *sat = uif->u.single_ASN1_type;
416 oident *oid = oid_getentbyoid(uif->direct_reference);
417 if (oid->value == VAL_OCLCUI) {
418 Z_OCLC_UserInformation *oclc_ui;
419 ODR decode = odr_createmem(ODR_DECODE);
420 odr_setbuf(decode, (char *) sat->buf, sat->len, 0);
421 if (!z_OCLC_UserInformation(decode, &oclc_ui, 0, 0))
422 printf ("Bad OCLC UserInformation:\n");
424 printf ("OCLC UserInformation:\n");
425 if (!z_OCLC_UserInformation(print, &oclc_ui, 0, 0))
426 printf ("Bad OCLC UserInformation spec\n");
431 /* Peek at any private Init-diagnostic APDUs */
432 printf("### NAUGHTY: External is '%.*s'\n",
440 yaz_init_opt_decode(res->options, pr_opt, 0);
443 if (ODR_MASK_GET(res->options, Z_Options_namedResultSets))
446 if (ODR_MASK_GET(res->options, Z_Options_negotiationModel)) {
448 Z_CharSetandLanguageNegotiation *p =
449 yaz_get_charneg_record(res->otherInfo);
453 char *charset=NULL, *lang=NULL;
456 yaz_get_response_charneg(session_mem, p, &charset, &lang,
459 if (outputCharset && negotiationCharset) {
460 odr_set_charset (out, charset, outputCharset);
461 odr_set_charset (in, outputCharset, charset);
464 odr_set_charset (out, 0, 0);
465 odr_set_charset (in, 0, 0);
468 printf("Accepted character set : %s\n", charset);
469 printf("Accepted code language : %s\n", lang ? lang : "none");
470 printf("Accepted records in ...: %d\n", selected );
478 static void render_initUserInfo(Z_OtherInformation *ui1) {
480 printf("Init response contains %d otherInfo unit%s:\n",
481 ui1->num_elements, ui1->num_elements == 1 ? "" : "s");
483 for (i = 0; i < ui1->num_elements; i++) {
484 Z_OtherInformationUnit *unit = ui1->list[i];
485 printf(" %d: otherInfo unit contains ", i+1);
486 if (unit->which == Z_OtherInfo_externallyDefinedInfo &&
487 unit->information.externallyDefinedInfo &&
488 unit->information.externallyDefinedInfo->which ==
490 render_diag(unit->information.externallyDefinedInfo->u.diag1);
492 else if (unit->which != Z_OtherInfo_externallyDefinedInfo)
494 printf("unsupported otherInfo unit->which = %d\n", unit->which);
498 printf("unsupported otherInfo unit external %d\n",
499 unit->information.externallyDefinedInfo ?
500 unit->information.externallyDefinedInfo->which : -2);
506 /* ### should this share code with display_diagrecs()? */
507 static void render_diag(Z_DiagnosticFormat *diag) {
510 printf("%d diagnostic%s:\n", diag->num, diag->num == 1 ? "" : "s");
511 for (i = 0; i < diag->num; i++) {
512 Z_DiagnosticFormat_s *ds = diag->elements[i];
513 printf(" %d: ", i+1);
515 case Z_DiagnosticFormat_s_defaultDiagRec: {
516 Z_DefaultDiagFormat *dd = ds->u.defaultDiagRec;
517 /* ### should check `dd->diagnosticSetId' */
518 printf("code=%d (%s)", *dd->condition,
519 diagbib1_str(*dd->condition));
520 /* Both types of addinfo are the same, so use type-pun */
521 if (dd->u.v2Addinfo != 0)
522 printf(",\n\taddinfo='%s'", dd->u.v2Addinfo);
525 case Z_DiagnosticFormat_s_explicitDiagnostic:
526 printf("Explicit diagnostic (not supported)");
529 printf("Unrecognised diagnostic type %d", ds->which);
533 if (ds->message != 0)
534 printf(", message='%s'", ds->message);
540 static int set_base(const char *arg)
545 for (i = 0; i<num_databaseNames; i++)
546 xfree (databaseNames[i]);
547 num_databaseNames = 0;
551 if (!(cp = strchr(arg, ' ')))
552 cp = arg + strlen(arg);
555 databaseNames[num_databaseNames] = (char *)xmalloc (1 + cp - arg);
556 memcpy (databaseNames[num_databaseNames], arg, cp - arg);
557 databaseNames[num_databaseNames][cp - arg] = '\0';
559 for (cp1 = databaseNames[num_databaseNames]; *cp1 ; cp1++)
568 if (num_databaseNames == 0)
570 num_databaseNames = 1;
571 databaseNames[0] = xstrdup("");
576 static int parse_cmd_doc(const char **arg, ODR out, char **buf,
580 while (**arg && strchr(" \t\n\r\f", **arg))
582 if ((*arg)[0] == '\"' && (sep=strchr(*arg+1, '"')))
586 *buf = odr_strdupn(out, *arg, *len);
590 else if ((*arg)[0] && (*arg)[0] != '\"')
594 const char *fname = *arg;
596 while (**arg != '\0' && **arg != ' ')
599 inf = fopen(fname, "rb");
602 printf("Couldn't open %s\n", fname);
605 if (fseek(inf, 0L, SEEK_END) == -1)
607 printf("Couldn't seek in %s\n", fname);
612 if (fseek(inf, 0L, SEEK_SET) == -1)
614 printf("Couldn't seek in %s\n", fname);
619 *buf = odr_malloc(out, fsize);
620 if (fread(*buf, 1, fsize, inf) != fsize)
622 printf("Unable to read %s\n", fname);
629 else if (**arg == '\0')
637 printf("Missing doc argument\n");
640 printf("Bad doc argument %s\n", *arg);
644 static int cmd_base(const char *arg)
648 printf("Usage: base <database> <database> ...\n");
651 return set_base(arg);
654 void cmd_open_remember_last_open_command(const char* arg, char* new_open_command)
656 if(last_open_command != arg)
658 if(last_open_command) xfree(last_open_command);
659 last_open_command = xstrdup(new_open_command);
663 int session_connect(const char *arg)
666 char type_and_host[101];
667 const char *basep = 0;
668 #if HAVE_OPENSSL_SSL_H
678 nmem_destroy (session_mem);
680 session_initResponse = 0;
682 cs_get_host_args(arg, &basep);
684 strncpy(type_and_host, arg, sizeof(type_and_host)-1);
685 type_and_host[sizeof(type_and_host)-1] = '\0';
687 cmd_open_remember_last_open_command(arg, type_and_host);
690 conn = cs_create_host(yazProxy, 1, &add);
692 conn = cs_create_host(arg, 1, &add);
695 printf ("Could not resolve address %s\n", arg);
699 if (conn->protocol == PROTO_HTTP)
700 queryType = QueryType_CQL;
702 if (conn->protocol == PROTO_HTTP)
704 printf ("SRW/HTTP not enabled in this YAZ\n");
710 protocol = conn->protocol;
711 if (conn->protocol == PROTO_HTTP)
715 printf("Connecting...");
717 if (cs_connect(conn, add) < 0)
719 printf ("error = %s\n", cs_strerror(conn));
725 #if HAVE_OPENSSL_SSL_H
726 if ((ssl = (SSL *) cs_get_ssl(conn)))
728 X509 *server_cert = SSL_get_peer_certificate (ssl);
734 BIO *bio = BIO_new(BIO_s_mem());
736 /* get PEM buffer in memory */
737 PEM_write_bio_X509(bio, server_cert);
738 pem_len = BIO_get_mem_data(bio, &pem_buf);
739 fwrite(pem_buf, pem_len, 1, stdout);
741 /* print all info on screen .. */
742 X509_print_fp(stdout, server_cert);
745 X509_free (server_cert);
751 if (protocol == PROTO_Z3950)
753 send_initRequest(type_and_host);
759 int cmd_open(const char *arg)
763 strncpy (cur_host, arg, sizeof(cur_host)-1);
764 cur_host[sizeof(cur_host)-1] = 0;
766 return session_connect(cur_host);
769 void try_reconnect(void)
773 if(!( auto_reconnect && last_open_command) ) return ;
775 open_command = (char *) xmalloc (strlen(last_open_command)+6);
776 strcpy (open_command, "open ");
778 strcat (open_command, last_open_command);
780 process_cmd_line(open_command);
785 int cmd_authentication(const char *arg)
787 static Z_IdAuthentication au;
788 static char user[40], group[40], pass[40];
789 static Z_IdPass idPass;
794 printf("Auth field set to null\n");
798 r = sscanf (arg, "%39s %39s %39s", user, group, pass);
801 printf("Authentication set to null\n");
807 if (!strcmp(user, "-")) {
808 au.which = Z_IdAuthentication_anonymous;
809 printf("Authentication set to Anonymous\n");
811 au.which = Z_IdAuthentication_open;
813 printf("Authentication set to Open (%s)\n", user);
819 au.which = Z_IdAuthentication_idPass;
820 au.u.idPass = &idPass;
821 idPass.groupId = NULL;
822 idPass.userId = user;
823 idPass.password = group;
824 printf("Authentication set to User (%s), Pass (%s)\n", user, group);
829 au.which = Z_IdAuthentication_idPass;
830 au.u.idPass = &idPass;
831 idPass.groupId = group;
832 idPass.userId = user;
833 idPass.password = pass;
834 printf("Authentication set to User (%s), Group (%s), Pass (%s)\n",
840 /* SEARCH SERVICE ------------------------------ */
841 static void display_record(Z_External *r);
843 static void print_record(const unsigned char *buf, size_t len)
846 print_stringn (buf, len);
847 /* add newline if not already added ... */
848 if (i <= 0 || buf[i-1] != '\n')
852 static void display_record(Z_External *r)
854 oident *ent = oid_getentbyoid(r->direct_reference);
858 * Tell the user what we got.
860 if (r->direct_reference)
862 printf("Record type: ");
864 printf("%s\n", ent->desc);
865 else if (!odr_oid(print, &r->direct_reference, 0, 0))
867 odr_perror(print, "print oid");
871 /* Check if this is a known, ASN.1 type tucked away in an octet string */
872 if (ent && r->which == Z_External_octet)
874 Z_ext_typeent *type = z_ext_getentbyref(ent->value);
880 * Call the given decoder to process the record.
882 odr_setbuf(in, (char*)r->u.octet_aligned->buf,
883 r->u.octet_aligned->len, 0);
884 if (!(*type->fun)(in, &rr, 0, 0))
886 odr_perror(in, "Decoding constructed record.");
887 fprintf(stdout, "[Near %ld]\n", (long) odr_offset(in));
888 fprintf(stdout, "Packet dump:\n---------\n");
889 odr_dumpBER(stdout, (char*)r->u.octet_aligned->buf,
890 r->u.octet_aligned->len);
891 fprintf(stdout, "---------\n");
893 /* note just ignores the error ant print the bytes form the octet_aligned later */
896 * Note: we throw away the original, BER-encoded record here.
897 * Do something else with it if you want to keep it.
899 r->u.sutrs = (Z_SUTRS *) rr; /* we don't actually check the type here. */
900 r->which = type->what;
904 if (ent && ent->value == VAL_SOIF)
906 print_record((const unsigned char *) r->u.octet_aligned->buf,
907 r->u.octet_aligned->len);
909 fwrite (r->u.octet_aligned->buf, 1, r->u.octet_aligned->len, marc_file);
911 else if (r->which == Z_External_octet)
913 const char *octet_buf = (char*)r->u.octet_aligned->buf;
914 if (ent->oclass == CLASS_RECSYN &&
915 (ent->value == VAL_TEXT_XML ||
916 ent->value == VAL_APPLICATION_XML ||
917 ent->value == VAL_HTML))
919 print_record((const unsigned char *) octet_buf,
920 r->u.octet_aligned->len);
922 else if (ent->value == VAL_POSTSCRIPT)
924 int size = r->u.octet_aligned->len;
927 print_record((const unsigned char *) octet_buf, size);
932 #if AVOID_MARC_DECODE
933 /* primitive check for a marc OID 5.1-29 except 16 */
934 ent->oidsuffix[0] == 5 && ent->oidsuffix[1] < 30 &&
935 ent->oidsuffix[1] != 16
944 yaz_marc_t mt = yaz_marc_create();
945 const char *from = 0;
947 if (marcCharset && !strcmp(marcCharset, "auto"))
949 if (ent->value == VAL_USMARC)
951 if (octet_buf[9] == 'a')
959 else if (marcCharset)
961 if (outputCharset && from)
963 cd = yaz_iconv_open(outputCharset, from);
964 printf ("convert from %s to %s", from,
967 printf (" unsupported\n");
970 yaz_marc_iconv(mt, cd);
975 if (yaz_marc_decode_buf(mt, octet_buf,r->u.octet_aligned->len,
978 fwrite (result, rlen, 1, stdout);
982 printf ("bad MARC. Dumping as it is:\n");
983 print_record((const unsigned char*) octet_buf,
984 r->u.octet_aligned->len);
986 yaz_marc_destroy(mt);
992 print_record((const unsigned char*) octet_buf,
993 r->u.octet_aligned->len);
997 fwrite (octet_buf, 1, r->u.octet_aligned->len, marc_file);
999 else if (ent && ent->value == VAL_SUTRS)
1001 if (r->which != Z_External_sutrs)
1003 printf("Expecting single SUTRS type for SUTRS.\n");
1006 print_record(r->u.sutrs->buf, r->u.sutrs->len);
1008 fwrite (r->u.sutrs->buf, 1, r->u.sutrs->len, marc_file);
1010 else if (ent && ent->value == VAL_GRS1)
1013 if (r->which != Z_External_grs1)
1015 printf("Expecting single GRS type for GRS.\n");
1019 yaz_display_grs1(w, r->u.grs1, 0);
1020 puts (wrbuf_buf(w));
1023 else if (ent && ent->value == VAL_OPAC)
1026 if (r->u.opac->bibliographicRecord)
1027 display_record(r->u.opac->bibliographicRecord);
1028 for (i = 0; i<r->u.opac->num_holdingsData; i++)
1030 Z_HoldingsRecord *h = r->u.opac->holdingsData[i];
1031 if (h->which == Z_HoldingsRecord_marcHoldingsRecord)
1033 printf ("MARC holdings %d\n", i);
1034 display_record(h->u.marcHoldingsRecord);
1036 else if (h->which == Z_HoldingsRecord_holdingsAndCirc)
1040 Z_HoldingsAndCircData *data = h->u.holdingsAndCirc;
1042 printf ("Data holdings %d\n", i);
1043 if (data->typeOfRecord)
1044 printf ("typeOfRecord: %s\n", data->typeOfRecord);
1045 if (data->encodingLevel)
1046 printf ("encodingLevel: %s\n", data->encodingLevel);
1047 if (data->receiptAcqStatus)
1048 printf ("receiptAcqStatus: %s\n", data->receiptAcqStatus);
1049 if (data->generalRetention)
1050 printf ("generalRetention: %s\n", data->generalRetention);
1051 if (data->completeness)
1052 printf ("completeness: %s\n", data->completeness);
1053 if (data->dateOfReport)
1054 printf ("dateOfReport: %s\n", data->dateOfReport);
1056 printf ("nucCode: %s\n", data->nucCode);
1057 if (data->localLocation)
1058 printf ("localLocation: %s\n", data->localLocation);
1059 if (data->shelvingLocation)
1060 printf ("shelvingLocation: %s\n", data->shelvingLocation);
1061 if (data->callNumber)
1062 printf ("callNumber: %s\n", data->callNumber);
1063 if (data->shelvingData)
1064 printf ("shelvingData: %s\n", data->shelvingData);
1065 if (data->copyNumber)
1066 printf ("copyNumber: %s\n", data->copyNumber);
1067 if (data->publicNote)
1068 printf ("publicNote: %s\n", data->publicNote);
1069 if (data->reproductionNote)
1070 printf ("reproductionNote: %s\n", data->reproductionNote);
1071 if (data->termsUseRepro)
1072 printf ("termsUseRepro: %s\n", data->termsUseRepro);
1073 if (data->enumAndChron)
1074 printf ("enumAndChron: %s\n", data->enumAndChron);
1075 for (j = 0; j<data->num_volumes; j++)
1077 printf ("volume %d\n", j);
1078 if (data->volumes[j]->enumeration)
1079 printf (" enumeration: %s\n",
1080 data->volumes[j]->enumeration);
1081 if (data->volumes[j]->chronology)
1082 printf (" chronology: %s\n",
1083 data->volumes[j]->chronology);
1084 if (data->volumes[j]->enumAndChron)
1085 printf (" enumAndChron: %s\n",
1086 data->volumes[j]->enumAndChron);
1088 for (j = 0; j<data->num_circulationData; j++)
1090 printf ("circulation %d\n", j);
1091 if (data->circulationData[j]->availableNow)
1092 printf (" availableNow: %d\n",
1093 *data->circulationData[j]->availableNow);
1094 if (data->circulationData[j]->availablityDate)
1095 printf (" availabiltyDate: %s\n",
1096 data->circulationData[j]->availablityDate);
1097 if (data->circulationData[j]->availableThru)
1098 printf (" availableThru: %s\n",
1099 data->circulationData[j]->availableThru);
1100 if (data->circulationData[j]->restrictions)
1101 printf (" restrictions: %s\n",
1102 data->circulationData[j]->restrictions);
1103 if (data->circulationData[j]->itemId)
1104 printf (" itemId: %s\n",
1105 data->circulationData[j]->itemId);
1106 if (data->circulationData[j]->renewable)
1107 printf (" renewable: %d\n",
1108 *data->circulationData[j]->renewable);
1109 if (data->circulationData[j]->onHold)
1110 printf (" onHold: %d\n",
1111 *data->circulationData[j]->onHold);
1112 if (data->circulationData[j]->enumAndChron)
1113 printf (" enumAndChron: %s\n",
1114 data->circulationData[j]->enumAndChron);
1115 if (data->circulationData[j]->midspine)
1116 printf (" midspine: %s\n",
1117 data->circulationData[j]->midspine);
1118 if (data->circulationData[j]->temporaryLocation)
1119 printf (" temporaryLocation: %s\n",
1120 data->circulationData[j]->temporaryLocation);
1127 printf("Unknown record representation.\n");
1128 if (!z_External(print, &r, 0, 0))
1130 odr_perror(print, "Printing external");
1136 static void display_diagrecs(Z_DiagRec **pp, int num)
1140 Z_DefaultDiagFormat *r;
1142 printf("Diagnostic message(s) from database:\n");
1143 for (i = 0; i<num; i++)
1145 Z_DiagRec *p = pp[i];
1146 if (p->which != Z_DiagRec_defaultFormat)
1148 printf("Diagnostic record not in default format.\n");
1152 r = p->u.defaultFormat;
1153 if (!(ent = oid_getentbyoid(r->diagnosticSetId)) ||
1154 ent->oclass != CLASS_DIAGSET || ent->value != VAL_BIB1)
1155 printf("Missing or unknown diagset\n");
1156 printf(" [%d] %s", *r->condition, diagbib1_str(*r->condition));
1159 case Z_DefaultDiagFormat_v2Addinfo:
1160 printf (" -- v2 addinfo '%s'\n", r->u.v2Addinfo);
1162 case Z_DefaultDiagFormat_v3Addinfo:
1163 printf (" -- v3 addinfo '%s'\n", r->u.v3Addinfo);
1170 static void display_nameplusrecord(Z_NamePlusRecord *p)
1172 if (p->databaseName)
1173 printf("[%s]", p->databaseName);
1174 if (p->which == Z_NamePlusRecord_surrogateDiagnostic)
1175 display_diagrecs(&p->u.surrogateDiagnostic, 1);
1176 else if (p->which == Z_NamePlusRecord_databaseRecord)
1177 display_record(p->u.databaseRecord);
1180 static void display_records(Z_Records *p)
1184 if (p->which == Z_Records_NSD)
1186 Z_DiagRec dr, *dr_p = &dr;
1187 dr.which = Z_DiagRec_defaultFormat;
1188 dr.u.defaultFormat = p->u.nonSurrogateDiagnostic;
1189 display_diagrecs (&dr_p, 1);
1191 else if (p->which == Z_Records_multipleNSD)
1192 display_diagrecs (p->u.multipleNonSurDiagnostics->diagRecs,
1193 p->u.multipleNonSurDiagnostics->num_diagRecs);
1196 printf("Records: %d\n", p->u.databaseOrSurDiagnostics->num_records);
1197 for (i = 0; i < p->u.databaseOrSurDiagnostics->num_records; i++)
1198 display_nameplusrecord(p->u.databaseOrSurDiagnostics->records[i]);
1202 static int send_deleteResultSetRequest(const char *arg)
1207 Z_APDU *apdu = zget_APDU(out, Z_APDU_deleteResultSetRequest);
1208 Z_DeleteResultSetRequest *req = apdu->u.deleteResultSetRequest;
1210 req->referenceId = set_refid (out);
1212 req->num_resultSetList =
1213 sscanf (arg, "%30s %30s %30s %30s %30s %30s %30s %30s",
1214 names[0], names[1], names[2], names[3],
1215 names[4], names[5], names[6], names[7]);
1217 req->deleteFunction = (int *)
1218 odr_malloc (out, sizeof(*req->deleteFunction));
1219 if (req->num_resultSetList > 0)
1221 *req->deleteFunction = Z_DeleteResultSetRequest_list;
1222 req->resultSetList = (char **)
1223 odr_malloc (out, sizeof(*req->resultSetList)*
1224 req->num_resultSetList);
1225 for (i = 0; i<req->num_resultSetList; i++)
1226 req->resultSetList[i] = names[i];
1230 *req->deleteFunction = Z_DeleteResultSetRequest_all;
1231 req->resultSetList = 0;
1235 printf("Sent deleteResultSetRequest.\n");
1240 static int send_srw(Z_SRW_PDU *sr)
1242 const char *charset = negotiationCharset;
1243 const char *host_port = cur_host;
1247 path = odr_malloc(out, 2+strlen(databaseNames[0]));
1249 strcpy(path+1, databaseNames[0]);
1251 gdu = z_get_HTTP_Request_host_path(out, host_port, path);
1253 if (!strcmp(sru_method, "get"))
1255 yaz_sru_get_encode(gdu->u.HTTP_Request, sr, out, charset);
1257 else if (!strcmp(sru_method, "post"))
1259 yaz_sru_post_encode(gdu->u.HTTP_Request, sr, out, charset);
1261 else if (!strcmp(sru_method, "soap"))
1263 yaz_sru_soap_encode(gdu->u.HTTP_Request, sr, out, charset);
1266 if (z_GDU(out, &gdu, 0, 0))
1274 if (!z_GDU(print, &gdu, 0, 0))
1275 printf ("Failed to print outgoing SRU package\n");
1278 buf_out = odr_getbuf(out, &len_out, 0);
1280 /* we don't odr_reset(out), since we may need the buffer again */
1282 do_hex_dump(buf_out, len_out);
1284 r = cs_put(conn, buf_out, len_out);
1294 static char *encode_SRW_term(ODR o, const char *q)
1296 const char *in_charset = "ISO-8859-1";
1297 WRBUF w = wrbuf_alloc();
1301 in_charset = outputCharset;
1302 cd = yaz_iconv_open("UTF-8", in_charset);
1306 return odr_strdup(o, q);
1308 wrbuf_iconv_write(w, cd, q, strlen(q));
1311 int len = wrbuf_len(w);
1312 res = odr_strdupn(o, wrbuf_buf(w), len);
1315 res = odr_strdup(o, q);
1316 yaz_iconv_close(cd);
1322 static int send_SRW_scanRequest(const char *arg, int pos, int num)
1326 /* regular requestse .. */
1327 sr = yaz_srw_get(out, Z_SRW_scan_request);
1332 sr->u.scan_request->query_type = Z_SRW_query_type_cql;
1333 sr->u.scan_request->scanClause.cql = encode_SRW_term(out, arg);
1335 case QueryType_Prefix:
1336 sr->u.scan_request->query_type = Z_SRW_query_type_pqf;
1337 sr->u.scan_request->scanClause.pqf = encode_SRW_term(out, arg);
1340 printf ("Only CQL and PQF supported in SRW\n");
1343 sr->u.scan_request->responsePosition = odr_intdup(out, pos);
1344 sr->u.scan_request->maximumTerms = odr_intdup(out, num);
1345 return send_srw(sr);
1348 static int send_SRW_searchRequest(const char *arg)
1354 assert(srw_sr_odr_out == 0);
1355 srw_sr_odr_out = odr_createmem(ODR_ENCODE);
1357 odr_reset(srw_sr_odr_out);
1361 /* save this for later .. when fetching individual records */
1362 srw_sr = yaz_srw_get(srw_sr_odr_out, Z_SRW_searchRetrieve_request);
1364 /* regular request .. */
1365 sr = yaz_srw_get(out, Z_SRW_searchRetrieve_request);
1370 srw_sr->u.request->query_type = Z_SRW_query_type_cql;
1371 srw_sr->u.request->query.cql = encode_SRW_term(srw_sr_odr_out, arg);
1373 sr->u.request->query_type = Z_SRW_query_type_cql;
1374 sr->u.request->query.cql = encode_SRW_term(srw_sr_odr_out, arg);
1376 case QueryType_Prefix:
1377 srw_sr->u.request->query_type = Z_SRW_query_type_pqf;
1378 srw_sr->u.request->query.pqf = encode_SRW_term(srw_sr_odr_out, arg);
1380 sr->u.request->query_type = Z_SRW_query_type_pqf;
1381 sr->u.request->query.pqf = encode_SRW_term(srw_sr_odr_out, arg);
1384 printf ("Only CQL and PQF supported in SRW\n");
1387 sr->u.request->maximumRecords = odr_intdup(out, 0);
1390 sr->u.request->recordSchema = record_schema;
1391 if (recordsyntax_size == 1 && recordsyntax_list[0] == VAL_TEXT_XML)
1392 sr->u.request->recordPacking = "xml";
1393 return send_srw(sr);
1397 static int send_searchRequest(const char *arg)
1399 Z_APDU *apdu = zget_APDU(out, Z_APDU_searchRequest);
1400 Z_SearchRequest *req = apdu->u.searchRequest;
1402 struct ccl_rpn_node *rpn = NULL;
1404 char setstring[100];
1405 Z_RPNQuery *RPNquery;
1407 YAZ_PQF_Parser pqf_parser;
1409 QueryType myQueryType = queryType;
1412 if (myQueryType == QueryType_CCL2RPN)
1414 rpn = ccl_find_str(bibset, arg, &error, &pos);
1417 printf("CCL ERROR: %s\n", ccl_err_msg(error));
1420 } else if (myQueryType == QueryType_CQL2RPN) {
1421 /* ### All this code should be wrapped in a utility function */
1423 struct cql_node *node;
1424 const char *addinfo;
1425 if (cqltrans == 0) {
1426 printf("Can't use CQL: no translation file. Try set_cqlfile\n");
1429 parser = cql_parser_create();
1430 if ((error = cql_parser_string(parser, arg)) != 0) {
1431 printf("Can't parse CQL: must be a syntax error\n");
1434 node = cql_parser_result(parser);
1435 if ((error = cql_transform_buf(cqltrans, node, pqfbuf,
1436 sizeof pqfbuf)) != 0) {
1437 error = cql_transform_error(cqltrans, &addinfo);
1438 printf ("Can't convert CQL to PQF: %s (addinfo=%s)\n",
1439 cql_strerror(error), addinfo);
1443 myQueryType = QueryType_Prefix;
1446 req->referenceId = set_refid (out);
1447 if (!strcmp(arg, "@big")) /* strictly for troublemaking */
1449 static unsigned char big[2100];
1450 static Odr_oct bigo;
1452 /* send a very big referenceid to test transport stack etc. */
1453 memset(big, 'A', 2100);
1454 bigo.len = bigo.size = 2100;
1456 req->referenceId = &bigo;
1461 sprintf(setstring, "%d", ++setnumber);
1462 req->resultSetName = setstring;
1464 *req->smallSetUpperBound = smallSetUpperBound;
1465 *req->largeSetLowerBound = largeSetLowerBound;
1466 *req->mediumSetPresentNumber = mediumSetPresentNumber;
1467 if (smallSetUpperBound > 0 || (largeSetLowerBound > 1 &&
1468 mediumSetPresentNumber > 0))
1470 if (recordsyntax_size > 0)
1471 req->preferredRecordSyntax =
1472 yaz_oidval_to_z3950oid(out, CLASS_RECSYN, recordsyntax_list[0]);
1473 req->smallSetElementSetNames =
1474 req->mediumSetElementSetNames = elementSetNames;
1476 req->num_databaseNames = num_databaseNames;
1477 req->databaseNames = databaseNames;
1479 req->query = &query;
1481 switch (myQueryType)
1483 case QueryType_Prefix:
1484 query.which = Z_Query_type_1;
1485 pqf_parser = yaz_pqf_create ();
1486 RPNquery = yaz_pqf_parse (pqf_parser, out, arg);
1489 const char *pqf_msg;
1491 int code = yaz_pqf_error (pqf_parser, &pqf_msg, &off);
1493 printf("%*s^\n", ioff+4, "");
1494 printf("Prefix query error: %s (code %d)\n", pqf_msg, code);
1496 yaz_pqf_destroy (pqf_parser);
1499 yaz_pqf_destroy (pqf_parser);
1500 query.u.type_1 = RPNquery;
1503 query.which = Z_Query_type_2;
1504 query.u.type_2 = &ccl_query;
1505 ccl_query.buf = (unsigned char*) arg;
1506 ccl_query.len = strlen(arg);
1508 case QueryType_CCL2RPN:
1509 query.which = Z_Query_type_1;
1510 RPNquery = ccl_rpn_query(out, rpn);
1513 printf ("Couldn't convert from CCL to RPN\n");
1516 query.u.type_1 = RPNquery;
1517 ccl_rpn_delete (rpn);
1520 query.which = Z_Query_type_104;
1521 ext = (Z_External *) odr_malloc(out, sizeof(*ext));
1522 ext->direct_reference = odr_getoidbystr(out, "1.2.840.10003.16.2");
1523 ext->indirect_reference = 0;
1524 ext->descriptor = 0;
1525 ext->which = Z_External_CQL;
1526 ext->u.cql = odr_strdup(out, arg);
1527 query.u.type_104 = ext;
1530 printf ("Unsupported query type\n");
1533 if (send_apdu(apdu))
1534 printf("Sent searchRequest.\n");
1539 /* display Query Expression as part of searchResult-1 */
1540 static void display_queryExpression (const char *lead, Z_QueryExpression *qe)
1544 printf(" %s=", lead);
1545 if (qe->which == Z_QueryExpression_term)
1547 if (qe->u.term->queryTerm)
1549 Z_Term *term = qe->u.term->queryTerm;
1550 switch (term->which)
1552 case Z_Term_general:
1553 printf ("%.*s", term->u.general->len, term->u.general->buf);
1555 case Z_Term_characterString:
1556 printf ("%s", term->u.characterString);
1558 case Z_Term_numeric:
1559 printf ("%d", *term->u.numeric);
1569 /* see if we can find USR:SearchResult-1 */
1570 static void display_searchResult (Z_OtherInformation *o)
1575 for (i = 0; i < o->num_elements; i++)
1577 if (o->list[i]->which == Z_OtherInfo_externallyDefinedInfo)
1579 Z_External *ext = o->list[i]->information.externallyDefinedInfo;
1581 if (ext->which == Z_External_searchResult1)
1584 Z_SearchInfoReport *sr = ext->u.searchResult1;
1585 printf ("SearchResult-1:");
1586 for (j = 0; j < sr->num; j++)
1590 if (!sr->elements[j]->subqueryExpression)
1592 display_queryExpression("term",
1593 sr->elements[j]->subqueryExpression);
1594 display_queryExpression("interpretation",
1595 sr->elements[j]->subqueryInterpretation);
1596 display_queryExpression("recommendation",
1597 sr->elements[j]->subqueryRecommendation);
1598 if (sr->elements[j]->subqueryCount)
1599 printf(" cnt=%d", *sr->elements[j]->subqueryCount);
1600 if (sr->elements[j]->subqueryId)
1601 printf(" id=%s ", sr->elements[j]->subqueryId);
1609 static int process_searchResponse(Z_SearchResponse *res)
1611 printf ("Received SearchResponse.\n");
1612 print_refid (res->referenceId);
1613 if (*res->searchStatus)
1614 printf("Search was a success.\n");
1616 printf("Search was a bloomin' failure.\n");
1617 printf("Number of hits: %d", *res->resultCount);
1618 last_hit_count = *res->resultCount;
1620 printf (", setno %d", setnumber);
1622 if (res->resultSetStatus)
1624 printf("Result Set Status: ");
1625 switch(*res->resultSetStatus)
1627 case Z_SearchResponse_subset:
1628 printf("subset"); break;
1629 case Z_SearchResponse_interim:
1630 printf("interim"); break;
1631 case Z_SearchResponse_none:
1632 printf("none"); break;
1633 case Z_SearchResponse_estimate:
1634 printf("estimate"); break;
1636 printf("%d", *res->resultSetStatus);
1640 display_searchResult (res->additionalSearchInfo);
1641 printf("records returned: %d\n",
1642 *res->numberOfRecordsReturned);
1643 setno += *res->numberOfRecordsReturned;
1645 display_records(res->records);
1649 static void print_level(int iLevel)
1652 for (i = 0; i < iLevel * 4; i++)
1656 static void print_int(int iLevel, const char *pTag, int *pInt)
1660 print_level(iLevel);
1661 printf("%s: %d\n", pTag, *pInt);
1665 static void print_string(int iLevel, const char *pTag, const char *pString)
1667 if (pString != NULL)
1669 print_level(iLevel);
1670 printf("%s: %s\n", pTag, pString);
1674 static void print_oid(int iLevel, const char *pTag, Odr_oid *pOid)
1680 print_level(iLevel);
1681 printf("%s:", pTag);
1682 for (; *pInt != -1; pInt++)
1683 printf(" %d", *pInt);
1688 static void print_referenceId(int iLevel, Z_ReferenceId *referenceId)
1690 if (referenceId != NULL)
1694 print_level(iLevel);
1695 printf("Ref Id (%d, %d): ", referenceId->len, referenceId->size);
1696 for (i = 0; i < referenceId->len; i++)
1697 printf("%c", referenceId->buf[i]);
1702 static void print_string_or_numeric(int iLevel, const char *pTag, Z_StringOrNumeric *pStringNumeric)
1704 if (pStringNumeric != NULL)
1706 switch (pStringNumeric->which)
1708 case Z_StringOrNumeric_string:
1709 print_string(iLevel, pTag, pStringNumeric->u.string);
1712 case Z_StringOrNumeric_numeric:
1713 print_int(iLevel, pTag, pStringNumeric->u.numeric);
1717 print_level(iLevel);
1718 printf("%s: valid type for Z_StringOrNumeric\n", pTag);
1724 static void print_universe_report_duplicate(
1726 Z_UniverseReportDuplicate *pUniverseReportDuplicate)
1728 if (pUniverseReportDuplicate != NULL)
1730 print_level(iLevel);
1731 printf("Universe Report Duplicate: \n");
1733 print_string_or_numeric(iLevel, "Hit No",
1734 pUniverseReportDuplicate->hitno);
1738 static void print_universe_report_hits(
1740 Z_UniverseReportHits *pUniverseReportHits)
1742 if (pUniverseReportHits != NULL)
1744 print_level(iLevel);
1745 printf("Universe Report Hits: \n");
1747 print_string_or_numeric(iLevel, "Database",
1748 pUniverseReportHits->database);
1749 print_string_or_numeric(iLevel, "Hits", pUniverseReportHits->hits);
1753 static void print_universe_report(int iLevel, Z_UniverseReport *pUniverseReport)
1755 if (pUniverseReport != NULL)
1757 print_level(iLevel);
1758 printf("Universe Report: \n");
1760 print_int(iLevel, "Total Hits", pUniverseReport->totalHits);
1761 switch (pUniverseReport->which)
1763 case Z_UniverseReport_databaseHits:
1764 print_universe_report_hits(iLevel,
1765 pUniverseReport->u.databaseHits);
1768 case Z_UniverseReport_duplicate:
1769 print_universe_report_duplicate(iLevel,
1770 pUniverseReport->u.duplicate);
1774 print_level(iLevel);
1775 printf("Type: %d\n", pUniverseReport->which);
1781 static void print_external(int iLevel, Z_External *pExternal)
1783 if (pExternal != NULL)
1785 print_level(iLevel);
1786 printf("External: \n");
1788 print_oid(iLevel, "Direct Reference", pExternal->direct_reference);
1789 print_int(iLevel, "InDirect Reference", pExternal->indirect_reference);
1790 print_string(iLevel, "Descriptor", pExternal->descriptor);
1791 switch (pExternal->which)
1793 case Z_External_universeReport:
1794 print_universe_report(iLevel, pExternal->u.universeReport);
1798 print_level(iLevel);
1799 printf("Type: %d\n", pExternal->which);
1805 static int process_resourceControlRequest (Z_ResourceControlRequest *req)
1807 printf ("Received ResourceControlRequest.\n");
1808 print_referenceId(1, req->referenceId);
1809 print_int(1, "Suspended Flag", req->suspendedFlag);
1810 print_int(1, "Partial Results Available", req->partialResultsAvailable);
1811 print_int(1, "Response Required", req->responseRequired);
1812 print_int(1, "Triggered Request Flag", req->triggeredRequestFlag);
1813 print_external(1, req->resourceReport);
1817 void process_ESResponse(Z_ExtendedServicesResponse *res)
1820 switch (*res->operationStatus)
1822 case Z_ExtendedServicesResponse_done:
1825 case Z_ExtendedServicesResponse_accepted:
1826 printf ("accepted\n");
1828 case Z_ExtendedServicesResponse_failure:
1829 printf ("failure\n");
1830 display_diagrecs(res->diagnostics, res->num_diagnostics);
1833 printf ("unknown\n");
1835 if ( (*res->operationStatus != Z_ExtendedServicesResponse_failure) &&
1836 (res->num_diagnostics != 0) ) {
1837 display_diagrecs(res->diagnostics, res->num_diagnostics);
1839 print_refid (res->referenceId);
1840 if (res->taskPackage &&
1841 res->taskPackage->which == Z_External_extendedService)
1843 Z_TaskPackage *taskPackage = res->taskPackage->u.extendedService;
1844 Odr_oct *id = taskPackage->targetReference;
1845 Z_External *ext = taskPackage->taskSpecificParameters;
1849 printf ("Target Reference: ");
1850 print_stringn (id->buf, id->len);
1853 if (ext->which == Z_External_update)
1855 Z_IUUpdateTaskPackage *utp = ext->u.update->u.taskPackage;
1856 if (utp && utp->targetPart)
1858 Z_IUTargetPart *targetPart = utp->targetPart;
1861 for (i = 0; i<targetPart->num_taskPackageRecords; i++)
1864 Z_IUTaskPackageRecordStructure *tpr =
1865 targetPart->taskPackageRecords[i];
1866 printf ("task package record %d\n", i+1);
1867 if (tpr->which == Z_IUTaskPackageRecordStructure_record)
1869 display_record (tpr->u.record);
1873 printf ("other type\n");
1879 if (res->taskPackage && res->taskPackage->which == Z_External_octet)
1881 Odr_oct *doc = res->taskPackage->u.octet_aligned;
1882 printf("%.*s\n", doc->len, doc->buf);
1886 const char *get_ill_element (void *clientData, const char *element)
1891 static Z_External *create_external_itemRequest(void)
1893 struct ill_get_ctl ctl;
1894 ILL_ItemRequest *req;
1896 int item_request_size = 0;
1897 char *item_request_buf = 0;
1901 ctl.f = get_ill_element;
1903 req = ill_get_ItemRequest(&ctl, "ill", 0);
1905 printf ("ill_get_ItemRequest failed\n");
1907 if (!ill_ItemRequest (out, &req, 0, 0))
1911 ill_ItemRequest(print, &req, 0, 0);
1914 item_request_buf = odr_getbuf (out, &item_request_size, 0);
1915 if (item_request_buf)
1916 odr_setbuf (out, item_request_buf, item_request_size, 1);
1917 printf ("Couldn't encode ItemRequest, size %d\n", item_request_size);
1924 item_request_buf = odr_getbuf (out, &item_request_size, 0);
1925 oid.proto = PROTO_GENERAL;
1926 oid.oclass = CLASS_GENERAL;
1927 oid.value = VAL_ISO_ILL_1;
1929 r = (Z_External *) odr_malloc (out, sizeof(*r));
1930 r->direct_reference = odr_oiddup(out,oid_getoidbyent(&oid));
1931 r->indirect_reference = 0;
1933 r->which = Z_External_single;
1935 r->u.single_ASN1_type = (Odr_oct *)
1936 odr_malloc (out, sizeof(*r->u.single_ASN1_type));
1937 r->u.single_ASN1_type->buf = (unsigned char *)
1938 odr_malloc (out, item_request_size);
1939 r->u.single_ASN1_type->len = item_request_size;
1940 r->u.single_ASN1_type->size = item_request_size;
1941 memcpy (r->u.single_ASN1_type->buf, item_request_buf,
1944 do_hex_dump(item_request_buf,item_request_size);
1949 static Z_External *create_external_ILL_APDU(int which)
1951 struct ill_get_ctl ctl;
1954 int ill_request_size = 0;
1955 char *ill_request_buf = 0;
1959 ctl.f = get_ill_element;
1961 ill_apdu = ill_get_APDU(&ctl, "ill", 0);
1963 if (!ill_APDU (out, &ill_apdu, 0, 0))
1967 printf ("-------------------\n");
1968 ill_APDU(print, &ill_apdu, 0, 0);
1970 printf ("-------------------\n");
1972 ill_request_buf = odr_getbuf (out, &ill_request_size, 0);
1973 if (ill_request_buf)
1974 odr_setbuf (out, ill_request_buf, ill_request_size, 1);
1975 printf ("Couldn't encode ILL-Request, size %d\n", ill_request_size);
1981 ill_request_buf = odr_getbuf (out, &ill_request_size, 0);
1983 oid.proto = PROTO_GENERAL;
1984 oid.oclass = CLASS_GENERAL;
1985 oid.value = VAL_ISO_ILL_1;
1987 r = (Z_External *) odr_malloc (out, sizeof(*r));
1988 r->direct_reference = odr_oiddup(out,oid_getoidbyent(&oid));
1989 r->indirect_reference = 0;
1991 r->which = Z_External_single;
1993 r->u.single_ASN1_type = (Odr_oct *)
1994 odr_malloc (out, sizeof(*r->u.single_ASN1_type));
1995 r->u.single_ASN1_type->buf = (unsigned char *)
1996 odr_malloc (out, ill_request_size);
1997 r->u.single_ASN1_type->len = ill_request_size;
1998 r->u.single_ASN1_type->size = ill_request_size;
1999 memcpy (r->u.single_ASN1_type->buf, ill_request_buf, ill_request_size);
2000 /* printf ("len = %d\n", ill_request_size); */
2001 /* do_hex_dump(ill_request_buf,ill_request_size); */
2002 /* printf("--- end of extenal\n"); */
2009 static Z_External *create_ItemOrderExternal(const char *type, int itemno)
2011 Z_External *r = (Z_External *) odr_malloc(out, sizeof(Z_External));
2012 oident ItemOrderRequest;
2014 ItemOrderRequest.proto = PROTO_Z3950;
2015 ItemOrderRequest.oclass = CLASS_EXTSERV;
2016 ItemOrderRequest.value = VAL_ITEMORDER;
2018 r->direct_reference = odr_oiddup(out,oid_getoidbyent(&ItemOrderRequest));
2019 r->indirect_reference = 0;
2022 r->which = Z_External_itemOrder;
2024 r->u.itemOrder = (Z_ItemOrder *) odr_malloc(out,sizeof(Z_ItemOrder));
2025 memset(r->u.itemOrder, 0, sizeof(Z_ItemOrder));
2026 r->u.itemOrder->which=Z_IOItemOrder_esRequest;
2028 r->u.itemOrder->u.esRequest = (Z_IORequest *)
2029 odr_malloc(out,sizeof(Z_IORequest));
2030 memset(r->u.itemOrder->u.esRequest, 0, sizeof(Z_IORequest));
2032 r->u.itemOrder->u.esRequest->toKeep = (Z_IOOriginPartToKeep *)
2033 odr_malloc(out,sizeof(Z_IOOriginPartToKeep));
2034 memset(r->u.itemOrder->u.esRequest->toKeep, 0, sizeof(Z_IOOriginPartToKeep));
2035 r->u.itemOrder->u.esRequest->notToKeep = (Z_IOOriginPartNotToKeep *)
2036 odr_malloc(out,sizeof(Z_IOOriginPartNotToKeep));
2037 memset(r->u.itemOrder->u.esRequest->notToKeep, 0, sizeof(Z_IOOriginPartNotToKeep));
2039 r->u.itemOrder->u.esRequest->toKeep->supplDescription = NULL;
2040 r->u.itemOrder->u.esRequest->toKeep->contact = NULL;
2041 r->u.itemOrder->u.esRequest->toKeep->addlBilling = NULL;
2043 r->u.itemOrder->u.esRequest->notToKeep->resultSetItem =
2044 (Z_IOResultSetItem *) odr_malloc(out, sizeof(Z_IOResultSetItem));
2045 memset(r->u.itemOrder->u.esRequest->notToKeep->resultSetItem, 0, sizeof(Z_IOResultSetItem));
2046 r->u.itemOrder->u.esRequest->notToKeep->resultSetItem->resultSetId = "1";
2048 r->u.itemOrder->u.esRequest->notToKeep->resultSetItem->item =
2049 (int *) odr_malloc(out, sizeof(int));
2050 *r->u.itemOrder->u.esRequest->notToKeep->resultSetItem->item = itemno;
2052 if (!strcmp (type, "item") || !strcmp(type, "2"))
2054 printf ("using item-request\n");
2055 r->u.itemOrder->u.esRequest->notToKeep->itemRequest =
2056 create_external_itemRequest();
2058 else if (!strcmp(type, "ill") || !strcmp(type, "1"))
2060 printf ("using ILL-request\n");
2061 r->u.itemOrder->u.esRequest->notToKeep->itemRequest =
2062 create_external_ILL_APDU(ILL_APDU_ILL_Request);
2064 else if (!strcmp(type, "xml") || !strcmp(type, "3"))
2066 const char *xml_buf =
2068 " <type>request</type>\n"
2069 " <libraryNo>000200</libraryNo>\n"
2070 " <borrowerTicketNo> 1212 </borrowerTicketNo>\n"
2072 r->u.itemOrder->u.esRequest->notToKeep->itemRequest =
2073 z_ext_record (out, VAL_TEXT_XML, xml_buf, strlen(xml_buf));
2076 r->u.itemOrder->u.esRequest->notToKeep->itemRequest = 0;
2081 static int send_itemorder(const char *type, int itemno)
2083 Z_APDU *apdu = zget_APDU(out, Z_APDU_extendedServicesRequest);
2084 Z_ExtendedServicesRequest *req = apdu->u.extendedServicesRequest;
2085 oident ItemOrderRequest;
2088 req->referenceId = set_refid (out);
2090 ItemOrderRequest.proto = PROTO_Z3950;
2091 ItemOrderRequest.oclass = CLASS_EXTSERV;
2092 ItemOrderRequest.value = VAL_ITEMORDER;
2093 req->packageType = odr_oiddup(out,oid_getoidbyent(&ItemOrderRequest));
2094 req->packageName = esPackageName;
2096 req->taskSpecificParameters = create_ItemOrderExternal(type, itemno);
2102 static int only_z3950(void)
2106 printf ("Not connected yet\n");
2109 if (protocol == PROTO_HTTP)
2111 printf ("Not supported by SRW\n");
2117 static int cmd_update_common(const char *arg, int version);
2119 static int cmd_update(const char *arg)
2121 return cmd_update_common(arg, 1);
2124 static int cmd_update0(const char *arg)
2126 return cmd_update_common(arg, 0);
2129 static int cmd_update_Z3950(int version, int action_no, const char *recid,
2130 char *rec_buf, int rec_len);
2132 static int cmd_update_SRW(int action_no, const char *recid,
2133 char *rec_buf, int rec_len);
2135 static int cmd_update_common(const char *arg, int version)
2137 char action[20], recid_buf[20];
2138 const char *recid = 0;
2146 sscanf (arg, "%19s %19s%n", action, recid_buf, &noread);
2149 printf("Use: update action recid [fname]\n");
2150 printf(" where action is one of insert,replace,delete.update\n");
2151 printf(" recid is some record ID. Use none for no ID\n");
2152 printf(" fname is file of record to be updated\n");
2156 if (!strcmp (action, "insert"))
2157 action_no = Z_IUOriginPartToKeep_recordInsert;
2158 else if (!strcmp (action, "replace"))
2159 action_no = Z_IUOriginPartToKeep_recordReplace;
2160 else if (!strcmp (action, "delete"))
2161 action_no = Z_IUOriginPartToKeep_recordDelete;
2162 else if (!strcmp (action, "update"))
2163 action_no = Z_IUOriginPartToKeep_specialUpdate;
2166 printf ("Bad action: %s\n", action);
2167 printf ("Possible values: insert, replace, delete, update\n");
2171 if (strcmp(recid_buf, "none")) /* none means no record ID */
2175 if (parse_cmd_doc(&arg, out, &rec_buf, &rec_len, 1) == 0)
2179 if (protocol == PROTO_HTTP)
2180 return cmd_update_SRW(action_no, recid, rec_buf, rec_len);
2182 return cmd_update_Z3950(version, action_no, recid, rec_buf, rec_len);
2186 static int cmd_update_SRW(int action_no, const char *recid,
2187 char *rec_buf, int rec_len)
2195 Z_SRW_PDU *srw = yaz_srw_get(out, Z_SRW_update_request);
2196 Z_SRW_updateRequest *sr = srw->u.update_request;
2200 case Z_IUOriginPartToKeep_recordInsert:
2201 sr->operation = "info:srw/action/1/create";
2203 case Z_IUOriginPartToKeep_recordReplace:
2204 sr->operation = "info:srw/action/1/replace";
2206 case Z_IUOriginPartToKeep_recordDelete:
2207 sr->operation = "info:srw/action/1/delete";
2212 sr->record = yaz_srw_get_record(out);
2213 sr->record->recordData_buf = rec_buf;
2214 sr->record->recordData_len = rec_len;
2215 sr->record->recordSchema = record_schema;
2218 sr->recordId = odr_strdup(out, recid);
2219 return send_srw(srw);
2224 static int cmd_update_Z3950(int version, int action_no, const char *recid,
2225 char *rec_buf, int rec_len)
2227 Z_APDU *apdu = zget_APDU(out, Z_APDU_extendedServicesRequest );
2228 Z_ExtendedServicesRequest *req = apdu->u.extendedServicesRequest;
2230 Z_External *record_this = 0;
2233 record_this = z_ext_record (out, VAL_TEXT_XML, rec_buf, rec_len);
2238 printf ("No last record (update ignored)\n");
2241 record_this = record_last;
2245 yaz_oidval_to_z3950oid(out, CLASS_EXTSERV,
2246 version == 0 ? VAL_DBUPDATE0 : VAL_DBUPDATE);
2248 req->packageName = esPackageName;
2250 req->referenceId = set_refid (out);
2252 r = req->taskSpecificParameters = (Z_External *)
2253 odr_malloc (out, sizeof(*r));
2254 r->direct_reference = req->packageType;
2255 r->indirect_reference = 0;
2259 Z_IU0OriginPartToKeep *toKeep;
2260 Z_IU0SuppliedRecords *notToKeep;
2262 r->which = Z_External_update0;
2263 r->u.update0 = (Z_IU0Update *) odr_malloc(out, sizeof(*r->u.update0));
2264 r->u.update0->which = Z_IUUpdate_esRequest;
2265 r->u.update0->u.esRequest = (Z_IU0UpdateEsRequest *)
2266 odr_malloc(out, sizeof(*r->u.update0->u.esRequest));
2267 toKeep = r->u.update0->u.esRequest->toKeep = (Z_IU0OriginPartToKeep *)
2268 odr_malloc(out, sizeof(*r->u.update0->u.esRequest->toKeep));
2270 toKeep->databaseName = databaseNames[0];
2272 toKeep->elementSetName = 0;
2274 toKeep->action = (int *) odr_malloc(out, sizeof(*toKeep->action));
2275 *toKeep->action = action_no;
2277 notToKeep = r->u.update0->u.esRequest->notToKeep = (Z_IU0SuppliedRecords *)
2278 odr_malloc(out, sizeof(*r->u.update0->u.esRequest->notToKeep));
2280 notToKeep->elements = (Z_IU0SuppliedRecords_elem **)
2281 odr_malloc(out, sizeof(*notToKeep->elements));
2282 notToKeep->elements[0] = (Z_IU0SuppliedRecords_elem *)
2283 odr_malloc(out, sizeof(**notToKeep->elements));
2284 notToKeep->elements[0]->which = Z_IUSuppliedRecords_elem_opaque;
2287 notToKeep->elements[0]->u.opaque = (Odr_oct *)
2288 odr_malloc (out, sizeof(Odr_oct));
2289 notToKeep->elements[0]->u.opaque->buf = (unsigned char *) recid;
2290 notToKeep->elements[0]->u.opaque->size = strlen(recid);
2291 notToKeep->elements[0]->u.opaque->len = strlen(recid);
2294 notToKeep->elements[0]->u.opaque = 0;
2295 notToKeep->elements[0]->supplementalId = 0;
2296 notToKeep->elements[0]->correlationInfo = 0;
2297 notToKeep->elements[0]->record = record_this;
2301 Z_IUOriginPartToKeep *toKeep;
2302 Z_IUSuppliedRecords *notToKeep;
2304 r->which = Z_External_update;
2305 r->u.update = (Z_IUUpdate *) odr_malloc(out, sizeof(*r->u.update));
2306 r->u.update->which = Z_IUUpdate_esRequest;
2307 r->u.update->u.esRequest = (Z_IUUpdateEsRequest *)
2308 odr_malloc(out, sizeof(*r->u.update->u.esRequest));
2309 toKeep = r->u.update->u.esRequest->toKeep = (Z_IUOriginPartToKeep *)
2310 odr_malloc(out, sizeof(*r->u.update->u.esRequest->toKeep));
2312 toKeep->databaseName = databaseNames[0];
2314 toKeep->elementSetName = 0;
2315 toKeep->actionQualifier = 0;
2316 toKeep->action = (int *) odr_malloc(out, sizeof(*toKeep->action));
2317 *toKeep->action = action_no;
2319 notToKeep = r->u.update->u.esRequest->notToKeep = (Z_IUSuppliedRecords *)
2320 odr_malloc(out, sizeof(*r->u.update->u.esRequest->notToKeep));
2322 notToKeep->elements = (Z_IUSuppliedRecords_elem **)
2323 odr_malloc(out, sizeof(*notToKeep->elements));
2324 notToKeep->elements[0] = (Z_IUSuppliedRecords_elem *)
2325 odr_malloc(out, sizeof(**notToKeep->elements));
2326 notToKeep->elements[0]->which = Z_IUSuppliedRecords_elem_opaque;
2329 notToKeep->elements[0]->u.opaque = (Odr_oct *)
2330 odr_malloc (out, sizeof(Odr_oct));
2331 notToKeep->elements[0]->u.opaque->buf = (unsigned char *) recid;
2332 notToKeep->elements[0]->u.opaque->size = strlen(recid);
2333 notToKeep->elements[0]->u.opaque->len = strlen(recid);
2336 notToKeep->elements[0]->u.opaque = 0;
2337 notToKeep->elements[0]->supplementalId = 0;
2338 notToKeep->elements[0]->correlationInfo = 0;
2339 notToKeep->elements[0]->record = record_this;
2347 static int cmd_xmles(const char *arg)
2356 int oid_value_xmles = VAL_XMLES;
2357 Z_APDU *apdu = zget_APDU(out, Z_APDU_extendedServicesRequest);
2358 Z_ExtendedServicesRequest *req = apdu->u.extendedServicesRequest;
2361 Z_External *ext = (Z_External *) odr_malloc(out, sizeof(*ext));
2363 req->referenceId = set_refid (out);
2364 req->taskSpecificParameters = ext;
2365 ext->indirect_reference = 0;
2366 ext->descriptor = 0;
2367 ext->which = Z_External_octet;
2368 ext->u.single_ASN1_type = (Odr_oct *) odr_malloc (out, sizeof(Odr_oct));
2369 sscanf(arg, "%50s%n", oid_str, &noread);
2372 printf("Missing OID for xmles\n");
2376 oid_value_xmles = oid_getvalbyname(oid_str);
2377 if (oid_value_xmles == VAL_NONE)
2379 printf("Bad OID: %s\n", oid_str);
2383 if (parse_cmd_doc(&arg, out, &asn_buf,
2384 &ext->u.single_ASN1_type->len, 0) == 0)
2387 ext->u.single_ASN1_type->buf = (unsigned char *) asn_buf;
2389 req->packageType = yaz_oidval_to_z3950oid(out, CLASS_EXTSERV,
2392 ext->direct_reference = yaz_oidval_to_z3950oid(out, CLASS_EXTSERV,
2400 static int cmd_itemorder(const char *arg)
2407 if (sscanf (arg, "%10s %d", type, &itemno) != 2)
2410 printf("Item order request\n");
2412 send_itemorder(type, itemno);
2416 static void show_opt(const char *arg, void *clientData)
2418 printf ("%s ", arg);
2421 static int cmd_zversion(const char *arg)
2424 z3950_version = atoi(arg);
2426 printf ("version is %d\n", z3950_version);
2430 static int cmd_options(const char *arg)
2436 r = yaz_init_opt_encode(&z3950_options, arg, &pos);
2438 printf("Unknown option(s) near %s\n", arg+pos);
2442 yaz_init_opt_decode(&z3950_options, show_opt, 0);
2448 static int cmd_explain(const char *arg)
2450 if (protocol != PROTO_HTTP)
2461 /* save this for later .. when fetching individual records */
2462 sr = yaz_srw_get(out, Z_SRW_explain_request);
2463 if (recordsyntax_size > 0 && recordsyntax_list[0] == VAL_TEXT_XML)
2464 sr->u.explain_request->recordPacking = "xml";
2472 static int cmd_init(const char *arg)
2476 strncpy (cur_host, arg, sizeof(cur_host)-1);
2477 cur_host[sizeof(cur_host)-1] = 0;
2481 send_initRequest(cur_host);
2485 static int cmd_sru(const char *arg)
2489 printf("SRU method is: %s\n", sru_method);
2493 if (!yaz_matchstr(arg, "post"))
2494 sru_method = "post";
2495 else if (!yaz_matchstr(arg, "get"))
2497 else if (!yaz_matchstr(arg, "soap"))
2498 sru_method = "soap";
2501 printf("Unknown SRU method: %s\n", arg);
2502 printf("Specify one of POST, GET, SOAP\n");
2508 static int cmd_find(const char *arg)
2512 printf("Find what?\n");
2515 if (protocol == PROTO_HTTP)
2522 if (!send_SRW_searchRequest(arg))
2535 printf("Not connected yet\n");
2539 if (!send_searchRequest(arg))
2545 static int cmd_delete(const char *arg)
2549 if (!send_deleteResultSetRequest(arg))
2554 static int cmd_ssub(const char *arg)
2556 if (!(smallSetUpperBound = atoi(arg)))
2561 static int cmd_lslb(const char *arg)
2563 if (!(largeSetLowerBound = atoi(arg)))
2568 static int cmd_mspn(const char *arg)
2570 if (!(mediumSetPresentNumber = atoi(arg)))
2575 static int cmd_status(const char *arg)
2577 printf("smallSetUpperBound: %d\n", smallSetUpperBound);
2578 printf("largeSetLowerBound: %d\n", largeSetLowerBound);
2579 printf("mediumSetPresentNumber: %d\n", mediumSetPresentNumber);
2583 static int cmd_setnames(const char *arg)
2585 if (*arg == '1') /* enable ? */
2587 else if (*arg == '0') /* disable ? */
2589 else if (setnumber < 0) /* no args, toggle .. */
2595 printf("Set numbering enabled.\n");
2597 printf("Set numbering disabled.\n");
2601 /* PRESENT SERVICE ----------------------------- */
2603 static void parse_show_args(const char *arg_c, char *setstring,
2604 int *start, int *number)
2609 strncpy(arg, arg_c, sizeof(arg)-1);
2610 arg[sizeof(arg)-1] = '\0';
2612 if ((p = strchr(arg, '+')))
2614 *number = atoi(p + 1);
2619 if (!strcmp(arg, "all"))
2621 *number = last_hit_count;
2627 if (p && (p=strchr(p+1, '+')))
2628 strcpy (setstring, p+1);
2629 else if (setnumber >= 0)
2630 sprintf(setstring, "%d", setnumber);
2635 static int send_presentRequest(const char *arg)
2637 Z_APDU *apdu = zget_APDU(out, Z_APDU_presentRequest);
2638 Z_PresentRequest *req = apdu->u.presentRequest;
2639 Z_RecordComposition compo;
2641 char setstring[100];
2643 req->referenceId = set_refid (out);
2645 parse_show_args(arg, setstring, &setno, &nos);
2647 req->resultSetId = setstring;
2649 req->resultSetStartPoint = &setno;
2650 req->numberOfRecordsRequested = &nos;
2652 if (recordsyntax_size == 1)
2653 req->preferredRecordSyntax =
2654 yaz_oidval_to_z3950oid(out, CLASS_RECSYN, recordsyntax_list[0]);
2656 if (record_schema || recordsyntax_size >= 2)
2658 req->recordComposition = &compo;
2659 compo.which = Z_RecordComp_complex;
2660 compo.u.complex = (Z_CompSpec *)
2661 odr_malloc(out, sizeof(*compo.u.complex));
2662 compo.u.complex->selectAlternativeSyntax = (bool_t *)
2663 odr_malloc(out, sizeof(bool_t));
2664 *compo.u.complex->selectAlternativeSyntax = 0;
2666 compo.u.complex->generic = (Z_Specification *)
2667 odr_malloc(out, sizeof(*compo.u.complex->generic));
2669 compo.u.complex->generic->which = Z_Schema_oid;
2671 compo.u.complex->generic->schema.oid = 0;
2674 compo.u.complex->generic->schema.oid =
2675 yaz_str_to_z3950oid(out, CLASS_SCHEMA, record_schema);
2677 if (!compo.u.complex->generic->schema.oid)
2679 /* OID wasn't a schema! Try record syntax instead. */
2680 compo.u.complex->generic->schema.oid = (Odr_oid *)
2681 yaz_str_to_z3950oid(out, CLASS_RECSYN, record_schema);
2684 if (!elementSetNames)
2685 compo.u.complex->generic->elementSpec = 0;
2688 compo.u.complex->generic->elementSpec = (Z_ElementSpec *)
2689 odr_malloc(out, sizeof(Z_ElementSpec));
2690 compo.u.complex->generic->elementSpec->which =
2691 Z_ElementSpec_elementSetName;
2692 compo.u.complex->generic->elementSpec->u.elementSetName =
2693 elementSetNames->u.generic;
2695 compo.u.complex->num_dbSpecific = 0;
2696 compo.u.complex->dbSpecific = 0;
2697 if (recordsyntax_size >= 2)
2700 compo.u.complex->num_recordSyntax = recordsyntax_size;
2701 compo.u.complex->recordSyntax = (Odr_oid **)
2702 odr_malloc(out, recordsyntax_size * sizeof(Odr_oid*));
2703 for (i = 0; i < recordsyntax_size; i++)
2704 compo.u.complex->recordSyntax[i] =
2705 yaz_oidval_to_z3950oid(out, CLASS_RECSYN,
2706 recordsyntax_list[i]);
2710 compo.u.complex->num_recordSyntax = 0;
2711 compo.u.complex->recordSyntax = 0;
2714 else if (elementSetNames)
2716 req->recordComposition = &compo;
2717 compo.which = Z_RecordComp_simple;
2718 compo.u.simple = elementSetNames;
2721 printf("Sent presentRequest (%d+%d).\n", setno, nos);
2726 static int send_SRW_presentRequest(const char *arg)
2728 char setstring[100];
2730 Z_SRW_PDU *sr = srw_sr;
2734 parse_show_args(arg, setstring, &setno, &nos);
2735 sr->u.request->startRecord = odr_intdup(out, setno);
2736 sr->u.request->maximumRecords = odr_intdup(out, nos);
2738 sr->u.request->recordSchema = record_schema;
2739 if (recordsyntax_size == 1 && recordsyntax_list[0] == VAL_TEXT_XML)
2740 sr->u.request->recordPacking = "xml";
2741 return send_srw(sr);
2745 static void close_session (void)
2757 void process_close(Z_Close *req)
2759 Z_APDU *apdu = zget_APDU(out, Z_APDU_close);
2760 Z_Close *res = apdu->u.close;
2762 static char *reasons[] =
2767 "cost limit reached",
2769 "security violation",
2776 printf("Reason: %s, message: %s\n", reasons[*req->closeReason],
2777 req->diagnosticInformation ? req->diagnosticInformation : "NULL");
2782 *res->closeReason = Z_Close_finished;
2784 printf("Sent response.\n");
2789 static int cmd_show(const char *arg)
2791 if (protocol == PROTO_HTTP)
2798 if (!send_SRW_presentRequest(arg))
2808 printf("Not connected yet\n");
2811 if (!send_presentRequest(arg))
2817 void exit_client(int code)
2819 file_history_save(file_history);
2820 file_history_destroy(&file_history);
2824 int cmd_quit(const char *arg)
2826 printf("See you later, alligator.\n");
2832 int cmd_cancel(const char *arg)
2834 Z_APDU *apdu = zget_APDU(out, Z_APDU_triggerResourceControlRequest);
2835 Z_TriggerResourceControlRequest *req =
2836 apdu->u.triggerResourceControlRequest;
2841 sscanf(arg, "%15s", command);
2845 if (session_initResponse &&
2846 !ODR_MASK_GET(session_initResponse->options,
2847 Z_Options_triggerResourceCtrl))
2849 printf("Target doesn't support cancel (trigger resource ctrl)\n");
2852 *req->requestedAction = Z_TriggerResourceControlRequest_cancel;
2853 req->resultSetWanted = &rfalse;
2854 req->referenceId = set_refid (out);
2857 printf("Sent cancel request\n");
2858 if (!strcmp(command, "wait"))
2864 int cmd_cancel_find(const char *arg) {
2868 return cmd_cancel("");
2873 int send_scanrequest(const char *query, int pp, int num, const char *term)
2875 Z_APDU *apdu = zget_APDU(out, Z_APDU_scanRequest);
2876 Z_ScanRequest *req = apdu->u.scanRequest;
2880 if (queryType == QueryType_CCL2RPN)
2883 struct ccl_rpn_node *rpn;
2885 rpn = ccl_find_str (bibset, query, &error, &pos);
2888 printf("CCL ERROR: %s\n", ccl_err_msg(error));
2892 yaz_oidval_to_z3950oid(out, CLASS_ATTSET, VAL_BIB1);
2893 if (!(req->termListAndStartPoint = ccl_scan_query (out, rpn)))
2895 printf("Couldn't convert CCL to Scan term\n");
2898 ccl_rpn_delete (rpn);
2902 YAZ_PQF_Parser pqf_parser = yaz_pqf_create ();
2904 if (!(req->termListAndStartPoint =
2905 yaz_pqf_scan(pqf_parser, out, &req->attributeSet, query)))
2907 const char *pqf_msg;
2909 int code = yaz_pqf_error (pqf_parser, &pqf_msg, &off);
2911 printf("%*s^\n", ioff+7, "");
2912 printf("Prefix query error: %s (code %d)\n", pqf_msg, code);
2913 yaz_pqf_destroy (pqf_parser);
2916 yaz_pqf_destroy (pqf_parser);
2920 if (req->termListAndStartPoint->term &&
2921 req->termListAndStartPoint->term->which == Z_Term_general &&
2922 req->termListAndStartPoint->term->u.general)
2924 req->termListAndStartPoint->term->u.general->buf =
2925 (unsigned char *) odr_strdup(out, term);
2926 req->termListAndStartPoint->term->u.general->len =
2927 req->termListAndStartPoint->term->u.general->size =
2931 req->referenceId = set_refid (out);
2932 req->num_databaseNames = num_databaseNames;
2933 req->databaseNames = databaseNames;
2934 req->numberOfTermsRequested = #
2935 req->preferredPositionInResponse = &pp;
2936 req->stepSize = odr_intdup(out, scan_stepSize);
2941 int send_sortrequest(const char *arg, int newset)
2943 Z_APDU *apdu = zget_APDU(out, Z_APDU_sortRequest);
2944 Z_SortRequest *req = apdu->u.sortRequest;
2945 Z_SortKeySpecList *sksl = (Z_SortKeySpecList *)
2946 odr_malloc (out, sizeof(*sksl));
2952 sprintf (setstring, "%d", setnumber);
2954 sprintf (setstring, "default");
2956 req->referenceId = set_refid (out);
2958 req->num_inputResultSetNames = 1;
2959 req->inputResultSetNames = (Z_InternationalString **)
2960 odr_malloc (out, sizeof(*req->inputResultSetNames));
2961 req->inputResultSetNames[0] = odr_strdup (out, setstring);
2963 if (newset && setnumber >= 0)
2964 sprintf (setstring, "%d", ++setnumber);
2966 req->sortedResultSetName = odr_strdup (out, setstring);
2968 req->sortSequence = yaz_sort_spec (out, arg);
2969 if (!req->sortSequence)
2971 printf ("Missing sort specifications\n");
2978 void display_term(Z_TermInfo *t)
2981 printf("%s", t->displayTerm);
2982 else if (t->term->which == Z_Term_general)
2984 printf("%.*s", t->term->u.general->len, t->term->u.general->buf);
2985 sprintf(last_scan_line, "%.*s", t->term->u.general->len,
2986 t->term->u.general->buf);
2989 printf("Term (not general)");
2990 if (t->globalOccurrences)
2991 printf (" (%d)\n", *t->globalOccurrences);
2996 void process_scanResponse(Z_ScanResponse *res)
2999 Z_Entry **entries = NULL;
3000 int num_entries = 0;
3002 printf("Received ScanResponse\n");
3003 print_refid (res->referenceId);
3004 printf("%d entries", *res->numberOfEntriesReturned);
3005 if (res->positionOfTerm)
3006 printf (", position=%d", *res->positionOfTerm);
3008 if (*res->scanStatus != Z_Scan_success)
3009 printf("Scan returned code %d\n", *res->scanStatus);
3012 if ((entries = res->entries->entries))
3013 num_entries = res->entries->num_entries;
3014 for (i = 0; i < num_entries; i++)
3016 int pos_term = res->positionOfTerm ? *res->positionOfTerm : -1;
3017 if (entries[i]->which == Z_Entry_termInfo)
3019 printf("%c ", i + 1 == pos_term ? '*' : ' ');
3020 display_term(entries[i]->u.termInfo);
3023 display_diagrecs(&entries[i]->u.surrogateDiagnostic, 1);
3025 if (res->entries->nonsurrogateDiagnostics)
3026 display_diagrecs (res->entries->nonsurrogateDiagnostics,
3027 res->entries->num_nonsurrogateDiagnostics);
3030 void process_sortResponse(Z_SortResponse *res)
3032 printf("Received SortResponse: status=");
3033 switch (*res->sortStatus)
3035 case Z_SortResponse_success:
3036 printf ("success"); break;
3037 case Z_SortResponse_partial_1:
3038 printf ("partial"); break;
3039 case Z_SortResponse_failure:
3040 printf ("failure"); break;
3042 printf ("unknown (%d)", *res->sortStatus);
3045 print_refid (res->referenceId);
3046 if (res->diagnostics)
3047 display_diagrecs(res->diagnostics,
3048 res->num_diagnostics);
3051 void process_deleteResultSetResponse (Z_DeleteResultSetResponse *res)
3053 printf("Got deleteResultSetResponse status=%d\n",
3054 *res->deleteOperationStatus);
3055 if (res->deleteListStatuses)
3058 for (i = 0; i < res->deleteListStatuses->num; i++)
3060 printf ("%s status=%d\n", res->deleteListStatuses->elements[i]->id,
3061 *res->deleteListStatuses->elements[i]->status);
3066 int cmd_sort_generic(const char *arg, int newset)
3070 if (session_initResponse &&
3071 !ODR_MASK_GET(session_initResponse->options, Z_Options_sort))
3073 printf("Target doesn't support sort\n");
3078 if (send_sortrequest(arg, newset) < 0)
3085 int cmd_sort(const char *arg)
3087 return cmd_sort_generic (arg, 0);
3090 int cmd_sort_newset (const char *arg)
3092 return cmd_sort_generic (arg, 1);
3095 int cmd_scanstep(const char *arg)
3097 scan_stepSize = atoi(arg);
3101 int cmd_scanpos(const char *arg)
3103 int r = sscanf(arg, "%d", &scan_position);
3109 int cmd_scansize(const char *arg)
3111 int r = sscanf(arg, "%d", &scan_size);
3117 int cmd_scan(const char *arg)
3119 if (protocol == PROTO_HTTP)
3128 if (send_SRW_scanRequest(arg, scan_position, scan_size) < 0)
3133 if (send_SRW_scanRequest(last_scan_line, 1, scan_size) < 0)
3148 printf("Session not initialized yet\n");
3152 if (session_initResponse &&
3153 !ODR_MASK_GET(session_initResponse->options, Z_Options_scan))
3155 printf("Target doesn't support scan\n");
3160 strcpy (last_scan_query, arg);
3161 if (send_scanrequest(arg, scan_position, scan_size, 0) < 0)
3166 if (send_scanrequest(last_scan_query, 1, scan_size, last_scan_line) < 0)
3173 int cmd_schema(const char *arg)
3175 xfree(record_schema);
3178 record_schema = xstrdup(arg);
3182 int cmd_format(const char *arg)
3184 const char *cp = arg;
3187 oid_value nsyntax[RECORDSYNTAX_MAX];
3191 printf("Usage: format <recordsyntax>\n");
3194 while (sscanf(cp, "%40s%n", form_str, &nor) >= 1 && nor > 0
3195 && idx < RECORDSYNTAX_MAX)
3197 nsyntax[idx] = oid_getvalbyname(form_str);
3198 if (!strcmp(form_str, "none"))
3200 if (nsyntax[idx] == VAL_NONE)
3202 printf ("unknown record syntax: %s\n", form_str);
3208 recordsyntax_size = idx;
3209 memcpy(recordsyntax_list, nsyntax, idx * sizeof(*nsyntax));
3213 int cmd_elements(const char *arg)
3215 static Z_ElementSetNames esn;
3216 static char what[100];
3220 elementSetNames = 0;
3224 esn.which = Z_ElementSetNames_generic;
3225 esn.u.generic = what;
3226 elementSetNames = &esn;
3230 int cmd_attributeset(const char *arg)
3236 printf("Usage: attributeset <setname>\n");
3239 sscanf(arg, "%s", what);
3240 if (p_query_attset (what))
3242 printf("Unknown attribute set name\n");
3248 int cmd_querytype (const char *arg)
3250 if (!strcmp (arg, "ccl"))
3251 queryType = QueryType_CCL;
3252 else if (!strcmp (arg, "prefix") || !strcmp(arg, "rpn"))
3253 queryType = QueryType_Prefix;
3254 else if (!strcmp (arg, "ccl2rpn") || !strcmp (arg, "cclrpn"))
3255 queryType = QueryType_CCL2RPN;
3256 else if (!strcmp(arg, "cql"))
3257 queryType = QueryType_CQL;
3258 else if (!strcmp (arg, "cql2rpn") || !strcmp (arg, "cqlrpn"))
3259 queryType = QueryType_CQL2RPN;
3262 printf ("Querytype must be one of:\n");
3263 printf (" prefix - Prefix query\n");
3264 printf (" ccl - CCL query\n");
3265 printf (" ccl2rpn - CCL query converted to RPN\n");
3266 printf (" cql - CQL\n");
3267 printf (" cql2rpn - CQL query converted to RPN\n");
3273 int cmd_refid (const char *arg)
3278 refid = xstrdup (arg);
3282 int cmd_close(const char *arg)
3288 apdu = zget_APDU(out, Z_APDU_close);
3289 req = apdu->u.close;
3290 *req->closeReason = Z_Close_finished;
3292 printf("Sent close request.\n");
3297 int cmd_packagename(const char* arg)
3299 xfree (esPackageName);
3300 esPackageName = NULL;
3302 esPackageName = xstrdup(arg);
3306 int cmd_proxy(const char* arg)
3311 yazProxy = xstrdup (arg);
3315 int cmd_marccharset(const char *arg)
3320 if (sscanf(arg, "%29s", l1) < 1)
3322 printf("MARC character set is `%s'\n",
3323 marcCharset ? marcCharset: "none");
3326 xfree (marcCharset);
3328 if (strcmp(l1, "-"))
3329 marcCharset = xstrdup(l1);
3333 int cmd_displaycharset(const char *arg)
3338 if (sscanf(arg, "%29s", l1) < 1)
3340 printf("Display character set is `%s'\n",
3341 outputCharset ? outputCharset: "none");
3345 xfree (outputCharset);
3347 if (!strcmp(l1, "auto") && codeset)
3351 printf ("Display character set: %s\n", codeset);
3352 outputCharset = xstrdup(codeset);
3355 printf ("No codeset found on this system\n");
3357 else if (strcmp(l1, "-") && strcmp(l1, "none"))
3358 outputCharset = xstrdup(l1);
3363 int cmd_negcharset(const char *arg)
3368 if (sscanf(arg, "%29s %d %d", l1, &negotiationCharsetRecords,
3369 &negotiationCharsetVersion) < 1)
3371 printf("Current negotiation character set is `%s'\n",
3372 negotiationCharset ? negotiationCharset: "none");
3373 printf("Records in charset %s\n", negotiationCharsetRecords ?
3375 printf("Charneg version %d\n", negotiationCharsetVersion);
3379 xfree (negotiationCharset);
3380 negotiationCharset = NULL;
3381 if (*l1 && strcmp(l1, "-") && strcmp(l1, "none"))
3383 negotiationCharset = xstrdup(l1);
3384 printf ("Character set negotiation : %s\n", negotiationCharset);
3390 int cmd_charset(const char* arg)
3392 char l1[30], l2[30], l3[30];
3394 *l1 = *l2 = *l3 = 0;
3395 if (sscanf(arg, "%29s %29s %29s", l1, l2, l3) < 1)
3398 cmd_displaycharset("");
3399 cmd_marccharset("");
3405 cmd_displaycharset(l2);
3407 cmd_marccharset(l3);
3412 int cmd_lang(const char* arg)
3415 printf("Current language is `%s'\n", (yazLang)?yazLang:NULL);
3421 yazLang = xstrdup(arg);
3425 int cmd_source(const char* arg, int echo )
3427 /* first should open the file and read one line at a time.. */
3429 char line[102400], *cp;
3432 fprintf(stderr,"Error in source command use a filename\n");
3436 includeFile = fopen (arg, "r");
3439 fprintf(stderr,"Unable to open file %s for reading\n",arg);
3443 while(!feof(includeFile)) {
3444 memset(line,0,sizeof(line));
3445 fgets(line,sizeof(line),includeFile);
3447 if(strlen(line) < 2) continue;
3448 if(line[0] == '#') continue;
3450 if ((cp = strrchr (line, '\n')))
3454 printf( "processing line: %s\n",line );
3456 process_cmd_line(line);
3459 if(fclose(includeFile)<0) {
3460 perror("unable to close include file");
3466 int cmd_source_echo(const char* arg)
3472 int cmd_source_noecho(const char* arg)
3479 int cmd_subshell(const char* args)
3484 system(getenv("SHELL"));
3490 int cmd_set_berfile(const char *arg)
3492 if (ber_file && ber_file != stdout && ber_file != stderr)
3494 if (!strcmp(arg, ""))
3496 else if (!strcmp(arg, "-"))
3499 ber_file = fopen(arg, "a");
3503 int cmd_set_apdufile(const char *arg)
3505 if(apdu_file && apdu_file != stderr && apdu_file != stderr)
3507 if (!strcmp(arg, ""))
3509 else if (!strcmp(arg, "-"))
3513 apdu_file = fopen(arg, "a");
3515 perror("unable to open apdu log file");
3518 odr_setprint(print, apdu_file);
3522 int cmd_set_cclfile(const char* arg)
3526 bibset = ccl_qual_mk ();
3527 inf = fopen (arg, "r");
3529 perror("unable to open CCL file");
3532 ccl_qual_file (bibset, inf);
3535 strcpy(ccl_fields,arg);
3539 int cmd_set_cqlfile(const char* arg)
3541 cql_transform_t newcqltrans;
3543 if ((newcqltrans = cql_transform_open_fname(arg)) == 0) {
3544 perror("unable to open CQL file");
3548 cql_transform_close(cqltrans);
3550 cqltrans = newcqltrans;
3551 strcpy(cql_fields, arg);
3555 int cmd_set_auto_reconnect(const char* arg)
3557 if(strlen(arg)==0) {
3558 auto_reconnect = ! auto_reconnect;
3559 } else if(strcmp(arg,"on")==0) {
3561 } else if(strcmp(arg,"off")==0) {
3564 printf("Error use on or off\n");
3569 printf("Set auto reconnect enabled.\n");
3571 printf("Set auto reconnect disabled.\n");
3577 int cmd_set_auto_wait(const char* arg)
3579 if(strlen(arg)==0) {
3580 auto_wait = ! auto_wait;
3581 } else if(strcmp(arg,"on")==0) {
3583 } else if(strcmp(arg,"off")==0) {
3586 printf("Error use on or off\n");
3591 printf("Set auto wait enabled.\n");
3593 printf("Set auto wait disabled.\n");
3598 int cmd_set_marcdump(const char* arg)
3600 if(marc_file && marc_file != stderr) { /* don't close stdout*/
3604 if (!strcmp(arg, ""))
3606 else if (!strcmp(arg, "-"))
3610 marc_file = fopen(arg, "a");
3612 perror("unable to open marc log file");
3618 this command takes 3 arge {name class oid}
3620 int cmd_register_oid(const char* args) {
3625 {"appctx",CLASS_APPCTX},
3626 {"absyn",CLASS_ABSYN},
3627 {"attset",CLASS_ATTSET},
3628 {"transyn",CLASS_TRANSYN},
3629 {"diagset",CLASS_DIAGSET},
3630 {"recsyn",CLASS_RECSYN},
3631 {"resform",CLASS_RESFORM},
3632 {"accform",CLASS_ACCFORM},
3633 {"extserv",CLASS_EXTSERV},
3634 {"userinfo",CLASS_USERINFO},
3635 {"elemspec",CLASS_ELEMSPEC},
3636 {"varset",CLASS_VARSET},
3637 {"schema",CLASS_SCHEMA},
3638 {"tagset",CLASS_TAGSET},
3639 {"general",CLASS_GENERAL},
3640 {0,(enum oid_class) 0}
3642 char oname_str[101], oclass_str[101], oid_str[101];
3645 oid_class oidclass = CLASS_GENERAL;
3646 int val = 0, oid[OID_SIZE];
3647 struct oident * new_oident=NULL;
3649 if (sscanf (args, "%100[^ ] %100[^ ] %100s",
3650 oname_str,oclass_str, oid_str) < 1) {
3651 printf("Error in register command \n");
3655 for (i = 0; oid_classes[i].className; i++) {
3656 if (!strcmp(oid_classes[i].className, oclass_str))
3658 oidclass=oid_classes[i].oclass;
3663 if(!(oid_classes[i].className)) {
3664 printf("Unknown oid class %s\n",oclass_str);
3672 while (isdigit (*(unsigned char *) name))
3674 val = val*10 + (*name - '0');
3687 new_oident = oid_addent (oid, PROTO_GENERAL, oidclass, oname_str,
3689 if(strcmp(new_oident->desc,oname_str))
3691 fprintf(stderr,"oid is already named as %s, registration failed\n",
3697 int cmd_push_command(const char* arg)
3699 #if HAVE_READLINE_HISTORY_H
3703 fprintf(stderr,"Not compiled with the readline/history module\n");
3708 void source_rcfile(void)
3710 /* Look for a $HOME/.yazclientrc and source it if it exists */
3711 struct stat statbuf;
3713 char* homedir = getenv("HOME");
3715 sprintf(fname, "%.500s%s%s", homedir ? homedir : "",
3719 if (stat(fname,&statbuf)==0)
3720 cmd_source(fname, 0 );
3723 void add_to_readline_history(void *client_data, const char *line)
3725 #if HAVE_READLINE_HISTORY_H
3731 static void initialize(void)
3736 if (!(out = odr_createmem(ODR_ENCODE)) ||
3737 !(in = odr_createmem(ODR_DECODE)) ||
3738 !(print = odr_createmem(ODR_PRINT)))
3740 fprintf(stderr, "failed to allocate ODR streams\n");
3745 setvbuf(stdout, 0, _IONBF, 0);
3747 odr_setprint(print, apdu_file);
3749 bibset = ccl_qual_mk ();
3750 inf = fopen (ccl_fields, "r");
3753 ccl_qual_file (bibset, inf);
3757 cqltrans = cql_transform_open_fname(cql_fields);
3758 /* If this fails, no problem: we detect cqltrans == 0 later */
3760 #if HAVE_READLINE_READLINE_H
3761 rl_attempted_completion_function = (CPPFunction*)readline_completer;
3763 for(i = 0; i < maxOtherInfosSupported; ++i) {
3764 extraOtherInfos[i].oidval = -1;
3769 file_history = file_history_new();
3770 file_history_load(file_history);
3771 file_history_trav(file_history, 0, add_to_readline_history);
3775 #if HAVE_GETTIMEOFDAY
3776 struct timeval tv_start;
3780 static void handle_srw_record(Z_SRW_record *rec)
3782 if (rec->recordPosition)
3784 printf ("pos=%d", *rec->recordPosition);
3785 setno = *rec->recordPosition + 1;
3787 if (rec->recordSchema)
3788 printf (" schema=%s", rec->recordSchema);
3790 if (rec->recordData_buf && rec->recordData_len)
3792 fwrite(rec->recordData_buf, 1, rec->recordData_len, stdout);
3794 fwrite (rec->recordData_buf, 1, rec->recordData_len, marc_file);
3797 printf ("No data!");
3801 static void handle_srw_explain_response(Z_SRW_explainResponse *res)
3803 handle_srw_record(&res->record);
3806 static void handle_srw_response(Z_SRW_searchRetrieveResponse *res)
3810 printf ("Received SRW SearchRetrieve Response\n");
3812 for (i = 0; i<res->num_diagnostics; i++)
3814 if (res->diagnostics[i].uri)
3815 printf ("SRW diagnostic %s\n",
3816 res->diagnostics[i].uri);
3818 printf ("SRW diagnostic missing or could not be decoded\n");
3819 if (res->diagnostics[i].message)
3820 printf ("Message: %s\n", res->diagnostics[i].message);
3821 if (res->diagnostics[i].details)
3822 printf ("Details: %s\n", res->diagnostics[i].details);
3824 if (res->numberOfRecords)
3825 printf ("Number of hits: %d\n", *res->numberOfRecords);
3826 for (i = 0; i<res->num_records; i++)
3827 handle_srw_record(res->records + i);
3830 static void handle_srw_scan_term(Z_SRW_scanTerm *term)
3832 if (term->displayTerm)
3833 printf("%s:", term->displayTerm);
3834 else if (term->value)
3835 printf("%s:", term->value);
3837 printf("No value:");
3838 if (term->numberOfRecords)
3839 printf(" %d", *term->numberOfRecords);
3840 if (term->whereInList)
3841 printf(" %s", term->whereInList);
3842 if (term->value && term->displayTerm)
3843 printf(" %s", term->value);
3845 strcpy(last_scan_line, term->value);
3849 static void handle_srw_scan_response(Z_SRW_scanResponse *res)
3853 printf ("Received SRW Scan Response\n");
3855 for (i = 0; i<res->num_diagnostics; i++)
3857 if (res->diagnostics[i].uri)
3858 printf ("SRW diagnostic %s\n",
3859 res->diagnostics[i].uri);
3861 printf ("SRW diagnostic missing or could not be decoded\n");
3862 if (res->diagnostics[i].message)
3863 printf ("Message: %s\n", res->diagnostics[i].message);
3864 if (res->diagnostics[i].details)
3865 printf ("Details: %s\n", res->diagnostics[i].details);
3868 for (i = 0; i<res->num_terms; i++)
3869 handle_srw_scan_term(res->terms + i);
3872 static void http_response(Z_HTTP_Response *hres)
3875 const char *content_type = z_HTTP_header_lookup(hres->headers,
3877 const char *connection_head = z_HTTP_header_lookup(hres->headers,
3879 if (content_type && !yaz_strcmp_del("text/xml", content_type, "; "))
3881 Z_SOAP *soap_package = 0;
3882 ODR o = odr_createmem(ODR_DECODE);
3883 Z_SOAP_Handler soap_handlers[3] = {
3884 {YAZ_XMLNS_SRU_v1_1, 0, (Z_SOAP_fun) yaz_srw_codec},
3885 {YAZ_XMLNS_UPDATE_v0_9, 0, (Z_SOAP_fun) yaz_ucp_codec},
3888 ret = z_soap_codec(o, &soap_package,
3889 &hres->content_buf, &hres->content_len,
3891 if (!ret && soap_package->which == Z_SOAP_generic)
3893 Z_SRW_PDU *sr = soap_package->u.generic->p;
3894 if (sr->which == Z_SRW_searchRetrieve_response)
3895 handle_srw_response(sr->u.response);
3896 else if (sr->which == Z_SRW_explain_response)
3897 handle_srw_explain_response(sr->u.explain_response);
3898 else if (sr->which == Z_SRW_scan_response)
3899 handle_srw_scan_response(sr->u.scan_response);
3900 else if (sr->which == Z_SRW_update_response)
3901 printf("Got update response. Status: %s\n",
3902 sr->u.update_response->operationStatus);
3906 else if (soap_package && (soap_package->which == Z_SOAP_fault
3907 || soap_package->which == Z_SOAP_error))
3909 printf ("HTTP Error Status=%d\n", hres->code);
3910 printf ("SOAP Fault code %s\n",
3911 soap_package->u.fault->fault_code);
3912 printf ("SOAP Fault string %s\n",
3913 soap_package->u.fault->fault_string);
3914 if (soap_package->u.fault->details)
3915 printf ("SOAP Details %s\n",
3916 soap_package->u.fault->details);
3920 printf("z_soap_codec failed. (no SOAP error)\n");
3927 if (hres->code != 200)
3929 printf ("HTTP Error Status=%d\n", hres->code);
3933 printf ("Decoding of SRW package failed\n");
3939 if (!strcmp(hres->version, "1.0"))
3941 /* HTTP 1.0: only if Keep-Alive we stay alive.. */
3942 if (!connection_head || strcmp(connection_head, "Keep-Alive"))
3947 /* HTTP 1.1: only if no close we stay alive .. */
3948 if (connection_head && !strcmp(connection_head, "close"))
3955 void wait_and_handle_response(int one_response_only)
3957 int reconnect_ok = 1;
3960 int netbufferlen = 0;
3961 #if HAVE_GETTIMEOFDAY
3963 struct timeval tv_end;
3969 res = cs_get(conn, &netbuffer, &netbufferlen);
3970 if (reconnect_ok && res <= 0 && protocol == PROTO_HTTP)
3981 buf_out = odr_getbuf(out, &len_out, 0);
3983 do_hex_dump(buf_out, len_out);
3985 cs_put(conn, buf_out, len_out);
3993 printf("Target closed connection\n");
3997 #if HAVE_GETTIMEOFDAY
3998 if (got_tv_end == 0)
3999 gettimeofday (&tv_end, 0); /* count first one only */
4003 odr_reset(in); /* release APDU from last round */
4005 do_hex_dump(netbuffer, res);
4006 odr_setbuf(in, netbuffer, res, 0);
4008 if (!z_GDU(in, &gdu, 0, 0))
4010 FILE *f = ber_file ? ber_file : stdout;
4011 odr_perror(in, "Decoding incoming APDU");
4012 fprintf(f, "[Near %ld]\n", (long) odr_offset(in));
4013 fprintf(f, "Packet dump:\n---------\n");
4014 odr_dumpBER(f, netbuffer, res);
4015 fprintf(f, "---------\n");
4018 z_GDU(print, &gdu, 0, 0);
4021 if (conn && cs_more(conn))
4026 odr_dumpBER(ber_file, netbuffer, res);
4027 if (apdu_file && !z_GDU(print, &gdu, 0, 0))
4029 odr_perror(print, "Failed to print incoming APDU");
4033 if (gdu->which == Z_GDU_Z3950)
4035 Z_APDU *apdu = gdu->u.z3950;
4038 case Z_APDU_initResponse:
4039 process_initResponse(apdu->u.initResponse);
4041 case Z_APDU_searchResponse:
4042 process_searchResponse(apdu->u.searchResponse);
4044 case Z_APDU_scanResponse:
4045 process_scanResponse(apdu->u.scanResponse);
4047 case Z_APDU_presentResponse:
4048 print_refid (apdu->u.presentResponse->referenceId);
4050 *apdu->u.presentResponse->numberOfRecordsReturned;
4051 if (apdu->u.presentResponse->records)
4052 display_records(apdu->u.presentResponse->records);
4054 printf("No records.\n");
4055 printf ("nextResultSetPosition = %d\n",
4056 *apdu->u.presentResponse->nextResultSetPosition);
4058 case Z_APDU_sortResponse:
4059 process_sortResponse(apdu->u.sortResponse);
4061 case Z_APDU_extendedServicesResponse:
4062 printf("Got extended services response\n");
4063 process_ESResponse(apdu->u.extendedServicesResponse);
4066 printf("Target has closed the association.\n");
4067 process_close(apdu->u.close);
4069 case Z_APDU_resourceControlRequest:
4070 process_resourceControlRequest
4071 (apdu->u.resourceControlRequest);
4073 case Z_APDU_deleteResultSetResponse:
4074 process_deleteResultSetResponse(apdu->u.
4075 deleteResultSetResponse);
4078 printf("Received unknown APDU type (%d).\n",
4084 else if (gdu->which == Z_GDU_HTTP_Response)
4086 http_response(gdu->u.HTTP_Response);
4089 if (one_response_only)
4091 if (conn && !cs_more(conn))
4094 #if HAVE_GETTIMEOFDAY
4098 printf ("S/U S/U=%ld/%ld %ld/%ld",
4099 (long) tv_start.tv_sec,
4100 (long) tv_start.tv_usec,
4101 (long) tv_end.tv_sec,
4102 (long) tv_end.tv_usec);
4104 printf ("Elapsed: %.6f\n",
4105 (double) tv_end.tv_usec / 1e6 + tv_end.tv_sec -
4106 ((double) tv_start.tv_usec / 1e6 + tv_start.tv_sec));
4113 int cmd_cclparse(const char* arg)
4116 struct ccl_rpn_node *rpn=NULL;
4119 rpn = ccl_find_str (bibset, arg, &error, &pos);
4122 int ioff = 3+strlen(last_cmd)+1+pos;
4123 printf ("%*s^ - ", ioff, " ");
4124 printf ("%s\n", ccl_err_msg (error));
4130 ccl_pr_tree(rpn, stdout);
4134 ccl_rpn_delete(rpn);
4142 int cmd_set_otherinfo(const char* args)
4144 char oidstr[101], otherinfoString[101];
4149 sscan_res = sscanf (args, "%d %100[^ ] %100s",
4150 &otherinfoNo, oidstr, otherinfoString);
4152 /* reset this otherinfo */
4153 if(otherinfoNo>=maxOtherInfosSupported) {
4154 printf("Error otherinfo index to large (%d>%d)\n",
4155 otherinfoNo,maxOtherInfosSupported);
4157 extraOtherInfos[otherinfoNo].oidval = -1;
4158 if (extraOtherInfos[otherinfoNo].value)
4159 xfree(extraOtherInfos[otherinfoNo].value);
4160 extraOtherInfos[otherinfoNo].value = 0;
4164 printf("Error in set_otherinfo command \n");
4168 if (otherinfoNo>=maxOtherInfosSupported) {
4169 printf("Error otherinfo index too large (%d>=%d)\n",
4170 otherinfoNo,maxOtherInfosSupported);
4173 oidval = oid_getvalbyname (oidstr);
4174 if (oidval == VAL_NONE)
4176 printf("Error in set_otherinfo command unknown oid %s \n",oidstr);
4179 extraOtherInfos[otherinfoNo].oidval = oidval;
4180 if (extraOtherInfos[otherinfoNo].value)
4181 xfree(extraOtherInfos[otherinfoNo].value);
4182 extraOtherInfos[otherinfoNo].value = xstrdup(otherinfoString);
4187 int cmd_sleep(const char* args )
4196 printf("Done sleeping %d seconds\n", sec);
4201 int cmd_list_otherinfo(const char* args)
4205 if(strlen(args)>0) {
4207 if( i >= maxOtherInfosSupported ) {
4208 printf("Error otherinfo index to large (%d>%d)\n",i,maxOtherInfosSupported);
4212 if(extraOtherInfos[i].oidval != -1)
4213 printf(" otherinfo %d %s %s\n",
4215 yaz_z3950_oid_value_to_str(
4216 (enum oid_value) extraOtherInfos[i].oidval,
4218 extraOtherInfos[i].value);
4221 for(i=0; i<maxOtherInfosSupported; ++i) {
4222 if(extraOtherInfos[i].oidval != -1)
4223 printf(" otherinfo %d %s %s\n",
4225 yaz_z3950_oid_value_to_str(
4226 (enum oid_value) extraOtherInfos[i].oidval,
4228 extraOtherInfos[i].value);
4236 int cmd_list_all(const char* args) {
4239 /* connection options */
4241 printf("Connected to : %s\n",last_open_command);
4243 if(last_open_command)
4244 printf("Not connected to : %s\n",last_open_command);
4246 printf("Not connected : \n");
4249 if(yazProxy) printf("using proxy : %s\n",yazProxy);
4251 printf("auto_reconnect : %s\n",auto_reconnect?"on":"off");
4252 printf("auto_wait : %s\n",auto_wait?"on":"off");
4255 printf("Authentication : none\n");
4257 switch(auth->which) {
4258 case Z_IdAuthentication_idPass:
4259 printf("Authentication : IdPass\n");
4260 printf(" Login User : %s\n",auth->u.idPass->userId?auth->u.idPass->userId:"");
4261 printf(" Login Group : %s\n",auth->u.idPass->groupId?auth->u.idPass->groupId:"");
4262 printf(" Password : %s\n",auth->u.idPass->password?auth->u.idPass->password:"");
4264 case Z_IdAuthentication_open:
4265 printf("Authentication : psOpen\n");
4266 printf(" Open string : %s\n",auth->u.open);
4269 printf("Authentication : Unknown\n");
4272 if (negotiationCharset)
4273 printf("Neg. Character set : `%s'\n", negotiationCharset);
4277 for (i = 0; i<num_databaseNames; i++) printf("%s ",databaseNames[i]);
4281 printf("CCL file : %s\n",ccl_fields);
4282 printf("CQL file : %s\n",cql_fields);
4283 printf("Query type : %s\n",query_type_as_string(queryType));
4285 printf("Named Result Sets : %s\n",setnumber==-1?"off":"on");
4287 /* piggy back options */
4288 printf("ssub/lslb/mspn : %d/%d/%d\n",smallSetUpperBound,largeSetLowerBound,mediumSetPresentNumber);
4290 /* print present related options */
4291 printf("Format : %s\n",
4292 (recordsyntax_size > 0) ?
4293 yaz_z3950_oid_value_to_str(recordsyntax_list[0], CLASS_RECSYN) :
4295 printf("Schema : %s\n",record_schema ? record_schema : "not set");
4296 printf("Elements : %s\n",elementSetNames?elementSetNames->u.generic:"");
4298 /* loging options */
4299 printf("APDU log : %s\n",apdu_file?"on":"off");
4300 printf("Record log : %s\n",marc_file?"on":"off");
4303 printf("Other Info: \n");
4304 cmd_list_otherinfo("");
4309 int cmd_clear_otherinfo(const char* args)
4311 if(strlen(args)>0) {
4312 int otherinfoNo = atoi(args);
4313 if (otherinfoNo >= maxOtherInfosSupported) {
4314 printf("Error otherinfo index too large (%d>=%d)\n",
4315 otherinfoNo, maxOtherInfosSupported);
4318 if (extraOtherInfos[otherinfoNo].oidval != -1)
4320 /* only clear if set. */
4321 extraOtherInfos[otherinfoNo].oidval = -1;
4322 xfree(extraOtherInfos[otherinfoNo].value);
4326 for(i = 0; i < maxOtherInfosSupported; ++i)
4328 if (extraOtherInfos[i].oidval != -1)
4330 extraOtherInfos[i].oidval = -1;
4331 xfree(extraOtherInfos[i].value);
4338 int cmd_wait_response(const char *arg)
4340 int wait_for = atoi(arg);
4342 if( wait_for < 1 ) {
4346 for( i=0 ; i < wait_for ; ++i ) {
4347 wait_and_handle_response(1);
4352 static int cmd_help (const char *line);
4354 typedef char *(*completerFunctionType)(const char *text, int state);
4358 int (*fun)(const char *arg);
4360 completerFunctionType rl_completerfunction;
4361 int complete_filenames;
4362 char **local_tabcompletes;
4364 {"open", cmd_open, "('tcp'|'ssl')':<host>[':'<port>][/<db>]",NULL,0,NULL},
4365 {"quit", cmd_quit, "",NULL,0,NULL},
4366 {"find", cmd_find, "<query>",NULL,0,NULL},
4367 {"delete", cmd_delete, "<setname>",NULL,0,NULL},
4368 {"base", cmd_base, "<base-name>",NULL,0,NULL},
4369 {"show", cmd_show, "<rec#>['+'<#recs>['+'<setname>]]",NULL,0,NULL},
4370 {"scan", cmd_scan, "<term>",NULL,0,NULL},
4371 {"scanstep", cmd_scanstep, "<size>",NULL,0,NULL},
4372 {"scanpos", cmd_scanpos, "<size>",NULL,0,NULL},
4373 {"scansize", cmd_scansize, "<size>",NULL,0,NULL},
4374 {"sort", cmd_sort, "<sortkey> <flag> <sortkey> <flag> ...",NULL,0,NULL},
4375 {"sort+", cmd_sort_newset, "<sortkey> <flag> <sortkey> <flag> ...",NULL,0,NULL},
4376 {"authentication", cmd_authentication, "<acctstring>",NULL,0,NULL},
4377 {"lslb", cmd_lslb, "<largeSetLowerBound>",NULL,0,NULL},
4378 {"ssub", cmd_ssub, "<smallSetUpperBound>",NULL,0,NULL},
4379 {"mspn", cmd_mspn, "<mediumSetPresentNumber>",NULL,0,NULL},
4380 {"status", cmd_status, "",NULL,0,NULL},
4381 {"setnames", cmd_setnames, "",NULL,0,NULL},
4382 {"cancel", cmd_cancel, "",NULL,0,NULL},
4383 {"cancel_find", cmd_cancel_find, "<query>",NULL,0,NULL},
4384 {"format", cmd_format, "<recordsyntax>",complete_format,0,NULL},
4385 {"schema", cmd_schema, "<schema>",complete_schema,0,NULL},
4386 {"elements", cmd_elements, "<elementSetName>",NULL,0,NULL},
4387 {"close", cmd_close, "",NULL,0,NULL},
4388 {"attributeset", cmd_attributeset, "<attrset>",complete_attributeset,0,NULL},
4389 {"querytype", cmd_querytype, "<type>",complete_querytype,0,NULL},
4390 {"refid", cmd_refid, "<id>",NULL,0,NULL},
4391 {"itemorder", cmd_itemorder, "ill|item|xml <itemno>",NULL,0,NULL},
4392 {"update", cmd_update, "<action> <recid> [<doc>]",NULL,0,NULL},
4393 {"update0", cmd_update0, "<action> <recid> [<doc>]",NULL,0,NULL},
4394 {"xmles", cmd_xmles, "<OID> <doc>",NULL,0,NULL},
4395 {"packagename", cmd_packagename, "<packagename>",NULL,0,NULL},
4396 {"proxy", cmd_proxy, "[('tcp'|'ssl')]<host>[':'<port>]",NULL,0,NULL},
4397 {"charset", cmd_charset, "<nego_charset> <output_charset>",NULL,0,NULL},
4398 {"negcharset", cmd_negcharset, "<nego_charset>",NULL,0,NULL},
4399 {"displaycharset", cmd_displaycharset, "<output_charset>",NULL,0,NULL},
4400 {"marccharset", cmd_marccharset, "<charset_name>",NULL,0,NULL},
4401 {"lang", cmd_lang, "<language_code>",NULL,0,NULL},
4402 {"source", cmd_source_echo, "<filename>",NULL,1,NULL},
4403 {".", cmd_source_echo, "<filename>",NULL,1,NULL},
4404 {"!", cmd_subshell, "Subshell command",NULL,1,NULL},
4405 {"set_apdufile", cmd_set_apdufile, "<filename>",NULL,1,NULL},
4406 {"set_berfile", cmd_set_berfile, "<filename>",NULL,1,NULL},
4407 {"set_marcdump", cmd_set_marcdump," <filename>",NULL,1,NULL},
4408 {"set_cclfile", cmd_set_cclfile," <filename>",NULL,1,NULL},
4409 {"set_cqlfile", cmd_set_cqlfile," <filename>",NULL,1,NULL},
4410 {"set_auto_reconnect", cmd_set_auto_reconnect," on|off",complete_auto_reconnect,1,NULL},
4411 {"set_auto_wait", cmd_set_auto_wait," on|off",complete_auto_reconnect,1,NULL},
4412 {"set_otherinfo", cmd_set_otherinfo,"<otherinfoinddex> <oid> <string>",NULL,0,NULL},
4413 {"sleep", cmd_sleep,"<seconds>",NULL,0,NULL},
4414 {"register_oid", cmd_register_oid,"<name> <class> <oid>",NULL,0,NULL},
4415 {"push_command", cmd_push_command,"<command>",command_generator,0,NULL},
4416 {"register_tab", cmd_register_tab,"<commandname> <tab>",command_generator,0,NULL},
4417 {"cclparse", cmd_cclparse,"<ccl find command>",NULL,0,NULL},
4418 {"list_otherinfo",cmd_list_otherinfo,"[otherinfoinddex]",NULL,0,NULL},
4419 {"list_all",cmd_list_all,"",NULL,0,NULL},
4420 {"clear_otherinfo",cmd_clear_otherinfo,"",NULL,0,NULL},
4421 {"wait_response",cmd_wait_response,"<number>",NULL,0,NULL},
4422 /* Server Admin Functions */
4423 {"adm-reindex", cmd_adm_reindex, "<database-name>",NULL,0,NULL},
4424 {"adm-truncate", cmd_adm_truncate, "('database'|'index')<object-name>",NULL,0,NULL},
4425 {"adm-create", cmd_adm_create, "",NULL,0,NULL},
4426 {"adm-drop", cmd_adm_drop, "('database'|'index')<object-name>",NULL,0,NULL},
4427 {"adm-import", cmd_adm_import, "<record-type> <dir> <pattern>",NULL,0,NULL},
4428 {"adm-refresh", cmd_adm_refresh, "",NULL,0,NULL},
4429 {"adm-commit", cmd_adm_commit, "",NULL,0,NULL},
4430 {"adm-shutdown", cmd_adm_shutdown, "",NULL,0,NULL},
4431 {"adm-startup", cmd_adm_startup, "",NULL,0,NULL},
4432 {"explain", cmd_explain, "", NULL, 0, NULL},
4433 {"options", cmd_options, "", NULL, 0, NULL},
4434 {"zversion", cmd_zversion, "", NULL, 0, NULL},
4435 {"help", cmd_help, "", NULL,0,NULL},
4436 {"init", cmd_init, "", NULL,0,NULL},
4437 {"sru", cmd_sru, "", NULL,0,NULL},
4438 {"exit", cmd_quit, "",NULL,0,NULL},
4442 static int cmd_help (const char *line)
4448 sscanf (line, "%20s", topic);
4451 printf("Commands:\n");
4452 for (i = 0; cmd_array[i].cmd; i++)
4453 if (*topic == 0 || strcmp (topic, cmd_array[i].cmd) == 0)
4454 printf(" %s %s\n", cmd_array[i].cmd, cmd_array[i].ad);
4455 if (!strcmp(topic, "find"))
4458 printf(" \"term\" Simple Term\n");
4459 printf(" @attr [attset] type=value op Attribute\n");
4460 printf(" @and opl opr And\n");
4461 printf(" @or opl opr Or\n");
4462 printf(" @not opl opr And-Not\n");
4463 printf(" @set set Result set\n");
4464 printf(" @prox exl dist ord rel uc ut Proximity. Use help prox\n");
4466 printf("Bib-1 attribute types\n");
4468 printf("4=Title 7=ISBN 8=ISSN 30=Date 62=Abstract 1003=Author 1016=Any\n");
4469 printf("2=Relation: ");
4470 printf("1< 2<= 3= 4>= 5> 6!= 102=Relevance\n");
4471 printf("3=Position: ");
4472 printf("1=First in Field 2=First in subfield 3=Any position\n");
4473 printf("4=Structure: ");
4474 printf("1=Phrase 2=Word 3=Key 4=Year 5=Date 6=WordList\n");
4475 printf("5=Truncation: ");
4476 printf("1=Right 2=Left 3=L&R 100=No 101=# 102=Re-1 103=Re-2\n");
4477 printf("6=Completeness:");
4478 printf("1=Incomplete subfield 2=Complete subfield 3=Complete field\n");
4480 if (!strcmp(topic, "prox"))
4482 printf("Proximity:\n");
4483 printf(" @prox exl dist ord rel uc ut\n");
4484 printf(" exl: exclude flag . 0=include, 1=exclude.\n");
4485 printf(" dist: distance integer.\n");
4486 printf(" ord: order flag. 0=unordered, 1=ordered.\n");
4487 printf(" rel: relation integer. 1< 2<= 3= 4>= 5> 6!= .\n");
4488 printf(" uc: unit class. k=known, p=private.\n");
4489 printf(" ut: unit type. 1=character, 2=word, 3=sentence,\n");
4490 printf(" 4=paragraph, 5=section, 6=chapter, 7=document,\n");
4491 printf(" 8=element, 9=subelement, 10=elementType, 11=byte.\n");
4492 printf("\nExamples:\n");
4493 printf(" Search for a and b in-order at most 3 words apart:\n");
4494 printf(" @prox 0 3 1 2 k 2 a b\n");
4495 printf(" Search for any order of a and b next to each other:\n");
4496 printf(" @prox 0 1 0 3 k 2 a b\n");
4501 int cmd_register_tab(const char* arg)
4503 #if HAVE_READLINE_READLINE_H
4504 char command[101], tabargument[101];
4509 if (sscanf (arg, "%100s %100s", command, tabargument) < 1) {
4513 /* locate the amdn in the list */
4514 for (i = 0; cmd_array[i].cmd; i++) {
4515 if (!strncmp(cmd_array[i].cmd, command, strlen(command))) {
4520 if (!cmd_array[i].cmd) {
4521 fprintf(stderr,"Unknown command %s\n",command);
4526 if (!cmd_array[i].local_tabcompletes)
4527 cmd_array[i].local_tabcompletes = (char **) calloc(1,sizeof(char**));
4531 tabslist = cmd_array[i].local_tabcompletes;
4532 for(; tabslist && *tabslist; tabslist++) {
4536 cmd_array[i].local_tabcompletes = (char **)
4537 realloc(cmd_array[i].local_tabcompletes,
4538 (num_of_tabs+2)*sizeof(char**));
4539 tabslist = cmd_array[i].local_tabcompletes;
4540 tabslist[num_of_tabs] = strdup(tabargument);
4541 tabslist[num_of_tabs+1] = NULL;
4547 void process_cmd_line(char* line)
4550 char word[32], arg[10240];
4552 #if HAVE_GETTIMEOFDAY
4553 gettimeofday (&tv_start, 0);
4556 if ((res = sscanf(line, "%31s %10239[^;]", word, arg)) <= 0)
4558 strcpy(word, last_cmd);
4563 strcpy(last_cmd, word);
4565 /* removed tailing spaces from the arg command */
4568 char* lastnonspace=NULL;
4571 if(!isspace(*(unsigned char *) p)) {
4576 *(++lastnonspace) = 0;
4579 for (i = 0; cmd_array[i].cmd; i++)
4580 if (!strncmp(cmd_array[i].cmd, word, strlen(word)))
4582 res = (*cmd_array[i].fun)(arg);
4586 if (!cmd_array[i].cmd) /* dump our help-screen */
4588 printf("Unknown command: %s.\n", word);
4589 printf("Type 'help' for list of commands\n");
4593 if(apdu_file) fflush(apdu_file);
4595 if (res >= 2 && auto_wait)
4596 wait_and_handle_response(0);
4604 static char *command_generator(const char *text, int state)
4606 #if HAVE_READLINE_READLINE_H
4611 for( ; cmd_array[idx].cmd; ++idx) {
4612 if (!strncmp(cmd_array[idx].cmd, text, strlen(text))) {
4613 ++idx; /* skip this entry on the next run */
4614 return strdup(cmd_array[idx-1].cmd);
4621 #if HAVE_READLINE_READLINE_H
4622 static char** default_completer_list = NULL;
4624 static char* default_completer(const char* text, int state)
4626 return complete_from_list(default_completer_list, text, state);
4630 #if HAVE_READLINE_READLINE_H
4633 This function only known how to complete on the first word
4635 char **readline_completer(char *text, int start, int end)
4637 completerFunctionType completerToUse;
4640 #if HAVE_READLINE_RL_COMPLETION_MATCHES
4641 char** res = rl_completion_matches(text, command_generator);
4643 char** res = completion_matches(text,
4644 (CPFunction*)command_generator);
4646 rl_attempted_completion_over = 1;
4649 char arg[10240],word[32];
4651 if ((res = sscanf(rl_line_buffer, "%31s %10239[^;]", word, arg)) <= 0) {
4652 rl_attempted_completion_over = 1;
4656 for (i = 0; cmd_array[i].cmd; i++)
4657 if (!strncmp(cmd_array[i].cmd, word, strlen(word)))
4660 if(!cmd_array[i].cmd)
4663 default_completer_list = cmd_array[i].local_tabcompletes;
4665 completerToUse = cmd_array[i].rl_completerfunction;
4666 if (!completerToUse)
4667 { /* if command completer is not defined use the default completer */
4668 completerToUse = default_completer;
4670 if (completerToUse) {
4671 #ifdef HAVE_READLINE_RL_COMPLETION_MATCHES
4673 rl_completion_matches(text, completerToUse);
4676 completion_matches(text, (CPFunction*)completerToUse);
4678 if (!cmd_array[i].complete_filenames)
4679 rl_attempted_completion_over = 1;
4682 if (!cmd_array[i].complete_filenames)
4683 rl_attempted_completion_over = 1;
4691 void ctrl_c_handler(int x)
4697 static void client(void)
4704 signal(SIGINT, ctrl_c_handler);
4707 #if HAVE_GETTIMEOFDAY
4708 gettimeofday (&tv_start, 0);
4713 char *line_in = NULL;
4714 #if HAVE_READLINE_READLINE_H
4717 line_in=readline(C_PROMPT);
4720 #if HAVE_READLINE_HISTORY_H
4722 add_history(line_in);
4724 strncpy(line, line_in, sizeof(line)-1);
4733 if (!fgets(line, sizeof(line)-1, stdin))
4735 if ((end_p = strchr (line, '\n')))
4739 file_history_add_line(file_history, line);
4740 process_cmd_line(line);
4744 static void show_version(void)
4748 yaz_version(vstr, 0);
4749 printf ("YAZ version: %s\n", YAZ_VERSION);
4750 if (strcmp(vstr, YAZ_VERSION))
4751 printf ("YAZ DLL/SO: %s\n", vstr);
4755 int main(int argc, char **argv)
4758 char *open_command = 0;
4759 char *auth_command = 0;
4764 if (!setlocale(LC_CTYPE, ""))
4765 fprintf (stderr, "setlocale failed\n");
4769 codeset = nl_langinfo(CODESET);
4773 outputCharset = xstrdup(codeset);
4775 ODR_MASK_SET(&z3950_options, Z_Options_search);
4776 ODR_MASK_SET(&z3950_options, Z_Options_present);
4777 ODR_MASK_SET(&z3950_options, Z_Options_namedResultSets);
4778 ODR_MASK_SET(&z3950_options, Z_Options_triggerResourceCtrl);
4779 ODR_MASK_SET(&z3950_options, Z_Options_scan);
4780 ODR_MASK_SET(&z3950_options, Z_Options_sort);
4781 ODR_MASK_SET(&z3950_options, Z_Options_extendedServices);
4782 ODR_MASK_SET(&z3950_options, Z_Options_delSet);
4784 while ((ret = options("k:c:q:a:b:m:v:p:u:t:Vxd:", argv, argc, &arg)) != -2)
4791 open_command = (char *) xmalloc (strlen(arg)+6);
4792 strcpy (open_command, "open ");
4793 strcat (open_command, arg);
4797 fprintf(stderr, "%s: Specify at most one server address\n",
4803 dump_file_prefix = arg;
4806 kilobytes = atoi(arg);
4809 if (!(marc_file = fopen (arg, "a")))
4816 outputCharset = xstrdup(arg);
4819 strncpy (ccl_fields, arg, sizeof(ccl_fields)-1);
4820 ccl_fields[sizeof(ccl_fields)-1] = '\0';
4823 strncpy (cql_fields, arg, sizeof(cql_fields)-1);
4824 cql_fields[sizeof(cql_fields)-1] = '\0';
4827 if (!strcmp(arg, "-"))
4830 ber_file=fopen(arg, "a");
4833 if (!strcmp(arg, "-"))
4836 apdu_file=fopen(arg, "a");
4842 yazProxy = xstrdup(arg);
4847 auth_command = (char *) xmalloc (strlen(arg)+6);
4848 strcpy (auth_command, "auth ");
4849 strcat (auth_command, arg);
4853 yaz_log_init(yaz_log_mask_str(arg), "", 0);
4859 fprintf (stderr, "Usage: %s "
4866 " [-p <proxy-addr>]"
4870 " [<server-addr>]\n",
4878 #ifdef HAVE_GETTIMEOFDAY
4879 gettimeofday (&tv_start, 0);
4881 process_cmd_line (auth_command);
4882 #if HAVE_READLINE_HISTORY_H
4883 add_history(auth_command);
4885 xfree(auth_command);
4889 #ifdef HAVE_GETTIMEOFDAY
4890 gettimeofday (&tv_start, 0);
4892 process_cmd_line (open_command);
4893 #if HAVE_READLINE_HISTORY_H
4894 add_history(open_command);
4896 xfree(open_command);
4905 * indent-tabs-mode: nil
4907 * vim: shiftwidth=4 tabstop=8 expandtab