2 * Copyright (c) 1995-2004, Index Data
3 * See the file LICENSE for details.
5 * $Id: client.c,v 1.249 2004-09-13 09:24:42 adam Exp $
19 #if HAVE_OPENSSL_SSL_H
20 #include <openssl/bio.h>
21 #include <openssl/crypto.h>
22 #include <openssl/x509.h>
23 #include <openssl/pem.h>
24 #include <openssl/ssl.h>
25 #include <openssl/err.h>
33 #define S_ISREG(x) (x & _S_IFREG)
34 #define S_ISDIR(x) (x & _S_IFDIR)
37 #include <yaz/yaz-util.h>
39 #include <yaz/comstack.h>
41 #include <yaz/proto.h>
42 #include <yaz/marcdisp.h>
43 #include <yaz/diagbib1.h>
44 #include <yaz/otherinfo.h>
45 #include <yaz/charneg.h>
47 #include <yaz/pquery.h>
48 #include <yaz/sortspec.h>
52 #include <yaz/yaz-ccl.h>
55 #if HAVE_READLINE_READLINE_H
56 #include <readline/readline.h>
59 #if HAVE_READLINE_HISTORY_H
60 #include <readline/history.h>
66 #include "tabcomplete.h"
68 #define C_PROMPT "Z> "
70 static char *codeset = 0; /* character set for output */
71 static int hex_dump = 0;
72 static char *dump_file_prefix = 0;
73 static ODR out, in, print; /* encoding and decoding streams */
75 static ODR srw_sr_odr_out = 0;
76 static Z_SRW_PDU *srw_sr = 0;
78 static FILE *apdu_file = 0;
79 static FILE *ber_file = 0;
80 static COMSTACK conn = 0; /* our z-association */
81 static Z_IdAuthentication *auth = 0; /* our current auth definition */
82 char *databaseNames[128];
83 int num_databaseNames = 0;
84 static Z_External *record_last = 0;
85 static int setnumber = -1; /* current result set number */
86 static int smallSetUpperBound = 0;
87 static int largeSetLowerBound = 1;
88 static int mediumSetPresentNumber = 0;
89 static Z_ElementSetNames *elementSetNames = 0;
90 static int setno = 1; /* current set offset */
91 static enum oid_proto protocol = PROTO_Z3950; /* current app protocol */
92 static enum oid_value recordsyntax = VAL_USMARC;
93 static char *record_schema = 0;
94 static int sent_close = 0;
95 static NMEM session_mem = NULL; /* memory handle for init-response */
96 static Z_InitResponse *session = 0; /* session parameters */
97 static char last_scan_line[512] = "0";
98 static char last_scan_query[512] = "0";
99 static char ccl_fields[512] = "default.bib";
100 /* ### How can I set this path to use wherever YAZ is installed? */
101 static char cql_fields[512] = "/usr/local/share/yaz/etc/pqf.properties";
102 static char *esPackageName = 0;
103 static char *yazProxy = 0;
104 static int kilobytes = 1024;
105 static char *negotiationCharset = 0;
106 static char *outputCharset = 0;
107 static char *marcCharset = 0;
108 static char* yazLang = 0;
109 static char* http_version = "1.1";
111 static char last_cmd[32] = "?";
112 static FILE *marc_file = 0;
113 static char *refid = NULL;
114 static char *last_open_command = NULL;
115 static int auto_reconnect = 0;
116 static Odr_bitmask z3950_options;
117 static int z3950_version = 3;
119 static char cur_host[200];
129 static QueryType queryType = QueryType_Prefix;
131 static CCL_bibset bibset; /* CCL bibset handle */
132 static cql_transform_t cqltrans; /* CQL context-set handle */
134 #if HAVE_READLINE_COMPLETION_OVER
137 /* readline doesn't have this var. Define it ourselves. */
138 int rl_attempted_completion_over = 0;
141 /* set this one to 1, to avoid decode of unknown MARCs */
142 #define AVOID_MARC_DECODE 1
144 #define maxOtherInfosSupported 10
148 } extraOtherInfos[maxOtherInfosSupported];
151 void process_cmd_line(char* line);
152 char ** readline_completer(char *text, int start, int end);
153 char *command_generator(const char *text, int state);
154 char** curret_global_list=NULL;
155 int cmd_register_tab(const char* arg);
157 static void close_session (void);
159 ODR getODROutputStream()
164 const char* query_type_as_string(QueryType q)
167 case QueryType_Prefix: return "prefix (RPN sent to server)";
168 case QueryType_CCL: return "CCL (CCL sent to server) ";
169 case QueryType_CCL2RPN: return "CCL -> RPN (RPN sent to server)";
170 case QueryType_CQL: return "CQL (CQL sent to server)";
171 case QueryType_CQL2RPN: return "CQL -> RPN (RPN sent to server)";
173 return "unknown Query type internal yaz-client error";
177 static void do_hex_dump(const char* buf, int len)
182 for( i=0; i<len ; i=i+16 )
185 for(x=0 ; i+x<len && x<16; ++x)
187 printf("%2.2X ",(unsigned int)((unsigned char)buf[i+x]));
192 if (dump_file_prefix)
195 if (++no < 1000 && strlen(dump_file_prefix) < 500)
199 sprintf (fname, "%s.%03d.raw", dump_file_prefix, no);
200 of = fopen(fname, "wb");
202 fwrite (buf, 1, len, of);
209 void add_otherInfos(Z_APDU *a)
211 Z_OtherInformation **oi;
215 for(i=0; i<maxOtherInfosSupported; ++i)
217 if(extraOtherInfos[i].oidval != -1)
218 yaz_oi_set_string_oidval(oi, out, extraOtherInfos[i].oidval,
219 1, extraOtherInfos[i].value);
223 int send_apdu(Z_APDU *a)
232 z_APDU(print, &a, 0, 0);
235 if (!z_APDU(out, &a, 0, 0))
237 odr_perror(out, "Encoding APDU");
241 buf = odr_getbuf(out, &len, 0);
243 odr_dumpBER(ber_file, buf, len);
244 /* printf ("sending APDU of size %d\n", len); */
245 do_hex_dump(buf, len);
246 if (cs_put(conn, buf, len) < 0)
248 fprintf(stderr, "cs_put: %s", cs_errmsg(cs_errno(conn)));
252 odr_reset(out); /* release the APDU structure */
256 static void print_stringn(const unsigned char *buf, size_t len)
259 for (i = 0; i<len; i++)
260 if ((buf[i] <= 126 && buf[i] >= 32) || strchr ("\n\r\t\f", buf[i]))
261 printf ("%c", buf[i]);
263 printf ("\\X%02X", buf[i]);
266 static void print_refid (Z_ReferenceId *id)
270 printf ("Reference Id: ");
271 print_stringn (id->buf, id->len);
276 static Z_ReferenceId *set_refid (ODR out)
281 id = (Z_ReferenceId *) odr_malloc (out, sizeof(*id));
282 id->size = id->len = strlen(refid);
283 id->buf = (unsigned char *) odr_malloc (out, id->len);
284 memcpy (id->buf, refid, id->len);
288 /* INIT SERVICE ------------------------------- */
290 static void send_initRequest(const char* type_and_host)
292 Z_APDU *apdu = zget_APDU(out, Z_APDU_initRequest);
293 Z_InitRequest *req = apdu->u.initRequest;
296 req->options = &z3950_options;
298 ODR_MASK_ZERO(req->protocolVersion);
299 for (i = 0; i<z3950_version; i++)
300 ODR_MASK_SET(req->protocolVersion, i);
302 *req->maximumRecordSize = 1024*kilobytes;
303 *req->preferredMessageSize = 1024*kilobytes;
305 req->idAuthentication = auth;
307 req->referenceId = set_refid (out);
309 if (yazProxy && type_and_host)
310 yaz_oi_set_string_oidval(&req->otherInfo, out, VAL_PROXY,
313 if (negotiationCharset || yazLang) {
314 Z_OtherInformation **p;
315 Z_OtherInformationUnit *p0;
317 yaz_oi_APDU(apdu, &p);
319 if ((p0=yaz_oi_update(p, out, NULL, 0, 0))) {
320 ODR_MASK_SET(req->options, Z_Options_negotiationModel);
322 p0->which = Z_OtherInfo_externallyDefinedInfo;
323 p0->information.externallyDefinedInfo =
324 yaz_set_proposal_charneg(
326 (const char**)&negotiationCharset,
327 negotiationCharset ? 1 : 0,
328 (const char**)&yazLang, yazLang ? 1 : 0, 1);
333 printf("Sent initrequest.\n");
337 /* These two are used only from process_initResponse() */
338 static void render_initUserInfo(Z_OtherInformation *ui1);
339 static void render_diag(Z_DiagnosticFormat *diag);
341 static void pr_opt(const char *opt, void *clientData)
346 static int process_initResponse(Z_InitResponse *res)
349 /* save session parameters for later use */
350 session_mem = odr_extract_mem(in);
353 for (ver = 0; ver < 8; ver++)
354 if (!ODR_MASK_GET(res->protocolVersion, ver))
358 printf("Connection rejected by v%d target.\n", ver);
360 printf("Connection accepted by v%d target.\n", ver);
361 if (res->implementationId)
362 printf("ID : %s\n", res->implementationId);
363 if (res->implementationName)
364 printf("Name : %s\n", res->implementationName);
365 if (res->implementationVersion)
366 printf("Version: %s\n", res->implementationVersion);
367 if (res->userInformationField)
369 Z_External *uif = res->userInformationField;
370 if (uif->which == Z_External_userInfo1) {
371 render_initUserInfo(uif->u.userInfo1);
373 printf("UserInformationfield:\n");
374 if (!z_External(print, (Z_External**)&uif, 0, 0)) {
375 odr_perror(print, "Printing userinfo\n");
378 if (uif->which == Z_External_octet) {
379 printf("Guessing visiblestring:\n");
380 printf("'%s'\n", uif->u. octet_aligned->buf);
381 } else if (uif->which == Z_External_single) {
382 Odr_any *sat = uif->u.single_ASN1_type;
383 oident *oid = oid_getentbyoid(uif->direct_reference);
384 if (oid->value == VAL_OCLCUI) {
385 Z_OCLC_UserInformation *oclc_ui;
386 ODR decode = odr_createmem(ODR_DECODE);
387 odr_setbuf(decode, sat->buf, sat->len, 0);
388 if (!z_OCLC_UserInformation(decode, &oclc_ui, 0, 0))
389 printf ("Bad OCLC UserInformation:\n");
391 printf ("OCLC UserInformation:\n");
392 if (!z_OCLC_UserInformation(print, &oclc_ui, 0, 0))
393 printf ("Bad OCLC UserInformation spec\n");
398 /* Peek at any private Init-diagnostic APDUs */
399 printf("### NAUGHTY: External is '%.*s'\n", sat->len, sat->buf);
406 yaz_init_opt_decode(res->options, pr_opt, 0);
409 if (ODR_MASK_GET(res->options, Z_Options_namedResultSets))
412 if (ODR_MASK_GET(res->options, Z_Options_negotiationModel)) {
414 Z_CharSetandLanguageNegotiation *p =
415 yaz_get_charneg_record(res->otherInfo);
419 char *charset=NULL, *lang=NULL;
422 yaz_get_response_charneg(session_mem, p, &charset, &lang,
425 if (outputCharset && negotiationCharset) {
426 odr_set_charset (out, charset, outputCharset);
427 odr_set_charset (in, outputCharset, charset);
430 odr_set_charset (out, 0, 0);
431 odr_set_charset (in, 0, 0);
434 printf("Accepted character set : %s\n", charset);
435 printf("Accepted code language : %s\n", lang ? lang : "none");
436 printf("Accepted records in ...: %d\n", selected );
444 static void render_initUserInfo(Z_OtherInformation *ui1) {
446 printf("Init response contains %d otherInfo unit%s:\n",
447 ui1->num_elements, ui1->num_elements == 1 ? "" : "s");
449 for (i = 0; i < ui1->num_elements; i++) {
450 Z_OtherInformationUnit *unit = ui1->list[i];
451 printf(" %d: otherInfo unit contains ", i+1);
452 if (unit->which == Z_OtherInfo_externallyDefinedInfo &&
453 unit->information.externallyDefinedInfo->which ==
455 render_diag(unit->information.externallyDefinedInfo->u.diag1);
457 printf("unsupported otherInfo unit type %d\n", unit->which);
463 /* ### should this share code with display_diagrecs()? */
464 static void render_diag(Z_DiagnosticFormat *diag) {
467 printf("%d diagnostic%s:\n", diag->num, diag->num == 1 ? "" : "s");
468 for (i = 0; i < diag->num; i++) {
469 Z_DiagnosticFormat_s *ds = diag->elements[i];
470 printf(" %d: ", i+1);
472 case Z_DiagnosticFormat_s_defaultDiagRec: {
473 Z_DefaultDiagFormat *dd = ds->u.defaultDiagRec;
474 /* ### should check `dd->diagnosticSetId' */
475 printf("code=%d (%s)", *dd->condition,
476 diagbib1_str(*dd->condition));
477 /* Both types of addinfo are the same, so use type-pun */
478 if (dd->u.v2Addinfo != 0)
479 printf(",\n\taddinfo='%s'", dd->u.v2Addinfo);
482 case Z_DiagnosticFormat_s_explicitDiagnostic:
483 printf("Explicit diagnostic (not supported)");
486 printf("Unrecognised diagnostic type %d", ds->which);
490 if (ds->message != 0)
491 printf(", message='%s'", ds->message);
497 static int set_base(const char *arg)
502 for (i = 0; i<num_databaseNames; i++)
503 xfree (databaseNames[i]);
504 num_databaseNames = 0;
508 if (!(cp = strchr(arg, ' ')))
509 cp = arg + strlen(arg);
512 databaseNames[num_databaseNames] = (char *)xmalloc (1 + cp - arg);
513 memcpy (databaseNames[num_databaseNames], arg, cp - arg);
514 databaseNames[num_databaseNames][cp - arg] = '\0';
516 for (cp1 = databaseNames[num_databaseNames]; *cp1 ; cp1++)
525 if (num_databaseNames == 0)
527 num_databaseNames = 1;
528 databaseNames[0] = xstrdup("");
533 static int cmd_base(const char *arg)
537 printf("Usage: base <database> <database> ...\n");
540 return set_base(arg);
543 void cmd_open_remember_last_open_command(const char* arg, char* new_open_command)
545 if(last_open_command != arg)
547 if(last_open_command) xfree(last_open_command);
548 last_open_command = xstrdup(new_open_command);
552 int session_connect(const char *arg)
555 char type_and_host[101];
556 const char *basep = 0;
557 #if HAVE_OPENSSL_SSL_H
566 nmem_destroy (session_mem);
570 cs_get_host_args(arg, &basep);
572 strncpy(type_and_host, arg, sizeof(type_and_host)-1);
573 type_and_host[sizeof(type_and_host)-1] = '\0';
575 cmd_open_remember_last_open_command(arg,type_and_host);
578 conn = cs_create_host(yazProxy, 1, &add);
580 conn = cs_create_host(arg, 1, &add);
583 printf ("Couldn't create comstack\n");
587 if (conn->protocol == PROTO_HTTP)
588 queryType = QueryType_CQL;
590 if (conn->protocol == PROTO_HTTP)
592 printf ("SRW/HTTP not enabled in this YAZ\n");
598 protocol = conn->protocol;
599 if (conn->protocol == PROTO_HTTP)
603 printf("Connecting...");
605 if (cs_connect(conn, add) < 0)
607 printf ("error = %s\n", cs_strerror(conn));
608 if (conn->cerrno == CSYSERR)
611 yaz_strerror(msg, sizeof(msg));
612 printf ("%s\n", msg);
619 #if HAVE_OPENSSL_SSL_H
620 if ((ssl = (SSL *) cs_get_ssl(conn)))
622 X509 *server_cert = SSL_get_peer_certificate (ssl);
628 BIO *bio = BIO_new(BIO_s_mem());
630 /* get PEM buffer in memory */
631 PEM_write_bio_X509(bio, server_cert);
632 pem_len = BIO_get_mem_data(bio, &pem_buf);
633 fwrite(pem_buf, pem_len, 1, stdout);
635 /* print all info on screen .. */
636 X509_print_fp(stdout, server_cert);
639 X509_free (server_cert);
645 if (protocol == PROTO_Z3950)
647 send_initRequest(type_and_host);
653 int cmd_open(const char *arg)
657 strncpy (cur_host, arg, sizeof(cur_host)-1);
658 cur_host[sizeof(cur_host)-1] = 0;
660 return session_connect(cur_host);
667 if(!( auto_reconnect && last_open_command) ) return ;
669 open_command = (char *) xmalloc (strlen(last_open_command)+6);
670 strcpy (open_command, "open ");
672 strcat (open_command, last_open_command);
674 process_cmd_line(open_command);
679 int cmd_authentication(const char *arg)
681 static Z_IdAuthentication au;
682 static char user[40], group[40], pass[40];
683 static Z_IdPass idPass;
688 printf("Auth field set to null\n");
692 r = sscanf (arg, "%39s %39s %39s", user, group, pass);
695 printf("Authentication set to null\n");
701 if (!strcmp(user, "-")) {
702 au.which = Z_IdAuthentication_anonymous;
703 printf("Authentication set to Anonymous\n");
705 au.which = Z_IdAuthentication_open;
707 printf("Authentication set to Open (%s)\n", user);
713 au.which = Z_IdAuthentication_idPass;
714 au.u.idPass = &idPass;
715 idPass.groupId = NULL;
716 idPass.userId = user;
717 idPass.password = group;
718 printf("Authentication set to User (%s), Pass (%s)\n", user, group);
723 au.which = Z_IdAuthentication_idPass;
724 au.u.idPass = &idPass;
725 idPass.groupId = group;
726 idPass.userId = user;
727 idPass.password = pass;
728 printf("Authentication set to User (%s), Group (%s), Pass (%s)\n",
734 /* SEARCH SERVICE ------------------------------ */
735 static void display_record(Z_External *r);
737 static void print_record(const unsigned char *buf, size_t len)
740 print_stringn (buf, len);
741 /* add newline if not already added ... */
742 if (i <= 0 || buf[i-1] != '\n')
745 fwrite (buf, 1, len, marc_file);
748 static void display_record(Z_External *r)
750 oident *ent = oid_getentbyoid(r->direct_reference);
754 * Tell the user what we got.
756 if (r->direct_reference)
758 printf("Record type: ");
760 printf("%s\n", ent->desc);
761 else if (!odr_oid(print, &r->direct_reference, 0, 0))
763 odr_perror(print, "print oid");
767 /* Check if this is a known, ASN.1 type tucked away in an octet string */
768 if (ent && r->which == Z_External_octet)
770 Z_ext_typeent *type = z_ext_getentbyref(ent->value);
776 * Call the given decoder to process the record.
778 odr_setbuf(in, (char*)r->u.octet_aligned->buf,
779 r->u.octet_aligned->len, 0);
780 if (!(*type->fun)(in, &rr, 0, 0))
782 odr_perror(in, "Decoding constructed record.");
783 fprintf(stdout, "[Near %d]\n", odr_offset(in));
784 fprintf(stdout, "Packet dump:\n---------\n");
785 odr_dumpBER(stdout, (char*)r->u.octet_aligned->buf,
786 r->u.octet_aligned->len);
787 fprintf(stdout, "---------\n");
789 /* note just ignores the error ant print the bytes form the octet_aligned later */
792 * Note: we throw away the original, BER-encoded record here.
793 * Do something else with it if you want to keep it.
795 r->u.sutrs = (Z_SUTRS *) rr; /* we don't actually check the type here. */
796 r->which = type->what;
800 if (ent && ent->value == VAL_SOIF)
801 print_record((const unsigned char *) r->u.octet_aligned->buf,
802 r->u.octet_aligned->len);
803 else if (r->which == Z_External_octet)
805 const char *octet_buf = (char*)r->u.octet_aligned->buf;
806 if (ent->oclass == CLASS_RECSYN &&
807 (ent->value == VAL_TEXT_XML ||
808 ent->value == VAL_APPLICATION_XML ||
809 ent->value == VAL_HTML))
811 print_record((const unsigned char *) octet_buf,
812 r->u.octet_aligned->len);
814 else if (ent->value == VAL_POSTSCRIPT)
816 int size = r->u.octet_aligned->len;
819 print_record((const unsigned char *) octet_buf, size);
824 #if AVOID_MARC_DECODE
825 /* primitive check for a marc OID 5.1-29 except 16 */
826 ent->oidsuffix[0] == 5 && ent->oidsuffix[1] < 30 &&
827 ent->oidsuffix[1] != 16
836 yaz_marc_t mt = yaz_marc_create();
838 if (yaz_marc_decode_buf(mt, octet_buf,r->u.octet_aligned->len,
842 if (marcCharset && !strcmp(marcCharset, "auto"))
844 if (ent->value == VAL_USMARC)
846 if (octet_buf[9] == 'a')
854 else if (marcCharset)
856 if (outputCharset && from)
858 cd = yaz_iconv_open(outputCharset, from);
859 printf ("convert from %s to %s", from,
862 printf (" unsupported\n");
867 fwrite (result, 1, rlen, stdout);
871 size_t inbytesleft = rlen;
872 const char *inp = result;
876 size_t outbytesleft = sizeof(outbuf);
880 r = yaz_iconv (cd, (char**) &inp,
882 &outp, &outbytesleft);
883 if (r == (size_t) (-1))
885 int e = yaz_iconv_error(cd);
886 if (e != YAZ_ICONV_E2BIG)
889 fwrite (outbuf, outp - outbuf, 1, stdout);
895 printf ("bad MARC. Dumping as it is:\n");
896 print_record((const unsigned char*) octet_buf,
897 r->u.octet_aligned->len);
899 yaz_marc_destroy(mt);
905 print_record((const unsigned char*) octet_buf,
906 r->u.octet_aligned->len);
910 fwrite (octet_buf, 1, r->u.octet_aligned->len, marc_file);
912 else if (ent && ent->value == VAL_SUTRS)
914 if (r->which != Z_External_sutrs)
916 printf("Expecting single SUTRS type for SUTRS.\n");
919 print_record(r->u.sutrs->buf, r->u.sutrs->len);
921 else if (ent && ent->value == VAL_GRS1)
924 if (r->which != Z_External_grs1)
926 printf("Expecting single GRS type for GRS.\n");
930 yaz_display_grs1(w, r->u.grs1, 0);
934 else if ( /* OPAC display not complete yet .. */
935 ent && ent->value == VAL_OPAC)
938 if (r->u.opac->bibliographicRecord)
939 display_record(r->u.opac->bibliographicRecord);
940 for (i = 0; i<r->u.opac->num_holdingsData; i++)
942 Z_HoldingsRecord *h = r->u.opac->holdingsData[i];
943 if (h->which == Z_HoldingsRecord_marcHoldingsRecord)
945 printf ("MARC holdings %d\n", i);
946 display_record(h->u.marcHoldingsRecord);
948 else if (h->which == Z_HoldingsRecord_holdingsAndCirc)
952 Z_HoldingsAndCircData *data = h->u.holdingsAndCirc;
954 printf ("Data holdings %d\n", i);
955 if (data->typeOfRecord)
956 printf ("typeOfRecord: %s\n", data->typeOfRecord);
957 if (data->encodingLevel)
958 printf ("encodingLevel: %s\n", data->encodingLevel);
959 if (data->receiptAcqStatus)
960 printf ("receiptAcqStatus: %s\n", data->receiptAcqStatus);
961 if (data->generalRetention)
962 printf ("generalRetention: %s\n", data->generalRetention);
963 if (data->completeness)
964 printf ("completeness: %s\n", data->completeness);
965 if (data->dateOfReport)
966 printf ("dateOfReport: %s\n", data->dateOfReport);
968 printf ("nucCode: %s\n", data->nucCode);
969 if (data->localLocation)
970 printf ("localLocation: %s\n", data->localLocation);
971 if (data->shelvingLocation)
972 printf ("shelvingLocation: %s\n", data->shelvingLocation);
973 if (data->callNumber)
974 printf ("callNumber: %s\n", data->callNumber);
975 if (data->shelvingData)
976 printf ("shelvingData: %s\n", data->shelvingData);
977 if (data->copyNumber)
978 printf ("copyNumber: %s\n", data->copyNumber);
979 if (data->publicNote)
980 printf ("publicNote: %s\n", data->publicNote);
981 if (data->reproductionNote)
982 printf ("reproductionNote: %s\n", data->reproductionNote);
983 if (data->termsUseRepro)
984 printf ("termsUseRepro: %s\n", data->termsUseRepro);
985 if (data->enumAndChron)
986 printf ("enumAndChron: %s\n", data->enumAndChron);
987 for (j = 0; j<data->num_volumes; j++)
989 printf ("volume %d\n", j);
990 if (data->volumes[j]->enumeration)
991 printf (" enumeration: %s\n",
992 data->volumes[j]->enumeration);
993 if (data->volumes[j]->chronology)
994 printf (" chronology: %s\n",
995 data->volumes[j]->chronology);
996 if (data->volumes[j]->enumAndChron)
997 printf (" enumAndChron: %s\n",
998 data->volumes[j]->enumAndChron);
1000 for (j = 0; j<data->num_circulationData; j++)
1002 printf ("circulation %d\n", j);
1003 if (data->circulationData[j]->availableNow)
1004 printf (" availableNow: %d\n",
1005 *data->circulationData[j]->availableNow);
1006 if (data->circulationData[j]->availablityDate)
1007 printf (" availabiltyDate: %s\n",
1008 data->circulationData[j]->availablityDate);
1009 if (data->circulationData[j]->availableThru)
1010 printf (" availableThru: %s\n",
1011 data->circulationData[j]->availableThru);
1012 if (data->circulationData[j]->restrictions)
1013 printf (" restrictions: %s\n",
1014 data->circulationData[j]->restrictions);
1015 if (data->circulationData[j]->itemId)
1016 printf (" itemId: %s\n",
1017 data->circulationData[j]->itemId);
1018 if (data->circulationData[j]->renewable)
1019 printf (" renewable: %d\n",
1020 *data->circulationData[j]->renewable);
1021 if (data->circulationData[j]->onHold)
1022 printf (" onHold: %d\n",
1023 *data->circulationData[j]->onHold);
1024 if (data->circulationData[j]->enumAndChron)
1025 printf (" enumAndChron: %s\n",
1026 data->circulationData[j]->enumAndChron);
1027 if (data->circulationData[j]->midspine)
1028 printf (" midspine: %s\n",
1029 data->circulationData[j]->midspine);
1030 if (data->circulationData[j]->temporaryLocation)
1031 printf (" temporaryLocation: %s\n",
1032 data->circulationData[j]->temporaryLocation);
1039 printf("Unknown record representation.\n");
1040 if (!z_External(print, &r, 0, 0))
1042 odr_perror(print, "Printing external");
1048 static void display_diagrecs(Z_DiagRec **pp, int num)
1052 Z_DefaultDiagFormat *r;
1054 printf("Diagnostic message(s) from database:\n");
1055 for (i = 0; i<num; i++)
1057 Z_DiagRec *p = pp[i];
1058 if (p->which != Z_DiagRec_defaultFormat)
1060 printf("Diagnostic record not in default format.\n");
1064 r = p->u.defaultFormat;
1065 if (!(ent = oid_getentbyoid(r->diagnosticSetId)) ||
1066 ent->oclass != CLASS_DIAGSET || ent->value != VAL_BIB1)
1067 printf("Missing or unknown diagset\n");
1068 printf(" [%d] %s", *r->condition, diagbib1_str(*r->condition));
1071 case Z_DefaultDiagFormat_v2Addinfo:
1072 printf (" -- v2 addinfo '%s'\n", r->u.v2Addinfo);
1074 case Z_DefaultDiagFormat_v3Addinfo:
1075 printf (" -- v3 addinfo '%s'\n", r->u.v3Addinfo);
1082 static void display_nameplusrecord(Z_NamePlusRecord *p)
1084 if (p->databaseName)
1085 printf("[%s]", p->databaseName);
1086 if (p->which == Z_NamePlusRecord_surrogateDiagnostic)
1087 display_diagrecs(&p->u.surrogateDiagnostic, 1);
1088 else if (p->which == Z_NamePlusRecord_databaseRecord)
1089 display_record(p->u.databaseRecord);
1092 static void display_records(Z_Records *p)
1096 if (p->which == Z_Records_NSD)
1098 Z_DiagRec dr, *dr_p = &dr;
1099 dr.which = Z_DiagRec_defaultFormat;
1100 dr.u.defaultFormat = p->u.nonSurrogateDiagnostic;
1101 display_diagrecs (&dr_p, 1);
1103 else if (p->which == Z_Records_multipleNSD)
1104 display_diagrecs (p->u.multipleNonSurDiagnostics->diagRecs,
1105 p->u.multipleNonSurDiagnostics->num_diagRecs);
1108 printf("Records: %d\n", p->u.databaseOrSurDiagnostics->num_records);
1109 for (i = 0; i < p->u.databaseOrSurDiagnostics->num_records; i++)
1110 display_nameplusrecord(p->u.databaseOrSurDiagnostics->records[i]);
1114 static int send_deleteResultSetRequest(const char *arg)
1119 Z_APDU *apdu = zget_APDU(out, Z_APDU_deleteResultSetRequest);
1120 Z_DeleteResultSetRequest *req = apdu->u.deleteResultSetRequest;
1122 req->referenceId = set_refid (out);
1124 req->num_resultSetList =
1125 sscanf (arg, "%30s %30s %30s %30s %30s %30s %30s %30s",
1126 names[0], names[1], names[2], names[3],
1127 names[4], names[5], names[6], names[7]);
1129 req->deleteFunction = (int *)
1130 odr_malloc (out, sizeof(*req->deleteFunction));
1131 if (req->num_resultSetList > 0)
1133 *req->deleteFunction = Z_DeleteResultSetRequest_list;
1134 req->resultSetList = (char **)
1135 odr_malloc (out, sizeof(*req->resultSetList)*
1136 req->num_resultSetList);
1137 for (i = 0; i<req->num_resultSetList; i++)
1138 req->resultSetList[i] = names[i];
1142 *req->deleteFunction = Z_DeleteResultSetRequest_all;
1143 req->resultSetList = 0;
1147 printf("Sent deleteResultSetRequest.\n");
1152 static int send_srw(Z_SRW_PDU *sr)
1154 const char *charset = negotiationCharset;
1155 const char *host_port = cur_host;
1158 Z_SOAP_Handler h[2] = {
1159 {"http://www.loc.gov/zing/srw/", 0, (Z_SOAP_fun) yaz_srw_codec},
1162 ODR o = odr_createmem(ODR_ENCODE);
1164 Z_SOAP *p = odr_malloc(o, sizeof(*p));
1167 path = odr_malloc(out, strlen(databaseNames[0])+2);
1169 strcpy(path+1, databaseNames[0]);
1171 gdu = z_get_HTTP_Request(out);
1172 gdu->u.HTTP_Request->version = http_version;
1173 gdu->u.HTTP_Request->path = odr_strdup(out, path);
1177 const char *cp0 = strstr(host_port, "://");
1178 const char *cp1 = 0;
1184 cp1 = strchr(cp0, '/');
1186 cp1 = cp0+strlen(cp0);
1190 char *h = odr_malloc(out, cp1 - cp0 + 1);
1191 memcpy (h, cp0, cp1 - cp0);
1193 z_HTTP_header_add(out, &gdu->u.HTTP_Request->headers,
1198 strcpy(ctype, "text/xml");
1199 if (charset && strlen(charset) < 20)
1201 strcat(ctype, "; charset=");
1202 strcat(ctype, charset);
1204 z_HTTP_header_add(out, &gdu->u.HTTP_Request->headers,
1205 "Content-Type", ctype);
1206 z_HTTP_header_add(out, &gdu->u.HTTP_Request->headers,
1207 "SOAPAction", "\"\"");
1208 p->which = Z_SOAP_generic;
1209 p->u.generic = odr_malloc(o, sizeof(*p->u.generic));
1210 p->u.generic->no = 0;
1211 p->u.generic->ns = 0;
1212 p->u.generic->p = sr;
1213 p->ns = "http://schemas.xmlsoap.org/soap/envelope/";
1215 ret = z_soap_codec_enc(o, &p,
1216 &gdu->u.HTTP_Request->content_buf,
1217 &gdu->u.HTTP_Request->content_len, h,
1220 if (z_GDU(out, &gdu, 0, 0))
1228 if (!z_GDU(print, &gdu, 0, 0))
1229 printf ("Failed to print outgoing APDU\n");
1232 buf_out = odr_getbuf(out, &len_out, 0);
1234 /* we don't odr_reset(out), since we may need the buffer again */
1236 do_hex_dump(buf_out, len_out);
1238 r = cs_put(conn, buf_out, len_out);
1250 static int send_SRW_searchRequest(const char *arg)
1256 assert(srw_sr_odr_out == 0);
1257 srw_sr_odr_out = odr_createmem(ODR_ENCODE);
1259 odr_reset(srw_sr_odr_out);
1263 /* save this for later .. when fetching individual records */
1264 srw_sr = sr = yaz_srw_get(srw_sr_odr_out, Z_SRW_searchRetrieve_request);
1266 /* regular request .. */
1267 sr = yaz_srw_get(out, Z_SRW_searchRetrieve_request);
1272 sr->u.request->query_type = Z_SRW_query_type_cql;
1273 sr->u.request->query.cql = odr_strdup(srw_sr_odr_out, arg);
1274 sr->u.request->query_type = Z_SRW_query_type_cql;
1275 sr->u.request->query.cql = odr_strdup(out, arg);
1277 case QueryType_Prefix:
1278 sr->u.request->query_type = Z_SRW_query_type_pqf;
1279 sr->u.request->query.pqf = odr_strdup(srw_sr_odr_out, arg);
1280 sr->u.request->query_type = Z_SRW_query_type_pqf;
1281 sr->u.request->query.pqf = odr_strdup(out, arg);
1284 printf ("Only CQL and PQF supported in SRW\n");
1287 sr->u.request->maximumRecords = odr_intdup(out, 0);
1290 sr->u.request->recordSchema = record_schema;
1291 if (recordsyntax == VAL_TEXT_XML)
1292 sr->u.explain_request->recordPacking = "xml";
1293 return send_srw(sr);
1297 static int send_searchRequest(const char *arg)
1299 Z_APDU *apdu = zget_APDU(out, Z_APDU_searchRequest);
1300 Z_SearchRequest *req = apdu->u.searchRequest;
1302 struct ccl_rpn_node *rpn = NULL;
1304 char setstring[100];
1305 Z_RPNQuery *RPNquery;
1307 YAZ_PQF_Parser pqf_parser;
1309 QueryType myQueryType = queryType;
1312 if (myQueryType == QueryType_CCL2RPN)
1314 rpn = ccl_find_str(bibset, arg, &error, &pos);
1317 printf("CCL ERROR: %s\n", ccl_err_msg(error));
1320 } else if (myQueryType == QueryType_CQL2RPN) {
1321 /* ### All this code should be wrapped in a utility function */
1323 struct cql_node *node;
1324 const char *addinfo;
1325 if (cqltrans == 0) {
1326 printf("Can't use CQL: no translation file. Try set_cqlfile\n");
1329 parser = cql_parser_create();
1330 if ((error = cql_parser_string(parser, arg)) != 0) {
1331 printf("Can't parse CQL: must be a syntax error\n");
1334 node = cql_parser_result(parser);
1335 if ((error = cql_transform_buf(cqltrans, node, pqfbuf,
1336 sizeof pqfbuf)) != 0) {
1337 error = cql_transform_error(cqltrans, &addinfo);
1338 printf ("Can't convert CQL to PQF: %s (addinfo=%s)\n",
1339 cql_strerror(error), addinfo);
1343 myQueryType = QueryType_Prefix;
1346 req->referenceId = set_refid (out);
1347 if (!strcmp(arg, "@big")) /* strictly for troublemaking */
1349 static unsigned char big[2100];
1350 static Odr_oct bigo;
1352 /* send a very big referenceid to test transport stack etc. */
1353 memset(big, 'A', 2100);
1354 bigo.len = bigo.size = 2100;
1356 req->referenceId = &bigo;
1361 sprintf(setstring, "%d", ++setnumber);
1362 req->resultSetName = setstring;
1364 *req->smallSetUpperBound = smallSetUpperBound;
1365 *req->largeSetLowerBound = largeSetLowerBound;
1366 *req->mediumSetPresentNumber = mediumSetPresentNumber;
1367 if (smallSetUpperBound > 0 || (largeSetLowerBound > 1 &&
1368 mediumSetPresentNumber > 0))
1370 req->preferredRecordSyntax =
1371 yaz_oidval_to_z3950oid(out, CLASS_RECSYN, recordsyntax);
1373 req->smallSetElementSetNames =
1374 req->mediumSetElementSetNames = elementSetNames;
1376 req->num_databaseNames = num_databaseNames;
1377 req->databaseNames = databaseNames;
1379 req->query = &query;
1381 switch (myQueryType)
1383 case QueryType_Prefix:
1384 query.which = Z_Query_type_1;
1385 pqf_parser = yaz_pqf_create ();
1386 RPNquery = yaz_pqf_parse (pqf_parser, out, arg);
1389 const char *pqf_msg;
1391 int code = yaz_pqf_error (pqf_parser, &pqf_msg, &off);
1392 printf("%*s^\n", off+4, "");
1393 printf("Prefix query error: %s (code %d)\n", pqf_msg, code);
1395 yaz_pqf_destroy (pqf_parser);
1398 yaz_pqf_destroy (pqf_parser);
1399 query.u.type_1 = RPNquery;
1402 query.which = Z_Query_type_2;
1403 query.u.type_2 = &ccl_query;
1404 ccl_query.buf = (unsigned char*) arg;
1405 ccl_query.len = strlen(arg);
1407 case QueryType_CCL2RPN:
1408 query.which = Z_Query_type_1;
1409 RPNquery = ccl_rpn_query(out, rpn);
1412 printf ("Couldn't convert from CCL to RPN\n");
1415 query.u.type_1 = RPNquery;
1416 ccl_rpn_delete (rpn);
1419 query.which = Z_Query_type_104;
1420 ext = (Z_External *) odr_malloc(out, sizeof(*ext));
1421 ext->direct_reference = odr_getoidbystr(out, "1.2.840.10003.16.2");
1422 ext->indirect_reference = 0;
1423 ext->descriptor = 0;
1424 ext->which = Z_External_CQL;
1425 ext->u.cql = odr_strdup(out, arg);
1426 query.u.type_104 = ext;
1429 printf ("Unsupported query type\n");
1432 if (send_apdu(apdu))
1433 printf("Sent searchRequest.\n");
1438 /* display Query Expression as part of searchResult-1 */
1439 static void display_queryExpression (Z_QueryExpression *qe)
1443 if (qe->which == Z_QueryExpression_term)
1445 if (qe->u.term->queryTerm)
1447 Z_Term *term = qe->u.term->queryTerm;
1448 switch (term->which)
1450 case Z_Term_general:
1451 printf (" %.*s", term->u.general->len, term->u.general->buf);
1453 case Z_Term_characterString:
1454 printf (" %s", term->u.characterString);
1456 case Z_Term_numeric:
1457 printf (" %d", *term->u.numeric);
1467 /* see if we can find USR:SearchResult-1 */
1468 static void display_searchResult (Z_OtherInformation *o)
1473 for (i = 0; i < o->num_elements; i++)
1475 if (o->list[i]->which == Z_OtherInfo_externallyDefinedInfo)
1477 Z_External *ext = o->list[i]->information.externallyDefinedInfo;
1479 if (ext->which == Z_External_searchResult1)
1482 Z_SearchInfoReport *sr = ext->u.searchResult1;
1483 printf ("SearchResult-1:");
1484 for (j = 0; j < sr->num; j++)
1486 if (!sr->elements[j]->subqueryExpression)
1488 display_queryExpression (
1489 sr->elements[j]->subqueryExpression);
1490 display_queryExpression (
1491 sr->elements[j]->subqueryInterpretation);
1492 display_queryExpression (
1493 sr->elements[j]->subqueryRecommendation);
1494 if (sr->elements[j]->subqueryCount)
1495 printf ("(%d)", *sr->elements[j]->subqueryCount);
1503 static int process_searchResponse(Z_SearchResponse *res)
1505 printf ("Received SearchResponse.\n");
1506 print_refid (res->referenceId);
1507 if (*res->searchStatus)
1508 printf("Search was a success.\n");
1510 printf("Search was a bloomin' failure.\n");
1511 printf("Number of hits: %d", *res->resultCount);
1513 printf (", setno %d", setnumber);
1515 display_searchResult (res->additionalSearchInfo);
1516 printf("records returned: %d\n",
1517 *res->numberOfRecordsReturned);
1518 setno += *res->numberOfRecordsReturned;
1520 display_records(res->records);
1524 static void print_level(int iLevel)
1527 for (i = 0; i < iLevel * 4; i++)
1531 static void print_int(int iLevel, const char *pTag, int *pInt)
1535 print_level(iLevel);
1536 printf("%s: %d\n", pTag, *pInt);
1540 static void print_string(int iLevel, const char *pTag, const char *pString)
1542 if (pString != NULL)
1544 print_level(iLevel);
1545 printf("%s: %s\n", pTag, pString);
1549 static void print_oid(int iLevel, const char *pTag, Odr_oid *pOid)
1555 print_level(iLevel);
1556 printf("%s:", pTag);
1557 for (; *pInt != -1; pInt++)
1558 printf(" %d", *pInt);
1563 static void print_referenceId(int iLevel, Z_ReferenceId *referenceId)
1565 if (referenceId != NULL)
1569 print_level(iLevel);
1570 printf("Ref Id (%d, %d): ", referenceId->len, referenceId->size);
1571 for (i = 0; i < referenceId->len; i++)
1572 printf("%c", referenceId->buf[i]);
1577 static void print_string_or_numeric(int iLevel, const char *pTag, Z_StringOrNumeric *pStringNumeric)
1579 if (pStringNumeric != NULL)
1581 switch (pStringNumeric->which)
1583 case Z_StringOrNumeric_string:
1584 print_string(iLevel, pTag, pStringNumeric->u.string);
1587 case Z_StringOrNumeric_numeric:
1588 print_int(iLevel, pTag, pStringNumeric->u.numeric);
1592 print_level(iLevel);
1593 printf("%s: valid type for Z_StringOrNumeric\n", pTag);
1599 static void print_universe_report_duplicate(
1601 Z_UniverseReportDuplicate *pUniverseReportDuplicate)
1603 if (pUniverseReportDuplicate != NULL)
1605 print_level(iLevel);
1606 printf("Universe Report Duplicate: \n");
1608 print_string_or_numeric(iLevel, "Hit No",
1609 pUniverseReportDuplicate->hitno);
1613 static void print_universe_report_hits(
1615 Z_UniverseReportHits *pUniverseReportHits)
1617 if (pUniverseReportHits != NULL)
1619 print_level(iLevel);
1620 printf("Universe Report Hits: \n");
1622 print_string_or_numeric(iLevel, "Database",
1623 pUniverseReportHits->database);
1624 print_string_or_numeric(iLevel, "Hits", pUniverseReportHits->hits);
1628 static void print_universe_report(int iLevel, Z_UniverseReport *pUniverseReport)
1630 if (pUniverseReport != NULL)
1632 print_level(iLevel);
1633 printf("Universe Report: \n");
1635 print_int(iLevel, "Total Hits", pUniverseReport->totalHits);
1636 switch (pUniverseReport->which)
1638 case Z_UniverseReport_databaseHits:
1639 print_universe_report_hits(iLevel,
1640 pUniverseReport->u.databaseHits);
1643 case Z_UniverseReport_duplicate:
1644 print_universe_report_duplicate(iLevel,
1645 pUniverseReport->u.duplicate);
1649 print_level(iLevel);
1650 printf("Type: %d\n", pUniverseReport->which);
1656 static void print_external(int iLevel, Z_External *pExternal)
1658 if (pExternal != NULL)
1660 print_level(iLevel);
1661 printf("External: \n");
1663 print_oid(iLevel, "Direct Reference", pExternal->direct_reference);
1664 print_int(iLevel, "InDirect Reference", pExternal->indirect_reference);
1665 print_string(iLevel, "Descriptor", pExternal->descriptor);
1666 switch (pExternal->which)
1668 case Z_External_universeReport:
1669 print_universe_report(iLevel, pExternal->u.universeReport);
1673 print_level(iLevel);
1674 printf("Type: %d\n", pExternal->which);
1680 static int process_resourceControlRequest (Z_ResourceControlRequest *req)
1682 printf ("Received ResourceControlRequest.\n");
1683 print_referenceId(1, req->referenceId);
1684 print_int(1, "Suspended Flag", req->suspendedFlag);
1685 print_int(1, "Partial Results Available", req->partialResultsAvailable);
1686 print_int(1, "Response Required", req->responseRequired);
1687 print_int(1, "Triggered Request Flag", req->triggeredRequestFlag);
1688 print_external(1, req->resourceReport);
1692 void process_ESResponse(Z_ExtendedServicesResponse *res)
1695 switch (*res->operationStatus)
1697 case Z_ExtendedServicesResponse_done:
1700 case Z_ExtendedServicesResponse_accepted:
1701 printf ("accepted\n");
1703 case Z_ExtendedServicesResponse_failure:
1704 printf ("failure\n");
1705 display_diagrecs(res->diagnostics, res->num_diagnostics);
1708 printf ("unknown\n");
1710 if ( (*res->operationStatus != Z_ExtendedServicesResponse_failure) &&
1711 (res->num_diagnostics != 0) ) {
1712 display_diagrecs(res->diagnostics, res->num_diagnostics);
1714 print_refid (res->referenceId);
1715 if (res->taskPackage &&
1716 res->taskPackage->which == Z_External_extendedService)
1718 Z_TaskPackage *taskPackage = res->taskPackage->u.extendedService;
1719 Odr_oct *id = taskPackage->targetReference;
1720 Z_External *ext = taskPackage->taskSpecificParameters;
1724 printf ("Target Reference: ");
1725 print_stringn (id->buf, id->len);
1728 if (ext->which == Z_External_update)
1730 Z_IUUpdateTaskPackage *utp = ext->u.update->u.taskPackage;
1731 if (utp && utp->targetPart)
1733 Z_IUTargetPart *targetPart = utp->targetPart;
1736 for (i = 0; i<targetPart->num_taskPackageRecords; i++)
1739 Z_IUTaskPackageRecordStructure *tpr =
1740 targetPart->taskPackageRecords[i];
1741 printf ("task package record %d\n", i+1);
1742 if (tpr->which == Z_IUTaskPackageRecordStructure_record)
1744 display_record (tpr->u.record);
1748 printf ("other type\n");
1756 const char *get_ill_element (void *clientData, const char *element)
1761 static Z_External *create_external_itemRequest()
1763 struct ill_get_ctl ctl;
1764 ILL_ItemRequest *req;
1766 int item_request_size = 0;
1767 char *item_request_buf = 0;
1771 ctl.f = get_ill_element;
1773 req = ill_get_ItemRequest(&ctl, "ill", 0);
1775 printf ("ill_get_ItemRequest failed\n");
1777 if (!ill_ItemRequest (out, &req, 0, 0))
1781 ill_ItemRequest(print, &req, 0, 0);
1784 item_request_buf = odr_getbuf (out, &item_request_size, 0);
1785 if (item_request_buf)
1786 odr_setbuf (out, item_request_buf, item_request_size, 1);
1787 printf ("Couldn't encode ItemRequest, size %d\n", item_request_size);
1794 item_request_buf = odr_getbuf (out, &item_request_size, 0);
1795 oid.proto = PROTO_GENERAL;
1796 oid.oclass = CLASS_GENERAL;
1797 oid.value = VAL_ISO_ILL_1;
1799 r = (Z_External *) odr_malloc (out, sizeof(*r));
1800 r->direct_reference = odr_oiddup(out,oid_getoidbyent(&oid));
1801 r->indirect_reference = 0;
1803 r->which = Z_External_single;
1805 r->u.single_ASN1_type = (Odr_oct *)
1806 odr_malloc (out, sizeof(*r->u.single_ASN1_type));
1807 r->u.single_ASN1_type->buf = (unsigned char *)
1808 odr_malloc (out, item_request_size);
1809 r->u.single_ASN1_type->len = item_request_size;
1810 r->u.single_ASN1_type->size = item_request_size;
1811 memcpy (r->u.single_ASN1_type->buf, item_request_buf,
1814 do_hex_dump(item_request_buf,item_request_size);
1819 static Z_External *create_external_ILL_APDU(int which)
1821 struct ill_get_ctl ctl;
1824 int ill_request_size = 0;
1825 char *ill_request_buf = 0;
1829 ctl.f = get_ill_element;
1831 ill_apdu = ill_get_APDU(&ctl, "ill", 0);
1833 if (!ill_APDU (out, &ill_apdu, 0, 0))
1837 printf ("-------------------\n");
1838 ill_APDU(print, &ill_apdu, 0, 0);
1840 printf ("-------------------\n");
1842 ill_request_buf = odr_getbuf (out, &ill_request_size, 0);
1843 if (ill_request_buf)
1844 odr_setbuf (out, ill_request_buf, ill_request_size, 1);
1845 printf ("Couldn't encode ILL-Request, size %d\n", ill_request_size);
1851 ill_request_buf = odr_getbuf (out, &ill_request_size, 0);
1853 oid.proto = PROTO_GENERAL;
1854 oid.oclass = CLASS_GENERAL;
1855 oid.value = VAL_ISO_ILL_1;
1857 r = (Z_External *) odr_malloc (out, sizeof(*r));
1858 r->direct_reference = odr_oiddup(out,oid_getoidbyent(&oid));
1859 r->indirect_reference = 0;
1861 r->which = Z_External_single;
1863 r->u.single_ASN1_type = (Odr_oct *)
1864 odr_malloc (out, sizeof(*r->u.single_ASN1_type));
1865 r->u.single_ASN1_type->buf = (unsigned char *)
1866 odr_malloc (out, ill_request_size);
1867 r->u.single_ASN1_type->len = ill_request_size;
1868 r->u.single_ASN1_type->size = ill_request_size;
1869 memcpy (r->u.single_ASN1_type->buf, ill_request_buf, ill_request_size);
1870 /* printf ("len = %d\n", ill_request_size); */
1871 /* do_hex_dump(ill_request_buf,ill_request_size); */
1872 /* printf("--- end of extenal\n"); */
1879 static Z_External *create_ItemOrderExternal(const char *type, int itemno)
1881 Z_External *r = (Z_External *) odr_malloc(out, sizeof(Z_External));
1882 oident ItemOrderRequest;
1884 ItemOrderRequest.proto = PROTO_Z3950;
1885 ItemOrderRequest.oclass = CLASS_EXTSERV;
1886 ItemOrderRequest.value = VAL_ITEMORDER;
1888 r->direct_reference = odr_oiddup(out,oid_getoidbyent(&ItemOrderRequest));
1889 r->indirect_reference = 0;
1892 r->which = Z_External_itemOrder;
1894 r->u.itemOrder = (Z_ItemOrder *) odr_malloc(out,sizeof(Z_ItemOrder));
1895 memset(r->u.itemOrder, 0, sizeof(Z_ItemOrder));
1896 r->u.itemOrder->which=Z_IOItemOrder_esRequest;
1898 r->u.itemOrder->u.esRequest = (Z_IORequest *)
1899 odr_malloc(out,sizeof(Z_IORequest));
1900 memset(r->u.itemOrder->u.esRequest, 0, sizeof(Z_IORequest));
1902 r->u.itemOrder->u.esRequest->toKeep = (Z_IOOriginPartToKeep *)
1903 odr_malloc(out,sizeof(Z_IOOriginPartToKeep));
1904 memset(r->u.itemOrder->u.esRequest->toKeep, 0, sizeof(Z_IOOriginPartToKeep));
1905 r->u.itemOrder->u.esRequest->notToKeep = (Z_IOOriginPartNotToKeep *)
1906 odr_malloc(out,sizeof(Z_IOOriginPartNotToKeep));
1907 memset(r->u.itemOrder->u.esRequest->notToKeep, 0, sizeof(Z_IOOriginPartNotToKeep));
1909 r->u.itemOrder->u.esRequest->toKeep->supplDescription = NULL;
1910 r->u.itemOrder->u.esRequest->toKeep->contact = NULL;
1911 r->u.itemOrder->u.esRequest->toKeep->addlBilling = NULL;
1913 r->u.itemOrder->u.esRequest->notToKeep->resultSetItem =
1914 (Z_IOResultSetItem *) odr_malloc(out, sizeof(Z_IOResultSetItem));
1915 memset(r->u.itemOrder->u.esRequest->notToKeep->resultSetItem, 0, sizeof(Z_IOResultSetItem));
1916 r->u.itemOrder->u.esRequest->notToKeep->resultSetItem->resultSetId = "1";
1918 r->u.itemOrder->u.esRequest->notToKeep->resultSetItem->item =
1919 (int *) odr_malloc(out, sizeof(int));
1920 *r->u.itemOrder->u.esRequest->notToKeep->resultSetItem->item = itemno;
1922 if (!strcmp (type, "item") || !strcmp(type, "2"))
1924 printf ("using item-request\n");
1925 r->u.itemOrder->u.esRequest->notToKeep->itemRequest =
1926 create_external_itemRequest();
1928 else if (!strcmp(type, "ill") || !strcmp(type, "1"))
1930 printf ("using ILL-request\n");
1931 r->u.itemOrder->u.esRequest->notToKeep->itemRequest =
1932 create_external_ILL_APDU(ILL_APDU_ILL_Request);
1934 else if (!strcmp(type, "xml") || !strcmp(type, "3"))
1936 const char *xml_buf =
1938 " <type>request</type>\n"
1939 " <libraryNo>000200</libraryNo>\n"
1940 " <borrowerTicketNo> 1212 </borrowerTicketNo>\n"
1942 r->u.itemOrder->u.esRequest->notToKeep->itemRequest =
1943 z_ext_record (out, VAL_TEXT_XML, xml_buf, strlen(xml_buf));
1946 r->u.itemOrder->u.esRequest->notToKeep->itemRequest = 0;
1951 static int send_itemorder(const char *type, int itemno)
1953 Z_APDU *apdu = zget_APDU(out, Z_APDU_extendedServicesRequest);
1954 Z_ExtendedServicesRequest *req = apdu->u.extendedServicesRequest;
1955 oident ItemOrderRequest;
1957 ItemOrderRequest.proto = PROTO_Z3950;
1958 ItemOrderRequest.oclass = CLASS_EXTSERV;
1959 ItemOrderRequest.value = VAL_ITEMORDER;
1960 req->packageType = odr_oiddup(out,oid_getoidbyent(&ItemOrderRequest));
1961 req->packageName = esPackageName;
1963 req->taskSpecificParameters = create_ItemOrderExternal(type, itemno);
1969 static int only_z3950()
1971 if (protocol == PROTO_HTTP)
1973 printf ("Not supported by SRW\n");
1979 static int cmd_update_common(const char *arg, int version);
1981 static int cmd_update(const char *arg)
1983 return cmd_update_common(arg, 1);
1986 static int cmd_update0(const char *arg)
1988 return cmd_update_common(arg, 0);
1991 static int cmd_update_common(const char *arg, int version)
1993 Z_APDU *apdu = zget_APDU(out, Z_APDU_extendedServicesRequest );
1994 Z_ExtendedServicesRequest *req = apdu->u.extendedServicesRequest;
1996 char action[20], recid[20], fname[80];
1998 Z_External *record_this = 0;
2005 sscanf (arg, "%19s %19s %79s", action, recid, fname);
2007 if (!strcmp (action, "insert"))
2008 action_no = Z_IUOriginPartToKeep_recordInsert;
2009 else if (!strcmp (action, "replace"))
2010 action_no = Z_IUOriginPartToKeep_recordReplace;
2011 else if (!strcmp (action, "delete"))
2012 action_no = Z_IUOriginPartToKeep_recordDelete;
2013 else if (!strcmp (action, "update"))
2014 action_no = Z_IUOriginPartToKeep_specialUpdate;
2017 printf ("Bad action: %s\n", action);
2018 printf ("Possible values: insert, replace, delete, update\n");
2026 stat (fname, &status);
2027 if (S_ISREG(status.st_mode) && (inf = fopen(fname, "r")))
2029 size_t len = status.st_size;
2030 char *buf = (char *) xmalloc (len);
2032 fread (buf, 1, len, inf);
2036 record_this = z_ext_record (out, VAL_TEXT_XML, buf, len);
2042 printf ("File %s doesn't exist\n", fname);
2050 printf ("No last record (update ignored)\n");
2053 record_this = record_last;
2057 yaz_oidval_to_z3950oid(out, CLASS_EXTSERV,
2058 version == 0 ? VAL_DBUPDATE0 : VAL_DBUPDATE);
2060 req->packageName = esPackageName;
2062 req->referenceId = set_refid (out);
2064 r = req->taskSpecificParameters = (Z_External *)
2065 odr_malloc (out, sizeof(*r));
2066 r->direct_reference = req->packageType;
2067 r->indirect_reference = 0;
2071 Z_IU0OriginPartToKeep *toKeep;
2072 Z_IU0SuppliedRecords *notToKeep;
2074 r->which = Z_External_update0;
2075 r->u.update0 = (Z_IU0Update *) odr_malloc(out, sizeof(*r->u.update0));
2076 r->u.update0->which = Z_IUUpdate_esRequest;
2077 r->u.update0->u.esRequest = (Z_IU0UpdateEsRequest *)
2078 odr_malloc(out, sizeof(*r->u.update0->u.esRequest));
2079 toKeep = r->u.update0->u.esRequest->toKeep = (Z_IU0OriginPartToKeep *)
2080 odr_malloc(out, sizeof(*r->u.update0->u.esRequest->toKeep));
2082 toKeep->databaseName = databaseNames[0];
2084 toKeep->elementSetName = 0;
2086 toKeep->action = (int *) odr_malloc(out, sizeof(*toKeep->action));
2087 *toKeep->action = action_no;
2089 notToKeep = r->u.update0->u.esRequest->notToKeep = (Z_IU0SuppliedRecords *)
2090 odr_malloc(out, sizeof(*r->u.update0->u.esRequest->notToKeep));
2092 notToKeep->elements = (Z_IU0SuppliedRecords_elem **)
2093 odr_malloc(out, sizeof(*notToKeep->elements));
2094 notToKeep->elements[0] = (Z_IU0SuppliedRecords_elem *)
2095 odr_malloc(out, sizeof(**notToKeep->elements));
2096 notToKeep->elements[0]->which = Z_IUSuppliedRecords_elem_opaque;
2099 notToKeep->elements[0]->u.opaque = (Odr_oct *)
2100 odr_malloc (out, sizeof(Odr_oct));
2101 notToKeep->elements[0]->u.opaque->buf = (unsigned char *) recid;
2102 notToKeep->elements[0]->u.opaque->size = strlen(recid);
2103 notToKeep->elements[0]->u.opaque->len = strlen(recid);
2106 notToKeep->elements[0]->u.opaque = 0;
2107 notToKeep->elements[0]->supplementalId = 0;
2108 notToKeep->elements[0]->correlationInfo = 0;
2109 notToKeep->elements[0]->record = record_this;
2113 Z_IUOriginPartToKeep *toKeep;
2114 Z_IUSuppliedRecords *notToKeep;
2116 r->which = Z_External_update;
2117 r->u.update = (Z_IUUpdate *) odr_malloc(out, sizeof(*r->u.update));
2118 r->u.update->which = Z_IUUpdate_esRequest;
2119 r->u.update->u.esRequest = (Z_IUUpdateEsRequest *)
2120 odr_malloc(out, sizeof(*r->u.update->u.esRequest));
2121 toKeep = r->u.update->u.esRequest->toKeep = (Z_IUOriginPartToKeep *)
2122 odr_malloc(out, sizeof(*r->u.update->u.esRequest->toKeep));
2124 toKeep->databaseName = databaseNames[0];
2126 toKeep->elementSetName = 0;
2127 toKeep->actionQualifier = 0;
2128 toKeep->action = (int *) odr_malloc(out, sizeof(*toKeep->action));
2129 *toKeep->action = action_no;
2131 notToKeep = r->u.update->u.esRequest->notToKeep = (Z_IUSuppliedRecords *)
2132 odr_malloc(out, sizeof(*r->u.update->u.esRequest->notToKeep));
2134 notToKeep->elements = (Z_IUSuppliedRecords_elem **)
2135 odr_malloc(out, sizeof(*notToKeep->elements));
2136 notToKeep->elements[0] = (Z_IUSuppliedRecords_elem *)
2137 odr_malloc(out, sizeof(**notToKeep->elements));
2138 notToKeep->elements[0]->which = Z_IUSuppliedRecords_elem_opaque;
2141 notToKeep->elements[0]->u.opaque = (Odr_oct *)
2142 odr_malloc (out, sizeof(Odr_oct));
2143 notToKeep->elements[0]->u.opaque->buf = (unsigned char *) recid;
2144 notToKeep->elements[0]->u.opaque->size = strlen(recid);
2145 notToKeep->elements[0]->u.opaque->len = strlen(recid);
2148 notToKeep->elements[0]->u.opaque = 0;
2149 notToKeep->elements[0]->supplementalId = 0;
2150 notToKeep->elements[0]->correlationInfo = 0;
2151 notToKeep->elements[0]->record = record_this;
2159 static int cmd_itemorder(const char *arg)
2166 if (sscanf (arg, "%10s %d", type, &itemno) != 2)
2169 printf("Item order request\n");
2171 send_itemorder(type, itemno);
2175 static void show_opt(const char *arg, void *clientData)
2177 printf ("%s ", arg);
2180 static int cmd_zversion(const char *arg)
2183 z3950_version = atoi(arg);
2185 printf ("version is %d\n", z3950_version);
2189 static int cmd_options(const char *arg)
2195 r = yaz_init_opt_encode(&z3950_options, arg, &pos);
2199 yaz_init_opt_decode(&z3950_options, show_opt, 0);
2205 static int cmd_explain(const char *arg)
2207 if (protocol != PROTO_HTTP)
2218 /* save this for later .. when fetching individual records */
2219 sr = yaz_srw_get(out, Z_SRW_explain_request);
2220 if (recordsyntax == VAL_TEXT_XML)
2221 sr->u.explain_request->recordPacking = "xml";
2229 static int cmd_init(const char *arg)
2231 if (!conn || protocol != PROTO_Z3950)
2233 send_initRequest(0);
2237 static int cmd_find(const char *arg)
2241 printf("Find what?\n");
2244 if (protocol == PROTO_HTTP)
2251 if (!send_SRW_searchRequest(arg))
2264 printf("Not connected yet\n");
2268 if (!send_searchRequest(arg))
2274 static int cmd_delete(const char *arg)
2278 printf("Not connected yet\n");
2283 if (!send_deleteResultSetRequest(arg))
2288 static int cmd_ssub(const char *arg)
2290 if (!(smallSetUpperBound = atoi(arg)))
2295 static int cmd_lslb(const char *arg)
2299 if (!(largeSetLowerBound = atoi(arg)))
2304 static int cmd_mspn(const char *arg)
2308 if (!(mediumSetPresentNumber = atoi(arg)))
2313 static int cmd_status(const char *arg)
2315 printf("smallSetUpperBound: %d\n", smallSetUpperBound);
2316 printf("largeSetLowerBound: %d\n", largeSetLowerBound);
2317 printf("mediumSetPresentNumber: %d\n", mediumSetPresentNumber);
2321 static int cmd_setnames(const char *arg)
2323 if (*arg == '1') /* enable ? */
2325 else if (*arg == '0') /* disable ? */
2327 else if (setnumber < 0) /* no args, toggle .. */
2333 printf("Set numbering enabled.\n");
2335 printf("Set numbering disabled.\n");
2339 /* PRESENT SERVICE ----------------------------- */
2341 static void parse_show_args(const char *arg_c, char *setstring,
2342 int *start, int *number)
2347 strncpy(arg, arg_c, sizeof(arg)-1);
2348 arg[sizeof(arg)-1] = '\0';
2350 if ((p = strchr(arg, '+')))
2352 *number = atoi(p + 1);
2357 if (p && (p=strchr(p+1, '+')))
2358 strcpy (setstring, p+1);
2359 else if (setnumber >= 0)
2360 sprintf(setstring, "%d", setnumber);
2365 static int send_presentRequest(const char *arg)
2367 Z_APDU *apdu = zget_APDU(out, Z_APDU_presentRequest);
2368 Z_PresentRequest *req = apdu->u.presentRequest;
2369 Z_RecordComposition compo;
2371 char setstring[100];
2373 req->referenceId = set_refid (out);
2375 parse_show_args(arg, setstring, &setno, &nos);
2377 req->resultSetId = setstring;
2379 req->resultSetStartPoint = &setno;
2380 req->numberOfRecordsRequested = &nos;
2382 req->preferredRecordSyntax =
2383 yaz_oidval_to_z3950oid(out, CLASS_RECSYN, recordsyntax);
2387 req->recordComposition = &compo;
2388 compo.which = Z_RecordComp_complex;
2389 compo.u.complex = (Z_CompSpec *)
2390 odr_malloc(out, sizeof(*compo.u.complex));
2391 compo.u.complex->selectAlternativeSyntax = (bool_t *)
2392 odr_malloc(out, sizeof(bool_t));
2393 *compo.u.complex->selectAlternativeSyntax = 0;
2395 compo.u.complex->generic = (Z_Specification *)
2396 odr_malloc(out, sizeof(*compo.u.complex->generic));
2397 compo.u.complex->generic->which = Z_Schema_oid;
2399 compo.u.complex->generic->schema.oid =
2400 yaz_str_to_z3950oid(out, CLASS_SCHEMA, record_schema);
2402 if (!compo.u.complex->generic->schema.oid)
2404 /* OID wasn't a schema! Try record syntax instead. */
2405 compo.u.complex->generic->schema.oid = (Odr_oid *)
2406 yaz_str_to_z3950oid(out, CLASS_RECSYN, record_schema);
2408 if (!elementSetNames)
2409 compo.u.complex->generic->elementSpec = 0;
2412 compo.u.complex->generic->elementSpec = (Z_ElementSpec *)
2413 odr_malloc(out, sizeof(Z_ElementSpec));
2414 compo.u.complex->generic->elementSpec->which =
2415 Z_ElementSpec_elementSetName;
2416 compo.u.complex->generic->elementSpec->u.elementSetName =
2417 elementSetNames->u.generic;
2419 compo.u.complex->num_dbSpecific = 0;
2420 compo.u.complex->dbSpecific = 0;
2421 compo.u.complex->num_recordSyntax = 0;
2422 compo.u.complex->recordSyntax = 0;
2424 else if (elementSetNames)
2426 req->recordComposition = &compo;
2427 compo.which = Z_RecordComp_simple;
2428 compo.u.simple = elementSetNames;
2431 printf("Sent presentRequest (%d+%d).\n", setno, nos);
2436 static int send_SRW_presentRequest(const char *arg)
2438 char setstring[100];
2440 Z_SRW_PDU *sr = srw_sr;
2444 parse_show_args(arg, setstring, &setno, &nos);
2445 sr->u.request->startRecord = odr_intdup(out, setno);
2446 sr->u.request->maximumRecords = odr_intdup(out, nos);
2448 sr->u.request->recordSchema = record_schema;
2449 if (recordsyntax == VAL_TEXT_XML)
2450 sr->u.request->recordPacking = "xml";
2451 return send_srw(sr);
2455 static void close_session (void)
2462 nmem_destroy (session_mem);
2471 void process_close(Z_Close *req)
2473 Z_APDU *apdu = zget_APDU(out, Z_APDU_close);
2474 Z_Close *res = apdu->u.close;
2476 static char *reasons[] =
2481 "cost limit reached",
2483 "security violation",
2490 printf("Reason: %s, message: %s\n", reasons[*req->closeReason],
2491 req->diagnosticInformation ? req->diagnosticInformation : "NULL");
2496 *res->closeReason = Z_Close_finished;
2498 printf("Sent response.\n");
2503 static int cmd_show(const char *arg)
2505 if (protocol == PROTO_HTTP)
2512 if (!send_SRW_presentRequest(arg))
2522 printf("Not connected yet\n");
2525 if (!send_presentRequest(arg))
2531 int cmd_quit(const char *arg)
2533 printf("See you later, alligator.\n");
2539 int cmd_cancel(const char *arg)
2541 Z_APDU *apdu = zget_APDU(out, Z_APDU_triggerResourceControlRequest);
2542 Z_TriggerResourceControlRequest *req =
2543 apdu->u.triggerResourceControlRequest;
2548 printf("Session not initialized yet\n");
2553 if (!ODR_MASK_GET(session->options, Z_Options_triggerResourceCtrl))
2555 printf("Target doesn't support cancel (trigger resource ctrl)\n");
2558 *req->requestedAction = Z_TriggerResourceControlRequest_cancel;
2559 req->resultSetWanted = &rfalse;
2560 req->referenceId = set_refid (out);
2563 printf("Sent cancel request\n");
2568 int cmd_cancel_find(const char *arg) {
2572 return cmd_cancel("");
2577 int send_scanrequest(const char *query, int pp, int num, const char *term)
2579 Z_APDU *apdu = zget_APDU(out, Z_APDU_scanRequest);
2580 Z_ScanRequest *req = apdu->u.scanRequest;
2584 if (queryType == QueryType_CCL2RPN)
2587 struct ccl_rpn_node *rpn;
2589 rpn = ccl_find_str (bibset, query, &error, &pos);
2592 printf("CCL ERROR: %s\n", ccl_err_msg(error));
2596 yaz_oidval_to_z3950oid(out, CLASS_ATTSET, VAL_BIB1);
2597 if (!(req->termListAndStartPoint = ccl_scan_query (out, rpn)))
2599 printf("Couldn't convert CCL to Scan term\n");
2602 ccl_rpn_delete (rpn);
2606 YAZ_PQF_Parser pqf_parser = yaz_pqf_create ();
2608 if (!(req->termListAndStartPoint =
2609 yaz_pqf_scan(pqf_parser, out, &req->attributeSet, query)))
2611 const char *pqf_msg;
2613 int code = yaz_pqf_error (pqf_parser, &pqf_msg, &off);
2614 printf("%*s^\n", off+7, "");
2615 printf("Prefix query error: %s (code %d)\n", pqf_msg, code);
2616 yaz_pqf_destroy (pqf_parser);
2619 yaz_pqf_destroy (pqf_parser);
2623 if (req->termListAndStartPoint->term &&
2624 req->termListAndStartPoint->term->which == Z_Term_general &&
2625 req->termListAndStartPoint->term->u.general)
2627 req->termListAndStartPoint->term->u.general->buf =
2628 (unsigned char *) odr_strdup(out, term);
2629 req->termListAndStartPoint->term->u.general->len =
2630 req->termListAndStartPoint->term->u.general->size =
2634 req->referenceId = set_refid (out);
2635 req->num_databaseNames = num_databaseNames;
2636 req->databaseNames = databaseNames;
2637 req->numberOfTermsRequested = #
2638 req->preferredPositionInResponse = &pp;
2643 int send_sortrequest(const char *arg, int newset)
2645 Z_APDU *apdu = zget_APDU(out, Z_APDU_sortRequest);
2646 Z_SortRequest *req = apdu->u.sortRequest;
2647 Z_SortKeySpecList *sksl = (Z_SortKeySpecList *)
2648 odr_malloc (out, sizeof(*sksl));
2654 sprintf (setstring, "%d", setnumber);
2656 sprintf (setstring, "default");
2658 req->referenceId = set_refid (out);
2660 req->num_inputResultSetNames = 1;
2661 req->inputResultSetNames = (Z_InternationalString **)
2662 odr_malloc (out, sizeof(*req->inputResultSetNames));
2663 req->inputResultSetNames[0] = odr_strdup (out, setstring);
2665 if (newset && setnumber >= 0)
2666 sprintf (setstring, "%d", ++setnumber);
2668 req->sortedResultSetName = odr_strdup (out, setstring);
2670 req->sortSequence = yaz_sort_spec (out, arg);
2671 if (!req->sortSequence)
2673 printf ("Missing sort specifications\n");
2680 void display_term(Z_TermInfo *t)
2683 printf("%s", t->displayTerm);
2684 else if (t->term->which == Z_Term_general)
2686 printf("%.*s", t->term->u.general->len, t->term->u.general->buf);
2687 sprintf(last_scan_line, "%.*s", t->term->u.general->len,
2688 t->term->u.general->buf);
2691 printf("Term (not general)");
2692 if (t->globalOccurrences)
2693 printf (" (%d)\n", *t->globalOccurrences);
2698 void process_scanResponse(Z_ScanResponse *res)
2701 Z_Entry **entries = NULL;
2702 int num_entries = 0;
2704 printf("Received ScanResponse\n");
2705 print_refid (res->referenceId);
2706 printf("%d entries", *res->numberOfEntriesReturned);
2707 if (res->positionOfTerm)
2708 printf (", position=%d", *res->positionOfTerm);
2710 if (*res->scanStatus != Z_Scan_success)
2711 printf("Scan returned code %d\n", *res->scanStatus);
2714 if ((entries = res->entries->entries))
2715 num_entries = res->entries->num_entries;
2716 for (i = 0; i < num_entries; i++)
2718 int pos_term = res->positionOfTerm ? *res->positionOfTerm : -1;
2719 if (entries[i]->which == Z_Entry_termInfo)
2721 printf("%c ", i + 1 == pos_term ? '*' : ' ');
2722 display_term(entries[i]->u.termInfo);
2725 display_diagrecs(&entries[i]->u.surrogateDiagnostic, 1);
2727 if (res->entries->nonsurrogateDiagnostics)
2728 display_diagrecs (res->entries->nonsurrogateDiagnostics,
2729 res->entries->num_nonsurrogateDiagnostics);
2732 void process_sortResponse(Z_SortResponse *res)
2734 printf("Received SortResponse: status=");
2735 switch (*res->sortStatus)
2737 case Z_SortResponse_success:
2738 printf ("success"); break;
2739 case Z_SortResponse_partial_1:
2740 printf ("partial"); break;
2741 case Z_SortResponse_failure:
2742 printf ("failure"); break;
2744 printf ("unknown (%d)", *res->sortStatus);
2747 print_refid (res->referenceId);
2748 if (res->diagnostics)
2749 display_diagrecs(res->diagnostics,
2750 res->num_diagnostics);
2753 void process_deleteResultSetResponse (Z_DeleteResultSetResponse *res)
2755 printf("Got deleteResultSetResponse status=%d\n",
2756 *res->deleteOperationStatus);
2757 if (res->deleteListStatuses)
2760 for (i = 0; i < res->deleteListStatuses->num; i++)
2762 printf ("%s status=%d\n", res->deleteListStatuses->elements[i]->id,
2763 *res->deleteListStatuses->elements[i]->status);
2768 int cmd_sort_generic(const char *arg, int newset)
2772 printf("Session not initialized yet\n");
2777 if (!ODR_MASK_GET(session->options, Z_Options_sort))
2779 printf("Target doesn't support sort\n");
2784 if (send_sortrequest(arg, newset) < 0)
2791 int cmd_sort(const char *arg)
2793 return cmd_sort_generic (arg, 0);
2796 int cmd_sort_newset (const char *arg)
2798 return cmd_sort_generic (arg, 1);
2801 int cmd_scan(const char *arg)
2810 printf("Session not initialized yet\n");
2814 if (!ODR_MASK_GET(session->options, Z_Options_scan))
2816 printf("Target doesn't support scan\n");
2821 strcpy (last_scan_query, arg);
2822 if (send_scanrequest(arg, 1, 20, 0) < 0)
2827 if (send_scanrequest(last_scan_query, 1, 20, last_scan_line) < 0)
2833 int cmd_schema(const char *arg)
2835 xfree(record_schema);
2838 record_schema = xstrdup(arg);
2842 int cmd_format(const char *arg)
2847 printf("Usage: format <recordsyntax>\n");
2850 nsyntax = oid_getvalbyname (arg);
2851 if (strcmp(arg, "none") && nsyntax == VAL_NONE)
2853 printf ("unknown record syntax\n");
2856 recordsyntax = nsyntax;
2860 int cmd_elements(const char *arg)
2862 static Z_ElementSetNames esn;
2863 static char what[100];
2867 elementSetNames = 0;
2871 esn.which = Z_ElementSetNames_generic;
2872 esn.u.generic = what;
2873 elementSetNames = &esn;
2877 int cmd_attributeset(const char *arg)
2883 printf("Usage: attributeset <setname>\n");
2886 sscanf(arg, "%s", what);
2887 if (p_query_attset (what))
2889 printf("Unknown attribute set name\n");
2895 int cmd_querytype (const char *arg)
2897 if (!strcmp (arg, "ccl"))
2898 queryType = QueryType_CCL;
2899 else if (!strcmp (arg, "prefix") || !strcmp(arg, "rpn"))
2900 queryType = QueryType_Prefix;
2901 else if (!strcmp (arg, "ccl2rpn") || !strcmp (arg, "cclrpn"))
2902 queryType = QueryType_CCL2RPN;
2903 else if (!strcmp(arg, "cql"))
2904 queryType = QueryType_CQL;
2905 else if (!strcmp (arg, "cql2rpn") || !strcmp (arg, "cqlrpn"))
2906 queryType = QueryType_CQL2RPN;
2909 printf ("Querytype must be one of:\n");
2910 printf (" prefix - Prefix query\n");
2911 printf (" ccl - CCL query\n");
2912 printf (" ccl2rpn - CCL query converted to RPN\n");
2913 printf (" cql - CQL\n");
2914 printf (" cql2rpn - CQL query converted to RPN\n");
2920 int cmd_refid (const char *arg)
2925 refid = xstrdup (arg);
2929 int cmd_close(const char *arg)
2938 apdu = zget_APDU(out, Z_APDU_close);
2939 req = apdu->u.close;
2940 *req->closeReason = Z_Close_finished;
2942 printf("Sent close request.\n");
2947 int cmd_packagename(const char* arg)
2949 xfree (esPackageName);
2950 esPackageName = NULL;
2952 esPackageName = xstrdup(arg);
2956 int cmd_proxy(const char* arg)
2961 yazProxy = xstrdup (arg);
2965 int cmd_marccharset(const char *arg)
2970 if (sscanf(arg, "%29s", l1) < 1)
2972 xfree (marcCharset);
2974 if (strcmp(l1, "-"))
2975 marcCharset = xstrdup(l1);
2979 int cmd_charset(const char* arg)
2981 char l1[30], l2[30];
2984 if (sscanf(arg, "%29s %29s", l1, l2) < 1)
2986 printf("Current negotiation character set is `%s'\n",
2987 negotiationCharset ? negotiationCharset: "none");
2988 printf("Current output character set is `%s'\n",
2989 outputCharset ? outputCharset: "none");
2992 xfree (negotiationCharset);
2993 negotiationCharset = NULL;
2994 if (*l1 && strcmp(l1, "-"))
2996 negotiationCharset = xstrdup(l1);
2997 printf ("Character set negotiation : %s\n", negotiationCharset);
3000 printf ("Character set negotiation disabled\n");
3003 xfree (outputCharset);
3005 if (!strcmp(l2, "auto") && codeset)
3009 printf ("output charset: %s\n", codeset);
3010 outputCharset = xstrdup(codeset);
3015 printf ("No codeset found on this system\n");
3017 else if (strcmp(l2, "-"))
3018 outputCharset = xstrdup(l2);
3020 printf ("Output charset conversion disabled\n");
3026 int cmd_lang(const char* arg)
3029 printf("Current language is `%s'\n", (yazLang)?yazLang:NULL);
3035 yazLang = xstrdup(arg);
3039 int cmd_source(const char* arg)
3041 /* first should open the file and read one line at a time.. */
3043 char line[102400], *cp;
3046 fprintf(stderr,"Error in source command use a filename\n");
3050 includeFile = fopen (arg, "r");
3053 fprintf(stderr,"Unable to open file %s for reading\n",arg);
3057 while(!feof(includeFile)) {
3058 memset(line,0,sizeof(line));
3059 fgets(line,sizeof(line),includeFile);
3061 if(strlen(line) < 2) continue;
3062 if(line[0] == '#') continue;
3064 if ((cp = strrchr (line, '\n')))
3067 process_cmd_line(line);
3070 if(fclose(includeFile)<0) {
3071 perror("unable to close include file");
3077 int cmd_subshell(const char* args)
3082 system(getenv("SHELL"));
3088 int cmd_set_berfile(const char *arg)
3090 if (ber_file && ber_file != stdout && ber_file != stderr)
3092 if (!strcmp(arg, ""))
3094 else if (!strcmp(arg, "-"))
3097 ber_file = fopen(arg, "a");
3101 int cmd_set_apdufile(const char *arg)
3103 if(apdu_file && apdu_file != stderr && apdu_file != stderr)
3105 if (!strcmp(arg, ""))
3107 else if (!strcmp(arg, "-"))
3111 apdu_file = fopen(arg, "a");
3113 perror("unable to open apdu log file");
3116 odr_setprint(print, apdu_file);
3120 int cmd_set_cclfile(const char* arg)
3124 bibset = ccl_qual_mk ();
3125 inf = fopen (arg, "r");
3127 perror("unable to open CCL file");
3130 ccl_qual_file (bibset, inf);
3133 strcpy(ccl_fields,arg);
3137 int cmd_set_cqlfile(const char* arg)
3139 cql_transform_t newcqltrans;
3141 if ((newcqltrans = cql_transform_open_fname(arg)) == 0) {
3142 perror("unable to open CQL file");
3146 cql_transform_close(cqltrans);
3148 cqltrans = newcqltrans;
3149 strcpy(cql_fields, arg);
3153 int cmd_set_auto_reconnect(const char* arg)
3155 if(strlen(arg)==0) {
3156 auto_reconnect = ! auto_reconnect;
3157 } else if(strcmp(arg,"on")==0) {
3159 } else if(strcmp(arg,"off")==0) {
3162 printf("Error use on or off\n");
3167 printf("Set auto reconnect enabled.\n");
3169 printf("Set auto reconnect disabled.\n");
3174 int cmd_set_marcdump(const char* arg)
3176 if(marc_file && marc_file != stderr) { /* don't close stdout*/
3180 if (!strcmp(arg, ""))
3182 else if (!strcmp(arg, "-"))
3186 marc_file = fopen(arg, "a");
3188 perror("unable to open marc log file");
3194 this command takes 3 arge {name class oid}
3196 int cmd_register_oid(const char* args) {
3201 {"appctx",CLASS_APPCTX},
3202 {"absyn",CLASS_ABSYN},
3203 {"attset",CLASS_ATTSET},
3204 {"transyn",CLASS_TRANSYN},
3205 {"diagset",CLASS_DIAGSET},
3206 {"recsyn",CLASS_RECSYN},
3207 {"resform",CLASS_RESFORM},
3208 {"accform",CLASS_ACCFORM},
3209 {"extserv",CLASS_EXTSERV},
3210 {"userinfo",CLASS_USERINFO},
3211 {"elemspec",CLASS_ELEMSPEC},
3212 {"varset",CLASS_VARSET},
3213 {"schema",CLASS_SCHEMA},
3214 {"tagset",CLASS_TAGSET},
3215 {"general",CLASS_GENERAL},
3216 {0,(enum oid_class) 0}
3218 char oname_str[101], oclass_str[101], oid_str[101];
3221 oid_class oidclass = CLASS_GENERAL;
3222 int val = 0, oid[OID_SIZE];
3223 struct oident * new_oident=NULL;
3225 if (sscanf (args, "%100[^ ] %100[^ ] %100s",
3226 oname_str,oclass_str, oid_str) < 1) {
3227 printf("Error in register command \n");
3231 for (i = 0; oid_classes[i].className; i++) {
3232 if (!strcmp(oid_classes[i].className, oclass_str))
3234 oidclass=oid_classes[i].oclass;
3239 if(!(oid_classes[i].className)) {
3240 printf("Unknown oid class %s\n",oclass_str);
3248 while (isdigit (*(unsigned char *) name))
3250 val = val*10 + (*name - '0');
3263 new_oident = oid_addent (oid, PROTO_GENERAL, oidclass, oname_str,
3265 if(strcmp(new_oident->desc,oname_str))
3267 fprintf(stderr,"oid is already named as %s, registration failed\n",
3273 int cmd_push_command(const char* arg)
3275 #if HAVE_READLINE_HISTORY_H
3279 fprintf(stderr,"Not compiled with the readline/history module\n");
3284 void source_rcfile()
3286 /* Look for a $HOME/.yazclientrc and source it if it exists */
3287 struct stat statbuf;
3289 char* homedir=getenv("HOME");
3291 if(!homedir) return;
3293 sprintf(buffer,"%s/.yazclientrc",homedir);
3295 if(stat(buffer,&statbuf)==0) {
3299 if(stat(".yazclientrc",&statbuf)==0) {
3300 cmd_source(".yazclientrc");
3305 static void initialize(void)
3310 if (!(out = odr_createmem(ODR_ENCODE)) ||
3311 !(in = odr_createmem(ODR_DECODE)) ||
3312 !(print = odr_createmem(ODR_PRINT)))
3314 fprintf(stderr, "failed to allocate ODR streams\n");
3319 setvbuf(stdout, 0, _IONBF, 0);
3321 odr_setprint(print, apdu_file);
3323 bibset = ccl_qual_mk ();
3324 inf = fopen (ccl_fields, "r");
3327 ccl_qual_file (bibset, inf);
3331 cqltrans = cql_transform_open_fname(cql_fields);
3332 /* If this fails, no problem: we detect cqltrans == 0 later */
3334 #if HAVE_READLINE_READLINE_H
3335 rl_attempted_completion_function = (CPPFunction*)readline_completer;
3339 for(i=0; i<maxOtherInfosSupported; ++i) {
3340 extraOtherInfos[i].oidval = -1;
3347 #if HAVE_GETTIMEOFDAY
3348 struct timeval tv_start, tv_end;
3352 static void handle_srw_record(Z_SRW_record *rec)
3354 if (rec->recordPosition)
3356 printf ("pos=%d", *rec->recordPosition);
3357 setno = *rec->recordPosition + 1;
3359 if (rec->recordSchema)
3360 printf (" schema=%s", rec->recordSchema);
3362 if (rec->recordData_buf && rec->recordData_len)
3364 fwrite(rec->recordData_buf, 1, rec->recordData_len, stdout);
3366 fwrite (rec->recordData_buf, 1, rec->recordData_len, marc_file);
3369 printf ("No data!");
3373 static void handle_srw_explain_response(Z_SRW_explainResponse *res)
3375 handle_srw_record(&res->record);
3378 static void handle_srw_response(Z_SRW_searchRetrieveResponse *res)
3382 printf ("Received SRW SearchRetrieve Response\n");
3384 for (i = 0; i<res->num_diagnostics; i++)
3386 if (res->diagnostics[i].uri)
3387 printf ("SRW diagnostic %s\n",
3388 res->diagnostics[i].uri);
3390 printf ("SRW diagnostic missing or could not be decoded\n");
3391 if (res->diagnostics[i].message)
3392 printf ("Message: %s\n", res->diagnostics[i].message);
3393 if (res->diagnostics[i].details)
3394 printf ("Details: %s\n", res->diagnostics[i].details);
3396 if (res->numberOfRecords)
3397 printf ("Number of hits: %d\n", *res->numberOfRecords);
3398 for (i = 0; i<res->num_records; i++)
3399 handle_srw_record(res->records + i);
3402 static void http_response(Z_HTTP_Response *hres)
3405 const char *content_type = z_HTTP_header_lookup(hres->headers,
3407 const char *connection_head = z_HTTP_header_lookup(hres->headers,
3409 if (content_type && !yaz_strcmp_del("text/xml", content_type, "; "))
3411 Z_SOAP *soap_package = 0;
3412 ODR o = odr_createmem(ODR_DECODE);
3413 Z_SOAP_Handler soap_handlers[2] = {
3414 {"http://www.loc.gov/zing/srw/", 0,
3415 (Z_SOAP_fun) yaz_srw_codec},
3418 ret = z_soap_codec(o, &soap_package,
3419 &hres->content_buf, &hres->content_len,
3421 if (!ret && soap_package->which == Z_SOAP_generic &&
3422 soap_package->u.generic->no == 0)
3424 Z_SRW_PDU *sr = soap_package->u.generic->p;
3425 if (sr->which == Z_SRW_searchRetrieve_response)
3426 handle_srw_response(sr->u.response);
3427 else if (sr->which == Z_SRW_explain_response)
3428 handle_srw_explain_response(sr->u.explain_response);
3432 else if (soap_package && (soap_package->which == Z_SOAP_fault
3433 || soap_package->which == Z_SOAP_error))
3435 printf ("HTTP Error Status=%d\n", hres->code);
3436 printf ("SOAP Fault code %s\n",
3437 soap_package->u.fault->fault_code);
3438 printf ("SOAP Fault string %s\n",
3439 soap_package->u.fault->fault_string);
3440 if (soap_package->u.fault->details)
3441 printf ("SOAP Details %s\n",
3442 soap_package->u.fault->details);
3450 if (hres->code != 200)
3452 printf ("HTTP Error Status=%d\n", hres->code);
3456 printf ("Decoding of SRW package failed\n");
3462 if (!strcmp(hres->version, "1.0"))
3464 /* HTTP 1.0: only if Keep-Alive we stay alive.. */
3465 if (!connection_head || strcmp(connection_head, "Keep-Alive"))
3470 /* HTTP 1.1: only if no close we stay alive .. */
3471 if (connection_head && !strcmp(connection_head, "close"))
3478 void wait_and_handle_response()
3480 int reconnect_ok = 1;
3483 int netbufferlen = 0;
3488 res = cs_get(conn, &netbuffer, &netbufferlen);
3489 if (reconnect_ok && res <= 0 && protocol == PROTO_HTTP)
3500 buf_out = odr_getbuf(out, &len_out, 0);
3502 do_hex_dump(buf_out, len_out);
3504 cs_put(conn, buf_out, len_out);
3512 printf("Target closed connection\n");
3517 odr_reset(in); /* release APDU from last round */
3519 do_hex_dump(netbuffer, res);
3520 odr_setbuf(in, netbuffer, res, 0);
3522 if (!z_GDU(in, &gdu, 0, 0))
3524 FILE *f = ber_file ? ber_file : stdout;
3525 odr_perror(in, "Decoding incoming APDU");
3526 fprintf(f, "[Near %d]\n", odr_offset(in));
3527 fprintf(f, "Packet dump:\n---------\n");
3528 odr_dumpBER(f, netbuffer, res);
3529 fprintf(f, "---------\n");
3532 z_GDU(print, &gdu, 0, 0);
3535 if (conn && cs_more(conn))
3540 odr_dumpBER(ber_file, netbuffer, res);
3541 if (apdu_file && !z_GDU(print, &gdu, 0, 0))
3543 odr_perror(print, "Failed to print incoming APDU");
3547 if (gdu->which == Z_GDU_Z3950)
3549 Z_APDU *apdu = gdu->u.z3950;
3552 case Z_APDU_initResponse:
3553 process_initResponse(apdu->u.initResponse);
3555 case Z_APDU_searchResponse:
3556 process_searchResponse(apdu->u.searchResponse);
3558 case Z_APDU_scanResponse:
3559 process_scanResponse(apdu->u.scanResponse);
3561 case Z_APDU_presentResponse:
3562 print_refid (apdu->u.presentResponse->referenceId);
3564 *apdu->u.presentResponse->numberOfRecordsReturned;
3565 if (apdu->u.presentResponse->records)
3566 display_records(apdu->u.presentResponse->records);
3568 printf("No records.\n");
3569 printf ("nextResultSetPosition = %d\n",
3570 *apdu->u.presentResponse->nextResultSetPosition);
3572 case Z_APDU_sortResponse:
3573 process_sortResponse(apdu->u.sortResponse);
3575 case Z_APDU_extendedServicesResponse:
3576 printf("Got extended services response\n");
3577 process_ESResponse(apdu->u.extendedServicesResponse);
3580 printf("Target has closed the association.\n");
3581 process_close(apdu->u.close);
3583 case Z_APDU_resourceControlRequest:
3584 process_resourceControlRequest
3585 (apdu->u.resourceControlRequest);
3587 case Z_APDU_deleteResultSetResponse:
3588 process_deleteResultSetResponse(apdu->u.
3589 deleteResultSetResponse);
3592 printf("Received unknown APDU type (%d).\n",
3598 else if (gdu->which == Z_GDU_HTTP_Response)
3600 http_response(gdu->u.HTTP_Response);
3603 if (conn && !cs_more(conn))
3608 #if HAVE_GETTIMEOFDAY
3609 gettimeofday (&tv_end, 0);
3611 printf ("S/U S/U=%ld/%ld %ld/%ld",
3612 (long) tv_start.tv_sec,
3613 (long) tv_start.tv_usec,
3614 (long) tv_end.tv_sec,
3615 (long) tv_end.tv_usec);
3617 printf ("Elapsed: %.6f\n",
3618 (double) tv_end.tv_usec / 1e6 + tv_end.tv_sec -
3619 ((double) tv_start.tv_usec / 1e6 + tv_start.tv_sec));
3626 int cmd_cclparse(const char* arg)
3629 struct ccl_rpn_node *rpn=NULL;
3632 rpn = ccl_find_str (bibset, arg, &error, &pos);
3635 printf ("%*s^ - ", 3+strlen(last_cmd)+1+pos, " ");
3636 printf ("%s\n", ccl_err_msg (error));
3642 ccl_pr_tree(rpn, stdout);
3646 ccl_rpn_delete(rpn);
3654 int cmd_set_otherinfo(const char* args)
3656 char oidstr[101], otherinfoString[101];
3661 sscan_res = sscanf (args, "%d %100[^ ] %100s", &otherinfoNo, oidstr, otherinfoString);
3663 /* reset this otherinfo */
3664 if(otherinfoNo>=maxOtherInfosSupported) {
3665 printf("Error otherinfo index to large (%d>%d)\n",
3666 otherinfoNo,maxOtherInfosSupported);
3668 extraOtherInfos[otherinfoNo].oidval = -1;
3669 if (extraOtherInfos[otherinfoNo].value)
3670 free(extraOtherInfos[otherinfoNo].value);
3674 printf("Error in set_otherinfo command \n");
3678 if (otherinfoNo>=maxOtherInfosSupported) {
3679 printf("Error otherinfo index to large (%d>%d)\n",
3680 otherinfoNo,maxOtherInfosSupported);
3683 oidval = oid_getvalbyname (oidstr);
3684 if (oidval == -1 ) {
3685 printf("Error in set_otherinfo command unknown oid %s \n",oidstr);
3688 extraOtherInfos[otherinfoNo].oidval = oidval;
3689 if(extraOtherInfos[otherinfoNo].value) free(extraOtherInfos[otherinfoNo].value);
3690 extraOtherInfos[otherinfoNo].value = strdup(otherinfoString);
3695 int cmd_list_otherinfo(const char* args)
3699 if(strlen(args)>0) {
3701 if( i >= maxOtherInfosSupported ) {
3702 printf("Error otherinfo index to large (%d>%d)\n",i,maxOtherInfosSupported);
3706 if(extraOtherInfos[i].oidval != -1)
3707 printf(" otherinfo %d %s %s\n",
3709 yaz_z3950_oid_value_to_str(
3710 (enum oid_value) extraOtherInfos[i].oidval,
3712 extraOtherInfos[i].value);
3715 for(i=0; i<maxOtherInfosSupported; ++i) {
3716 if(extraOtherInfos[i].oidval != -1)
3717 printf(" otherinfo %d %s %s\n",
3719 yaz_z3950_oid_value_to_str(
3720 (enum oid_value) extraOtherInfos[i].oidval,
3722 extraOtherInfos[i].value);
3730 int cmd_list_all(const char* args) {
3733 /* connection options */
3735 printf("Connected to : %s\n",last_open_command);
3737 if(last_open_command)
3738 printf("Not connected to : %s\n",last_open_command);
3740 printf("Not connected : \n");
3743 if(yazProxy) printf("using proxy : %s\n",yazProxy);
3745 printf("auto_reconnect : %s\n",auto_reconnect?"on":"off");
3748 printf("Authentication : none\n");
3750 switch(auth->which) {
3751 case Z_IdAuthentication_idPass:
3752 printf("Authentication : IdPass\n");
3753 printf(" Login User : %s\n",auth->u.idPass->userId?auth->u.idPass->userId:"");
3754 printf(" Login Group : %s\n",auth->u.idPass->groupId?auth->u.idPass->groupId:"");
3755 printf(" Password : %s\n",auth->u.idPass->password?auth->u.idPass->password:"");
3757 case Z_IdAuthentication_open:
3758 printf("Authentication : psOpen\n");
3759 printf(" Open string : %s\n",auth->u.open);
3762 printf("Authentication : Unknown\n");
3765 if (negotiationCharset)
3766 printf("Neg. Character set : `%s'\n", negotiationCharset);
3770 for (i = 0; i<num_databaseNames; i++) printf("%s ",databaseNames[i]);
3774 printf("CCL file : %s\n",ccl_fields);
3775 printf("CQL file : %s\n",cql_fields);
3776 printf("Query type : %s\n",query_type_as_string(queryType));
3778 printf("Named Result Sets : %s\n",setnumber==-1?"off":"on");
3780 /* piggy back options */
3781 printf("ssub/lslb/mspn : %d/%d/%d\n",smallSetUpperBound,largeSetLowerBound,mediumSetPresentNumber);
3783 /* print present related options */
3784 printf("Format : %s\n",yaz_z3950_oid_value_to_str(recordsyntax,CLASS_RECSYN));
3785 printf("Schema : %s\n",record_schema ? record_schema : "not set");
3786 printf("Elements : %s\n",elementSetNames?elementSetNames->u.generic:"");
3788 /* loging options */
3789 printf("APDU log : %s\n",apdu_file?"on":"off");
3790 printf("Record log : %s\n",marc_file?"on":"off");
3793 printf("Other Info: \n");
3794 cmd_list_otherinfo("");
3799 int cmd_clear_otherinfo(const char* args)
3801 if(strlen(args)>0) {
3803 otherinfoNo = atoi(args);
3804 if( otherinfoNo >= maxOtherInfosSupported ) {
3805 printf("Error otherinfo index to large (%d>%d)\n",otherinfoNo,maxOtherInfosSupported);
3809 if(extraOtherInfos[otherinfoNo].oidval != -1) {
3810 /* only clear if set. */
3811 extraOtherInfos[otherinfoNo].oidval=-1;
3812 free(extraOtherInfos[otherinfoNo].value);
3817 for(i=0; i<maxOtherInfosSupported; ++i) {
3818 if (extraOtherInfos[i].oidval!=-1 ) {
3819 extraOtherInfos[i].oidval=-1;
3820 free(extraOtherInfos[i].value);
3827 static int cmd_help (const char *line);
3829 typedef char *(*completerFunctionType)(const char *text, int state);
3833 int (*fun)(const char *arg);
3835 completerFunctionType rl_completerfunction;
3836 int complete_filenames;
3837 char **local_tabcompletes;
3839 {"open", cmd_open, "('tcp'|'ssl')':<host>[':'<port>][/<db>]",NULL,0,NULL},
3840 {"quit", cmd_quit, "",NULL,0,NULL},
3841 {"find", cmd_find, "<query>",NULL,0,NULL},
3842 {"delete", cmd_delete, "<setname>",NULL,0,NULL},
3843 {"base", cmd_base, "<base-name>",NULL,0,NULL},
3844 {"show", cmd_show, "<rec#>['+'<#recs>['+'<setname>]]",NULL,0,NULL},
3845 {"scan", cmd_scan, "<term>",NULL,0,NULL},
3846 {"sort", cmd_sort, "<sortkey> <flag> <sortkey> <flag> ...",NULL,0,NULL},
3847 {"sort+", cmd_sort_newset, "<sortkey> <flag> <sortkey> <flag> ...",NULL,0,NULL},
3848 {"authentication", cmd_authentication, "<acctstring>",NULL,0,NULL},
3849 {"lslb", cmd_lslb, "<largeSetLowerBound>",NULL,0,NULL},
3850 {"ssub", cmd_ssub, "<smallSetUpperBound>",NULL,0,NULL},
3851 {"mspn", cmd_mspn, "<mediumSetPresentNumber>",NULL,0,NULL},
3852 {"status", cmd_status, "",NULL,0,NULL},
3853 {"setnames", cmd_setnames, "",NULL,0,NULL},
3854 {"cancel", cmd_cancel, "",NULL,0,NULL},
3855 {"cancel_find", cmd_cancel_find, "<query>",NULL,0,NULL},
3856 {"format", cmd_format, "<recordsyntax>",complete_format,0,NULL},
3857 {"schema", cmd_schema, "<schema>",complete_schema,0,NULL},
3858 {"elements", cmd_elements, "<elementSetName>",NULL,0,NULL},
3859 {"close", cmd_close, "",NULL,0,NULL},
3860 {"attributeset", cmd_attributeset, "<attrset>",complete_attributeset,0,NULL},
3861 {"querytype", cmd_querytype, "<type>",complete_querytype,0,NULL},
3862 {"refid", cmd_refid, "<id>",NULL,0,NULL},
3863 {"itemorder", cmd_itemorder, "ill|item <itemno>",NULL,0,NULL},
3864 {"update", cmd_update, "<action> <recid> [<file>]",NULL,0,NULL},
3865 {"update0", cmd_update0, "<action> <recid> [<file>]",NULL,0,NULL},
3866 {"packagename", cmd_packagename, "<packagename>",NULL,0,NULL},
3867 {"proxy", cmd_proxy, "[('tcp'|'ssl')]<host>[':'<port>]",NULL,0,NULL},
3868 {"charset", cmd_charset, "<nego_charset> <output_charset>",NULL,0,NULL},
3869 {"marccharset", cmd_marccharset, "<charset_name>",NULL,0,NULL},
3870 {"lang", cmd_lang, "<language_code>",NULL,0,NULL},
3871 {".", cmd_source, "<filename>",NULL,1,NULL},
3872 {"!", cmd_subshell, "Subshell command",NULL,1,NULL},
3873 {"set_apdufile", cmd_set_apdufile, "<filename>",NULL,1,NULL},
3874 {"set_berfile", cmd_set_berfile, "<filename>",NULL,1,NULL},
3875 {"set_marcdump", cmd_set_marcdump," <filename>",NULL,1,NULL},
3876 {"set_cclfile", cmd_set_cclfile," <filename>",NULL,1,NULL},
3877 {"set_cqlfile", cmd_set_cqlfile," <filename>",NULL,1,NULL},
3878 {"set_auto_reconnect", cmd_set_auto_reconnect," on|off",complete_auto_reconnect,1,NULL},
3879 {"set_otherinfo", cmd_set_otherinfo,"<otherinfoinddex> <oid> <string>",NULL,0,NULL},
3880 {"register_oid", cmd_register_oid,"<name> <class> <oid>",NULL,0,NULL},
3881 {"push_command", cmd_push_command,"<command>",command_generator,0,NULL},
3882 {"register_tab", cmd_register_tab,"<commandname> <tab>",command_generator,0,NULL},
3883 {"cclparse", cmd_cclparse,"<ccl find command>",NULL,0,NULL},
3884 {"list_otherinfo",cmd_list_otherinfo,"[otherinfoinddex]",NULL,0,NULL},
3885 {"list_all",cmd_list_all,"",NULL,0,NULL},
3886 {"clear_otherinfo",cmd_clear_otherinfo,"",NULL,0,NULL},
3887 /* Server Admin Functions */
3888 {"adm-reindex", cmd_adm_reindex, "<database-name>",NULL,0,NULL},
3889 {"adm-truncate", cmd_adm_truncate, "('database'|'index')<object-name>",NULL,0,NULL},
3890 {"adm-create", cmd_adm_create, "",NULL,0,NULL},
3891 {"adm-drop", cmd_adm_drop, "('database'|'index')<object-name>",NULL,0,NULL},
3892 {"adm-import", cmd_adm_import, "<record-type> <dir> <pattern>",NULL,0,NULL},
3893 {"adm-refresh", cmd_adm_refresh, "",NULL,0,NULL},
3894 {"adm-commit", cmd_adm_commit, "",NULL,0,NULL},
3895 {"adm-shutdown", cmd_adm_shutdown, "",NULL,0,NULL},
3896 {"adm-startup", cmd_adm_startup, "",NULL,0,NULL},
3897 {"explain", cmd_explain, "", NULL, 0, NULL},
3898 {"options", cmd_options, "", NULL, 0, NULL},
3899 {"zversion", cmd_zversion, "", NULL, 0, NULL},
3900 {"help", cmd_help, "", NULL,0,NULL},
3901 {"init", cmd_init, "", NULL,0,NULL},
3905 static int cmd_help (const char *line)
3911 sscanf (line, "%20s", topic);
3914 printf("Commands:\n");
3915 for (i = 0; cmd_array[i].cmd; i++)
3916 if (*topic == 0 || strcmp (topic, cmd_array[i].cmd) == 0)
3917 printf(" %s %s\n", cmd_array[i].cmd, cmd_array[i].ad);
3918 if (strcmp (topic, "find") == 0)
3921 printf (" \"term\" Simple Term\n");
3922 printf (" @attr [attset] type=value op Attribute\n");
3923 printf (" @and opl opr And\n");
3924 printf (" @or opl opr Or\n");
3925 printf (" @not opl opr And-Not\n");
3926 printf (" @set set Result set\n");
3928 printf ("Bib-1 attribute types\n");
3930 printf ("4=Title 7=ISBN 8=ISSN 30=Date 62=Abstract 1003=Author 1016=Any\n");
3931 printf ("2=Relation: ");
3932 printf ("1< 2<= 3= 4>= 5> 6!= 102=Relevance\n");
3933 printf ("3=Position: ");
3934 printf ("1=First in Field 2=First in subfield 3=Any position\n");
3935 printf ("4=Structure: ");
3936 printf ("1=Phrase 2=Word 3=Key 4=Year 5=Date 6=WordList\n");
3937 printf ("5=Truncation: ");
3938 printf ("1=Right 2=Left 3=L&R 100=No 101=# 102=Re-1 103=Re-2\n");
3939 printf ("6=Completeness:");
3940 printf ("1=Incomplete subfield 2=Complete subfield 3=Complete field\n");
3945 int cmd_register_tab(const char* arg) {
3947 char command[101], tabargument[101];
3952 if (sscanf (arg, "%100s %100s", command, tabargument) < 1) {
3956 /* locate the amdn in the list */
3957 for (i = 0; cmd_array[i].cmd; i++) {
3958 if (!strncmp(cmd_array[i].cmd, command, strlen(command))) {
3963 if(!cmd_array[i].cmd) {
3964 fprintf(stderr,"Unknown command %s\n",command);
3969 if(!cmd_array[i].local_tabcompletes)
3970 cmd_array[i].local_tabcompletes = (char **) calloc(1,sizeof(char**));
3974 tabslist = cmd_array[i].local_tabcompletes;
3975 for(;tabslist && *tabslist;tabslist++) {
3979 cmd_array[i].local_tabcompletes = (char **)
3980 realloc(cmd_array[i].local_tabcompletes,(num_of_tabs+2)*sizeof(char**));
3981 tabslist=cmd_array[i].local_tabcompletes;
3982 tabslist[num_of_tabs]=strdup(tabargument);
3983 tabslist[num_of_tabs+1]=NULL;
3988 void process_cmd_line(char* line)
3991 char word[32], arg[10240];
3993 #if HAVE_GETTIMEOFDAY
3994 gettimeofday (&tv_start, 0);
3997 if ((res = sscanf(line, "%31s %10239[^;]", word, arg)) <= 0)
3999 strcpy(word, last_cmd);
4004 strcpy(last_cmd, word);
4006 /* removed tailing spaces from the arg command */
4009 char* lastnonspace=NULL;
4012 if(!isspace(*(unsigned char *) p)) {
4017 *(++lastnonspace) = 0;
4020 for (i = 0; cmd_array[i].cmd; i++)
4021 if (!strncmp(cmd_array[i].cmd, word, strlen(word)))
4023 res = (*cmd_array[i].fun)(arg);
4027 if (!cmd_array[i].cmd) /* dump our help-screen */
4029 printf("Unknown command: %s.\n", word);
4030 printf("use help for list of commands\n");
4031 /* cmd_help (""); */
4035 if(apdu_file) fflush(apdu_file);
4038 wait_and_handle_response();
4047 char *command_generator(const char *text, int state)
4053 for( ; cmd_array[idx].cmd; ++idx) {
4054 if (!strncmp(cmd_array[idx].cmd,text,strlen(text))) {
4055 ++idx; /* skip this entry on the next run */
4056 return strdup(cmd_array[idx-1].cmd);
4064 This function only known how to complete on the first word
4066 char ** readline_completer(char *text, int start, int end) {
4067 #if HAVE_READLINE_READLINE_H
4069 completerFunctionType completerToUse;
4072 #if HAVE_READLINE_RL_COMPLETION_MATCHES
4073 char** res=rl_completion_matches(text,
4076 char** res=completion_matches(text,
4077 (CPFunction*)command_generator);
4079 rl_attempted_completion_over = 1;
4082 char arg[10240],word[32];
4084 if ((res = sscanf(rl_line_buffer, "%31s %10239[^;]", word, arg)) <= 0) {
4085 rl_attempted_completion_over = 1;
4089 for (i = 0; cmd_array[i].cmd; i++) {
4090 if (!strncmp(cmd_array[i].cmd, word, strlen(word))) {
4095 if(!cmd_array[i].cmd) return NULL;
4097 curret_global_list = cmd_array[i].local_tabcompletes;
4099 completerToUse = cmd_array[i].rl_completerfunction;
4100 if(completerToUse==NULL) /* if no pr. command completer is defined use the default completer */
4101 completerToUse = default_completer;
4103 if(completerToUse) {
4104 #ifdef HAVE_READLINE_RL_COMPLETION_MATCHES
4106 rl_completion_matches(text,
4110 completion_matches(text,
4111 (CPFunction*)completerToUse);
4113 if(!cmd_array[i].complete_filenames)
4114 rl_attempted_completion_over = 1;
4117 if(!cmd_array[i].complete_filenames)
4118 rl_attempted_completion_over = 1;
4128 static void client(void)
4134 #if HAVE_GETTIMEOFDAY
4135 gettimeofday (&tv_start, 0);
4140 char *line_in = NULL;
4141 #if HAVE_READLINE_READLINE_H
4144 line_in=readline(C_PROMPT);
4147 #if HAVE_READLINE_HISTORY_H
4149 add_history(line_in);
4151 strncpy(line, line_in, 10239);
4160 if (!fgets(line, 10239, stdin))
4162 if ((end_p = strchr (line, '\n')))
4165 process_cmd_line(line);
4169 static void show_version(void)
4173 yaz_version(vstr, 0);
4174 printf ("YAZ version: %s\n", YAZ_VERSION);
4175 if (strcmp(vstr, YAZ_VERSION))
4176 printf ("YAZ DLL/SO: %s\n", vstr);
4180 int main(int argc, char **argv)
4183 char *open_command = 0;
4184 char *auth_command = 0;
4189 if (!setlocale(LC_CTYPE, ""))
4190 fprintf (stderr, "setlocale failed\n");
4194 codeset = nl_langinfo(CODESET);
4198 outputCharset = xstrdup(codeset);
4200 ODR_MASK_SET(&z3950_options, Z_Options_search);
4201 ODR_MASK_SET(&z3950_options, Z_Options_present);
4202 ODR_MASK_SET(&z3950_options, Z_Options_namedResultSets);
4203 ODR_MASK_SET(&z3950_options, Z_Options_triggerResourceCtrl);
4204 ODR_MASK_SET(&z3950_options, Z_Options_scan);
4205 ODR_MASK_SET(&z3950_options, Z_Options_sort);
4206 ODR_MASK_SET(&z3950_options, Z_Options_extendedServices);
4207 ODR_MASK_SET(&z3950_options, Z_Options_delSet);
4209 while ((ret = options("k:c:q:a:b:m:v:p:u:t:Vxd:", argv, argc, &arg)) != -2)
4216 open_command = (char *) xmalloc (strlen(arg)+6);
4217 strcpy (open_command, "open ");
4218 strcat (open_command, arg);
4222 dump_file_prefix = arg;
4225 kilobytes = atoi(arg);
4228 if (!(marc_file = fopen (arg, "a")))
4235 outputCharset = xstrdup(arg);
4238 strncpy (ccl_fields, arg, sizeof(ccl_fields)-1);
4239 ccl_fields[sizeof(ccl_fields)-1] = '\0';
4242 strncpy (cql_fields, arg, sizeof(cql_fields)-1);
4243 cql_fields[sizeof(cql_fields)-1] = '\0';
4246 if (!strcmp(arg, "-"))
4249 ber_file=fopen(arg, "a");
4252 if (!strcmp(arg, "-"))
4255 apdu_file=fopen(arg, "a");
4261 yazProxy=strdup(arg);
4266 auth_command = (char *) xmalloc (strlen(arg)+6);
4267 strcpy (auth_command, "auth ");
4268 strcat (auth_command, arg);
4272 yaz_log_init(yaz_log_mask_str(arg), "", 0);
4278 fprintf (stderr, "Usage: %s [-m <marclog>] [ -a <apdulog>] "
4279 "[-b berdump] [-c cclfields] \n"
4280 "[-q cqlfields] [-p <proxy-addr>] [-u <auth>] "
4281 "[-k size] [-d dump] [-V] [<server-addr>]\n",
4289 #ifdef HAVE_GETTIMEOFDAY
4290 gettimeofday (&tv_start, 0);
4292 process_cmd_line (auth_command);
4293 #if HAVE_READLINE_HISTORY_H
4294 add_history(auth_command);
4296 xfree(auth_command);
4300 #ifdef HAVE_GETTIMEOFDAY
4301 gettimeofday (&tv_start, 0);
4303 process_cmd_line (open_command);
4304 #if HAVE_READLINE_HISTORY_H
4305 add_history(open_command);
4307 xfree(open_command);
4318 * vim600: sw=4 ts=8 fdm=marker
4319 * vim<600: sw=4 ts=8