2 * Copyright (C) 1995-2005, Index Data ApS
3 * See the file LICENSE for details.
5 * $Id: client.c,v 1.272 2005-01-27 09:05:09 adam Exp $
14 #include <sys/types.h>
32 #if HAVE_OPENSSL_SSL_H
33 #include <openssl/bio.h>
34 #include <openssl/crypto.h>
35 #include <openssl/x509.h>
36 #include <openssl/pem.h>
37 #include <openssl/ssl.h>
38 #include <openssl/err.h>
45 #define S_ISREG(x) (x & _S_IFREG)
46 #define S_ISDIR(x) (x & _S_IFDIR)
49 #include <yaz/yaz-util.h>
51 #include <yaz/comstack.h>
53 #include <yaz/proto.h>
54 #include <yaz/marcdisp.h>
55 #include <yaz/diagbib1.h>
56 #include <yaz/otherinfo.h>
57 #include <yaz/charneg.h>
59 #include <yaz/pquery.h>
60 #include <yaz/sortspec.h>
64 #include <yaz/yaz-ccl.h>
68 #if HAVE_READLINE_READLINE_H
69 #include <readline/readline.h>
71 #if HAVE_READLINE_HISTORY_H
72 #include <readline/history.h>
77 #include "tabcomplete.h"
79 #define C_PROMPT "Z> "
81 static char *codeset = 0; /* character set for output */
82 static int hex_dump = 0;
83 static char *dump_file_prefix = 0;
84 static ODR out, in, print; /* encoding and decoding streams */
86 static ODR srw_sr_odr_out = 0;
87 static Z_SRW_PDU *srw_sr = 0;
89 static FILE *apdu_file = 0;
90 static FILE *ber_file = 0;
91 static COMSTACK conn = 0; /* our z-association */
92 static Z_IdAuthentication *auth = 0; /* our current auth definition */
93 char *databaseNames[128];
94 int num_databaseNames = 0;
95 static Z_External *record_last = 0;
96 static int setnumber = -1; /* current result set number */
97 static int smallSetUpperBound = 0;
98 static int largeSetLowerBound = 1;
99 static int mediumSetPresentNumber = 0;
100 static Z_ElementSetNames *elementSetNames = 0;
101 static int setno = 1; /* current set offset */
102 static enum oid_proto protocol = PROTO_Z3950; /* current app protocol */
103 static enum oid_value recordsyntax = VAL_USMARC;
104 static char *record_schema = 0;
105 static int sent_close = 0;
106 static NMEM session_mem = NULL; /* memory handle for init-response */
107 static Z_InitResponse *session = 0; /* session parameters */
108 static char last_scan_line[512] = "0";
109 static char last_scan_query[512] = "0";
110 static char ccl_fields[512] = "default.bib";
111 /* ### How can I set this path to use wherever YAZ is installed? */
112 static char cql_fields[512] = "/usr/local/share/yaz/etc/pqf.properties";
113 static char *esPackageName = 0;
114 static char *yazProxy = 0;
115 static int kilobytes = 1024;
116 static char *negotiationCharset = 0;
117 static int negotiationCharsetRecords = 1;
118 static int negotiationCharsetVersion = 3;
119 static char *outputCharset = 0;
120 static char *marcCharset = 0;
121 static char* yazLang = 0;
122 static char* http_version = "1.1";
124 static char last_cmd[32] = "?";
125 static FILE *marc_file = 0;
126 static char *refid = NULL;
127 static char *last_open_command = NULL;
128 static int auto_reconnect = 0;
129 static Odr_bitmask z3950_options;
130 static int z3950_version = 3;
131 static int scan_stepSize = 0;
132 static int scan_position = 1;
133 static char cur_host[200];
143 static QueryType queryType = QueryType_Prefix;
145 static CCL_bibset bibset; /* CCL bibset handle */
146 static cql_transform_t cqltrans; /* CQL context-set handle */
148 #if HAVE_READLINE_COMPLETION_OVER
151 /* readline doesn't have this var. Define it ourselves. */
152 int rl_attempted_completion_over = 0;
155 /* set this one to 1, to avoid decode of unknown MARCs */
156 #define AVOID_MARC_DECODE 1
158 #define maxOtherInfosSupported 10
162 } extraOtherInfos[maxOtherInfosSupported];
165 void process_cmd_line(char* line);
166 char ** readline_completer(char *text, int start, int end);
167 char *command_generator(const char *text, int state);
168 char** curret_global_list=NULL;
169 int cmd_register_tab(const char* arg);
171 static void close_session (void);
173 ODR getODROutputStream()
178 const char* query_type_as_string(QueryType q)
181 case QueryType_Prefix: return "prefix (RPN sent to server)";
182 case QueryType_CCL: return "CCL (CCL sent to server) ";
183 case QueryType_CCL2RPN: return "CCL -> RPN (RPN sent to server)";
184 case QueryType_CQL: return "CQL (CQL sent to server)";
185 case QueryType_CQL2RPN: return "CQL -> RPN (RPN sent to server)";
187 return "unknown Query type internal yaz-client error";
191 static void do_hex_dump(const char* buf, int len)
196 for( i=0; i<len ; i=i+16 )
199 for(x=0 ; i+x<len && x<16; ++x)
201 printf("%2.2X ",(unsigned int)((unsigned char)buf[i+x]));
206 if (dump_file_prefix)
209 if (++no < 1000 && strlen(dump_file_prefix) < 500)
213 sprintf (fname, "%s.%03d.raw", dump_file_prefix, no);
214 of = fopen(fname, "wb");
216 fwrite (buf, 1, len, of);
223 void add_otherInfos(Z_APDU *a)
225 Z_OtherInformation **oi;
229 for(i=0; i<maxOtherInfosSupported; ++i)
231 if(extraOtherInfos[i].oidval != -1)
232 yaz_oi_set_string_oidval(oi, out, extraOtherInfos[i].oidval,
233 1, extraOtherInfos[i].value);
237 int send_apdu(Z_APDU *a)
246 z_APDU(print, &a, 0, 0);
249 if (!z_APDU(out, &a, 0, 0))
251 odr_perror(out, "Encoding APDU");
255 buf = odr_getbuf(out, &len, 0);
257 odr_dumpBER(ber_file, buf, len);
258 /* printf ("sending APDU of size %d\n", len); */
259 do_hex_dump(buf, len);
260 if (cs_put(conn, buf, len) < 0)
262 fprintf(stderr, "cs_put: %s", cs_errmsg(cs_errno(conn)));
266 odr_reset(out); /* release the APDU structure */
270 static void print_stringn(const unsigned char *buf, size_t len)
273 for (i = 0; i<len; i++)
274 if ((buf[i] <= 126 && buf[i] >= 32) || strchr ("\n\r\t\f", buf[i]))
275 printf ("%c", buf[i]);
277 printf ("\\X%02X", buf[i]);
280 static void print_refid (Z_ReferenceId *id)
284 printf ("Reference Id: ");
285 print_stringn (id->buf, id->len);
290 static Z_ReferenceId *set_refid (ODR out)
295 id = (Z_ReferenceId *) odr_malloc (out, sizeof(*id));
296 id->size = id->len = strlen(refid);
297 id->buf = (unsigned char *) odr_malloc (out, id->len);
298 memcpy (id->buf, refid, id->len);
302 /* INIT SERVICE ------------------------------- */
304 static void send_initRequest(const char* type_and_host)
306 Z_APDU *apdu = zget_APDU(out, Z_APDU_initRequest);
307 Z_InitRequest *req = apdu->u.initRequest;
310 req->options = &z3950_options;
312 ODR_MASK_ZERO(req->protocolVersion);
313 for (i = 0; i<z3950_version; i++)
314 ODR_MASK_SET(req->protocolVersion, i);
316 *req->maximumRecordSize = 1024*kilobytes;
317 *req->preferredMessageSize = 1024*kilobytes;
319 req->idAuthentication = auth;
321 req->referenceId = set_refid (out);
323 if (yazProxy && type_and_host)
324 yaz_oi_set_string_oidval(&req->otherInfo, out, VAL_PROXY,
327 if (negotiationCharset || yazLang) {
328 Z_OtherInformation **p;
329 Z_OtherInformationUnit *p0;
331 yaz_oi_APDU(apdu, &p);
333 if ((p0=yaz_oi_update(p, out, NULL, 0, 0))) {
334 ODR_MASK_SET(req->options, Z_Options_negotiationModel);
336 p0->which = Z_OtherInfo_externallyDefinedInfo;
337 p0->information.externallyDefinedInfo =
338 yaz_set_proposal_charneg(
340 (const char**)&negotiationCharset,
341 negotiationCharset ? 1 : 0,
342 (const char**)&yazLang, yazLang ? 1 : 0,
343 negotiationCharsetRecords);
348 printf("Sent initrequest.\n");
352 /* These two are used only from process_initResponse() */
353 static void render_initUserInfo(Z_OtherInformation *ui1);
354 static void render_diag(Z_DiagnosticFormat *diag);
356 static void pr_opt(const char *opt, void *clientData)
361 static int process_initResponse(Z_InitResponse *res)
364 /* save session parameters for later use */
365 session_mem = odr_extract_mem(in);
368 for (ver = 0; ver < 8; ver++)
369 if (!ODR_MASK_GET(res->protocolVersion, ver))
373 printf("Connection rejected by v%d target.\n", ver);
375 printf("Connection accepted by v%d target.\n", ver);
376 if (res->implementationId)
377 printf("ID : %s\n", res->implementationId);
378 if (res->implementationName)
379 printf("Name : %s\n", res->implementationName);
380 if (res->implementationVersion)
381 printf("Version: %s\n", res->implementationVersion);
382 if (res->userInformationField)
384 Z_External *uif = res->userInformationField;
385 if (uif->which == Z_External_userInfo1) {
386 render_initUserInfo(uif->u.userInfo1);
388 printf("UserInformationfield:\n");
389 if (!z_External(print, (Z_External**)&uif, 0, 0))
391 odr_perror(print, "Printing userinfo\n");
394 if (uif->which == Z_External_octet) {
395 printf("Guessing visiblestring:\n");
396 printf("'%.*s'\n", uif->u.octet_aligned->len,
397 uif->u.octet_aligned->buf);
399 else if (uif->which == Z_External_single)
401 Odr_any *sat = uif->u.single_ASN1_type;
402 oident *oid = oid_getentbyoid(uif->direct_reference);
403 if (oid->value == VAL_OCLCUI) {
404 Z_OCLC_UserInformation *oclc_ui;
405 ODR decode = odr_createmem(ODR_DECODE);
406 odr_setbuf(decode, sat->buf, sat->len, 0);
407 if (!z_OCLC_UserInformation(decode, &oclc_ui, 0, 0))
408 printf ("Bad OCLC UserInformation:\n");
410 printf ("OCLC UserInformation:\n");
411 if (!z_OCLC_UserInformation(print, &oclc_ui, 0, 0))
412 printf ("Bad OCLC UserInformation spec\n");
417 /* Peek at any private Init-diagnostic APDUs */
418 printf("### NAUGHTY: External is '%.*s'\n",
426 yaz_init_opt_decode(res->options, pr_opt, 0);
429 if (ODR_MASK_GET(res->options, Z_Options_namedResultSets))
432 if (ODR_MASK_GET(res->options, Z_Options_negotiationModel)) {
434 Z_CharSetandLanguageNegotiation *p =
435 yaz_get_charneg_record(res->otherInfo);
439 char *charset=NULL, *lang=NULL;
442 yaz_get_response_charneg(session_mem, p, &charset, &lang,
445 if (outputCharset && negotiationCharset) {
446 odr_set_charset (out, charset, outputCharset);
447 odr_set_charset (in, outputCharset, charset);
450 odr_set_charset (out, 0, 0);
451 odr_set_charset (in, 0, 0);
454 printf("Accepted character set : %s\n", charset);
455 printf("Accepted code language : %s\n", lang ? lang : "none");
456 printf("Accepted records in ...: %d\n", selected );
464 static void render_initUserInfo(Z_OtherInformation *ui1) {
466 printf("Init response contains %d otherInfo unit%s:\n",
467 ui1->num_elements, ui1->num_elements == 1 ? "" : "s");
469 for (i = 0; i < ui1->num_elements; i++) {
470 Z_OtherInformationUnit *unit = ui1->list[i];
471 printf(" %d: otherInfo unit contains ", i+1);
472 if (unit->which == Z_OtherInfo_externallyDefinedInfo &&
473 unit->information.externallyDefinedInfo &&
474 unit->information.externallyDefinedInfo->which ==
476 render_diag(unit->information.externallyDefinedInfo->u.diag1);
478 else if (unit->which != Z_OtherInfo_externallyDefinedInfo)
480 printf("unsupported otherInfo unit->which = %d\n", unit->which);
484 printf("unsupported otherInfo unit external %d\n",
485 unit->information.externallyDefinedInfo ?
486 unit->information.externallyDefinedInfo->which : -2);
492 /* ### should this share code with display_diagrecs()? */
493 static void render_diag(Z_DiagnosticFormat *diag) {
496 printf("%d diagnostic%s:\n", diag->num, diag->num == 1 ? "" : "s");
497 for (i = 0; i < diag->num; i++) {
498 Z_DiagnosticFormat_s *ds = diag->elements[i];
499 printf(" %d: ", i+1);
501 case Z_DiagnosticFormat_s_defaultDiagRec: {
502 Z_DefaultDiagFormat *dd = ds->u.defaultDiagRec;
503 /* ### should check `dd->diagnosticSetId' */
504 printf("code=%d (%s)", *dd->condition,
505 diagbib1_str(*dd->condition));
506 /* Both types of addinfo are the same, so use type-pun */
507 if (dd->u.v2Addinfo != 0)
508 printf(",\n\taddinfo='%s'", dd->u.v2Addinfo);
511 case Z_DiagnosticFormat_s_explicitDiagnostic:
512 printf("Explicit diagnostic (not supported)");
515 printf("Unrecognised diagnostic type %d", ds->which);
519 if (ds->message != 0)
520 printf(", message='%s'", ds->message);
526 static int set_base(const char *arg)
531 for (i = 0; i<num_databaseNames; i++)
532 xfree (databaseNames[i]);
533 num_databaseNames = 0;
537 if (!(cp = strchr(arg, ' ')))
538 cp = arg + strlen(arg);
541 databaseNames[num_databaseNames] = (char *)xmalloc (1 + cp - arg);
542 memcpy (databaseNames[num_databaseNames], arg, cp - arg);
543 databaseNames[num_databaseNames][cp - arg] = '\0';
545 for (cp1 = databaseNames[num_databaseNames]; *cp1 ; cp1++)
554 if (num_databaseNames == 0)
556 num_databaseNames = 1;
557 databaseNames[0] = xstrdup("");
562 static int cmd_base(const char *arg)
566 printf("Usage: base <database> <database> ...\n");
569 return set_base(arg);
572 void cmd_open_remember_last_open_command(const char* arg, char* new_open_command)
574 if(last_open_command != arg)
576 if(last_open_command) xfree(last_open_command);
577 last_open_command = xstrdup(new_open_command);
581 int session_connect(const char *arg)
584 char type_and_host[101];
585 const char *basep = 0;
586 #if HAVE_OPENSSL_SSL_H
595 nmem_destroy (session_mem);
599 cs_get_host_args(arg, &basep);
601 strncpy(type_and_host, arg, sizeof(type_and_host)-1);
602 type_and_host[sizeof(type_and_host)-1] = '\0';
604 cmd_open_remember_last_open_command(arg,type_and_host);
607 conn = cs_create_host(yazProxy, 1, &add);
609 conn = cs_create_host(arg, 1, &add);
612 printf ("Couldn't create comstack\n");
616 if (conn->protocol == PROTO_HTTP)
617 queryType = QueryType_CQL;
619 if (conn->protocol == PROTO_HTTP)
621 printf ("SRW/HTTP not enabled in this YAZ\n");
627 protocol = conn->protocol;
628 if (conn->protocol == PROTO_HTTP)
632 printf("Connecting...");
634 if (cs_connect(conn, add) < 0)
636 printf ("error = %s\n", cs_strerror(conn));
637 if (conn->cerrno == CSYSERR)
640 yaz_strerror(msg, sizeof(msg));
641 printf ("%s\n", msg);
648 #if HAVE_OPENSSL_SSL_H
649 if ((ssl = (SSL *) cs_get_ssl(conn)))
651 X509 *server_cert = SSL_get_peer_certificate (ssl);
657 BIO *bio = BIO_new(BIO_s_mem());
659 /* get PEM buffer in memory */
660 PEM_write_bio_X509(bio, server_cert);
661 pem_len = BIO_get_mem_data(bio, &pem_buf);
662 fwrite(pem_buf, pem_len, 1, stdout);
664 /* print all info on screen .. */
665 X509_print_fp(stdout, server_cert);
668 X509_free (server_cert);
674 if (protocol == PROTO_Z3950)
676 send_initRequest(type_and_host);
682 int cmd_open(const char *arg)
686 strncpy (cur_host, arg, sizeof(cur_host)-1);
687 cur_host[sizeof(cur_host)-1] = 0;
689 return session_connect(cur_host);
696 if(!( auto_reconnect && last_open_command) ) return ;
698 open_command = (char *) xmalloc (strlen(last_open_command)+6);
699 strcpy (open_command, "open ");
701 strcat (open_command, last_open_command);
703 process_cmd_line(open_command);
708 int cmd_authentication(const char *arg)
710 static Z_IdAuthentication au;
711 static char user[40], group[40], pass[40];
712 static Z_IdPass idPass;
717 printf("Auth field set to null\n");
721 r = sscanf (arg, "%39s %39s %39s", user, group, pass);
724 printf("Authentication set to null\n");
730 if (!strcmp(user, "-")) {
731 au.which = Z_IdAuthentication_anonymous;
732 printf("Authentication set to Anonymous\n");
734 au.which = Z_IdAuthentication_open;
736 printf("Authentication set to Open (%s)\n", user);
742 au.which = Z_IdAuthentication_idPass;
743 au.u.idPass = &idPass;
744 idPass.groupId = NULL;
745 idPass.userId = user;
746 idPass.password = group;
747 printf("Authentication set to User (%s), Pass (%s)\n", user, group);
752 au.which = Z_IdAuthentication_idPass;
753 au.u.idPass = &idPass;
754 idPass.groupId = group;
755 idPass.userId = user;
756 idPass.password = pass;
757 printf("Authentication set to User (%s), Group (%s), Pass (%s)\n",
763 /* SEARCH SERVICE ------------------------------ */
764 static void display_record(Z_External *r);
766 static void print_record(const unsigned char *buf, size_t len)
769 print_stringn (buf, len);
770 /* add newline if not already added ... */
771 if (i <= 0 || buf[i-1] != '\n')
774 fwrite (buf, 1, len, marc_file);
777 static void display_record(Z_External *r)
779 oident *ent = oid_getentbyoid(r->direct_reference);
783 * Tell the user what we got.
785 if (r->direct_reference)
787 printf("Record type: ");
789 printf("%s\n", ent->desc);
790 else if (!odr_oid(print, &r->direct_reference, 0, 0))
792 odr_perror(print, "print oid");
796 /* Check if this is a known, ASN.1 type tucked away in an octet string */
797 if (ent && r->which == Z_External_octet)
799 Z_ext_typeent *type = z_ext_getentbyref(ent->value);
805 * Call the given decoder to process the record.
807 odr_setbuf(in, (char*)r->u.octet_aligned->buf,
808 r->u.octet_aligned->len, 0);
809 if (!(*type->fun)(in, &rr, 0, 0))
811 odr_perror(in, "Decoding constructed record.");
812 fprintf(stdout, "[Near %d]\n", odr_offset(in));
813 fprintf(stdout, "Packet dump:\n---------\n");
814 odr_dumpBER(stdout, (char*)r->u.octet_aligned->buf,
815 r->u.octet_aligned->len);
816 fprintf(stdout, "---------\n");
818 /* note just ignores the error ant print the bytes form the octet_aligned later */
821 * Note: we throw away the original, BER-encoded record here.
822 * Do something else with it if you want to keep it.
824 r->u.sutrs = (Z_SUTRS *) rr; /* we don't actually check the type here. */
825 r->which = type->what;
829 if (ent && ent->value == VAL_SOIF)
830 print_record((const unsigned char *) r->u.octet_aligned->buf,
831 r->u.octet_aligned->len);
832 else if (r->which == Z_External_octet)
834 const char *octet_buf = (char*)r->u.octet_aligned->buf;
835 if (ent->oclass == CLASS_RECSYN &&
836 (ent->value == VAL_TEXT_XML ||
837 ent->value == VAL_APPLICATION_XML ||
838 ent->value == VAL_HTML))
840 print_record((const unsigned char *) octet_buf,
841 r->u.octet_aligned->len);
843 else if (ent->value == VAL_POSTSCRIPT)
845 int size = r->u.octet_aligned->len;
848 print_record((const unsigned char *) octet_buf, size);
853 #if AVOID_MARC_DECODE
854 /* primitive check for a marc OID 5.1-29 except 16 */
855 ent->oidsuffix[0] == 5 && ent->oidsuffix[1] < 30 &&
856 ent->oidsuffix[1] != 16
865 yaz_marc_t mt = yaz_marc_create();
867 if (yaz_marc_decode_buf(mt, octet_buf,r->u.octet_aligned->len,
871 if (marcCharset && !strcmp(marcCharset, "auto"))
873 if (ent->value == VAL_USMARC)
875 if (octet_buf[9] == 'a')
883 else if (marcCharset)
885 if (outputCharset && from)
887 cd = yaz_iconv_open(outputCharset, from);
888 printf ("convert from %s to %s", from,
891 printf (" unsupported\n");
896 fwrite (result, 1, rlen, stdout);
900 size_t inbytesleft = rlen;
901 const char *inp = result;
905 size_t outbytesleft = sizeof(outbuf);
909 r = yaz_iconv (cd, (char**) &inp,
911 &outp, &outbytesleft);
912 if (r == (size_t) (-1))
914 int e = yaz_iconv_error(cd);
915 if (e != YAZ_ICONV_E2BIG)
918 fwrite (outbuf, outp - outbuf, 1, stdout);
924 printf ("bad MARC. Dumping as it is:\n");
925 print_record((const unsigned char*) octet_buf,
926 r->u.octet_aligned->len);
928 yaz_marc_destroy(mt);
934 print_record((const unsigned char*) octet_buf,
935 r->u.octet_aligned->len);
939 fwrite (octet_buf, 1, r->u.octet_aligned->len, marc_file);
941 else if (ent && ent->value == VAL_SUTRS)
943 if (r->which != Z_External_sutrs)
945 printf("Expecting single SUTRS type for SUTRS.\n");
948 print_record(r->u.sutrs->buf, r->u.sutrs->len);
950 else if (ent && ent->value == VAL_GRS1)
953 if (r->which != Z_External_grs1)
955 printf("Expecting single GRS type for GRS.\n");
959 yaz_display_grs1(w, r->u.grs1, 0);
963 else if ( /* OPAC display not complete yet .. */
964 ent && ent->value == VAL_OPAC)
967 if (r->u.opac->bibliographicRecord)
968 display_record(r->u.opac->bibliographicRecord);
969 for (i = 0; i<r->u.opac->num_holdingsData; i++)
971 Z_HoldingsRecord *h = r->u.opac->holdingsData[i];
972 if (h->which == Z_HoldingsRecord_marcHoldingsRecord)
974 printf ("MARC holdings %d\n", i);
975 display_record(h->u.marcHoldingsRecord);
977 else if (h->which == Z_HoldingsRecord_holdingsAndCirc)
981 Z_HoldingsAndCircData *data = h->u.holdingsAndCirc;
983 printf ("Data holdings %d\n", i);
984 if (data->typeOfRecord)
985 printf ("typeOfRecord: %s\n", data->typeOfRecord);
986 if (data->encodingLevel)
987 printf ("encodingLevel: %s\n", data->encodingLevel);
988 if (data->receiptAcqStatus)
989 printf ("receiptAcqStatus: %s\n", data->receiptAcqStatus);
990 if (data->generalRetention)
991 printf ("generalRetention: %s\n", data->generalRetention);
992 if (data->completeness)
993 printf ("completeness: %s\n", data->completeness);
994 if (data->dateOfReport)
995 printf ("dateOfReport: %s\n", data->dateOfReport);
997 printf ("nucCode: %s\n", data->nucCode);
998 if (data->localLocation)
999 printf ("localLocation: %s\n", data->localLocation);
1000 if (data->shelvingLocation)
1001 printf ("shelvingLocation: %s\n", data->shelvingLocation);
1002 if (data->callNumber)
1003 printf ("callNumber: %s\n", data->callNumber);
1004 if (data->shelvingData)
1005 printf ("shelvingData: %s\n", data->shelvingData);
1006 if (data->copyNumber)
1007 printf ("copyNumber: %s\n", data->copyNumber);
1008 if (data->publicNote)
1009 printf ("publicNote: %s\n", data->publicNote);
1010 if (data->reproductionNote)
1011 printf ("reproductionNote: %s\n", data->reproductionNote);
1012 if (data->termsUseRepro)
1013 printf ("termsUseRepro: %s\n", data->termsUseRepro);
1014 if (data->enumAndChron)
1015 printf ("enumAndChron: %s\n", data->enumAndChron);
1016 for (j = 0; j<data->num_volumes; j++)
1018 printf ("volume %d\n", j);
1019 if (data->volumes[j]->enumeration)
1020 printf (" enumeration: %s\n",
1021 data->volumes[j]->enumeration);
1022 if (data->volumes[j]->chronology)
1023 printf (" chronology: %s\n",
1024 data->volumes[j]->chronology);
1025 if (data->volumes[j]->enumAndChron)
1026 printf (" enumAndChron: %s\n",
1027 data->volumes[j]->enumAndChron);
1029 for (j = 0; j<data->num_circulationData; j++)
1031 printf ("circulation %d\n", j);
1032 if (data->circulationData[j]->availableNow)
1033 printf (" availableNow: %d\n",
1034 *data->circulationData[j]->availableNow);
1035 if (data->circulationData[j]->availablityDate)
1036 printf (" availabiltyDate: %s\n",
1037 data->circulationData[j]->availablityDate);
1038 if (data->circulationData[j]->availableThru)
1039 printf (" availableThru: %s\n",
1040 data->circulationData[j]->availableThru);
1041 if (data->circulationData[j]->restrictions)
1042 printf (" restrictions: %s\n",
1043 data->circulationData[j]->restrictions);
1044 if (data->circulationData[j]->itemId)
1045 printf (" itemId: %s\n",
1046 data->circulationData[j]->itemId);
1047 if (data->circulationData[j]->renewable)
1048 printf (" renewable: %d\n",
1049 *data->circulationData[j]->renewable);
1050 if (data->circulationData[j]->onHold)
1051 printf (" onHold: %d\n",
1052 *data->circulationData[j]->onHold);
1053 if (data->circulationData[j]->enumAndChron)
1054 printf (" enumAndChron: %s\n",
1055 data->circulationData[j]->enumAndChron);
1056 if (data->circulationData[j]->midspine)
1057 printf (" midspine: %s\n",
1058 data->circulationData[j]->midspine);
1059 if (data->circulationData[j]->temporaryLocation)
1060 printf (" temporaryLocation: %s\n",
1061 data->circulationData[j]->temporaryLocation);
1068 printf("Unknown record representation.\n");
1069 if (!z_External(print, &r, 0, 0))
1071 odr_perror(print, "Printing external");
1077 static void display_diagrecs(Z_DiagRec **pp, int num)
1081 Z_DefaultDiagFormat *r;
1083 printf("Diagnostic message(s) from database:\n");
1084 for (i = 0; i<num; i++)
1086 Z_DiagRec *p = pp[i];
1087 if (p->which != Z_DiagRec_defaultFormat)
1089 printf("Diagnostic record not in default format.\n");
1093 r = p->u.defaultFormat;
1094 if (!(ent = oid_getentbyoid(r->diagnosticSetId)) ||
1095 ent->oclass != CLASS_DIAGSET || ent->value != VAL_BIB1)
1096 printf("Missing or unknown diagset\n");
1097 printf(" [%d] %s", *r->condition, diagbib1_str(*r->condition));
1100 case Z_DefaultDiagFormat_v2Addinfo:
1101 printf (" -- v2 addinfo '%s'\n", r->u.v2Addinfo);
1103 case Z_DefaultDiagFormat_v3Addinfo:
1104 printf (" -- v3 addinfo '%s'\n", r->u.v3Addinfo);
1111 static void display_nameplusrecord(Z_NamePlusRecord *p)
1113 if (p->databaseName)
1114 printf("[%s]", p->databaseName);
1115 if (p->which == Z_NamePlusRecord_surrogateDiagnostic)
1116 display_diagrecs(&p->u.surrogateDiagnostic, 1);
1117 else if (p->which == Z_NamePlusRecord_databaseRecord)
1118 display_record(p->u.databaseRecord);
1121 static void display_records(Z_Records *p)
1125 if (p->which == Z_Records_NSD)
1127 Z_DiagRec dr, *dr_p = &dr;
1128 dr.which = Z_DiagRec_defaultFormat;
1129 dr.u.defaultFormat = p->u.nonSurrogateDiagnostic;
1130 display_diagrecs (&dr_p, 1);
1132 else if (p->which == Z_Records_multipleNSD)
1133 display_diagrecs (p->u.multipleNonSurDiagnostics->diagRecs,
1134 p->u.multipleNonSurDiagnostics->num_diagRecs);
1137 printf("Records: %d\n", p->u.databaseOrSurDiagnostics->num_records);
1138 for (i = 0; i < p->u.databaseOrSurDiagnostics->num_records; i++)
1139 display_nameplusrecord(p->u.databaseOrSurDiagnostics->records[i]);
1143 static int send_deleteResultSetRequest(const char *arg)
1148 Z_APDU *apdu = zget_APDU(out, Z_APDU_deleteResultSetRequest);
1149 Z_DeleteResultSetRequest *req = apdu->u.deleteResultSetRequest;
1151 req->referenceId = set_refid (out);
1153 req->num_resultSetList =
1154 sscanf (arg, "%30s %30s %30s %30s %30s %30s %30s %30s",
1155 names[0], names[1], names[2], names[3],
1156 names[4], names[5], names[6], names[7]);
1158 req->deleteFunction = (int *)
1159 odr_malloc (out, sizeof(*req->deleteFunction));
1160 if (req->num_resultSetList > 0)
1162 *req->deleteFunction = Z_DeleteResultSetRequest_list;
1163 req->resultSetList = (char **)
1164 odr_malloc (out, sizeof(*req->resultSetList)*
1165 req->num_resultSetList);
1166 for (i = 0; i<req->num_resultSetList; i++)
1167 req->resultSetList[i] = names[i];
1171 *req->deleteFunction = Z_DeleteResultSetRequest_all;
1172 req->resultSetList = 0;
1176 printf("Sent deleteResultSetRequest.\n");
1181 static int send_srw(Z_SRW_PDU *sr)
1183 const char *charset = negotiationCharset;
1184 const char *host_port = cur_host;
1187 Z_SOAP_Handler h[2] = {
1188 {"http://www.loc.gov/zing/srw/", 0, (Z_SOAP_fun) yaz_srw_codec},
1191 ODR o = odr_createmem(ODR_ENCODE);
1193 Z_SOAP *p = odr_malloc(o, sizeof(*p));
1196 path = odr_malloc(out, strlen(databaseNames[0])+2);
1198 strcpy(path+1, databaseNames[0]);
1200 gdu = z_get_HTTP_Request(out);
1201 gdu->u.HTTP_Request->version = http_version;
1202 gdu->u.HTTP_Request->path = odr_strdup(out, path);
1206 const char *cp0 = strstr(host_port, "://");
1207 const char *cp1 = 0;
1213 cp1 = strchr(cp0, '/');
1215 cp1 = cp0+strlen(cp0);
1219 char *h = odr_malloc(out, cp1 - cp0 + 1);
1220 memcpy (h, cp0, cp1 - cp0);
1222 z_HTTP_header_add(out, &gdu->u.HTTP_Request->headers,
1227 strcpy(ctype, "text/xml");
1228 if (charset && strlen(charset) < 20)
1230 strcat(ctype, "; charset=");
1231 strcat(ctype, charset);
1233 z_HTTP_header_add(out, &gdu->u.HTTP_Request->headers,
1234 "Content-Type", ctype);
1235 z_HTTP_header_add(out, &gdu->u.HTTP_Request->headers,
1236 "SOAPAction", "\"\"");
1237 p->which = Z_SOAP_generic;
1238 p->u.generic = odr_malloc(o, sizeof(*p->u.generic));
1239 p->u.generic->no = 0;
1240 p->u.generic->ns = 0;
1241 p->u.generic->p = sr;
1242 p->ns = "http://schemas.xmlsoap.org/soap/envelope/";
1244 ret = z_soap_codec_enc(o, &p,
1245 &gdu->u.HTTP_Request->content_buf,
1246 &gdu->u.HTTP_Request->content_len, h,
1249 if (z_GDU(out, &gdu, 0, 0))
1257 if (!z_GDU(print, &gdu, 0, 0))
1258 printf ("Failed to print outgoing APDU\n");
1261 buf_out = odr_getbuf(out, &len_out, 0);
1263 /* we don't odr_reset(out), since we may need the buffer again */
1265 do_hex_dump(buf_out, len_out);
1267 r = cs_put(conn, buf_out, len_out);
1279 static int send_SRW_scanRequest(const char *arg, int pos, int num)
1283 /* regular requestse .. */
1284 sr = yaz_srw_get(out, Z_SRW_scan_request);
1289 sr->u.scan_request->query_type = Z_SRW_query_type_cql;
1290 sr->u.scan_request->scanClause.cql = odr_strdup(out, arg);
1292 case QueryType_Prefix:
1293 sr->u.scan_request->query_type = Z_SRW_query_type_pqf;
1294 sr->u.scan_request->scanClause.pqf = odr_strdup(out, arg);
1297 printf ("Only CQL and PQF supported in SRW\n");
1300 sr->u.scan_request->responsePosition = odr_intdup(out, pos);
1301 sr->u.scan_request->maximumTerms = odr_intdup(out, num);
1302 return send_srw(sr);
1305 static int send_SRW_searchRequest(const char *arg)
1311 assert(srw_sr_odr_out == 0);
1312 srw_sr_odr_out = odr_createmem(ODR_ENCODE);
1314 odr_reset(srw_sr_odr_out);
1318 /* save this for later .. when fetching individual records */
1319 srw_sr = yaz_srw_get(srw_sr_odr_out, Z_SRW_searchRetrieve_request);
1321 /* regular request .. */
1322 sr = yaz_srw_get(out, Z_SRW_searchRetrieve_request);
1327 srw_sr->u.request->query_type = Z_SRW_query_type_cql;
1328 srw_sr->u.request->query.cql = odr_strdup(srw_sr_odr_out, arg);
1330 sr->u.request->query_type = Z_SRW_query_type_cql;
1331 sr->u.request->query.cql = odr_strdup(out, arg);
1333 case QueryType_Prefix:
1334 srw_sr->u.request->query_type = Z_SRW_query_type_pqf;
1335 srw_sr->u.request->query.pqf = odr_strdup(srw_sr_odr_out, arg);
1337 sr->u.request->query_type = Z_SRW_query_type_pqf;
1338 sr->u.request->query.pqf = odr_strdup(out, arg);
1341 printf ("Only CQL and PQF supported in SRW\n");
1344 sr->u.request->maximumRecords = odr_intdup(out, 0);
1347 sr->u.request->recordSchema = record_schema;
1348 if (recordsyntax == VAL_TEXT_XML)
1349 sr->u.explain_request->recordPacking = "xml";
1350 return send_srw(sr);
1354 static int send_searchRequest(const char *arg)
1356 Z_APDU *apdu = zget_APDU(out, Z_APDU_searchRequest);
1357 Z_SearchRequest *req = apdu->u.searchRequest;
1359 struct ccl_rpn_node *rpn = NULL;
1361 char setstring[100];
1362 Z_RPNQuery *RPNquery;
1364 YAZ_PQF_Parser pqf_parser;
1366 QueryType myQueryType = queryType;
1369 if (myQueryType == QueryType_CCL2RPN)
1371 rpn = ccl_find_str(bibset, arg, &error, &pos);
1374 printf("CCL ERROR: %s\n", ccl_err_msg(error));
1377 } else if (myQueryType == QueryType_CQL2RPN) {
1378 /* ### All this code should be wrapped in a utility function */
1380 struct cql_node *node;
1381 const char *addinfo;
1382 if (cqltrans == 0) {
1383 printf("Can't use CQL: no translation file. Try set_cqlfile\n");
1386 parser = cql_parser_create();
1387 if ((error = cql_parser_string(parser, arg)) != 0) {
1388 printf("Can't parse CQL: must be a syntax error\n");
1391 node = cql_parser_result(parser);
1392 if ((error = cql_transform_buf(cqltrans, node, pqfbuf,
1393 sizeof pqfbuf)) != 0) {
1394 error = cql_transform_error(cqltrans, &addinfo);
1395 printf ("Can't convert CQL to PQF: %s (addinfo=%s)\n",
1396 cql_strerror(error), addinfo);
1400 myQueryType = QueryType_Prefix;
1403 req->referenceId = set_refid (out);
1404 if (!strcmp(arg, "@big")) /* strictly for troublemaking */
1406 static unsigned char big[2100];
1407 static Odr_oct bigo;
1409 /* send a very big referenceid to test transport stack etc. */
1410 memset(big, 'A', 2100);
1411 bigo.len = bigo.size = 2100;
1413 req->referenceId = &bigo;
1418 sprintf(setstring, "%d", ++setnumber);
1419 req->resultSetName = setstring;
1421 *req->smallSetUpperBound = smallSetUpperBound;
1422 *req->largeSetLowerBound = largeSetLowerBound;
1423 *req->mediumSetPresentNumber = mediumSetPresentNumber;
1424 if (smallSetUpperBound > 0 || (largeSetLowerBound > 1 &&
1425 mediumSetPresentNumber > 0))
1427 req->preferredRecordSyntax =
1428 yaz_oidval_to_z3950oid(out, CLASS_RECSYN, recordsyntax);
1430 req->smallSetElementSetNames =
1431 req->mediumSetElementSetNames = elementSetNames;
1433 req->num_databaseNames = num_databaseNames;
1434 req->databaseNames = databaseNames;
1436 req->query = &query;
1438 switch (myQueryType)
1440 case QueryType_Prefix:
1441 query.which = Z_Query_type_1;
1442 pqf_parser = yaz_pqf_create ();
1443 RPNquery = yaz_pqf_parse (pqf_parser, out, arg);
1446 const char *pqf_msg;
1448 int code = yaz_pqf_error (pqf_parser, &pqf_msg, &off);
1449 printf("%*s^\n", off+4, "");
1450 printf("Prefix query error: %s (code %d)\n", pqf_msg, code);
1452 yaz_pqf_destroy (pqf_parser);
1455 yaz_pqf_destroy (pqf_parser);
1456 query.u.type_1 = RPNquery;
1459 query.which = Z_Query_type_2;
1460 query.u.type_2 = &ccl_query;
1461 ccl_query.buf = (unsigned char*) arg;
1462 ccl_query.len = strlen(arg);
1464 case QueryType_CCL2RPN:
1465 query.which = Z_Query_type_1;
1466 RPNquery = ccl_rpn_query(out, rpn);
1469 printf ("Couldn't convert from CCL to RPN\n");
1472 query.u.type_1 = RPNquery;
1473 ccl_rpn_delete (rpn);
1476 query.which = Z_Query_type_104;
1477 ext = (Z_External *) odr_malloc(out, sizeof(*ext));
1478 ext->direct_reference = odr_getoidbystr(out, "1.2.840.10003.16.2");
1479 ext->indirect_reference = 0;
1480 ext->descriptor = 0;
1481 ext->which = Z_External_CQL;
1482 ext->u.cql = odr_strdup(out, arg);
1483 query.u.type_104 = ext;
1486 printf ("Unsupported query type\n");
1489 if (send_apdu(apdu))
1490 printf("Sent searchRequest.\n");
1495 /* display Query Expression as part of searchResult-1 */
1496 static void display_queryExpression (Z_QueryExpression *qe)
1500 if (qe->which == Z_QueryExpression_term)
1502 if (qe->u.term->queryTerm)
1504 Z_Term *term = qe->u.term->queryTerm;
1505 switch (term->which)
1507 case Z_Term_general:
1508 printf (" %.*s", term->u.general->len, term->u.general->buf);
1510 case Z_Term_characterString:
1511 printf (" %s", term->u.characterString);
1513 case Z_Term_numeric:
1514 printf (" %d", *term->u.numeric);
1524 /* see if we can find USR:SearchResult-1 */
1525 static void display_searchResult (Z_OtherInformation *o)
1530 for (i = 0; i < o->num_elements; i++)
1532 if (o->list[i]->which == Z_OtherInfo_externallyDefinedInfo)
1534 Z_External *ext = o->list[i]->information.externallyDefinedInfo;
1536 if (ext->which == Z_External_searchResult1)
1539 Z_SearchInfoReport *sr = ext->u.searchResult1;
1540 printf ("SearchResult-1:");
1541 for (j = 0; j < sr->num; j++)
1543 if (!sr->elements[j]->subqueryExpression)
1545 display_queryExpression (
1546 sr->elements[j]->subqueryExpression);
1547 display_queryExpression (
1548 sr->elements[j]->subqueryInterpretation);
1549 display_queryExpression (
1550 sr->elements[j]->subqueryRecommendation);
1551 if (sr->elements[j]->subqueryCount)
1552 printf ("(%d)", *sr->elements[j]->subqueryCount);
1560 static int process_searchResponse(Z_SearchResponse *res)
1562 printf ("Received SearchResponse.\n");
1563 print_refid (res->referenceId);
1564 if (*res->searchStatus)
1565 printf("Search was a success.\n");
1567 printf("Search was a bloomin' failure.\n");
1568 printf("Number of hits: %d", *res->resultCount);
1570 printf (", setno %d", setnumber);
1572 display_searchResult (res->additionalSearchInfo);
1573 printf("records returned: %d\n",
1574 *res->numberOfRecordsReturned);
1575 setno += *res->numberOfRecordsReturned;
1577 display_records(res->records);
1581 static void print_level(int iLevel)
1584 for (i = 0; i < iLevel * 4; i++)
1588 static void print_int(int iLevel, const char *pTag, int *pInt)
1592 print_level(iLevel);
1593 printf("%s: %d\n", pTag, *pInt);
1597 static void print_string(int iLevel, const char *pTag, const char *pString)
1599 if (pString != NULL)
1601 print_level(iLevel);
1602 printf("%s: %s\n", pTag, pString);
1606 static void print_oid(int iLevel, const char *pTag, Odr_oid *pOid)
1612 print_level(iLevel);
1613 printf("%s:", pTag);
1614 for (; *pInt != -1; pInt++)
1615 printf(" %d", *pInt);
1620 static void print_referenceId(int iLevel, Z_ReferenceId *referenceId)
1622 if (referenceId != NULL)
1626 print_level(iLevel);
1627 printf("Ref Id (%d, %d): ", referenceId->len, referenceId->size);
1628 for (i = 0; i < referenceId->len; i++)
1629 printf("%c", referenceId->buf[i]);
1634 static void print_string_or_numeric(int iLevel, const char *pTag, Z_StringOrNumeric *pStringNumeric)
1636 if (pStringNumeric != NULL)
1638 switch (pStringNumeric->which)
1640 case Z_StringOrNumeric_string:
1641 print_string(iLevel, pTag, pStringNumeric->u.string);
1644 case Z_StringOrNumeric_numeric:
1645 print_int(iLevel, pTag, pStringNumeric->u.numeric);
1649 print_level(iLevel);
1650 printf("%s: valid type for Z_StringOrNumeric\n", pTag);
1656 static void print_universe_report_duplicate(
1658 Z_UniverseReportDuplicate *pUniverseReportDuplicate)
1660 if (pUniverseReportDuplicate != NULL)
1662 print_level(iLevel);
1663 printf("Universe Report Duplicate: \n");
1665 print_string_or_numeric(iLevel, "Hit No",
1666 pUniverseReportDuplicate->hitno);
1670 static void print_universe_report_hits(
1672 Z_UniverseReportHits *pUniverseReportHits)
1674 if (pUniverseReportHits != NULL)
1676 print_level(iLevel);
1677 printf("Universe Report Hits: \n");
1679 print_string_or_numeric(iLevel, "Database",
1680 pUniverseReportHits->database);
1681 print_string_or_numeric(iLevel, "Hits", pUniverseReportHits->hits);
1685 static void print_universe_report(int iLevel, Z_UniverseReport *pUniverseReport)
1687 if (pUniverseReport != NULL)
1689 print_level(iLevel);
1690 printf("Universe Report: \n");
1692 print_int(iLevel, "Total Hits", pUniverseReport->totalHits);
1693 switch (pUniverseReport->which)
1695 case Z_UniverseReport_databaseHits:
1696 print_universe_report_hits(iLevel,
1697 pUniverseReport->u.databaseHits);
1700 case Z_UniverseReport_duplicate:
1701 print_universe_report_duplicate(iLevel,
1702 pUniverseReport->u.duplicate);
1706 print_level(iLevel);
1707 printf("Type: %d\n", pUniverseReport->which);
1713 static void print_external(int iLevel, Z_External *pExternal)
1715 if (pExternal != NULL)
1717 print_level(iLevel);
1718 printf("External: \n");
1720 print_oid(iLevel, "Direct Reference", pExternal->direct_reference);
1721 print_int(iLevel, "InDirect Reference", pExternal->indirect_reference);
1722 print_string(iLevel, "Descriptor", pExternal->descriptor);
1723 switch (pExternal->which)
1725 case Z_External_universeReport:
1726 print_universe_report(iLevel, pExternal->u.universeReport);
1730 print_level(iLevel);
1731 printf("Type: %d\n", pExternal->which);
1737 static int process_resourceControlRequest (Z_ResourceControlRequest *req)
1739 printf ("Received ResourceControlRequest.\n");
1740 print_referenceId(1, req->referenceId);
1741 print_int(1, "Suspended Flag", req->suspendedFlag);
1742 print_int(1, "Partial Results Available", req->partialResultsAvailable);
1743 print_int(1, "Response Required", req->responseRequired);
1744 print_int(1, "Triggered Request Flag", req->triggeredRequestFlag);
1745 print_external(1, req->resourceReport);
1749 void process_ESResponse(Z_ExtendedServicesResponse *res)
1752 switch (*res->operationStatus)
1754 case Z_ExtendedServicesResponse_done:
1757 case Z_ExtendedServicesResponse_accepted:
1758 printf ("accepted\n");
1760 case Z_ExtendedServicesResponse_failure:
1761 printf ("failure\n");
1762 display_diagrecs(res->diagnostics, res->num_diagnostics);
1765 printf ("unknown\n");
1767 if ( (*res->operationStatus != Z_ExtendedServicesResponse_failure) &&
1768 (res->num_diagnostics != 0) ) {
1769 display_diagrecs(res->diagnostics, res->num_diagnostics);
1771 print_refid (res->referenceId);
1772 if (res->taskPackage &&
1773 res->taskPackage->which == Z_External_extendedService)
1775 Z_TaskPackage *taskPackage = res->taskPackage->u.extendedService;
1776 Odr_oct *id = taskPackage->targetReference;
1777 Z_External *ext = taskPackage->taskSpecificParameters;
1781 printf ("Target Reference: ");
1782 print_stringn (id->buf, id->len);
1785 if (ext->which == Z_External_update)
1787 Z_IUUpdateTaskPackage *utp = ext->u.update->u.taskPackage;
1788 if (utp && utp->targetPart)
1790 Z_IUTargetPart *targetPart = utp->targetPart;
1793 for (i = 0; i<targetPart->num_taskPackageRecords; i++)
1796 Z_IUTaskPackageRecordStructure *tpr =
1797 targetPart->taskPackageRecords[i];
1798 printf ("task package record %d\n", i+1);
1799 if (tpr->which == Z_IUTaskPackageRecordStructure_record)
1801 display_record (tpr->u.record);
1805 printf ("other type\n");
1813 const char *get_ill_element (void *clientData, const char *element)
1818 static Z_External *create_external_itemRequest()
1820 struct ill_get_ctl ctl;
1821 ILL_ItemRequest *req;
1823 int item_request_size = 0;
1824 char *item_request_buf = 0;
1828 ctl.f = get_ill_element;
1830 req = ill_get_ItemRequest(&ctl, "ill", 0);
1832 printf ("ill_get_ItemRequest failed\n");
1834 if (!ill_ItemRequest (out, &req, 0, 0))
1838 ill_ItemRequest(print, &req, 0, 0);
1841 item_request_buf = odr_getbuf (out, &item_request_size, 0);
1842 if (item_request_buf)
1843 odr_setbuf (out, item_request_buf, item_request_size, 1);
1844 printf ("Couldn't encode ItemRequest, size %d\n", item_request_size);
1851 item_request_buf = odr_getbuf (out, &item_request_size, 0);
1852 oid.proto = PROTO_GENERAL;
1853 oid.oclass = CLASS_GENERAL;
1854 oid.value = VAL_ISO_ILL_1;
1856 r = (Z_External *) odr_malloc (out, sizeof(*r));
1857 r->direct_reference = odr_oiddup(out,oid_getoidbyent(&oid));
1858 r->indirect_reference = 0;
1860 r->which = Z_External_single;
1862 r->u.single_ASN1_type = (Odr_oct *)
1863 odr_malloc (out, sizeof(*r->u.single_ASN1_type));
1864 r->u.single_ASN1_type->buf = (unsigned char *)
1865 odr_malloc (out, item_request_size);
1866 r->u.single_ASN1_type->len = item_request_size;
1867 r->u.single_ASN1_type->size = item_request_size;
1868 memcpy (r->u.single_ASN1_type->buf, item_request_buf,
1871 do_hex_dump(item_request_buf,item_request_size);
1876 static Z_External *create_external_ILL_APDU(int which)
1878 struct ill_get_ctl ctl;
1881 int ill_request_size = 0;
1882 char *ill_request_buf = 0;
1886 ctl.f = get_ill_element;
1888 ill_apdu = ill_get_APDU(&ctl, "ill", 0);
1890 if (!ill_APDU (out, &ill_apdu, 0, 0))
1894 printf ("-------------------\n");
1895 ill_APDU(print, &ill_apdu, 0, 0);
1897 printf ("-------------------\n");
1899 ill_request_buf = odr_getbuf (out, &ill_request_size, 0);
1900 if (ill_request_buf)
1901 odr_setbuf (out, ill_request_buf, ill_request_size, 1);
1902 printf ("Couldn't encode ILL-Request, size %d\n", ill_request_size);
1908 ill_request_buf = odr_getbuf (out, &ill_request_size, 0);
1910 oid.proto = PROTO_GENERAL;
1911 oid.oclass = CLASS_GENERAL;
1912 oid.value = VAL_ISO_ILL_1;
1914 r = (Z_External *) odr_malloc (out, sizeof(*r));
1915 r->direct_reference = odr_oiddup(out,oid_getoidbyent(&oid));
1916 r->indirect_reference = 0;
1918 r->which = Z_External_single;
1920 r->u.single_ASN1_type = (Odr_oct *)
1921 odr_malloc (out, sizeof(*r->u.single_ASN1_type));
1922 r->u.single_ASN1_type->buf = (unsigned char *)
1923 odr_malloc (out, ill_request_size);
1924 r->u.single_ASN1_type->len = ill_request_size;
1925 r->u.single_ASN1_type->size = ill_request_size;
1926 memcpy (r->u.single_ASN1_type->buf, ill_request_buf, ill_request_size);
1927 /* printf ("len = %d\n", ill_request_size); */
1928 /* do_hex_dump(ill_request_buf,ill_request_size); */
1929 /* printf("--- end of extenal\n"); */
1936 static Z_External *create_ItemOrderExternal(const char *type, int itemno)
1938 Z_External *r = (Z_External *) odr_malloc(out, sizeof(Z_External));
1939 oident ItemOrderRequest;
1941 ItemOrderRequest.proto = PROTO_Z3950;
1942 ItemOrderRequest.oclass = CLASS_EXTSERV;
1943 ItemOrderRequest.value = VAL_ITEMORDER;
1945 r->direct_reference = odr_oiddup(out,oid_getoidbyent(&ItemOrderRequest));
1946 r->indirect_reference = 0;
1949 r->which = Z_External_itemOrder;
1951 r->u.itemOrder = (Z_ItemOrder *) odr_malloc(out,sizeof(Z_ItemOrder));
1952 memset(r->u.itemOrder, 0, sizeof(Z_ItemOrder));
1953 r->u.itemOrder->which=Z_IOItemOrder_esRequest;
1955 r->u.itemOrder->u.esRequest = (Z_IORequest *)
1956 odr_malloc(out,sizeof(Z_IORequest));
1957 memset(r->u.itemOrder->u.esRequest, 0, sizeof(Z_IORequest));
1959 r->u.itemOrder->u.esRequest->toKeep = (Z_IOOriginPartToKeep *)
1960 odr_malloc(out,sizeof(Z_IOOriginPartToKeep));
1961 memset(r->u.itemOrder->u.esRequest->toKeep, 0, sizeof(Z_IOOriginPartToKeep));
1962 r->u.itemOrder->u.esRequest->notToKeep = (Z_IOOriginPartNotToKeep *)
1963 odr_malloc(out,sizeof(Z_IOOriginPartNotToKeep));
1964 memset(r->u.itemOrder->u.esRequest->notToKeep, 0, sizeof(Z_IOOriginPartNotToKeep));
1966 r->u.itemOrder->u.esRequest->toKeep->supplDescription = NULL;
1967 r->u.itemOrder->u.esRequest->toKeep->contact = NULL;
1968 r->u.itemOrder->u.esRequest->toKeep->addlBilling = NULL;
1970 r->u.itemOrder->u.esRequest->notToKeep->resultSetItem =
1971 (Z_IOResultSetItem *) odr_malloc(out, sizeof(Z_IOResultSetItem));
1972 memset(r->u.itemOrder->u.esRequest->notToKeep->resultSetItem, 0, sizeof(Z_IOResultSetItem));
1973 r->u.itemOrder->u.esRequest->notToKeep->resultSetItem->resultSetId = "1";
1975 r->u.itemOrder->u.esRequest->notToKeep->resultSetItem->item =
1976 (int *) odr_malloc(out, sizeof(int));
1977 *r->u.itemOrder->u.esRequest->notToKeep->resultSetItem->item = itemno;
1979 if (!strcmp (type, "item") || !strcmp(type, "2"))
1981 printf ("using item-request\n");
1982 r->u.itemOrder->u.esRequest->notToKeep->itemRequest =
1983 create_external_itemRequest();
1985 else if (!strcmp(type, "ill") || !strcmp(type, "1"))
1987 printf ("using ILL-request\n");
1988 r->u.itemOrder->u.esRequest->notToKeep->itemRequest =
1989 create_external_ILL_APDU(ILL_APDU_ILL_Request);
1991 else if (!strcmp(type, "xml") || !strcmp(type, "3"))
1993 const char *xml_buf =
1995 " <type>request</type>\n"
1996 " <libraryNo>000200</libraryNo>\n"
1997 " <borrowerTicketNo> 1212 </borrowerTicketNo>\n"
1999 r->u.itemOrder->u.esRequest->notToKeep->itemRequest =
2000 z_ext_record (out, VAL_TEXT_XML, xml_buf, strlen(xml_buf));
2003 r->u.itemOrder->u.esRequest->notToKeep->itemRequest = 0;
2008 static int send_itemorder(const char *type, int itemno)
2010 Z_APDU *apdu = zget_APDU(out, Z_APDU_extendedServicesRequest);
2011 Z_ExtendedServicesRequest *req = apdu->u.extendedServicesRequest;
2012 oident ItemOrderRequest;
2014 ItemOrderRequest.proto = PROTO_Z3950;
2015 ItemOrderRequest.oclass = CLASS_EXTSERV;
2016 ItemOrderRequest.value = VAL_ITEMORDER;
2017 req->packageType = odr_oiddup(out,oid_getoidbyent(&ItemOrderRequest));
2018 req->packageName = esPackageName;
2020 req->taskSpecificParameters = create_ItemOrderExternal(type, itemno);
2026 static int only_z3950()
2028 if (protocol == PROTO_HTTP)
2030 printf ("Not supported by SRW\n");
2036 static int cmd_update_common(const char *arg, int version);
2038 static int cmd_update(const char *arg)
2040 return cmd_update_common(arg, 1);
2043 static int cmd_update0(const char *arg)
2045 return cmd_update_common(arg, 0);
2048 static int cmd_update_common(const char *arg, int version)
2050 Z_APDU *apdu = zget_APDU(out, Z_APDU_extendedServicesRequest );
2051 Z_ExtendedServicesRequest *req = apdu->u.extendedServicesRequest;
2053 char action[20], recid[20], fname[80];
2055 Z_External *record_this = 0;
2062 sscanf (arg, "%19s %19s %79s", action, recid, fname);
2064 if (!strcmp (action, "insert"))
2065 action_no = Z_IUOriginPartToKeep_recordInsert;
2066 else if (!strcmp (action, "replace"))
2067 action_no = Z_IUOriginPartToKeep_recordReplace;
2068 else if (!strcmp (action, "delete"))
2069 action_no = Z_IUOriginPartToKeep_recordDelete;
2070 else if (!strcmp (action, "update"))
2071 action_no = Z_IUOriginPartToKeep_specialUpdate;
2074 printf ("Bad action: %s\n", action);
2075 printf ("Possible values: insert, replace, delete, update\n");
2083 stat (fname, &status);
2084 if (S_ISREG(status.st_mode) && (inf = fopen(fname, "r")))
2086 size_t len = status.st_size;
2087 char *buf = (char *) xmalloc (len);
2089 fread (buf, 1, len, inf);
2093 record_this = z_ext_record (out, VAL_TEXT_XML, buf, len);
2099 printf ("File %s doesn't exist\n", fname);
2107 printf ("No last record (update ignored)\n");
2110 record_this = record_last;
2114 yaz_oidval_to_z3950oid(out, CLASS_EXTSERV,
2115 version == 0 ? VAL_DBUPDATE0 : VAL_DBUPDATE);
2117 req->packageName = esPackageName;
2119 req->referenceId = set_refid (out);
2121 r = req->taskSpecificParameters = (Z_External *)
2122 odr_malloc (out, sizeof(*r));
2123 r->direct_reference = req->packageType;
2124 r->indirect_reference = 0;
2128 Z_IU0OriginPartToKeep *toKeep;
2129 Z_IU0SuppliedRecords *notToKeep;
2131 r->which = Z_External_update0;
2132 r->u.update0 = (Z_IU0Update *) odr_malloc(out, sizeof(*r->u.update0));
2133 r->u.update0->which = Z_IUUpdate_esRequest;
2134 r->u.update0->u.esRequest = (Z_IU0UpdateEsRequest *)
2135 odr_malloc(out, sizeof(*r->u.update0->u.esRequest));
2136 toKeep = r->u.update0->u.esRequest->toKeep = (Z_IU0OriginPartToKeep *)
2137 odr_malloc(out, sizeof(*r->u.update0->u.esRequest->toKeep));
2139 toKeep->databaseName = databaseNames[0];
2141 toKeep->elementSetName = 0;
2143 toKeep->action = (int *) odr_malloc(out, sizeof(*toKeep->action));
2144 *toKeep->action = action_no;
2146 notToKeep = r->u.update0->u.esRequest->notToKeep = (Z_IU0SuppliedRecords *)
2147 odr_malloc(out, sizeof(*r->u.update0->u.esRequest->notToKeep));
2149 notToKeep->elements = (Z_IU0SuppliedRecords_elem **)
2150 odr_malloc(out, sizeof(*notToKeep->elements));
2151 notToKeep->elements[0] = (Z_IU0SuppliedRecords_elem *)
2152 odr_malloc(out, sizeof(**notToKeep->elements));
2153 notToKeep->elements[0]->which = Z_IUSuppliedRecords_elem_opaque;
2156 notToKeep->elements[0]->u.opaque = (Odr_oct *)
2157 odr_malloc (out, sizeof(Odr_oct));
2158 notToKeep->elements[0]->u.opaque->buf = (unsigned char *) recid;
2159 notToKeep->elements[0]->u.opaque->size = strlen(recid);
2160 notToKeep->elements[0]->u.opaque->len = strlen(recid);
2163 notToKeep->elements[0]->u.opaque = 0;
2164 notToKeep->elements[0]->supplementalId = 0;
2165 notToKeep->elements[0]->correlationInfo = 0;
2166 notToKeep->elements[0]->record = record_this;
2170 Z_IUOriginPartToKeep *toKeep;
2171 Z_IUSuppliedRecords *notToKeep;
2173 r->which = Z_External_update;
2174 r->u.update = (Z_IUUpdate *) odr_malloc(out, sizeof(*r->u.update));
2175 r->u.update->which = Z_IUUpdate_esRequest;
2176 r->u.update->u.esRequest = (Z_IUUpdateEsRequest *)
2177 odr_malloc(out, sizeof(*r->u.update->u.esRequest));
2178 toKeep = r->u.update->u.esRequest->toKeep = (Z_IUOriginPartToKeep *)
2179 odr_malloc(out, sizeof(*r->u.update->u.esRequest->toKeep));
2181 toKeep->databaseName = databaseNames[0];
2183 toKeep->elementSetName = 0;
2184 toKeep->actionQualifier = 0;
2185 toKeep->action = (int *) odr_malloc(out, sizeof(*toKeep->action));
2186 *toKeep->action = action_no;
2188 notToKeep = r->u.update->u.esRequest->notToKeep = (Z_IUSuppliedRecords *)
2189 odr_malloc(out, sizeof(*r->u.update->u.esRequest->notToKeep));
2191 notToKeep->elements = (Z_IUSuppliedRecords_elem **)
2192 odr_malloc(out, sizeof(*notToKeep->elements));
2193 notToKeep->elements[0] = (Z_IUSuppliedRecords_elem *)
2194 odr_malloc(out, sizeof(**notToKeep->elements));
2195 notToKeep->elements[0]->which = Z_IUSuppliedRecords_elem_opaque;
2198 notToKeep->elements[0]->u.opaque = (Odr_oct *)
2199 odr_malloc (out, sizeof(Odr_oct));
2200 notToKeep->elements[0]->u.opaque->buf = (unsigned char *) recid;
2201 notToKeep->elements[0]->u.opaque->size = strlen(recid);
2202 notToKeep->elements[0]->u.opaque->len = strlen(recid);
2205 notToKeep->elements[0]->u.opaque = 0;
2206 notToKeep->elements[0]->supplementalId = 0;
2207 notToKeep->elements[0]->correlationInfo = 0;
2208 notToKeep->elements[0]->record = record_this;
2216 static int cmd_itemorder(const char *arg)
2223 if (sscanf (arg, "%10s %d", type, &itemno) != 2)
2226 printf("Item order request\n");
2228 send_itemorder(type, itemno);
2232 static void show_opt(const char *arg, void *clientData)
2234 printf ("%s ", arg);
2237 static int cmd_zversion(const char *arg)
2240 z3950_version = atoi(arg);
2242 printf ("version is %d\n", z3950_version);
2246 static int cmd_options(const char *arg)
2252 r = yaz_init_opt_encode(&z3950_options, arg, &pos);
2256 yaz_init_opt_decode(&z3950_options, show_opt, 0);
2262 static int cmd_explain(const char *arg)
2264 if (protocol != PROTO_HTTP)
2275 /* save this for later .. when fetching individual records */
2276 sr = yaz_srw_get(out, Z_SRW_explain_request);
2277 if (recordsyntax == VAL_TEXT_XML)
2278 sr->u.explain_request->recordPacking = "xml";
2286 static int cmd_init(const char *arg)
2288 if (!conn || protocol != PROTO_Z3950)
2290 send_initRequest(0);
2294 static int cmd_find(const char *arg)
2298 printf("Find what?\n");
2301 if (protocol == PROTO_HTTP)
2308 if (!send_SRW_searchRequest(arg))
2321 printf("Not connected yet\n");
2325 if (!send_searchRequest(arg))
2331 static int cmd_delete(const char *arg)
2335 printf("Not connected yet\n");
2340 if (!send_deleteResultSetRequest(arg))
2345 static int cmd_ssub(const char *arg)
2347 if (!(smallSetUpperBound = atoi(arg)))
2352 static int cmd_lslb(const char *arg)
2356 if (!(largeSetLowerBound = atoi(arg)))
2361 static int cmd_mspn(const char *arg)
2365 if (!(mediumSetPresentNumber = atoi(arg)))
2370 static int cmd_status(const char *arg)
2372 printf("smallSetUpperBound: %d\n", smallSetUpperBound);
2373 printf("largeSetLowerBound: %d\n", largeSetLowerBound);
2374 printf("mediumSetPresentNumber: %d\n", mediumSetPresentNumber);
2378 static int cmd_setnames(const char *arg)
2380 if (*arg == '1') /* enable ? */
2382 else if (*arg == '0') /* disable ? */
2384 else if (setnumber < 0) /* no args, toggle .. */
2390 printf("Set numbering enabled.\n");
2392 printf("Set numbering disabled.\n");
2396 /* PRESENT SERVICE ----------------------------- */
2398 static void parse_show_args(const char *arg_c, char *setstring,
2399 int *start, int *number)
2404 strncpy(arg, arg_c, sizeof(arg)-1);
2405 arg[sizeof(arg)-1] = '\0';
2407 if ((p = strchr(arg, '+')))
2409 *number = atoi(p + 1);
2414 if (p && (p=strchr(p+1, '+')))
2415 strcpy (setstring, p+1);
2416 else if (setnumber >= 0)
2417 sprintf(setstring, "%d", setnumber);
2422 static int send_presentRequest(const char *arg)
2424 Z_APDU *apdu = zget_APDU(out, Z_APDU_presentRequest);
2425 Z_PresentRequest *req = apdu->u.presentRequest;
2426 Z_RecordComposition compo;
2428 char setstring[100];
2430 req->referenceId = set_refid (out);
2432 parse_show_args(arg, setstring, &setno, &nos);
2434 req->resultSetId = setstring;
2436 req->resultSetStartPoint = &setno;
2437 req->numberOfRecordsRequested = &nos;
2439 req->preferredRecordSyntax =
2440 yaz_oidval_to_z3950oid(out, CLASS_RECSYN, recordsyntax);
2444 req->recordComposition = &compo;
2445 compo.which = Z_RecordComp_complex;
2446 compo.u.complex = (Z_CompSpec *)
2447 odr_malloc(out, sizeof(*compo.u.complex));
2448 compo.u.complex->selectAlternativeSyntax = (bool_t *)
2449 odr_malloc(out, sizeof(bool_t));
2450 *compo.u.complex->selectAlternativeSyntax = 0;
2452 compo.u.complex->generic = (Z_Specification *)
2453 odr_malloc(out, sizeof(*compo.u.complex->generic));
2454 compo.u.complex->generic->which = Z_Schema_oid;
2456 compo.u.complex->generic->schema.oid =
2457 yaz_str_to_z3950oid(out, CLASS_SCHEMA, record_schema);
2459 if (!compo.u.complex->generic->schema.oid)
2461 /* OID wasn't a schema! Try record syntax instead. */
2462 compo.u.complex->generic->schema.oid = (Odr_oid *)
2463 yaz_str_to_z3950oid(out, CLASS_RECSYN, record_schema);
2465 if (!elementSetNames)
2466 compo.u.complex->generic->elementSpec = 0;
2469 compo.u.complex->generic->elementSpec = (Z_ElementSpec *)
2470 odr_malloc(out, sizeof(Z_ElementSpec));
2471 compo.u.complex->generic->elementSpec->which =
2472 Z_ElementSpec_elementSetName;
2473 compo.u.complex->generic->elementSpec->u.elementSetName =
2474 elementSetNames->u.generic;
2476 compo.u.complex->num_dbSpecific = 0;
2477 compo.u.complex->dbSpecific = 0;
2478 compo.u.complex->num_recordSyntax = 0;
2479 compo.u.complex->recordSyntax = 0;
2481 else if (elementSetNames)
2483 req->recordComposition = &compo;
2484 compo.which = Z_RecordComp_simple;
2485 compo.u.simple = elementSetNames;
2488 printf("Sent presentRequest (%d+%d).\n", setno, nos);
2493 static int send_SRW_presentRequest(const char *arg)
2495 char setstring[100];
2497 Z_SRW_PDU *sr = srw_sr;
2501 parse_show_args(arg, setstring, &setno, &nos);
2502 sr->u.request->startRecord = odr_intdup(out, setno);
2503 sr->u.request->maximumRecords = odr_intdup(out, nos);
2505 sr->u.request->recordSchema = record_schema;
2506 if (recordsyntax == VAL_TEXT_XML)
2507 sr->u.request->recordPacking = "xml";
2508 return send_srw(sr);
2512 static void close_session (void)
2519 nmem_destroy (session_mem);
2528 void process_close(Z_Close *req)
2530 Z_APDU *apdu = zget_APDU(out, Z_APDU_close);
2531 Z_Close *res = apdu->u.close;
2533 static char *reasons[] =
2538 "cost limit reached",
2540 "security violation",
2547 printf("Reason: %s, message: %s\n", reasons[*req->closeReason],
2548 req->diagnosticInformation ? req->diagnosticInformation : "NULL");
2553 *res->closeReason = Z_Close_finished;
2555 printf("Sent response.\n");
2560 static int cmd_show(const char *arg)
2562 if (protocol == PROTO_HTTP)
2569 if (!send_SRW_presentRequest(arg))
2579 printf("Not connected yet\n");
2582 if (!send_presentRequest(arg))
2588 int cmd_quit(const char *arg)
2590 printf("See you later, alligator.\n");
2596 int cmd_cancel(const char *arg)
2598 Z_APDU *apdu = zget_APDU(out, Z_APDU_triggerResourceControlRequest);
2599 Z_TriggerResourceControlRequest *req =
2600 apdu->u.triggerResourceControlRequest;
2605 printf("Session not initialized yet\n");
2610 if (!ODR_MASK_GET(session->options, Z_Options_triggerResourceCtrl))
2612 printf("Target doesn't support cancel (trigger resource ctrl)\n");
2615 *req->requestedAction = Z_TriggerResourceControlRequest_cancel;
2616 req->resultSetWanted = &rfalse;
2617 req->referenceId = set_refid (out);
2620 printf("Sent cancel request\n");
2625 int cmd_cancel_find(const char *arg) {
2629 return cmd_cancel("");
2634 int send_scanrequest(const char *query, int pp, int num, const char *term)
2636 Z_APDU *apdu = zget_APDU(out, Z_APDU_scanRequest);
2637 Z_ScanRequest *req = apdu->u.scanRequest;
2641 if (queryType == QueryType_CCL2RPN)
2644 struct ccl_rpn_node *rpn;
2646 rpn = ccl_find_str (bibset, query, &error, &pos);
2649 printf("CCL ERROR: %s\n", ccl_err_msg(error));
2653 yaz_oidval_to_z3950oid(out, CLASS_ATTSET, VAL_BIB1);
2654 if (!(req->termListAndStartPoint = ccl_scan_query (out, rpn)))
2656 printf("Couldn't convert CCL to Scan term\n");
2659 ccl_rpn_delete (rpn);
2663 YAZ_PQF_Parser pqf_parser = yaz_pqf_create ();
2665 if (!(req->termListAndStartPoint =
2666 yaz_pqf_scan(pqf_parser, out, &req->attributeSet, query)))
2668 const char *pqf_msg;
2670 int code = yaz_pqf_error (pqf_parser, &pqf_msg, &off);
2671 printf("%*s^\n", off+7, "");
2672 printf("Prefix query error: %s (code %d)\n", pqf_msg, code);
2673 yaz_pqf_destroy (pqf_parser);
2676 yaz_pqf_destroy (pqf_parser);
2680 if (req->termListAndStartPoint->term &&
2681 req->termListAndStartPoint->term->which == Z_Term_general &&
2682 req->termListAndStartPoint->term->u.general)
2684 req->termListAndStartPoint->term->u.general->buf =
2685 (unsigned char *) odr_strdup(out, term);
2686 req->termListAndStartPoint->term->u.general->len =
2687 req->termListAndStartPoint->term->u.general->size =
2691 req->referenceId = set_refid (out);
2692 req->num_databaseNames = num_databaseNames;
2693 req->databaseNames = databaseNames;
2694 req->numberOfTermsRequested = #
2695 req->preferredPositionInResponse = &pp;
2696 req->stepSize = odr_intdup(out, scan_stepSize);
2701 int send_sortrequest(const char *arg, int newset)
2703 Z_APDU *apdu = zget_APDU(out, Z_APDU_sortRequest);
2704 Z_SortRequest *req = apdu->u.sortRequest;
2705 Z_SortKeySpecList *sksl = (Z_SortKeySpecList *)
2706 odr_malloc (out, sizeof(*sksl));
2712 sprintf (setstring, "%d", setnumber);
2714 sprintf (setstring, "default");
2716 req->referenceId = set_refid (out);
2718 req->num_inputResultSetNames = 1;
2719 req->inputResultSetNames = (Z_InternationalString **)
2720 odr_malloc (out, sizeof(*req->inputResultSetNames));
2721 req->inputResultSetNames[0] = odr_strdup (out, setstring);
2723 if (newset && setnumber >= 0)
2724 sprintf (setstring, "%d", ++setnumber);
2726 req->sortedResultSetName = odr_strdup (out, setstring);
2728 req->sortSequence = yaz_sort_spec (out, arg);
2729 if (!req->sortSequence)
2731 printf ("Missing sort specifications\n");
2738 void display_term(Z_TermInfo *t)
2741 printf("%s", t->displayTerm);
2742 else if (t->term->which == Z_Term_general)
2744 printf("%.*s", t->term->u.general->len, t->term->u.general->buf);
2745 sprintf(last_scan_line, "%.*s", t->term->u.general->len,
2746 t->term->u.general->buf);
2749 printf("Term (not general)");
2750 if (t->globalOccurrences)
2751 printf (" (%d)\n", *t->globalOccurrences);
2756 void process_scanResponse(Z_ScanResponse *res)
2759 Z_Entry **entries = NULL;
2760 int num_entries = 0;
2762 printf("Received ScanResponse\n");
2763 print_refid (res->referenceId);
2764 printf("%d entries", *res->numberOfEntriesReturned);
2765 if (res->positionOfTerm)
2766 printf (", position=%d", *res->positionOfTerm);
2768 if (*res->scanStatus != Z_Scan_success)
2769 printf("Scan returned code %d\n", *res->scanStatus);
2772 if ((entries = res->entries->entries))
2773 num_entries = res->entries->num_entries;
2774 for (i = 0; i < num_entries; i++)
2776 int pos_term = res->positionOfTerm ? *res->positionOfTerm : -1;
2777 if (entries[i]->which == Z_Entry_termInfo)
2779 printf("%c ", i + 1 == pos_term ? '*' : ' ');
2780 display_term(entries[i]->u.termInfo);
2783 display_diagrecs(&entries[i]->u.surrogateDiagnostic, 1);
2785 if (res->entries->nonsurrogateDiagnostics)
2786 display_diagrecs (res->entries->nonsurrogateDiagnostics,
2787 res->entries->num_nonsurrogateDiagnostics);
2790 void process_sortResponse(Z_SortResponse *res)
2792 printf("Received SortResponse: status=");
2793 switch (*res->sortStatus)
2795 case Z_SortResponse_success:
2796 printf ("success"); break;
2797 case Z_SortResponse_partial_1:
2798 printf ("partial"); break;
2799 case Z_SortResponse_failure:
2800 printf ("failure"); break;
2802 printf ("unknown (%d)", *res->sortStatus);
2805 print_refid (res->referenceId);
2806 if (res->diagnostics)
2807 display_diagrecs(res->diagnostics,
2808 res->num_diagnostics);
2811 void process_deleteResultSetResponse (Z_DeleteResultSetResponse *res)
2813 printf("Got deleteResultSetResponse status=%d\n",
2814 *res->deleteOperationStatus);
2815 if (res->deleteListStatuses)
2818 for (i = 0; i < res->deleteListStatuses->num; i++)
2820 printf ("%s status=%d\n", res->deleteListStatuses->elements[i]->id,
2821 *res->deleteListStatuses->elements[i]->status);
2826 int cmd_sort_generic(const char *arg, int newset)
2830 printf("Session not initialized yet\n");
2835 if (!ODR_MASK_GET(session->options, Z_Options_sort))
2837 printf("Target doesn't support sort\n");
2842 if (send_sortrequest(arg, newset) < 0)
2849 int cmd_sort(const char *arg)
2851 return cmd_sort_generic (arg, 0);
2854 int cmd_sort_newset (const char *arg)
2856 return cmd_sort_generic (arg, 1);
2859 int cmd_scanstep(const char *arg)
2861 scan_stepSize = atoi(arg);
2865 int cmd_scanpos(const char *arg)
2867 int r = sscanf(arg, "%d", &scan_position);
2873 int cmd_scan(const char *arg)
2875 if (protocol == PROTO_HTTP)
2884 if (send_SRW_scanRequest(arg, scan_position, 20) < 0)
2889 if (send_SRW_scanRequest(last_scan_line, 1, 20) < 0)
2904 printf("Session not initialized yet\n");
2908 if (!ODR_MASK_GET(session->options, Z_Options_scan))
2910 printf("Target doesn't support scan\n");
2915 strcpy (last_scan_query, arg);
2916 if (send_scanrequest(arg, scan_position, 20, 0) < 0)
2921 if (send_scanrequest(last_scan_query, 1, 20, last_scan_line) < 0)
2928 int cmd_schema(const char *arg)
2930 xfree(record_schema);
2933 record_schema = xstrdup(arg);
2937 int cmd_format(const char *arg)
2942 printf("Usage: format <recordsyntax>\n");
2945 nsyntax = oid_getvalbyname (arg);
2946 if (strcmp(arg, "none") && nsyntax == VAL_NONE)
2948 printf ("unknown record syntax\n");
2951 recordsyntax = nsyntax;
2955 int cmd_elements(const char *arg)
2957 static Z_ElementSetNames esn;
2958 static char what[100];
2962 elementSetNames = 0;
2966 esn.which = Z_ElementSetNames_generic;
2967 esn.u.generic = what;
2968 elementSetNames = &esn;
2972 int cmd_attributeset(const char *arg)
2978 printf("Usage: attributeset <setname>\n");
2981 sscanf(arg, "%s", what);
2982 if (p_query_attset (what))
2984 printf("Unknown attribute set name\n");
2990 int cmd_querytype (const char *arg)
2992 if (!strcmp (arg, "ccl"))
2993 queryType = QueryType_CCL;
2994 else if (!strcmp (arg, "prefix") || !strcmp(arg, "rpn"))
2995 queryType = QueryType_Prefix;
2996 else if (!strcmp (arg, "ccl2rpn") || !strcmp (arg, "cclrpn"))
2997 queryType = QueryType_CCL2RPN;
2998 else if (!strcmp(arg, "cql"))
2999 queryType = QueryType_CQL;
3000 else if (!strcmp (arg, "cql2rpn") || !strcmp (arg, "cqlrpn"))
3001 queryType = QueryType_CQL2RPN;
3004 printf ("Querytype must be one of:\n");
3005 printf (" prefix - Prefix query\n");
3006 printf (" ccl - CCL query\n");
3007 printf (" ccl2rpn - CCL query converted to RPN\n");
3008 printf (" cql - CQL\n");
3009 printf (" cql2rpn - CQL query converted to RPN\n");
3015 int cmd_refid (const char *arg)
3020 refid = xstrdup (arg);
3024 int cmd_close(const char *arg)
3033 apdu = zget_APDU(out, Z_APDU_close);
3034 req = apdu->u.close;
3035 *req->closeReason = Z_Close_finished;
3037 printf("Sent close request.\n");
3042 int cmd_packagename(const char* arg)
3044 xfree (esPackageName);
3045 esPackageName = NULL;
3047 esPackageName = xstrdup(arg);
3051 int cmd_proxy(const char* arg)
3056 yazProxy = xstrdup (arg);
3060 int cmd_marccharset(const char *arg)
3065 if (sscanf(arg, "%29s", l1) < 1)
3067 printf("MARC character set is `%s'\n",
3068 marcCharset ? marcCharset: "none");
3071 xfree (marcCharset);
3073 if (strcmp(l1, "-"))
3074 marcCharset = xstrdup(l1);
3078 int cmd_displaycharset(const char *arg)
3083 if (sscanf(arg, "%29s", l1) < 1)
3085 printf("Display character set is `%s'\n",
3086 outputCharset ? outputCharset: "none");
3090 xfree (outputCharset);
3092 if (!strcmp(l1, "auto") && codeset)
3096 printf ("Display character set: %s\n", codeset);
3097 outputCharset = xstrdup(codeset);
3100 printf ("No codeset found on this system\n");
3102 else if (strcmp(l1, "-") && strcmp(l1, "none"))
3103 outputCharset = xstrdup(l1);
3108 int cmd_negcharset(const char *arg)
3113 if (sscanf(arg, "%29s %d %d", l1, &negotiationCharsetRecords,
3114 &negotiationCharsetVersion) < 1)
3116 printf("Current negotiation character set is `%s'\n",
3117 negotiationCharset ? negotiationCharset: "none");
3118 printf("Records in charset %s\n", negotiationCharsetRecords ?
3120 printf("Charneg version %d\n", negotiationCharsetVersion);
3124 xfree (negotiationCharset);
3125 negotiationCharset = NULL;
3126 if (*l1 && strcmp(l1, "-") && strcmp(l1, "none"))
3128 negotiationCharset = xstrdup(l1);
3129 printf ("Character set negotiation : %s\n", negotiationCharset);
3135 int cmd_charset(const char* arg)
3137 char l1[30], l2[30], l3[30];
3139 *l1 = *l2 = *l3 = 0;
3140 if (sscanf(arg, "%29s %29s %29s", l1, l2, l3) < 1)
3143 cmd_displaycharset("");
3144 cmd_marccharset("");
3150 cmd_displaycharset(l2);
3152 cmd_marccharset(l3);
3157 int cmd_lang(const char* arg)
3160 printf("Current language is `%s'\n", (yazLang)?yazLang:NULL);
3166 yazLang = xstrdup(arg);
3170 int cmd_source(const char* arg, int echo )
3172 /* first should open the file and read one line at a time.. */
3174 char line[102400], *cp;
3177 fprintf(stderr,"Error in source command use a filename\n");
3181 includeFile = fopen (arg, "r");
3184 fprintf(stderr,"Unable to open file %s for reading\n",arg);
3188 while(!feof(includeFile)) {
3189 memset(line,0,sizeof(line));
3190 fgets(line,sizeof(line),includeFile);
3192 if(strlen(line) < 2) continue;
3193 if(line[0] == '#') continue;
3195 if ((cp = strrchr (line, '\n')))
3199 printf( "processing line: %s\n",line );
3201 process_cmd_line(line);
3204 if(fclose(includeFile)<0) {
3205 perror("unable to close include file");
3211 int cmd_source_echo(const char* arg)
3217 int cmd_source_noecho(const char* arg)
3224 int cmd_subshell(const char* args)
3229 system(getenv("SHELL"));
3235 int cmd_set_berfile(const char *arg)
3237 if (ber_file && ber_file != stdout && ber_file != stderr)
3239 if (!strcmp(arg, ""))
3241 else if (!strcmp(arg, "-"))
3244 ber_file = fopen(arg, "a");
3248 int cmd_set_apdufile(const char *arg)
3250 if(apdu_file && apdu_file != stderr && apdu_file != stderr)
3252 if (!strcmp(arg, ""))
3254 else if (!strcmp(arg, "-"))
3258 apdu_file = fopen(arg, "a");
3260 perror("unable to open apdu log file");
3263 odr_setprint(print, apdu_file);
3267 int cmd_set_cclfile(const char* arg)
3271 bibset = ccl_qual_mk ();
3272 inf = fopen (arg, "r");
3274 perror("unable to open CCL file");
3277 ccl_qual_file (bibset, inf);
3280 strcpy(ccl_fields,arg);
3284 int cmd_set_cqlfile(const char* arg)
3286 cql_transform_t newcqltrans;
3288 if ((newcqltrans = cql_transform_open_fname(arg)) == 0) {
3289 perror("unable to open CQL file");
3293 cql_transform_close(cqltrans);
3295 cqltrans = newcqltrans;
3296 strcpy(cql_fields, arg);
3300 int cmd_set_auto_reconnect(const char* arg)
3302 if(strlen(arg)==0) {
3303 auto_reconnect = ! auto_reconnect;
3304 } else if(strcmp(arg,"on")==0) {
3306 } else if(strcmp(arg,"off")==0) {
3309 printf("Error use on or off\n");
3314 printf("Set auto reconnect enabled.\n");
3316 printf("Set auto reconnect disabled.\n");
3321 int cmd_set_marcdump(const char* arg)
3323 if(marc_file && marc_file != stderr) { /* don't close stdout*/
3327 if (!strcmp(arg, ""))
3329 else if (!strcmp(arg, "-"))
3333 marc_file = fopen(arg, "a");
3335 perror("unable to open marc log file");
3341 this command takes 3 arge {name class oid}
3343 int cmd_register_oid(const char* args) {
3348 {"appctx",CLASS_APPCTX},
3349 {"absyn",CLASS_ABSYN},
3350 {"attset",CLASS_ATTSET},
3351 {"transyn",CLASS_TRANSYN},
3352 {"diagset",CLASS_DIAGSET},
3353 {"recsyn",CLASS_RECSYN},
3354 {"resform",CLASS_RESFORM},
3355 {"accform",CLASS_ACCFORM},
3356 {"extserv",CLASS_EXTSERV},
3357 {"userinfo",CLASS_USERINFO},
3358 {"elemspec",CLASS_ELEMSPEC},
3359 {"varset",CLASS_VARSET},
3360 {"schema",CLASS_SCHEMA},
3361 {"tagset",CLASS_TAGSET},
3362 {"general",CLASS_GENERAL},
3363 {0,(enum oid_class) 0}
3365 char oname_str[101], oclass_str[101], oid_str[101];
3368 oid_class oidclass = CLASS_GENERAL;
3369 int val = 0, oid[OID_SIZE];
3370 struct oident * new_oident=NULL;
3372 if (sscanf (args, "%100[^ ] %100[^ ] %100s",
3373 oname_str,oclass_str, oid_str) < 1) {
3374 printf("Error in register command \n");
3378 for (i = 0; oid_classes[i].className; i++) {
3379 if (!strcmp(oid_classes[i].className, oclass_str))
3381 oidclass=oid_classes[i].oclass;
3386 if(!(oid_classes[i].className)) {
3387 printf("Unknown oid class %s\n",oclass_str);
3395 while (isdigit (*(unsigned char *) name))
3397 val = val*10 + (*name - '0');
3410 new_oident = oid_addent (oid, PROTO_GENERAL, oidclass, oname_str,
3412 if(strcmp(new_oident->desc,oname_str))
3414 fprintf(stderr,"oid is already named as %s, registration failed\n",
3420 int cmd_push_command(const char* arg)
3422 #if HAVE_READLINE_HISTORY_H
3426 fprintf(stderr,"Not compiled with the readline/history module\n");
3431 void source_rcfile()
3433 /* Look for a $HOME/.yazclientrc and source it if it exists */
3434 struct stat statbuf;
3436 char* homedir=getenv("HOME");
3440 sprintf(buffer,"%s/.yazclientrc",homedir);
3442 if(stat(buffer,&statbuf)==0) {
3443 cmd_source(buffer, 0 );
3448 if(stat(".yazclientrc",&statbuf)==0) {
3449 cmd_source(".yazclientrc", 0 );
3454 static void initialize(void)
3459 if (!(out = odr_createmem(ODR_ENCODE)) ||
3460 !(in = odr_createmem(ODR_DECODE)) ||
3461 !(print = odr_createmem(ODR_PRINT)))
3463 fprintf(stderr, "failed to allocate ODR streams\n");
3468 setvbuf(stdout, 0, _IONBF, 0);
3470 odr_setprint(print, apdu_file);
3472 bibset = ccl_qual_mk ();
3473 inf = fopen (ccl_fields, "r");
3476 ccl_qual_file (bibset, inf);
3480 cqltrans = cql_transform_open_fname(cql_fields);
3481 /* If this fails, no problem: we detect cqltrans == 0 later */
3483 #if HAVE_READLINE_READLINE_H
3484 rl_attempted_completion_function = (CPPFunction*)readline_completer;
3488 for(i=0; i<maxOtherInfosSupported; ++i) {
3489 extraOtherInfos[i].oidval = -1;
3496 #if HAVE_GETTIMEOFDAY
3497 struct timeval tv_start, tv_end;
3501 static void handle_srw_record(Z_SRW_record *rec)
3503 if (rec->recordPosition)
3505 printf ("pos=%d", *rec->recordPosition);
3506 setno = *rec->recordPosition + 1;
3508 if (rec->recordSchema)
3509 printf (" schema=%s", rec->recordSchema);
3511 if (rec->recordData_buf && rec->recordData_len)
3513 fwrite(rec->recordData_buf, 1, rec->recordData_len, stdout);
3515 fwrite (rec->recordData_buf, 1, rec->recordData_len, marc_file);
3518 printf ("No data!");
3522 static void handle_srw_explain_response(Z_SRW_explainResponse *res)
3524 handle_srw_record(&res->record);
3527 static void handle_srw_response(Z_SRW_searchRetrieveResponse *res)
3531 printf ("Received SRW SearchRetrieve Response\n");
3533 for (i = 0; i<res->num_diagnostics; i++)
3535 if (res->diagnostics[i].uri)
3536 printf ("SRW diagnostic %s\n",
3537 res->diagnostics[i].uri);
3539 printf ("SRW diagnostic missing or could not be decoded\n");
3540 if (res->diagnostics[i].message)
3541 printf ("Message: %s\n", res->diagnostics[i].message);
3542 if (res->diagnostics[i].details)
3543 printf ("Details: %s\n", res->diagnostics[i].details);
3545 if (res->numberOfRecords)
3546 printf ("Number of hits: %d\n", *res->numberOfRecords);
3547 for (i = 0; i<res->num_records; i++)
3548 handle_srw_record(res->records + i);
3551 static void handle_srw_scan_term(Z_SRW_scanTerm *term)
3553 if (term->displayTerm)
3554 printf("%s:", term->displayTerm);
3555 else if (term->value)
3556 printf("%s:", term->value);
3558 printf("No value:");
3559 if (term->numberOfRecords)
3560 printf(" %d", *term->numberOfRecords);
3561 if (term->whereInList)
3562 printf(" %s", term->whereInList);
3563 if (term->value && term->displayTerm)
3564 printf(" %s", term->value);
3566 strcpy(last_scan_line, term->value);
3570 static void handle_srw_scan_response(Z_SRW_scanResponse *res)
3574 printf ("Received SRW Scan Response\n");
3576 for (i = 0; i<res->num_diagnostics; i++)
3578 if (res->diagnostics[i].uri)
3579 printf ("SRW diagnostic %s\n",
3580 res->diagnostics[i].uri);
3582 printf ("SRW diagnostic missing or could not be decoded\n");
3583 if (res->diagnostics[i].message)
3584 printf ("Message: %s\n", res->diagnostics[i].message);
3585 if (res->diagnostics[i].details)
3586 printf ("Details: %s\n", res->diagnostics[i].details);
3589 for (i = 0; i<res->num_terms; i++)
3590 handle_srw_scan_term(res->terms + i);
3593 static void http_response(Z_HTTP_Response *hres)
3596 const char *content_type = z_HTTP_header_lookup(hres->headers,
3598 const char *connection_head = z_HTTP_header_lookup(hres->headers,
3600 if (content_type && !yaz_strcmp_del("text/xml", content_type, "; "))
3602 Z_SOAP *soap_package = 0;
3603 ODR o = odr_createmem(ODR_DECODE);
3604 Z_SOAP_Handler soap_handlers[2] = {
3605 {"http://www.loc.gov/zing/srw/", 0,
3606 (Z_SOAP_fun) yaz_srw_codec},
3609 ret = z_soap_codec(o, &soap_package,
3610 &hres->content_buf, &hres->content_len,
3612 if (!ret && soap_package->which == Z_SOAP_generic &&
3613 soap_package->u.generic->no == 0)
3615 Z_SRW_PDU *sr = soap_package->u.generic->p;
3616 if (sr->which == Z_SRW_searchRetrieve_response)
3617 handle_srw_response(sr->u.response);
3618 else if (sr->which == Z_SRW_explain_response)
3619 handle_srw_explain_response(sr->u.explain_response);
3620 else if (sr->which == Z_SRW_scan_response)
3621 handle_srw_scan_response(sr->u.scan_response);
3625 else if (soap_package && (soap_package->which == Z_SOAP_fault
3626 || soap_package->which == Z_SOAP_error))
3628 printf ("HTTP Error Status=%d\n", hres->code);
3629 printf ("SOAP Fault code %s\n",
3630 soap_package->u.fault->fault_code);
3631 printf ("SOAP Fault string %s\n",
3632 soap_package->u.fault->fault_string);
3633 if (soap_package->u.fault->details)
3634 printf ("SOAP Details %s\n",
3635 soap_package->u.fault->details);
3643 if (hres->code != 200)
3645 printf ("HTTP Error Status=%d\n", hres->code);
3649 printf ("Decoding of SRW package failed\n");
3655 if (!strcmp(hres->version, "1.0"))
3657 /* HTTP 1.0: only if Keep-Alive we stay alive.. */
3658 if (!connection_head || strcmp(connection_head, "Keep-Alive"))
3663 /* HTTP 1.1: only if no close we stay alive .. */
3664 if (connection_head && !strcmp(connection_head, "close"))
3671 void wait_and_handle_response()
3673 int reconnect_ok = 1;
3676 int netbufferlen = 0;
3681 res = cs_get(conn, &netbuffer, &netbufferlen);
3682 if (reconnect_ok && res <= 0 && protocol == PROTO_HTTP)
3693 buf_out = odr_getbuf(out, &len_out, 0);
3695 do_hex_dump(buf_out, len_out);
3697 cs_put(conn, buf_out, len_out);
3705 printf("Target closed connection\n");
3710 odr_reset(in); /* release APDU from last round */
3712 do_hex_dump(netbuffer, res);
3713 odr_setbuf(in, netbuffer, res, 0);
3715 if (!z_GDU(in, &gdu, 0, 0))
3717 FILE *f = ber_file ? ber_file : stdout;
3718 odr_perror(in, "Decoding incoming APDU");
3719 fprintf(f, "[Near %d]\n", odr_offset(in));
3720 fprintf(f, "Packet dump:\n---------\n");
3721 odr_dumpBER(f, netbuffer, res);
3722 fprintf(f, "---------\n");
3725 z_GDU(print, &gdu, 0, 0);
3728 if (conn && cs_more(conn))
3733 odr_dumpBER(ber_file, netbuffer, res);
3734 if (apdu_file && !z_GDU(print, &gdu, 0, 0))
3736 odr_perror(print, "Failed to print incoming APDU");
3740 if (gdu->which == Z_GDU_Z3950)
3742 Z_APDU *apdu = gdu->u.z3950;
3745 case Z_APDU_initResponse:
3746 process_initResponse(apdu->u.initResponse);
3748 case Z_APDU_searchResponse:
3749 process_searchResponse(apdu->u.searchResponse);
3751 case Z_APDU_scanResponse:
3752 process_scanResponse(apdu->u.scanResponse);
3754 case Z_APDU_presentResponse:
3755 print_refid (apdu->u.presentResponse->referenceId);
3757 *apdu->u.presentResponse->numberOfRecordsReturned;
3758 if (apdu->u.presentResponse->records)
3759 display_records(apdu->u.presentResponse->records);
3761 printf("No records.\n");
3762 printf ("nextResultSetPosition = %d\n",
3763 *apdu->u.presentResponse->nextResultSetPosition);
3765 case Z_APDU_sortResponse:
3766 process_sortResponse(apdu->u.sortResponse);
3768 case Z_APDU_extendedServicesResponse:
3769 printf("Got extended services response\n");
3770 process_ESResponse(apdu->u.extendedServicesResponse);
3773 printf("Target has closed the association.\n");
3774 process_close(apdu->u.close);
3776 case Z_APDU_resourceControlRequest:
3777 process_resourceControlRequest
3778 (apdu->u.resourceControlRequest);
3780 case Z_APDU_deleteResultSetResponse:
3781 process_deleteResultSetResponse(apdu->u.
3782 deleteResultSetResponse);
3785 printf("Received unknown APDU type (%d).\n",
3791 else if (gdu->which == Z_GDU_HTTP_Response)
3793 http_response(gdu->u.HTTP_Response);
3796 if (conn && !cs_more(conn))
3801 #if HAVE_GETTIMEOFDAY
3802 gettimeofday (&tv_end, 0);
3804 printf ("S/U S/U=%ld/%ld %ld/%ld",
3805 (long) tv_start.tv_sec,
3806 (long) tv_start.tv_usec,
3807 (long) tv_end.tv_sec,
3808 (long) tv_end.tv_usec);
3810 printf ("Elapsed: %.6f\n",
3811 (double) tv_end.tv_usec / 1e6 + tv_end.tv_sec -
3812 ((double) tv_start.tv_usec / 1e6 + tv_start.tv_sec));
3819 int cmd_cclparse(const char* arg)
3822 struct ccl_rpn_node *rpn=NULL;
3825 rpn = ccl_find_str (bibset, arg, &error, &pos);
3828 printf ("%*s^ - ", 3+strlen(last_cmd)+1+pos, " ");
3829 printf ("%s\n", ccl_err_msg (error));
3835 ccl_pr_tree(rpn, stdout);
3839 ccl_rpn_delete(rpn);
3847 int cmd_set_otherinfo(const char* args)
3849 char oidstr[101], otherinfoString[101];
3854 sscan_res = sscanf (args, "%d %100[^ ] %100s", &otherinfoNo, oidstr, otherinfoString);
3856 /* reset this otherinfo */
3857 if(otherinfoNo>=maxOtherInfosSupported) {
3858 printf("Error otherinfo index to large (%d>%d)\n",
3859 otherinfoNo,maxOtherInfosSupported);
3861 extraOtherInfos[otherinfoNo].oidval = -1;
3862 if (extraOtherInfos[otherinfoNo].value)
3863 free(extraOtherInfos[otherinfoNo].value);
3867 printf("Error in set_otherinfo command \n");
3871 if (otherinfoNo>=maxOtherInfosSupported) {
3872 printf("Error otherinfo index to large (%d>%d)\n",
3873 otherinfoNo,maxOtherInfosSupported);
3876 oidval = oid_getvalbyname (oidstr);
3877 if (oidval == -1 ) {
3878 printf("Error in set_otherinfo command unknown oid %s \n",oidstr);
3881 extraOtherInfos[otherinfoNo].oidval = oidval;
3882 if(extraOtherInfos[otherinfoNo].value) free(extraOtherInfos[otherinfoNo].value);
3883 extraOtherInfos[otherinfoNo].value = strdup(otherinfoString);
3888 int cmd_sleep(const char* args )
3897 printf("Done sleeping %d seconds\n", sec);
3902 int cmd_list_otherinfo(const char* args)
3906 if(strlen(args)>0) {
3908 if( i >= maxOtherInfosSupported ) {
3909 printf("Error otherinfo index to large (%d>%d)\n",i,maxOtherInfosSupported);
3913 if(extraOtherInfos[i].oidval != -1)
3914 printf(" otherinfo %d %s %s\n",
3916 yaz_z3950_oid_value_to_str(
3917 (enum oid_value) extraOtherInfos[i].oidval,
3919 extraOtherInfos[i].value);
3922 for(i=0; i<maxOtherInfosSupported; ++i) {
3923 if(extraOtherInfos[i].oidval != -1)
3924 printf(" otherinfo %d %s %s\n",
3926 yaz_z3950_oid_value_to_str(
3927 (enum oid_value) extraOtherInfos[i].oidval,
3929 extraOtherInfos[i].value);
3937 int cmd_list_all(const char* args) {
3940 /* connection options */
3942 printf("Connected to : %s\n",last_open_command);
3944 if(last_open_command)
3945 printf("Not connected to : %s\n",last_open_command);
3947 printf("Not connected : \n");
3950 if(yazProxy) printf("using proxy : %s\n",yazProxy);
3952 printf("auto_reconnect : %s\n",auto_reconnect?"on":"off");
3955 printf("Authentication : none\n");
3957 switch(auth->which) {
3958 case Z_IdAuthentication_idPass:
3959 printf("Authentication : IdPass\n");
3960 printf(" Login User : %s\n",auth->u.idPass->userId?auth->u.idPass->userId:"");
3961 printf(" Login Group : %s\n",auth->u.idPass->groupId?auth->u.idPass->groupId:"");
3962 printf(" Password : %s\n",auth->u.idPass->password?auth->u.idPass->password:"");
3964 case Z_IdAuthentication_open:
3965 printf("Authentication : psOpen\n");
3966 printf(" Open string : %s\n",auth->u.open);
3969 printf("Authentication : Unknown\n");
3972 if (negotiationCharset)
3973 printf("Neg. Character set : `%s'\n", negotiationCharset);
3977 for (i = 0; i<num_databaseNames; i++) printf("%s ",databaseNames[i]);
3981 printf("CCL file : %s\n",ccl_fields);
3982 printf("CQL file : %s\n",cql_fields);
3983 printf("Query type : %s\n",query_type_as_string(queryType));
3985 printf("Named Result Sets : %s\n",setnumber==-1?"off":"on");
3987 /* piggy back options */
3988 printf("ssub/lslb/mspn : %d/%d/%d\n",smallSetUpperBound,largeSetLowerBound,mediumSetPresentNumber);
3990 /* print present related options */
3991 printf("Format : %s\n",yaz_z3950_oid_value_to_str(recordsyntax,CLASS_RECSYN));
3992 printf("Schema : %s\n",record_schema ? record_schema : "not set");
3993 printf("Elements : %s\n",elementSetNames?elementSetNames->u.generic:"");
3995 /* loging options */
3996 printf("APDU log : %s\n",apdu_file?"on":"off");
3997 printf("Record log : %s\n",marc_file?"on":"off");
4000 printf("Other Info: \n");
4001 cmd_list_otherinfo("");
4006 int cmd_clear_otherinfo(const char* args)
4008 if(strlen(args)>0) {
4010 otherinfoNo = atoi(args);
4011 if( otherinfoNo >= maxOtherInfosSupported ) {
4012 printf("Error otherinfo index to large (%d>%d)\n",otherinfoNo,maxOtherInfosSupported);
4016 if(extraOtherInfos[otherinfoNo].oidval != -1) {
4017 /* only clear if set. */
4018 extraOtherInfos[otherinfoNo].oidval=-1;
4019 free(extraOtherInfos[otherinfoNo].value);
4024 for(i=0; i<maxOtherInfosSupported; ++i) {
4025 if (extraOtherInfos[i].oidval!=-1 ) {
4026 extraOtherInfos[i].oidval=-1;
4027 free(extraOtherInfos[i].value);
4034 static int cmd_help (const char *line);
4036 typedef char *(*completerFunctionType)(const char *text, int state);
4040 int (*fun)(const char *arg);
4042 completerFunctionType rl_completerfunction;
4043 int complete_filenames;
4044 char **local_tabcompletes;
4046 {"open", cmd_open, "('tcp'|'ssl')':<host>[':'<port>][/<db>]",NULL,0,NULL},
4047 {"quit", cmd_quit, "",NULL,0,NULL},
4048 {"find", cmd_find, "<query>",NULL,0,NULL},
4049 {"delete", cmd_delete, "<setname>",NULL,0,NULL},
4050 {"base", cmd_base, "<base-name>",NULL,0,NULL},
4051 {"show", cmd_show, "<rec#>['+'<#recs>['+'<setname>]]",NULL,0,NULL},
4052 {"scan", cmd_scan, "<term>",NULL,0,NULL},
4053 {"scanstep", cmd_scanstep, "<size>",NULL,0,NULL},
4054 {"scanpos", cmd_scanpos, "<size>",NULL,0,NULL},
4055 {"sort", cmd_sort, "<sortkey> <flag> <sortkey> <flag> ...",NULL,0,NULL},
4056 {"sort+", cmd_sort_newset, "<sortkey> <flag> <sortkey> <flag> ...",NULL,0,NULL},
4057 {"authentication", cmd_authentication, "<acctstring>",NULL,0,NULL},
4058 {"lslb", cmd_lslb, "<largeSetLowerBound>",NULL,0,NULL},
4059 {"ssub", cmd_ssub, "<smallSetUpperBound>",NULL,0,NULL},
4060 {"mspn", cmd_mspn, "<mediumSetPresentNumber>",NULL,0,NULL},
4061 {"status", cmd_status, "",NULL,0,NULL},
4062 {"setnames", cmd_setnames, "",NULL,0,NULL},
4063 {"cancel", cmd_cancel, "",NULL,0,NULL},
4064 {"cancel_find", cmd_cancel_find, "<query>",NULL,0,NULL},
4065 {"format", cmd_format, "<recordsyntax>",complete_format,0,NULL},
4066 {"schema", cmd_schema, "<schema>",complete_schema,0,NULL},
4067 {"elements", cmd_elements, "<elementSetName>",NULL,0,NULL},
4068 {"close", cmd_close, "",NULL,0,NULL},
4069 {"attributeset", cmd_attributeset, "<attrset>",complete_attributeset,0,NULL},
4070 {"querytype", cmd_querytype, "<type>",complete_querytype,0,NULL},
4071 {"refid", cmd_refid, "<id>",NULL,0,NULL},
4072 {"itemorder", cmd_itemorder, "ill|item <itemno>",NULL,0,NULL},
4073 {"update", cmd_update, "<action> <recid> [<file>]",NULL,0,NULL},
4074 {"update0", cmd_update0, "<action> <recid> [<file>]",NULL,0,NULL},
4075 {"packagename", cmd_packagename, "<packagename>",NULL,0,NULL},
4076 {"proxy", cmd_proxy, "[('tcp'|'ssl')]<host>[':'<port>]",NULL,0,NULL},
4077 {"charset", cmd_charset, "<nego_charset> <output_charset>",NULL,0,NULL},
4078 {"negcharset", cmd_negcharset, "<nego_charset>",NULL,0,NULL},
4079 {"displaycharset", cmd_displaycharset, "<output_charset>",NULL,0,NULL},
4080 {"marccharset", cmd_marccharset, "<charset_name>",NULL,0,NULL},
4081 {"lang", cmd_lang, "<language_code>",NULL,0,NULL},
4082 {".", cmd_source_echo, "<filename>",NULL,1,NULL},
4083 {"!", cmd_subshell, "Subshell command",NULL,1,NULL},
4084 {"set_apdufile", cmd_set_apdufile, "<filename>",NULL,1,NULL},
4085 {"set_berfile", cmd_set_berfile, "<filename>",NULL,1,NULL},
4086 {"set_marcdump", cmd_set_marcdump," <filename>",NULL,1,NULL},
4087 {"set_cclfile", cmd_set_cclfile," <filename>",NULL,1,NULL},
4088 {"set_cqlfile", cmd_set_cqlfile," <filename>",NULL,1,NULL},
4089 {"set_auto_reconnect", cmd_set_auto_reconnect," on|off",complete_auto_reconnect,1,NULL},
4090 {"set_otherinfo", cmd_set_otherinfo,"<otherinfoinddex> <oid> <string>",NULL,0,NULL},
4091 {"sleep", cmd_sleep,"<seconds>",NULL,0,NULL},
4092 {"register_oid", cmd_register_oid,"<name> <class> <oid>",NULL,0,NULL},
4093 {"push_command", cmd_push_command,"<command>",command_generator,0,NULL},
4094 {"register_tab", cmd_register_tab,"<commandname> <tab>",command_generator,0,NULL},
4095 {"cclparse", cmd_cclparse,"<ccl find command>",NULL,0,NULL},
4096 {"list_otherinfo",cmd_list_otherinfo,"[otherinfoinddex]",NULL,0,NULL},
4097 {"list_all",cmd_list_all,"",NULL,0,NULL},
4098 {"clear_otherinfo",cmd_clear_otherinfo,"",NULL,0,NULL},
4099 /* Server Admin Functions */
4100 {"adm-reindex", cmd_adm_reindex, "<database-name>",NULL,0,NULL},
4101 {"adm-truncate", cmd_adm_truncate, "('database'|'index')<object-name>",NULL,0,NULL},
4102 {"adm-create", cmd_adm_create, "",NULL,0,NULL},
4103 {"adm-drop", cmd_adm_drop, "('database'|'index')<object-name>",NULL,0,NULL},
4104 {"adm-import", cmd_adm_import, "<record-type> <dir> <pattern>",NULL,0,NULL},
4105 {"adm-refresh", cmd_adm_refresh, "",NULL,0,NULL},
4106 {"adm-commit", cmd_adm_commit, "",NULL,0,NULL},
4107 {"adm-shutdown", cmd_adm_shutdown, "",NULL,0,NULL},
4108 {"adm-startup", cmd_adm_startup, "",NULL,0,NULL},
4109 {"explain", cmd_explain, "", NULL, 0, NULL},
4110 {"options", cmd_options, "", NULL, 0, NULL},
4111 {"zversion", cmd_zversion, "", NULL, 0, NULL},
4112 {"help", cmd_help, "", NULL,0,NULL},
4113 {"init", cmd_init, "", NULL,0,NULL},
4117 static int cmd_help (const char *line)
4123 sscanf (line, "%20s", topic);
4126 printf("Commands:\n");
4127 for (i = 0; cmd_array[i].cmd; i++)
4128 if (*topic == 0 || strcmp (topic, cmd_array[i].cmd) == 0)
4129 printf(" %s %s\n", cmd_array[i].cmd, cmd_array[i].ad);
4130 if (strcmp (topic, "find") == 0)
4133 printf (" \"term\" Simple Term\n");
4134 printf (" @attr [attset] type=value op Attribute\n");
4135 printf (" @and opl opr And\n");
4136 printf (" @or opl opr Or\n");
4137 printf (" @not opl opr And-Not\n");
4138 printf (" @set set Result set\n");
4140 printf ("Bib-1 attribute types\n");
4142 printf ("4=Title 7=ISBN 8=ISSN 30=Date 62=Abstract 1003=Author 1016=Any\n");
4143 printf ("2=Relation: ");
4144 printf ("1< 2<= 3= 4>= 5> 6!= 102=Relevance\n");
4145 printf ("3=Position: ");
4146 printf ("1=First in Field 2=First in subfield 3=Any position\n");
4147 printf ("4=Structure: ");
4148 printf ("1=Phrase 2=Word 3=Key 4=Year 5=Date 6=WordList\n");
4149 printf ("5=Truncation: ");
4150 printf ("1=Right 2=Left 3=L&R 100=No 101=# 102=Re-1 103=Re-2\n");
4151 printf ("6=Completeness:");
4152 printf ("1=Incomplete subfield 2=Complete subfield 3=Complete field\n");
4157 int cmd_register_tab(const char* arg) {
4159 char command[101], tabargument[101];
4164 if (sscanf (arg, "%100s %100s", command, tabargument) < 1) {
4168 /* locate the amdn in the list */
4169 for (i = 0; cmd_array[i].cmd; i++) {
4170 if (!strncmp(cmd_array[i].cmd, command, strlen(command))) {
4175 if(!cmd_array[i].cmd) {
4176 fprintf(stderr,"Unknown command %s\n",command);
4181 if(!cmd_array[i].local_tabcompletes)
4182 cmd_array[i].local_tabcompletes = (char **) calloc(1,sizeof(char**));
4186 tabslist = cmd_array[i].local_tabcompletes;
4187 for(;tabslist && *tabslist;tabslist++) {
4191 cmd_array[i].local_tabcompletes = (char **)
4192 realloc(cmd_array[i].local_tabcompletes,(num_of_tabs+2)*sizeof(char**));
4193 tabslist=cmd_array[i].local_tabcompletes;
4194 tabslist[num_of_tabs]=strdup(tabargument);
4195 tabslist[num_of_tabs+1]=NULL;
4200 void process_cmd_line(char* line)
4203 char word[32], arg[10240];
4205 #if HAVE_GETTIMEOFDAY
4206 gettimeofday (&tv_start, 0);
4209 if ((res = sscanf(line, "%31s %10239[^;]", word, arg)) <= 0)
4211 strcpy(word, last_cmd);
4216 strcpy(last_cmd, word);
4218 /* removed tailing spaces from the arg command */
4221 char* lastnonspace=NULL;
4224 if(!isspace(*(unsigned char *) p)) {
4229 *(++lastnonspace) = 0;
4232 for (i = 0; cmd_array[i].cmd; i++)
4233 if (!strncmp(cmd_array[i].cmd, word, strlen(word)))
4235 res = (*cmd_array[i].fun)(arg);
4239 if (!cmd_array[i].cmd) /* dump our help-screen */
4241 printf("Unknown command: %s.\n", word);
4242 printf("use help for list of commands\n");
4243 /* cmd_help (""); */
4247 if(apdu_file) fflush(apdu_file);
4250 wait_and_handle_response();
4259 char *command_generator(const char *text, int state)
4265 for( ; cmd_array[idx].cmd; ++idx) {
4266 if (!strncmp(cmd_array[idx].cmd,text,strlen(text))) {
4267 ++idx; /* skip this entry on the next run */
4268 return strdup(cmd_array[idx-1].cmd);
4276 This function only known how to complete on the first word
4278 char ** readline_completer(char *text, int start, int end) {
4279 #if HAVE_READLINE_READLINE_H
4281 completerFunctionType completerToUse;
4284 #if HAVE_READLINE_RL_COMPLETION_MATCHES
4285 char** res=rl_completion_matches(text,
4288 char** res=completion_matches(text,
4289 (CPFunction*)command_generator);
4291 rl_attempted_completion_over = 1;
4294 char arg[10240],word[32];
4296 if ((res = sscanf(rl_line_buffer, "%31s %10239[^;]", word, arg)) <= 0) {
4297 rl_attempted_completion_over = 1;
4301 for (i = 0; cmd_array[i].cmd; i++) {
4302 if (!strncmp(cmd_array[i].cmd, word, strlen(word))) {
4307 if(!cmd_array[i].cmd) return NULL;
4309 curret_global_list = cmd_array[i].local_tabcompletes;
4311 completerToUse = cmd_array[i].rl_completerfunction;
4312 if(completerToUse==NULL) /* if no pr. command completer is defined use the default completer */
4313 completerToUse = default_completer;
4315 if(completerToUse) {
4316 #ifdef HAVE_READLINE_RL_COMPLETION_MATCHES
4318 rl_completion_matches(text,
4322 completion_matches(text,
4323 (CPFunction*)completerToUse);
4325 if(!cmd_array[i].complete_filenames)
4326 rl_attempted_completion_over = 1;
4329 if(!cmd_array[i].complete_filenames)
4330 rl_attempted_completion_over = 1;
4340 static void client(void)
4346 #if HAVE_GETTIMEOFDAY
4347 gettimeofday (&tv_start, 0);
4352 char *line_in = NULL;
4353 #if HAVE_READLINE_READLINE_H
4356 line_in=readline(C_PROMPT);
4359 #if HAVE_READLINE_HISTORY_H
4361 add_history(line_in);
4363 strncpy(line, line_in, 10239);
4372 if (!fgets(line, 10239, stdin))
4374 if ((end_p = strchr (line, '\n')))
4377 process_cmd_line(line);
4381 static void show_version(void)
4385 yaz_version(vstr, 0);
4386 printf ("YAZ version: %s\n", YAZ_VERSION);
4387 if (strcmp(vstr, YAZ_VERSION))
4388 printf ("YAZ DLL/SO: %s\n", vstr);
4392 int main(int argc, char **argv)
4395 char *open_command = 0;
4396 char *auth_command = 0;
4401 if (!setlocale(LC_CTYPE, ""))
4402 fprintf (stderr, "setlocale failed\n");
4406 codeset = nl_langinfo(CODESET);
4410 outputCharset = xstrdup(codeset);
4412 ODR_MASK_SET(&z3950_options, Z_Options_search);
4413 ODR_MASK_SET(&z3950_options, Z_Options_present);
4414 ODR_MASK_SET(&z3950_options, Z_Options_namedResultSets);
4415 ODR_MASK_SET(&z3950_options, Z_Options_triggerResourceCtrl);
4416 ODR_MASK_SET(&z3950_options, Z_Options_scan);
4417 ODR_MASK_SET(&z3950_options, Z_Options_sort);
4418 ODR_MASK_SET(&z3950_options, Z_Options_extendedServices);
4419 ODR_MASK_SET(&z3950_options, Z_Options_delSet);
4421 while ((ret = options("k:c:q:a:b:m:v:p:u:t:Vxd:", argv, argc, &arg)) != -2)
4428 open_command = (char *) xmalloc (strlen(arg)+6);
4429 strcpy (open_command, "open ");
4430 strcat (open_command, arg);
4434 dump_file_prefix = arg;
4437 kilobytes = atoi(arg);
4440 if (!(marc_file = fopen (arg, "a")))
4447 outputCharset = xstrdup(arg);
4450 strncpy (ccl_fields, arg, sizeof(ccl_fields)-1);
4451 ccl_fields[sizeof(ccl_fields)-1] = '\0';
4454 strncpy (cql_fields, arg, sizeof(cql_fields)-1);
4455 cql_fields[sizeof(cql_fields)-1] = '\0';
4458 if (!strcmp(arg, "-"))
4461 ber_file=fopen(arg, "a");
4464 if (!strcmp(arg, "-"))
4467 apdu_file=fopen(arg, "a");
4473 yazProxy=strdup(arg);
4478 auth_command = (char *) xmalloc (strlen(arg)+6);
4479 strcpy (auth_command, "auth ");
4480 strcat (auth_command, arg);
4484 yaz_log_init(yaz_log_mask_str(arg), "", 0);
4490 fprintf (stderr, "Usage: %s [-m <marclog>] [ -a <apdulog>] "
4491 "[-b berdump] [-c cclfields] \n"
4492 "[-q cqlfields] [-p <proxy-addr>] [-u <auth>] "
4493 "[-k size] [-d dump] [-V] [<server-addr>]\n",
4501 #ifdef HAVE_GETTIMEOFDAY
4502 gettimeofday (&tv_start, 0);
4504 process_cmd_line (auth_command);
4505 #if HAVE_READLINE_HISTORY_H
4506 add_history(auth_command);
4508 xfree(auth_command);
4512 #ifdef HAVE_GETTIMEOFDAY
4513 gettimeofday (&tv_start, 0);
4515 process_cmd_line (open_command);
4516 #if HAVE_READLINE_HISTORY_H
4517 add_history(open_command);
4519 xfree(open_command);
4530 * vim600: sw=4 ts=8 fdm=marker
4531 * vim<600: sw=4 ts=8