2 * Copyright (c) 1995-2004, Index Data
3 * See the file LICENSE for details.
5 * $Id: client.c,v 1.257 2004-12-02 13:55:35 ja7 Exp $
19 #if HAVE_OPENSSL_SSL_H
20 #include <openssl/bio.h>
21 #include <openssl/crypto.h>
22 #include <openssl/x509.h>
23 #include <openssl/pem.h>
24 #include <openssl/ssl.h>
25 #include <openssl/err.h>
33 #define S_ISREG(x) (x & _S_IFREG)
34 #define S_ISDIR(x) (x & _S_IFDIR)
37 #include <yaz/yaz-util.h>
39 #include <yaz/comstack.h>
41 #include <yaz/proto.h>
42 #include <yaz/marcdisp.h>
43 #include <yaz/diagbib1.h>
44 #include <yaz/otherinfo.h>
45 #include <yaz/charneg.h>
47 #include <yaz/pquery.h>
48 #include <yaz/sortspec.h>
52 #include <yaz/yaz-ccl.h>
56 #if HAVE_READLINE_READLINE_H
57 #include <readline/readline.h>
60 #if HAVE_READLINE_HISTORY_H
61 #include <readline/history.h>
67 #include "tabcomplete.h"
69 #define C_PROMPT "Z> "
71 static char *codeset = 0; /* character set for output */
72 static int hex_dump = 0;
73 static char *dump_file_prefix = 0;
74 static ODR out, in, print; /* encoding and decoding streams */
76 static ODR srw_sr_odr_out = 0;
77 static Z_SRW_PDU *srw_sr = 0;
79 static FILE *apdu_file = 0;
80 static FILE *ber_file = 0;
81 static COMSTACK conn = 0; /* our z-association */
82 static Z_IdAuthentication *auth = 0; /* our current auth definition */
83 char *databaseNames[128];
84 int num_databaseNames = 0;
85 static Z_External *record_last = 0;
86 static int setnumber = -1; /* current result set number */
87 static int smallSetUpperBound = 0;
88 static int largeSetLowerBound = 1;
89 static int mediumSetPresentNumber = 0;
90 static Z_ElementSetNames *elementSetNames = 0;
91 static int setno = 1; /* current set offset */
92 static enum oid_proto protocol = PROTO_Z3950; /* current app protocol */
93 static enum oid_value recordsyntax = VAL_USMARC;
94 static char *record_schema = 0;
95 static int sent_close = 0;
96 static NMEM session_mem = NULL; /* memory handle for init-response */
97 static Z_InitResponse *session = 0; /* session parameters */
98 static char last_scan_line[512] = "0";
99 static char last_scan_query[512] = "0";
100 static char ccl_fields[512] = "default.bib";
101 /* ### How can I set this path to use wherever YAZ is installed? */
102 static char cql_fields[512] = "/usr/local/share/yaz/etc/pqf.properties";
103 static char *esPackageName = 0;
104 static char *yazProxy = 0;
105 static int kilobytes = 1024;
106 static char *negotiationCharset = 0;
107 static char *outputCharset = 0;
108 static char *marcCharset = 0;
109 static char* yazLang = 0;
110 static char* http_version = "1.1";
112 static char last_cmd[32] = "?";
113 static FILE *marc_file = 0;
114 static char *refid = NULL;
115 static char *last_open_command = NULL;
116 static int auto_reconnect = 0;
117 static Odr_bitmask z3950_options;
118 static int z3950_version = 3;
119 static int scan_stepSize = 0;
120 static int scan_position = 1;
121 static char cur_host[200];
131 static QueryType queryType = QueryType_Prefix;
133 static CCL_bibset bibset; /* CCL bibset handle */
134 static cql_transform_t cqltrans; /* CQL context-set handle */
136 #if HAVE_READLINE_COMPLETION_OVER
139 /* readline doesn't have this var. Define it ourselves. */
140 int rl_attempted_completion_over = 0;
143 /* set this one to 1, to avoid decode of unknown MARCs */
144 #define AVOID_MARC_DECODE 1
146 #define maxOtherInfosSupported 10
150 } extraOtherInfos[maxOtherInfosSupported];
153 void process_cmd_line(char* line);
154 char ** readline_completer(char *text, int start, int end);
155 char *command_generator(const char *text, int state);
156 char** curret_global_list=NULL;
157 int cmd_register_tab(const char* arg);
159 static void close_session (void);
161 ODR getODROutputStream()
166 const char* query_type_as_string(QueryType q)
169 case QueryType_Prefix: return "prefix (RPN sent to server)";
170 case QueryType_CCL: return "CCL (CCL sent to server) ";
171 case QueryType_CCL2RPN: return "CCL -> RPN (RPN sent to server)";
172 case QueryType_CQL: return "CQL (CQL sent to server)";
173 case QueryType_CQL2RPN: return "CQL -> RPN (RPN sent to server)";
175 return "unknown Query type internal yaz-client error";
179 static void do_hex_dump(const char* buf, int len)
184 for( i=0; i<len ; i=i+16 )
187 for(x=0 ; i+x<len && x<16; ++x)
189 printf("%2.2X ",(unsigned int)((unsigned char)buf[i+x]));
194 if (dump_file_prefix)
197 if (++no < 1000 && strlen(dump_file_prefix) < 500)
201 sprintf (fname, "%s.%03d.raw", dump_file_prefix, no);
202 of = fopen(fname, "wb");
204 fwrite (buf, 1, len, of);
211 void add_otherInfos(Z_APDU *a)
213 Z_OtherInformation **oi;
217 for(i=0; i<maxOtherInfosSupported; ++i)
219 if(extraOtherInfos[i].oidval != -1)
220 yaz_oi_set_string_oidval(oi, out, extraOtherInfos[i].oidval,
221 1, extraOtherInfos[i].value);
225 int send_apdu(Z_APDU *a)
234 z_APDU(print, &a, 0, 0);
237 if (!z_APDU(out, &a, 0, 0))
239 odr_perror(out, "Encoding APDU");
243 buf = odr_getbuf(out, &len, 0);
245 odr_dumpBER(ber_file, buf, len);
246 /* printf ("sending APDU of size %d\n", len); */
247 do_hex_dump(buf, len);
248 if (cs_put(conn, buf, len) < 0)
250 fprintf(stderr, "cs_put: %s", cs_errmsg(cs_errno(conn)));
254 odr_reset(out); /* release the APDU structure */
258 static void print_stringn(const unsigned char *buf, size_t len)
261 for (i = 0; i<len; i++)
262 if ((buf[i] <= 126 && buf[i] >= 32) || strchr ("\n\r\t\f", buf[i]))
263 printf ("%c", buf[i]);
265 printf ("\\X%02X", buf[i]);
268 static void print_refid (Z_ReferenceId *id)
272 printf ("Reference Id: ");
273 print_stringn (id->buf, id->len);
278 static Z_ReferenceId *set_refid (ODR out)
283 id = (Z_ReferenceId *) odr_malloc (out, sizeof(*id));
284 id->size = id->len = strlen(refid);
285 id->buf = (unsigned char *) odr_malloc (out, id->len);
286 memcpy (id->buf, refid, id->len);
290 /* INIT SERVICE ------------------------------- */
292 static void send_initRequest(const char* type_and_host)
294 Z_APDU *apdu = zget_APDU(out, Z_APDU_initRequest);
295 Z_InitRequest *req = apdu->u.initRequest;
298 req->options = &z3950_options;
300 ODR_MASK_ZERO(req->protocolVersion);
301 for (i = 0; i<z3950_version; i++)
302 ODR_MASK_SET(req->protocolVersion, i);
304 *req->maximumRecordSize = 1024*kilobytes;
305 *req->preferredMessageSize = 1024*kilobytes;
307 req->idAuthentication = auth;
309 req->referenceId = set_refid (out);
311 if (yazProxy && type_and_host)
312 yaz_oi_set_string_oidval(&req->otherInfo, out, VAL_PROXY,
315 if (negotiationCharset || yazLang) {
316 Z_OtherInformation **p;
317 Z_OtherInformationUnit *p0;
319 yaz_oi_APDU(apdu, &p);
321 if ((p0=yaz_oi_update(p, out, NULL, 0, 0))) {
322 ODR_MASK_SET(req->options, Z_Options_negotiationModel);
324 p0->which = Z_OtherInfo_externallyDefinedInfo;
325 p0->information.externallyDefinedInfo =
326 yaz_set_proposal_charneg(
328 (const char**)&negotiationCharset,
329 negotiationCharset ? 1 : 0,
330 (const char**)&yazLang, yazLang ? 1 : 0, 1);
335 printf("Sent initrequest.\n");
339 /* These two are used only from process_initResponse() */
340 static void render_initUserInfo(Z_OtherInformation *ui1);
341 static void render_diag(Z_DiagnosticFormat *diag);
343 static void pr_opt(const char *opt, void *clientData)
348 static int process_initResponse(Z_InitResponse *res)
351 /* save session parameters for later use */
352 session_mem = odr_extract_mem(in);
355 for (ver = 0; ver < 8; ver++)
356 if (!ODR_MASK_GET(res->protocolVersion, ver))
360 printf("Connection rejected by v%d target.\n", ver);
362 printf("Connection accepted by v%d target.\n", ver);
363 if (res->implementationId)
364 printf("ID : %s\n", res->implementationId);
365 if (res->implementationName)
366 printf("Name : %s\n", res->implementationName);
367 if (res->implementationVersion)
368 printf("Version: %s\n", res->implementationVersion);
369 if (res->userInformationField)
371 Z_External *uif = res->userInformationField;
372 if (uif->which == Z_External_userInfo1) {
373 render_initUserInfo(uif->u.userInfo1);
375 printf("UserInformationfield:\n");
376 if (!z_External(print, (Z_External**)&uif, 0, 0)) {
377 odr_perror(print, "Printing userinfo\n");
380 if (uif->which == Z_External_octet) {
381 printf("Guessing visiblestring:\n");
382 printf("'%s'\n", uif->u. octet_aligned->buf);
383 } else if (uif->which == Z_External_single) {
384 Odr_any *sat = uif->u.single_ASN1_type;
385 oident *oid = oid_getentbyoid(uif->direct_reference);
386 if (oid->value == VAL_OCLCUI) {
387 Z_OCLC_UserInformation *oclc_ui;
388 ODR decode = odr_createmem(ODR_DECODE);
389 odr_setbuf(decode, sat->buf, sat->len, 0);
390 if (!z_OCLC_UserInformation(decode, &oclc_ui, 0, 0))
391 printf ("Bad OCLC UserInformation:\n");
393 printf ("OCLC UserInformation:\n");
394 if (!z_OCLC_UserInformation(print, &oclc_ui, 0, 0))
395 printf ("Bad OCLC UserInformation spec\n");
400 /* Peek at any private Init-diagnostic APDUs */
401 printf("### NAUGHTY: External is '%.*s'\n", sat->len, sat->buf);
408 yaz_init_opt_decode(res->options, pr_opt, 0);
411 if (ODR_MASK_GET(res->options, Z_Options_namedResultSets))
414 if (ODR_MASK_GET(res->options, Z_Options_negotiationModel)) {
416 Z_CharSetandLanguageNegotiation *p =
417 yaz_get_charneg_record(res->otherInfo);
421 char *charset=NULL, *lang=NULL;
424 yaz_get_response_charneg(session_mem, p, &charset, &lang,
427 if (outputCharset && negotiationCharset) {
428 odr_set_charset (out, charset, outputCharset);
429 odr_set_charset (in, outputCharset, charset);
432 odr_set_charset (out, 0, 0);
433 odr_set_charset (in, 0, 0);
436 printf("Accepted character set : %s\n", charset);
437 printf("Accepted code language : %s\n", lang ? lang : "none");
438 printf("Accepted records in ...: %d\n", selected );
446 static void render_initUserInfo(Z_OtherInformation *ui1) {
448 printf("Init response contains %d otherInfo unit%s:\n",
449 ui1->num_elements, ui1->num_elements == 1 ? "" : "s");
451 for (i = 0; i < ui1->num_elements; i++) {
452 Z_OtherInformationUnit *unit = ui1->list[i];
453 printf(" %d: otherInfo unit contains ", i+1);
454 if (unit->which == Z_OtherInfo_externallyDefinedInfo &&
455 unit->information.externallyDefinedInfo->which ==
457 render_diag(unit->information.externallyDefinedInfo->u.diag1);
459 printf("unsupported otherInfo unit type %d\n", unit->which);
465 /* ### should this share code with display_diagrecs()? */
466 static void render_diag(Z_DiagnosticFormat *diag) {
469 printf("%d diagnostic%s:\n", diag->num, diag->num == 1 ? "" : "s");
470 for (i = 0; i < diag->num; i++) {
471 Z_DiagnosticFormat_s *ds = diag->elements[i];
472 printf(" %d: ", i+1);
474 case Z_DiagnosticFormat_s_defaultDiagRec: {
475 Z_DefaultDiagFormat *dd = ds->u.defaultDiagRec;
476 /* ### should check `dd->diagnosticSetId' */
477 printf("code=%d (%s)", *dd->condition,
478 diagbib1_str(*dd->condition));
479 /* Both types of addinfo are the same, so use type-pun */
480 if (dd->u.v2Addinfo != 0)
481 printf(",\n\taddinfo='%s'", dd->u.v2Addinfo);
484 case Z_DiagnosticFormat_s_explicitDiagnostic:
485 printf("Explicit diagnostic (not supported)");
488 printf("Unrecognised diagnostic type %d", ds->which);
492 if (ds->message != 0)
493 printf(", message='%s'", ds->message);
499 static int set_base(const char *arg)
504 for (i = 0; i<num_databaseNames; i++)
505 xfree (databaseNames[i]);
506 num_databaseNames = 0;
510 if (!(cp = strchr(arg, ' ')))
511 cp = arg + strlen(arg);
514 databaseNames[num_databaseNames] = (char *)xmalloc (1 + cp - arg);
515 memcpy (databaseNames[num_databaseNames], arg, cp - arg);
516 databaseNames[num_databaseNames][cp - arg] = '\0';
518 for (cp1 = databaseNames[num_databaseNames]; *cp1 ; cp1++)
527 if (num_databaseNames == 0)
529 num_databaseNames = 1;
530 databaseNames[0] = xstrdup("");
535 static int cmd_base(const char *arg)
539 printf("Usage: base <database> <database> ...\n");
542 return set_base(arg);
545 void cmd_open_remember_last_open_command(const char* arg, char* new_open_command)
547 if(last_open_command != arg)
549 if(last_open_command) xfree(last_open_command);
550 last_open_command = xstrdup(new_open_command);
554 int session_connect(const char *arg)
557 char type_and_host[101];
558 const char *basep = 0;
559 #if HAVE_OPENSSL_SSL_H
568 nmem_destroy (session_mem);
572 cs_get_host_args(arg, &basep);
574 strncpy(type_and_host, arg, sizeof(type_and_host)-1);
575 type_and_host[sizeof(type_and_host)-1] = '\0';
577 cmd_open_remember_last_open_command(arg,type_and_host);
580 conn = cs_create_host(yazProxy, 1, &add);
582 conn = cs_create_host(arg, 1, &add);
585 printf ("Couldn't create comstack\n");
589 if (conn->protocol == PROTO_HTTP)
590 queryType = QueryType_CQL;
592 if (conn->protocol == PROTO_HTTP)
594 printf ("SRW/HTTP not enabled in this YAZ\n");
600 protocol = conn->protocol;
601 if (conn->protocol == PROTO_HTTP)
605 printf("Connecting...");
607 if (cs_connect(conn, add) < 0)
609 printf ("error = %s\n", cs_strerror(conn));
610 if (conn->cerrno == CSYSERR)
613 yaz_strerror(msg, sizeof(msg));
614 printf ("%s\n", msg);
621 #if HAVE_OPENSSL_SSL_H
622 if ((ssl = (SSL *) cs_get_ssl(conn)))
624 X509 *server_cert = SSL_get_peer_certificate (ssl);
630 BIO *bio = BIO_new(BIO_s_mem());
632 /* get PEM buffer in memory */
633 PEM_write_bio_X509(bio, server_cert);
634 pem_len = BIO_get_mem_data(bio, &pem_buf);
635 fwrite(pem_buf, pem_len, 1, stdout);
637 /* print all info on screen .. */
638 X509_print_fp(stdout, server_cert);
641 X509_free (server_cert);
647 if (protocol == PROTO_Z3950)
649 send_initRequest(type_and_host);
655 int cmd_open(const char *arg)
659 strncpy (cur_host, arg, sizeof(cur_host)-1);
660 cur_host[sizeof(cur_host)-1] = 0;
662 return session_connect(cur_host);
669 if(!( auto_reconnect && last_open_command) ) return ;
671 open_command = (char *) xmalloc (strlen(last_open_command)+6);
672 strcpy (open_command, "open ");
674 strcat (open_command, last_open_command);
676 process_cmd_line(open_command);
681 int cmd_authentication(const char *arg)
683 static Z_IdAuthentication au;
684 static char user[40], group[40], pass[40];
685 static Z_IdPass idPass;
690 printf("Auth field set to null\n");
694 r = sscanf (arg, "%39s %39s %39s", user, group, pass);
697 printf("Authentication set to null\n");
703 if (!strcmp(user, "-")) {
704 au.which = Z_IdAuthentication_anonymous;
705 printf("Authentication set to Anonymous\n");
707 au.which = Z_IdAuthentication_open;
709 printf("Authentication set to Open (%s)\n", user);
715 au.which = Z_IdAuthentication_idPass;
716 au.u.idPass = &idPass;
717 idPass.groupId = NULL;
718 idPass.userId = user;
719 idPass.password = group;
720 printf("Authentication set to User (%s), Pass (%s)\n", user, group);
725 au.which = Z_IdAuthentication_idPass;
726 au.u.idPass = &idPass;
727 idPass.groupId = group;
728 idPass.userId = user;
729 idPass.password = pass;
730 printf("Authentication set to User (%s), Group (%s), Pass (%s)\n",
736 /* SEARCH SERVICE ------------------------------ */
737 static void display_record(Z_External *r);
739 static void print_record(const unsigned char *buf, size_t len)
742 print_stringn (buf, len);
743 /* add newline if not already added ... */
744 if (i <= 0 || buf[i-1] != '\n')
747 fwrite (buf, 1, len, marc_file);
750 static void display_record(Z_External *r)
752 oident *ent = oid_getentbyoid(r->direct_reference);
756 * Tell the user what we got.
758 if (r->direct_reference)
760 printf("Record type: ");
762 printf("%s\n", ent->desc);
763 else if (!odr_oid(print, &r->direct_reference, 0, 0))
765 odr_perror(print, "print oid");
769 /* Check if this is a known, ASN.1 type tucked away in an octet string */
770 if (ent && r->which == Z_External_octet)
772 Z_ext_typeent *type = z_ext_getentbyref(ent->value);
778 * Call the given decoder to process the record.
780 odr_setbuf(in, (char*)r->u.octet_aligned->buf,
781 r->u.octet_aligned->len, 0);
782 if (!(*type->fun)(in, &rr, 0, 0))
784 odr_perror(in, "Decoding constructed record.");
785 fprintf(stdout, "[Near %d]\n", odr_offset(in));
786 fprintf(stdout, "Packet dump:\n---------\n");
787 odr_dumpBER(stdout, (char*)r->u.octet_aligned->buf,
788 r->u.octet_aligned->len);
789 fprintf(stdout, "---------\n");
791 /* note just ignores the error ant print the bytes form the octet_aligned later */
794 * Note: we throw away the original, BER-encoded record here.
795 * Do something else with it if you want to keep it.
797 r->u.sutrs = (Z_SUTRS *) rr; /* we don't actually check the type here. */
798 r->which = type->what;
802 if (ent && ent->value == VAL_SOIF)
803 print_record((const unsigned char *) r->u.octet_aligned->buf,
804 r->u.octet_aligned->len);
805 else if (r->which == Z_External_octet)
807 const char *octet_buf = (char*)r->u.octet_aligned->buf;
808 if (ent->oclass == CLASS_RECSYN &&
809 (ent->value == VAL_TEXT_XML ||
810 ent->value == VAL_APPLICATION_XML ||
811 ent->value == VAL_HTML))
813 print_record((const unsigned char *) octet_buf,
814 r->u.octet_aligned->len);
816 else if (ent->value == VAL_POSTSCRIPT)
818 int size = r->u.octet_aligned->len;
821 print_record((const unsigned char *) octet_buf, size);
826 #if AVOID_MARC_DECODE
827 /* primitive check for a marc OID 5.1-29 except 16 */
828 ent->oidsuffix[0] == 5 && ent->oidsuffix[1] < 30 &&
829 ent->oidsuffix[1] != 16
838 yaz_marc_t mt = yaz_marc_create();
840 if (yaz_marc_decode_buf(mt, octet_buf,r->u.octet_aligned->len,
844 if (marcCharset && !strcmp(marcCharset, "auto"))
846 if (ent->value == VAL_USMARC)
848 if (octet_buf[9] == 'a')
856 else if (marcCharset)
858 if (outputCharset && from)
860 cd = yaz_iconv_open(outputCharset, from);
861 printf ("convert from %s to %s", from,
864 printf (" unsupported\n");
869 fwrite (result, 1, rlen, stdout);
873 size_t inbytesleft = rlen;
874 const char *inp = result;
878 size_t outbytesleft = sizeof(outbuf);
882 r = yaz_iconv (cd, (char**) &inp,
884 &outp, &outbytesleft);
885 if (r == (size_t) (-1))
887 int e = yaz_iconv_error(cd);
888 if (e != YAZ_ICONV_E2BIG)
891 fwrite (outbuf, outp - outbuf, 1, stdout);
897 printf ("bad MARC. Dumping as it is:\n");
898 print_record((const unsigned char*) octet_buf,
899 r->u.octet_aligned->len);
901 yaz_marc_destroy(mt);
907 print_record((const unsigned char*) octet_buf,
908 r->u.octet_aligned->len);
912 fwrite (octet_buf, 1, r->u.octet_aligned->len, marc_file);
914 else if (ent && ent->value == VAL_SUTRS)
916 if (r->which != Z_External_sutrs)
918 printf("Expecting single SUTRS type for SUTRS.\n");
921 print_record(r->u.sutrs->buf, r->u.sutrs->len);
923 else if (ent && ent->value == VAL_GRS1)
926 if (r->which != Z_External_grs1)
928 printf("Expecting single GRS type for GRS.\n");
932 yaz_display_grs1(w, r->u.grs1, 0);
936 else if ( /* OPAC display not complete yet .. */
937 ent && ent->value == VAL_OPAC)
940 if (r->u.opac->bibliographicRecord)
941 display_record(r->u.opac->bibliographicRecord);
942 for (i = 0; i<r->u.opac->num_holdingsData; i++)
944 Z_HoldingsRecord *h = r->u.opac->holdingsData[i];
945 if (h->which == Z_HoldingsRecord_marcHoldingsRecord)
947 printf ("MARC holdings %d\n", i);
948 display_record(h->u.marcHoldingsRecord);
950 else if (h->which == Z_HoldingsRecord_holdingsAndCirc)
954 Z_HoldingsAndCircData *data = h->u.holdingsAndCirc;
956 printf ("Data holdings %d\n", i);
957 if (data->typeOfRecord)
958 printf ("typeOfRecord: %s\n", data->typeOfRecord);
959 if (data->encodingLevel)
960 printf ("encodingLevel: %s\n", data->encodingLevel);
961 if (data->receiptAcqStatus)
962 printf ("receiptAcqStatus: %s\n", data->receiptAcqStatus);
963 if (data->generalRetention)
964 printf ("generalRetention: %s\n", data->generalRetention);
965 if (data->completeness)
966 printf ("completeness: %s\n", data->completeness);
967 if (data->dateOfReport)
968 printf ("dateOfReport: %s\n", data->dateOfReport);
970 printf ("nucCode: %s\n", data->nucCode);
971 if (data->localLocation)
972 printf ("localLocation: %s\n", data->localLocation);
973 if (data->shelvingLocation)
974 printf ("shelvingLocation: %s\n", data->shelvingLocation);
975 if (data->callNumber)
976 printf ("callNumber: %s\n", data->callNumber);
977 if (data->shelvingData)
978 printf ("shelvingData: %s\n", data->shelvingData);
979 if (data->copyNumber)
980 printf ("copyNumber: %s\n", data->copyNumber);
981 if (data->publicNote)
982 printf ("publicNote: %s\n", data->publicNote);
983 if (data->reproductionNote)
984 printf ("reproductionNote: %s\n", data->reproductionNote);
985 if (data->termsUseRepro)
986 printf ("termsUseRepro: %s\n", data->termsUseRepro);
987 if (data->enumAndChron)
988 printf ("enumAndChron: %s\n", data->enumAndChron);
989 for (j = 0; j<data->num_volumes; j++)
991 printf ("volume %d\n", j);
992 if (data->volumes[j]->enumeration)
993 printf (" enumeration: %s\n",
994 data->volumes[j]->enumeration);
995 if (data->volumes[j]->chronology)
996 printf (" chronology: %s\n",
997 data->volumes[j]->chronology);
998 if (data->volumes[j]->enumAndChron)
999 printf (" enumAndChron: %s\n",
1000 data->volumes[j]->enumAndChron);
1002 for (j = 0; j<data->num_circulationData; j++)
1004 printf ("circulation %d\n", j);
1005 if (data->circulationData[j]->availableNow)
1006 printf (" availableNow: %d\n",
1007 *data->circulationData[j]->availableNow);
1008 if (data->circulationData[j]->availablityDate)
1009 printf (" availabiltyDate: %s\n",
1010 data->circulationData[j]->availablityDate);
1011 if (data->circulationData[j]->availableThru)
1012 printf (" availableThru: %s\n",
1013 data->circulationData[j]->availableThru);
1014 if (data->circulationData[j]->restrictions)
1015 printf (" restrictions: %s\n",
1016 data->circulationData[j]->restrictions);
1017 if (data->circulationData[j]->itemId)
1018 printf (" itemId: %s\n",
1019 data->circulationData[j]->itemId);
1020 if (data->circulationData[j]->renewable)
1021 printf (" renewable: %d\n",
1022 *data->circulationData[j]->renewable);
1023 if (data->circulationData[j]->onHold)
1024 printf (" onHold: %d\n",
1025 *data->circulationData[j]->onHold);
1026 if (data->circulationData[j]->enumAndChron)
1027 printf (" enumAndChron: %s\n",
1028 data->circulationData[j]->enumAndChron);
1029 if (data->circulationData[j]->midspine)
1030 printf (" midspine: %s\n",
1031 data->circulationData[j]->midspine);
1032 if (data->circulationData[j]->temporaryLocation)
1033 printf (" temporaryLocation: %s\n",
1034 data->circulationData[j]->temporaryLocation);
1041 printf("Unknown record representation.\n");
1042 if (!z_External(print, &r, 0, 0))
1044 odr_perror(print, "Printing external");
1050 static void display_diagrecs(Z_DiagRec **pp, int num)
1054 Z_DefaultDiagFormat *r;
1056 printf("Diagnostic message(s) from database:\n");
1057 for (i = 0; i<num; i++)
1059 Z_DiagRec *p = pp[i];
1060 if (p->which != Z_DiagRec_defaultFormat)
1062 printf("Diagnostic record not in default format.\n");
1066 r = p->u.defaultFormat;
1067 if (!(ent = oid_getentbyoid(r->diagnosticSetId)) ||
1068 ent->oclass != CLASS_DIAGSET || ent->value != VAL_BIB1)
1069 printf("Missing or unknown diagset\n");
1070 printf(" [%d] %s", *r->condition, diagbib1_str(*r->condition));
1073 case Z_DefaultDiagFormat_v2Addinfo:
1074 printf (" -- v2 addinfo '%s'\n", r->u.v2Addinfo);
1076 case Z_DefaultDiagFormat_v3Addinfo:
1077 printf (" -- v3 addinfo '%s'\n", r->u.v3Addinfo);
1084 static void display_nameplusrecord(Z_NamePlusRecord *p)
1086 if (p->databaseName)
1087 printf("[%s]", p->databaseName);
1088 if (p->which == Z_NamePlusRecord_surrogateDiagnostic)
1089 display_diagrecs(&p->u.surrogateDiagnostic, 1);
1090 else if (p->which == Z_NamePlusRecord_databaseRecord)
1091 display_record(p->u.databaseRecord);
1094 static void display_records(Z_Records *p)
1098 if (p->which == Z_Records_NSD)
1100 Z_DiagRec dr, *dr_p = &dr;
1101 dr.which = Z_DiagRec_defaultFormat;
1102 dr.u.defaultFormat = p->u.nonSurrogateDiagnostic;
1103 display_diagrecs (&dr_p, 1);
1105 else if (p->which == Z_Records_multipleNSD)
1106 display_diagrecs (p->u.multipleNonSurDiagnostics->diagRecs,
1107 p->u.multipleNonSurDiagnostics->num_diagRecs);
1110 printf("Records: %d\n", p->u.databaseOrSurDiagnostics->num_records);
1111 for (i = 0; i < p->u.databaseOrSurDiagnostics->num_records; i++)
1112 display_nameplusrecord(p->u.databaseOrSurDiagnostics->records[i]);
1116 static int send_deleteResultSetRequest(const char *arg)
1121 Z_APDU *apdu = zget_APDU(out, Z_APDU_deleteResultSetRequest);
1122 Z_DeleteResultSetRequest *req = apdu->u.deleteResultSetRequest;
1124 req->referenceId = set_refid (out);
1126 req->num_resultSetList =
1127 sscanf (arg, "%30s %30s %30s %30s %30s %30s %30s %30s",
1128 names[0], names[1], names[2], names[3],
1129 names[4], names[5], names[6], names[7]);
1131 req->deleteFunction = (int *)
1132 odr_malloc (out, sizeof(*req->deleteFunction));
1133 if (req->num_resultSetList > 0)
1135 *req->deleteFunction = Z_DeleteResultSetRequest_list;
1136 req->resultSetList = (char **)
1137 odr_malloc (out, sizeof(*req->resultSetList)*
1138 req->num_resultSetList);
1139 for (i = 0; i<req->num_resultSetList; i++)
1140 req->resultSetList[i] = names[i];
1144 *req->deleteFunction = Z_DeleteResultSetRequest_all;
1145 req->resultSetList = 0;
1149 printf("Sent deleteResultSetRequest.\n");
1154 static int send_srw(Z_SRW_PDU *sr)
1156 const char *charset = negotiationCharset;
1157 const char *host_port = cur_host;
1160 Z_SOAP_Handler h[2] = {
1161 {"http://www.loc.gov/zing/srw/", 0, (Z_SOAP_fun) yaz_srw_codec},
1164 ODR o = odr_createmem(ODR_ENCODE);
1166 Z_SOAP *p = odr_malloc(o, sizeof(*p));
1169 path = odr_malloc(out, strlen(databaseNames[0])+2);
1171 strcpy(path+1, databaseNames[0]);
1173 gdu = z_get_HTTP_Request(out);
1174 gdu->u.HTTP_Request->version = http_version;
1175 gdu->u.HTTP_Request->path = odr_strdup(out, path);
1179 const char *cp0 = strstr(host_port, "://");
1180 const char *cp1 = 0;
1186 cp1 = strchr(cp0, '/');
1188 cp1 = cp0+strlen(cp0);
1192 char *h = odr_malloc(out, cp1 - cp0 + 1);
1193 memcpy (h, cp0, cp1 - cp0);
1195 z_HTTP_header_add(out, &gdu->u.HTTP_Request->headers,
1200 strcpy(ctype, "text/xml");
1201 if (charset && strlen(charset) < 20)
1203 strcat(ctype, "; charset=");
1204 strcat(ctype, charset);
1206 z_HTTP_header_add(out, &gdu->u.HTTP_Request->headers,
1207 "Content-Type", ctype);
1208 z_HTTP_header_add(out, &gdu->u.HTTP_Request->headers,
1209 "SOAPAction", "\"\"");
1210 p->which = Z_SOAP_generic;
1211 p->u.generic = odr_malloc(o, sizeof(*p->u.generic));
1212 p->u.generic->no = 0;
1213 p->u.generic->ns = 0;
1214 p->u.generic->p = sr;
1215 p->ns = "http://schemas.xmlsoap.org/soap/envelope/";
1217 ret = z_soap_codec_enc(o, &p,
1218 &gdu->u.HTTP_Request->content_buf,
1219 &gdu->u.HTTP_Request->content_len, h,
1222 if (z_GDU(out, &gdu, 0, 0))
1230 if (!z_GDU(print, &gdu, 0, 0))
1231 printf ("Failed to print outgoing APDU\n");
1234 buf_out = odr_getbuf(out, &len_out, 0);
1236 /* we don't odr_reset(out), since we may need the buffer again */
1238 do_hex_dump(buf_out, len_out);
1240 r = cs_put(conn, buf_out, len_out);
1252 static int send_SRW_searchRequest(const char *arg)
1258 assert(srw_sr_odr_out == 0);
1259 srw_sr_odr_out = odr_createmem(ODR_ENCODE);
1261 odr_reset(srw_sr_odr_out);
1265 /* save this for later .. when fetching individual records */
1266 srw_sr = yaz_srw_get(srw_sr_odr_out, Z_SRW_searchRetrieve_request);
1268 /* regular request .. */
1269 sr = yaz_srw_get(out, Z_SRW_searchRetrieve_request);
1274 srw_sr->u.request->query_type = Z_SRW_query_type_cql;
1275 srw_sr->u.request->query.cql = odr_strdup(srw_sr_odr_out, arg);
1277 sr->u.request->query_type = Z_SRW_query_type_cql;
1278 sr->u.request->query.cql = odr_strdup(out, arg);
1280 case QueryType_Prefix:
1281 srw_sr->u.request->query_type = Z_SRW_query_type_pqf;
1282 srw_sr->u.request->query.pqf = odr_strdup(srw_sr_odr_out, arg);
1284 sr->u.request->query_type = Z_SRW_query_type_pqf;
1285 sr->u.request->query.pqf = odr_strdup(out, arg);
1288 printf ("Only CQL and PQF supported in SRW\n");
1291 sr->u.request->maximumRecords = odr_intdup(out, 0);
1294 sr->u.request->recordSchema = record_schema;
1295 if (recordsyntax == VAL_TEXT_XML)
1296 sr->u.explain_request->recordPacking = "xml";
1297 return send_srw(sr);
1301 static int send_searchRequest(const char *arg)
1303 Z_APDU *apdu = zget_APDU(out, Z_APDU_searchRequest);
1304 Z_SearchRequest *req = apdu->u.searchRequest;
1306 struct ccl_rpn_node *rpn = NULL;
1308 char setstring[100];
1309 Z_RPNQuery *RPNquery;
1311 YAZ_PQF_Parser pqf_parser;
1313 QueryType myQueryType = queryType;
1316 if (myQueryType == QueryType_CCL2RPN)
1318 rpn = ccl_find_str(bibset, arg, &error, &pos);
1321 printf("CCL ERROR: %s\n", ccl_err_msg(error));
1324 } else if (myQueryType == QueryType_CQL2RPN) {
1325 /* ### All this code should be wrapped in a utility function */
1327 struct cql_node *node;
1328 const char *addinfo;
1329 if (cqltrans == 0) {
1330 printf("Can't use CQL: no translation file. Try set_cqlfile\n");
1333 parser = cql_parser_create();
1334 if ((error = cql_parser_string(parser, arg)) != 0) {
1335 printf("Can't parse CQL: must be a syntax error\n");
1338 node = cql_parser_result(parser);
1339 if ((error = cql_transform_buf(cqltrans, node, pqfbuf,
1340 sizeof pqfbuf)) != 0) {
1341 error = cql_transform_error(cqltrans, &addinfo);
1342 printf ("Can't convert CQL to PQF: %s (addinfo=%s)\n",
1343 cql_strerror(error), addinfo);
1347 myQueryType = QueryType_Prefix;
1350 req->referenceId = set_refid (out);
1351 if (!strcmp(arg, "@big")) /* strictly for troublemaking */
1353 static unsigned char big[2100];
1354 static Odr_oct bigo;
1356 /* send a very big referenceid to test transport stack etc. */
1357 memset(big, 'A', 2100);
1358 bigo.len = bigo.size = 2100;
1360 req->referenceId = &bigo;
1365 sprintf(setstring, "%d", ++setnumber);
1366 req->resultSetName = setstring;
1368 *req->smallSetUpperBound = smallSetUpperBound;
1369 *req->largeSetLowerBound = largeSetLowerBound;
1370 *req->mediumSetPresentNumber = mediumSetPresentNumber;
1371 if (smallSetUpperBound > 0 || (largeSetLowerBound > 1 &&
1372 mediumSetPresentNumber > 0))
1374 req->preferredRecordSyntax =
1375 yaz_oidval_to_z3950oid(out, CLASS_RECSYN, recordsyntax);
1377 req->smallSetElementSetNames =
1378 req->mediumSetElementSetNames = elementSetNames;
1380 req->num_databaseNames = num_databaseNames;
1381 req->databaseNames = databaseNames;
1383 req->query = &query;
1385 switch (myQueryType)
1387 case QueryType_Prefix:
1388 query.which = Z_Query_type_1;
1389 pqf_parser = yaz_pqf_create ();
1390 RPNquery = yaz_pqf_parse (pqf_parser, out, arg);
1393 const char *pqf_msg;
1395 int code = yaz_pqf_error (pqf_parser, &pqf_msg, &off);
1396 printf("%*s^\n", off+4, "");
1397 printf("Prefix query error: %s (code %d)\n", pqf_msg, code);
1399 yaz_pqf_destroy (pqf_parser);
1402 yaz_pqf_destroy (pqf_parser);
1403 query.u.type_1 = RPNquery;
1406 query.which = Z_Query_type_2;
1407 query.u.type_2 = &ccl_query;
1408 ccl_query.buf = (unsigned char*) arg;
1409 ccl_query.len = strlen(arg);
1411 case QueryType_CCL2RPN:
1412 query.which = Z_Query_type_1;
1413 RPNquery = ccl_rpn_query(out, rpn);
1416 printf ("Couldn't convert from CCL to RPN\n");
1419 query.u.type_1 = RPNquery;
1420 ccl_rpn_delete (rpn);
1423 query.which = Z_Query_type_104;
1424 ext = (Z_External *) odr_malloc(out, sizeof(*ext));
1425 ext->direct_reference = odr_getoidbystr(out, "1.2.840.10003.16.2");
1426 ext->indirect_reference = 0;
1427 ext->descriptor = 0;
1428 ext->which = Z_External_CQL;
1429 ext->u.cql = odr_strdup(out, arg);
1430 query.u.type_104 = ext;
1433 printf ("Unsupported query type\n");
1436 if (send_apdu(apdu))
1437 printf("Sent searchRequest.\n");
1442 /* display Query Expression as part of searchResult-1 */
1443 static void display_queryExpression (Z_QueryExpression *qe)
1447 if (qe->which == Z_QueryExpression_term)
1449 if (qe->u.term->queryTerm)
1451 Z_Term *term = qe->u.term->queryTerm;
1452 switch (term->which)
1454 case Z_Term_general:
1455 printf (" %.*s", term->u.general->len, term->u.general->buf);
1457 case Z_Term_characterString:
1458 printf (" %s", term->u.characterString);
1460 case Z_Term_numeric:
1461 printf (" %d", *term->u.numeric);
1471 /* see if we can find USR:SearchResult-1 */
1472 static void display_searchResult (Z_OtherInformation *o)
1477 for (i = 0; i < o->num_elements; i++)
1479 if (o->list[i]->which == Z_OtherInfo_externallyDefinedInfo)
1481 Z_External *ext = o->list[i]->information.externallyDefinedInfo;
1483 if (ext->which == Z_External_searchResult1)
1486 Z_SearchInfoReport *sr = ext->u.searchResult1;
1487 printf ("SearchResult-1:");
1488 for (j = 0; j < sr->num; j++)
1490 if (!sr->elements[j]->subqueryExpression)
1492 display_queryExpression (
1493 sr->elements[j]->subqueryExpression);
1494 display_queryExpression (
1495 sr->elements[j]->subqueryInterpretation);
1496 display_queryExpression (
1497 sr->elements[j]->subqueryRecommendation);
1498 if (sr->elements[j]->subqueryCount)
1499 printf ("(%d)", *sr->elements[j]->subqueryCount);
1507 static int process_searchResponse(Z_SearchResponse *res)
1509 printf ("Received SearchResponse.\n");
1510 print_refid (res->referenceId);
1511 if (*res->searchStatus)
1512 printf("Search was a success.\n");
1514 printf("Search was a bloomin' failure.\n");
1515 printf("Number of hits: %d", *res->resultCount);
1517 printf (", setno %d", setnumber);
1519 display_searchResult (res->additionalSearchInfo);
1520 printf("records returned: %d\n",
1521 *res->numberOfRecordsReturned);
1522 setno += *res->numberOfRecordsReturned;
1524 display_records(res->records);
1528 static void print_level(int iLevel)
1531 for (i = 0; i < iLevel * 4; i++)
1535 static void print_int(int iLevel, const char *pTag, int *pInt)
1539 print_level(iLevel);
1540 printf("%s: %d\n", pTag, *pInt);
1544 static void print_string(int iLevel, const char *pTag, const char *pString)
1546 if (pString != NULL)
1548 print_level(iLevel);
1549 printf("%s: %s\n", pTag, pString);
1553 static void print_oid(int iLevel, const char *pTag, Odr_oid *pOid)
1559 print_level(iLevel);
1560 printf("%s:", pTag);
1561 for (; *pInt != -1; pInt++)
1562 printf(" %d", *pInt);
1567 static void print_referenceId(int iLevel, Z_ReferenceId *referenceId)
1569 if (referenceId != NULL)
1573 print_level(iLevel);
1574 printf("Ref Id (%d, %d): ", referenceId->len, referenceId->size);
1575 for (i = 0; i < referenceId->len; i++)
1576 printf("%c", referenceId->buf[i]);
1581 static void print_string_or_numeric(int iLevel, const char *pTag, Z_StringOrNumeric *pStringNumeric)
1583 if (pStringNumeric != NULL)
1585 switch (pStringNumeric->which)
1587 case Z_StringOrNumeric_string:
1588 print_string(iLevel, pTag, pStringNumeric->u.string);
1591 case Z_StringOrNumeric_numeric:
1592 print_int(iLevel, pTag, pStringNumeric->u.numeric);
1596 print_level(iLevel);
1597 printf("%s: valid type for Z_StringOrNumeric\n", pTag);
1603 static void print_universe_report_duplicate(
1605 Z_UniverseReportDuplicate *pUniverseReportDuplicate)
1607 if (pUniverseReportDuplicate != NULL)
1609 print_level(iLevel);
1610 printf("Universe Report Duplicate: \n");
1612 print_string_or_numeric(iLevel, "Hit No",
1613 pUniverseReportDuplicate->hitno);
1617 static void print_universe_report_hits(
1619 Z_UniverseReportHits *pUniverseReportHits)
1621 if (pUniverseReportHits != NULL)
1623 print_level(iLevel);
1624 printf("Universe Report Hits: \n");
1626 print_string_or_numeric(iLevel, "Database",
1627 pUniverseReportHits->database);
1628 print_string_or_numeric(iLevel, "Hits", pUniverseReportHits->hits);
1632 static void print_universe_report(int iLevel, Z_UniverseReport *pUniverseReport)
1634 if (pUniverseReport != NULL)
1636 print_level(iLevel);
1637 printf("Universe Report: \n");
1639 print_int(iLevel, "Total Hits", pUniverseReport->totalHits);
1640 switch (pUniverseReport->which)
1642 case Z_UniverseReport_databaseHits:
1643 print_universe_report_hits(iLevel,
1644 pUniverseReport->u.databaseHits);
1647 case Z_UniverseReport_duplicate:
1648 print_universe_report_duplicate(iLevel,
1649 pUniverseReport->u.duplicate);
1653 print_level(iLevel);
1654 printf("Type: %d\n", pUniverseReport->which);
1660 static void print_external(int iLevel, Z_External *pExternal)
1662 if (pExternal != NULL)
1664 print_level(iLevel);
1665 printf("External: \n");
1667 print_oid(iLevel, "Direct Reference", pExternal->direct_reference);
1668 print_int(iLevel, "InDirect Reference", pExternal->indirect_reference);
1669 print_string(iLevel, "Descriptor", pExternal->descriptor);
1670 switch (pExternal->which)
1672 case Z_External_universeReport:
1673 print_universe_report(iLevel, pExternal->u.universeReport);
1677 print_level(iLevel);
1678 printf("Type: %d\n", pExternal->which);
1684 static int process_resourceControlRequest (Z_ResourceControlRequest *req)
1686 printf ("Received ResourceControlRequest.\n");
1687 print_referenceId(1, req->referenceId);
1688 print_int(1, "Suspended Flag", req->suspendedFlag);
1689 print_int(1, "Partial Results Available", req->partialResultsAvailable);
1690 print_int(1, "Response Required", req->responseRequired);
1691 print_int(1, "Triggered Request Flag", req->triggeredRequestFlag);
1692 print_external(1, req->resourceReport);
1696 void process_ESResponse(Z_ExtendedServicesResponse *res)
1699 switch (*res->operationStatus)
1701 case Z_ExtendedServicesResponse_done:
1704 case Z_ExtendedServicesResponse_accepted:
1705 printf ("accepted\n");
1707 case Z_ExtendedServicesResponse_failure:
1708 printf ("failure\n");
1709 display_diagrecs(res->diagnostics, res->num_diagnostics);
1712 printf ("unknown\n");
1714 if ( (*res->operationStatus != Z_ExtendedServicesResponse_failure) &&
1715 (res->num_diagnostics != 0) ) {
1716 display_diagrecs(res->diagnostics, res->num_diagnostics);
1718 print_refid (res->referenceId);
1719 if (res->taskPackage &&
1720 res->taskPackage->which == Z_External_extendedService)
1722 Z_TaskPackage *taskPackage = res->taskPackage->u.extendedService;
1723 Odr_oct *id = taskPackage->targetReference;
1724 Z_External *ext = taskPackage->taskSpecificParameters;
1728 printf ("Target Reference: ");
1729 print_stringn (id->buf, id->len);
1732 if (ext->which == Z_External_update)
1734 Z_IUUpdateTaskPackage *utp = ext->u.update->u.taskPackage;
1735 if (utp && utp->targetPart)
1737 Z_IUTargetPart *targetPart = utp->targetPart;
1740 for (i = 0; i<targetPart->num_taskPackageRecords; i++)
1743 Z_IUTaskPackageRecordStructure *tpr =
1744 targetPart->taskPackageRecords[i];
1745 printf ("task package record %d\n", i+1);
1746 if (tpr->which == Z_IUTaskPackageRecordStructure_record)
1748 display_record (tpr->u.record);
1752 printf ("other type\n");
1760 const char *get_ill_element (void *clientData, const char *element)
1765 static Z_External *create_external_itemRequest()
1767 struct ill_get_ctl ctl;
1768 ILL_ItemRequest *req;
1770 int item_request_size = 0;
1771 char *item_request_buf = 0;
1775 ctl.f = get_ill_element;
1777 req = ill_get_ItemRequest(&ctl, "ill", 0);
1779 printf ("ill_get_ItemRequest failed\n");
1781 if (!ill_ItemRequest (out, &req, 0, 0))
1785 ill_ItemRequest(print, &req, 0, 0);
1788 item_request_buf = odr_getbuf (out, &item_request_size, 0);
1789 if (item_request_buf)
1790 odr_setbuf (out, item_request_buf, item_request_size, 1);
1791 printf ("Couldn't encode ItemRequest, size %d\n", item_request_size);
1798 item_request_buf = odr_getbuf (out, &item_request_size, 0);
1799 oid.proto = PROTO_GENERAL;
1800 oid.oclass = CLASS_GENERAL;
1801 oid.value = VAL_ISO_ILL_1;
1803 r = (Z_External *) odr_malloc (out, sizeof(*r));
1804 r->direct_reference = odr_oiddup(out,oid_getoidbyent(&oid));
1805 r->indirect_reference = 0;
1807 r->which = Z_External_single;
1809 r->u.single_ASN1_type = (Odr_oct *)
1810 odr_malloc (out, sizeof(*r->u.single_ASN1_type));
1811 r->u.single_ASN1_type->buf = (unsigned char *)
1812 odr_malloc (out, item_request_size);
1813 r->u.single_ASN1_type->len = item_request_size;
1814 r->u.single_ASN1_type->size = item_request_size;
1815 memcpy (r->u.single_ASN1_type->buf, item_request_buf,
1818 do_hex_dump(item_request_buf,item_request_size);
1823 static Z_External *create_external_ILL_APDU(int which)
1825 struct ill_get_ctl ctl;
1828 int ill_request_size = 0;
1829 char *ill_request_buf = 0;
1833 ctl.f = get_ill_element;
1835 ill_apdu = ill_get_APDU(&ctl, "ill", 0);
1837 if (!ill_APDU (out, &ill_apdu, 0, 0))
1841 printf ("-------------------\n");
1842 ill_APDU(print, &ill_apdu, 0, 0);
1844 printf ("-------------------\n");
1846 ill_request_buf = odr_getbuf (out, &ill_request_size, 0);
1847 if (ill_request_buf)
1848 odr_setbuf (out, ill_request_buf, ill_request_size, 1);
1849 printf ("Couldn't encode ILL-Request, size %d\n", ill_request_size);
1855 ill_request_buf = odr_getbuf (out, &ill_request_size, 0);
1857 oid.proto = PROTO_GENERAL;
1858 oid.oclass = CLASS_GENERAL;
1859 oid.value = VAL_ISO_ILL_1;
1861 r = (Z_External *) odr_malloc (out, sizeof(*r));
1862 r->direct_reference = odr_oiddup(out,oid_getoidbyent(&oid));
1863 r->indirect_reference = 0;
1865 r->which = Z_External_single;
1867 r->u.single_ASN1_type = (Odr_oct *)
1868 odr_malloc (out, sizeof(*r->u.single_ASN1_type));
1869 r->u.single_ASN1_type->buf = (unsigned char *)
1870 odr_malloc (out, ill_request_size);
1871 r->u.single_ASN1_type->len = ill_request_size;
1872 r->u.single_ASN1_type->size = ill_request_size;
1873 memcpy (r->u.single_ASN1_type->buf, ill_request_buf, ill_request_size);
1874 /* printf ("len = %d\n", ill_request_size); */
1875 /* do_hex_dump(ill_request_buf,ill_request_size); */
1876 /* printf("--- end of extenal\n"); */
1883 static Z_External *create_ItemOrderExternal(const char *type, int itemno)
1885 Z_External *r = (Z_External *) odr_malloc(out, sizeof(Z_External));
1886 oident ItemOrderRequest;
1888 ItemOrderRequest.proto = PROTO_Z3950;
1889 ItemOrderRequest.oclass = CLASS_EXTSERV;
1890 ItemOrderRequest.value = VAL_ITEMORDER;
1892 r->direct_reference = odr_oiddup(out,oid_getoidbyent(&ItemOrderRequest));
1893 r->indirect_reference = 0;
1896 r->which = Z_External_itemOrder;
1898 r->u.itemOrder = (Z_ItemOrder *) odr_malloc(out,sizeof(Z_ItemOrder));
1899 memset(r->u.itemOrder, 0, sizeof(Z_ItemOrder));
1900 r->u.itemOrder->which=Z_IOItemOrder_esRequest;
1902 r->u.itemOrder->u.esRequest = (Z_IORequest *)
1903 odr_malloc(out,sizeof(Z_IORequest));
1904 memset(r->u.itemOrder->u.esRequest, 0, sizeof(Z_IORequest));
1906 r->u.itemOrder->u.esRequest->toKeep = (Z_IOOriginPartToKeep *)
1907 odr_malloc(out,sizeof(Z_IOOriginPartToKeep));
1908 memset(r->u.itemOrder->u.esRequest->toKeep, 0, sizeof(Z_IOOriginPartToKeep));
1909 r->u.itemOrder->u.esRequest->notToKeep = (Z_IOOriginPartNotToKeep *)
1910 odr_malloc(out,sizeof(Z_IOOriginPartNotToKeep));
1911 memset(r->u.itemOrder->u.esRequest->notToKeep, 0, sizeof(Z_IOOriginPartNotToKeep));
1913 r->u.itemOrder->u.esRequest->toKeep->supplDescription = NULL;
1914 r->u.itemOrder->u.esRequest->toKeep->contact = NULL;
1915 r->u.itemOrder->u.esRequest->toKeep->addlBilling = NULL;
1917 r->u.itemOrder->u.esRequest->notToKeep->resultSetItem =
1918 (Z_IOResultSetItem *) odr_malloc(out, sizeof(Z_IOResultSetItem));
1919 memset(r->u.itemOrder->u.esRequest->notToKeep->resultSetItem, 0, sizeof(Z_IOResultSetItem));
1920 r->u.itemOrder->u.esRequest->notToKeep->resultSetItem->resultSetId = "1";
1922 r->u.itemOrder->u.esRequest->notToKeep->resultSetItem->item =
1923 (int *) odr_malloc(out, sizeof(int));
1924 *r->u.itemOrder->u.esRequest->notToKeep->resultSetItem->item = itemno;
1926 if (!strcmp (type, "item") || !strcmp(type, "2"))
1928 printf ("using item-request\n");
1929 r->u.itemOrder->u.esRequest->notToKeep->itemRequest =
1930 create_external_itemRequest();
1932 else if (!strcmp(type, "ill") || !strcmp(type, "1"))
1934 printf ("using ILL-request\n");
1935 r->u.itemOrder->u.esRequest->notToKeep->itemRequest =
1936 create_external_ILL_APDU(ILL_APDU_ILL_Request);
1938 else if (!strcmp(type, "xml") || !strcmp(type, "3"))
1940 const char *xml_buf =
1942 " <type>request</type>\n"
1943 " <libraryNo>000200</libraryNo>\n"
1944 " <borrowerTicketNo> 1212 </borrowerTicketNo>\n"
1946 r->u.itemOrder->u.esRequest->notToKeep->itemRequest =
1947 z_ext_record (out, VAL_TEXT_XML, xml_buf, strlen(xml_buf));
1950 r->u.itemOrder->u.esRequest->notToKeep->itemRequest = 0;
1955 static int send_itemorder(const char *type, int itemno)
1957 Z_APDU *apdu = zget_APDU(out, Z_APDU_extendedServicesRequest);
1958 Z_ExtendedServicesRequest *req = apdu->u.extendedServicesRequest;
1959 oident ItemOrderRequest;
1961 ItemOrderRequest.proto = PROTO_Z3950;
1962 ItemOrderRequest.oclass = CLASS_EXTSERV;
1963 ItemOrderRequest.value = VAL_ITEMORDER;
1964 req->packageType = odr_oiddup(out,oid_getoidbyent(&ItemOrderRequest));
1965 req->packageName = esPackageName;
1967 req->taskSpecificParameters = create_ItemOrderExternal(type, itemno);
1973 static int only_z3950()
1975 if (protocol == PROTO_HTTP)
1977 printf ("Not supported by SRW\n");
1983 static int cmd_update_common(const char *arg, int version);
1985 static int cmd_update(const char *arg)
1987 return cmd_update_common(arg, 1);
1990 static int cmd_update0(const char *arg)
1992 return cmd_update_common(arg, 0);
1995 static int cmd_update_common(const char *arg, int version)
1997 Z_APDU *apdu = zget_APDU(out, Z_APDU_extendedServicesRequest );
1998 Z_ExtendedServicesRequest *req = apdu->u.extendedServicesRequest;
2000 char action[20], recid[20], fname[80];
2002 Z_External *record_this = 0;
2009 sscanf (arg, "%19s %19s %79s", action, recid, fname);
2011 if (!strcmp (action, "insert"))
2012 action_no = Z_IUOriginPartToKeep_recordInsert;
2013 else if (!strcmp (action, "replace"))
2014 action_no = Z_IUOriginPartToKeep_recordReplace;
2015 else if (!strcmp (action, "delete"))
2016 action_no = Z_IUOriginPartToKeep_recordDelete;
2017 else if (!strcmp (action, "update"))
2018 action_no = Z_IUOriginPartToKeep_specialUpdate;
2021 printf ("Bad action: %s\n", action);
2022 printf ("Possible values: insert, replace, delete, update\n");
2030 stat (fname, &status);
2031 if (S_ISREG(status.st_mode) && (inf = fopen(fname, "r")))
2033 size_t len = status.st_size;
2034 char *buf = (char *) xmalloc (len);
2036 fread (buf, 1, len, inf);
2040 record_this = z_ext_record (out, VAL_TEXT_XML, buf, len);
2046 printf ("File %s doesn't exist\n", fname);
2054 printf ("No last record (update ignored)\n");
2057 record_this = record_last;
2061 yaz_oidval_to_z3950oid(out, CLASS_EXTSERV,
2062 version == 0 ? VAL_DBUPDATE0 : VAL_DBUPDATE);
2064 req->packageName = esPackageName;
2066 req->referenceId = set_refid (out);
2068 r = req->taskSpecificParameters = (Z_External *)
2069 odr_malloc (out, sizeof(*r));
2070 r->direct_reference = req->packageType;
2071 r->indirect_reference = 0;
2075 Z_IU0OriginPartToKeep *toKeep;
2076 Z_IU0SuppliedRecords *notToKeep;
2078 r->which = Z_External_update0;
2079 r->u.update0 = (Z_IU0Update *) odr_malloc(out, sizeof(*r->u.update0));
2080 r->u.update0->which = Z_IUUpdate_esRequest;
2081 r->u.update0->u.esRequest = (Z_IU0UpdateEsRequest *)
2082 odr_malloc(out, sizeof(*r->u.update0->u.esRequest));
2083 toKeep = r->u.update0->u.esRequest->toKeep = (Z_IU0OriginPartToKeep *)
2084 odr_malloc(out, sizeof(*r->u.update0->u.esRequest->toKeep));
2086 toKeep->databaseName = databaseNames[0];
2088 toKeep->elementSetName = 0;
2090 toKeep->action = (int *) odr_malloc(out, sizeof(*toKeep->action));
2091 *toKeep->action = action_no;
2093 notToKeep = r->u.update0->u.esRequest->notToKeep = (Z_IU0SuppliedRecords *)
2094 odr_malloc(out, sizeof(*r->u.update0->u.esRequest->notToKeep));
2096 notToKeep->elements = (Z_IU0SuppliedRecords_elem **)
2097 odr_malloc(out, sizeof(*notToKeep->elements));
2098 notToKeep->elements[0] = (Z_IU0SuppliedRecords_elem *)
2099 odr_malloc(out, sizeof(**notToKeep->elements));
2100 notToKeep->elements[0]->which = Z_IUSuppliedRecords_elem_opaque;
2103 notToKeep->elements[0]->u.opaque = (Odr_oct *)
2104 odr_malloc (out, sizeof(Odr_oct));
2105 notToKeep->elements[0]->u.opaque->buf = (unsigned char *) recid;
2106 notToKeep->elements[0]->u.opaque->size = strlen(recid);
2107 notToKeep->elements[0]->u.opaque->len = strlen(recid);
2110 notToKeep->elements[0]->u.opaque = 0;
2111 notToKeep->elements[0]->supplementalId = 0;
2112 notToKeep->elements[0]->correlationInfo = 0;
2113 notToKeep->elements[0]->record = record_this;
2117 Z_IUOriginPartToKeep *toKeep;
2118 Z_IUSuppliedRecords *notToKeep;
2120 r->which = Z_External_update;
2121 r->u.update = (Z_IUUpdate *) odr_malloc(out, sizeof(*r->u.update));
2122 r->u.update->which = Z_IUUpdate_esRequest;
2123 r->u.update->u.esRequest = (Z_IUUpdateEsRequest *)
2124 odr_malloc(out, sizeof(*r->u.update->u.esRequest));
2125 toKeep = r->u.update->u.esRequest->toKeep = (Z_IUOriginPartToKeep *)
2126 odr_malloc(out, sizeof(*r->u.update->u.esRequest->toKeep));
2128 toKeep->databaseName = databaseNames[0];
2130 toKeep->elementSetName = 0;
2131 toKeep->actionQualifier = 0;
2132 toKeep->action = (int *) odr_malloc(out, sizeof(*toKeep->action));
2133 *toKeep->action = action_no;
2135 notToKeep = r->u.update->u.esRequest->notToKeep = (Z_IUSuppliedRecords *)
2136 odr_malloc(out, sizeof(*r->u.update->u.esRequest->notToKeep));
2138 notToKeep->elements = (Z_IUSuppliedRecords_elem **)
2139 odr_malloc(out, sizeof(*notToKeep->elements));
2140 notToKeep->elements[0] = (Z_IUSuppliedRecords_elem *)
2141 odr_malloc(out, sizeof(**notToKeep->elements));
2142 notToKeep->elements[0]->which = Z_IUSuppliedRecords_elem_opaque;
2145 notToKeep->elements[0]->u.opaque = (Odr_oct *)
2146 odr_malloc (out, sizeof(Odr_oct));
2147 notToKeep->elements[0]->u.opaque->buf = (unsigned char *) recid;
2148 notToKeep->elements[0]->u.opaque->size = strlen(recid);
2149 notToKeep->elements[0]->u.opaque->len = strlen(recid);
2152 notToKeep->elements[0]->u.opaque = 0;
2153 notToKeep->elements[0]->supplementalId = 0;
2154 notToKeep->elements[0]->correlationInfo = 0;
2155 notToKeep->elements[0]->record = record_this;
2163 static int cmd_itemorder(const char *arg)
2170 if (sscanf (arg, "%10s %d", type, &itemno) != 2)
2173 printf("Item order request\n");
2175 send_itemorder(type, itemno);
2179 static void show_opt(const char *arg, void *clientData)
2181 printf ("%s ", arg);
2184 static int cmd_zversion(const char *arg)
2187 z3950_version = atoi(arg);
2189 printf ("version is %d\n", z3950_version);
2193 static int cmd_options(const char *arg)
2199 r = yaz_init_opt_encode(&z3950_options, arg, &pos);
2203 yaz_init_opt_decode(&z3950_options, show_opt, 0);
2209 static int cmd_explain(const char *arg)
2211 if (protocol != PROTO_HTTP)
2222 /* save this for later .. when fetching individual records */
2223 sr = yaz_srw_get(out, Z_SRW_explain_request);
2224 if (recordsyntax == VAL_TEXT_XML)
2225 sr->u.explain_request->recordPacking = "xml";
2233 static int cmd_init(const char *arg)
2235 if (!conn || protocol != PROTO_Z3950)
2237 send_initRequest(0);
2241 static int cmd_find(const char *arg)
2245 printf("Find what?\n");
2248 if (protocol == PROTO_HTTP)
2255 if (!send_SRW_searchRequest(arg))
2268 printf("Not connected yet\n");
2272 if (!send_searchRequest(arg))
2278 static int cmd_delete(const char *arg)
2282 printf("Not connected yet\n");
2287 if (!send_deleteResultSetRequest(arg))
2292 static int cmd_ssub(const char *arg)
2294 if (!(smallSetUpperBound = atoi(arg)))
2299 static int cmd_lslb(const char *arg)
2303 if (!(largeSetLowerBound = atoi(arg)))
2308 static int cmd_mspn(const char *arg)
2312 if (!(mediumSetPresentNumber = atoi(arg)))
2317 static int cmd_status(const char *arg)
2319 printf("smallSetUpperBound: %d\n", smallSetUpperBound);
2320 printf("largeSetLowerBound: %d\n", largeSetLowerBound);
2321 printf("mediumSetPresentNumber: %d\n", mediumSetPresentNumber);
2325 static int cmd_setnames(const char *arg)
2327 if (*arg == '1') /* enable ? */
2329 else if (*arg == '0') /* disable ? */
2331 else if (setnumber < 0) /* no args, toggle .. */
2337 printf("Set numbering enabled.\n");
2339 printf("Set numbering disabled.\n");
2343 /* PRESENT SERVICE ----------------------------- */
2345 static void parse_show_args(const char *arg_c, char *setstring,
2346 int *start, int *number)
2351 strncpy(arg, arg_c, sizeof(arg)-1);
2352 arg[sizeof(arg)-1] = '\0';
2354 if ((p = strchr(arg, '+')))
2356 *number = atoi(p + 1);
2361 if (p && (p=strchr(p+1, '+')))
2362 strcpy (setstring, p+1);
2363 else if (setnumber >= 0)
2364 sprintf(setstring, "%d", setnumber);
2369 static int send_presentRequest(const char *arg)
2371 Z_APDU *apdu = zget_APDU(out, Z_APDU_presentRequest);
2372 Z_PresentRequest *req = apdu->u.presentRequest;
2373 Z_RecordComposition compo;
2375 char setstring[100];
2377 req->referenceId = set_refid (out);
2379 parse_show_args(arg, setstring, &setno, &nos);
2381 req->resultSetId = setstring;
2383 req->resultSetStartPoint = &setno;
2384 req->numberOfRecordsRequested = &nos;
2386 req->preferredRecordSyntax =
2387 yaz_oidval_to_z3950oid(out, CLASS_RECSYN, recordsyntax);
2391 req->recordComposition = &compo;
2392 compo.which = Z_RecordComp_complex;
2393 compo.u.complex = (Z_CompSpec *)
2394 odr_malloc(out, sizeof(*compo.u.complex));
2395 compo.u.complex->selectAlternativeSyntax = (bool_t *)
2396 odr_malloc(out, sizeof(bool_t));
2397 *compo.u.complex->selectAlternativeSyntax = 0;
2399 compo.u.complex->generic = (Z_Specification *)
2400 odr_malloc(out, sizeof(*compo.u.complex->generic));
2401 compo.u.complex->generic->which = Z_Schema_oid;
2403 compo.u.complex->generic->schema.oid =
2404 yaz_str_to_z3950oid(out, CLASS_SCHEMA, record_schema);
2406 if (!compo.u.complex->generic->schema.oid)
2408 /* OID wasn't a schema! Try record syntax instead. */
2409 compo.u.complex->generic->schema.oid = (Odr_oid *)
2410 yaz_str_to_z3950oid(out, CLASS_RECSYN, record_schema);
2412 if (!elementSetNames)
2413 compo.u.complex->generic->elementSpec = 0;
2416 compo.u.complex->generic->elementSpec = (Z_ElementSpec *)
2417 odr_malloc(out, sizeof(Z_ElementSpec));
2418 compo.u.complex->generic->elementSpec->which =
2419 Z_ElementSpec_elementSetName;
2420 compo.u.complex->generic->elementSpec->u.elementSetName =
2421 elementSetNames->u.generic;
2423 compo.u.complex->num_dbSpecific = 0;
2424 compo.u.complex->dbSpecific = 0;
2425 compo.u.complex->num_recordSyntax = 0;
2426 compo.u.complex->recordSyntax = 0;
2428 else if (elementSetNames)
2430 req->recordComposition = &compo;
2431 compo.which = Z_RecordComp_simple;
2432 compo.u.simple = elementSetNames;
2435 printf("Sent presentRequest (%d+%d).\n", setno, nos);
2440 static int send_SRW_presentRequest(const char *arg)
2442 char setstring[100];
2444 Z_SRW_PDU *sr = srw_sr;
2448 parse_show_args(arg, setstring, &setno, &nos);
2449 sr->u.request->startRecord = odr_intdup(out, setno);
2450 sr->u.request->maximumRecords = odr_intdup(out, nos);
2452 sr->u.request->recordSchema = record_schema;
2453 if (recordsyntax == VAL_TEXT_XML)
2454 sr->u.request->recordPacking = "xml";
2455 return send_srw(sr);
2459 static void close_session (void)
2466 nmem_destroy (session_mem);
2475 void process_close(Z_Close *req)
2477 Z_APDU *apdu = zget_APDU(out, Z_APDU_close);
2478 Z_Close *res = apdu->u.close;
2480 static char *reasons[] =
2485 "cost limit reached",
2487 "security violation",
2494 printf("Reason: %s, message: %s\n", reasons[*req->closeReason],
2495 req->diagnosticInformation ? req->diagnosticInformation : "NULL");
2500 *res->closeReason = Z_Close_finished;
2502 printf("Sent response.\n");
2507 static int cmd_show(const char *arg)
2509 if (protocol == PROTO_HTTP)
2516 if (!send_SRW_presentRequest(arg))
2526 printf("Not connected yet\n");
2529 if (!send_presentRequest(arg))
2535 int cmd_quit(const char *arg)
2537 printf("See you later, alligator.\n");
2543 int cmd_cancel(const char *arg)
2545 Z_APDU *apdu = zget_APDU(out, Z_APDU_triggerResourceControlRequest);
2546 Z_TriggerResourceControlRequest *req =
2547 apdu->u.triggerResourceControlRequest;
2552 printf("Session not initialized yet\n");
2557 if (!ODR_MASK_GET(session->options, Z_Options_triggerResourceCtrl))
2559 printf("Target doesn't support cancel (trigger resource ctrl)\n");
2562 *req->requestedAction = Z_TriggerResourceControlRequest_cancel;
2563 req->resultSetWanted = &rfalse;
2564 req->referenceId = set_refid (out);
2567 printf("Sent cancel request\n");
2572 int cmd_cancel_find(const char *arg) {
2576 return cmd_cancel("");
2581 int send_scanrequest(const char *query, int pp, int num, const char *term)
2583 Z_APDU *apdu = zget_APDU(out, Z_APDU_scanRequest);
2584 Z_ScanRequest *req = apdu->u.scanRequest;
2588 if (queryType == QueryType_CCL2RPN)
2591 struct ccl_rpn_node *rpn;
2593 rpn = ccl_find_str (bibset, query, &error, &pos);
2596 printf("CCL ERROR: %s\n", ccl_err_msg(error));
2600 yaz_oidval_to_z3950oid(out, CLASS_ATTSET, VAL_BIB1);
2601 if (!(req->termListAndStartPoint = ccl_scan_query (out, rpn)))
2603 printf("Couldn't convert CCL to Scan term\n");
2606 ccl_rpn_delete (rpn);
2610 YAZ_PQF_Parser pqf_parser = yaz_pqf_create ();
2612 if (!(req->termListAndStartPoint =
2613 yaz_pqf_scan(pqf_parser, out, &req->attributeSet, query)))
2615 const char *pqf_msg;
2617 int code = yaz_pqf_error (pqf_parser, &pqf_msg, &off);
2618 printf("%*s^\n", off+7, "");
2619 printf("Prefix query error: %s (code %d)\n", pqf_msg, code);
2620 yaz_pqf_destroy (pqf_parser);
2623 yaz_pqf_destroy (pqf_parser);
2627 if (req->termListAndStartPoint->term &&
2628 req->termListAndStartPoint->term->which == Z_Term_general &&
2629 req->termListAndStartPoint->term->u.general)
2631 req->termListAndStartPoint->term->u.general->buf =
2632 (unsigned char *) odr_strdup(out, term);
2633 req->termListAndStartPoint->term->u.general->len =
2634 req->termListAndStartPoint->term->u.general->size =
2638 req->referenceId = set_refid (out);
2639 req->num_databaseNames = num_databaseNames;
2640 req->databaseNames = databaseNames;
2641 req->numberOfTermsRequested = #
2642 req->preferredPositionInResponse = &pp;
2643 req->stepSize = odr_intdup(out, scan_stepSize);
2648 int send_sortrequest(const char *arg, int newset)
2650 Z_APDU *apdu = zget_APDU(out, Z_APDU_sortRequest);
2651 Z_SortRequest *req = apdu->u.sortRequest;
2652 Z_SortKeySpecList *sksl = (Z_SortKeySpecList *)
2653 odr_malloc (out, sizeof(*sksl));
2659 sprintf (setstring, "%d", setnumber);
2661 sprintf (setstring, "default");
2663 req->referenceId = set_refid (out);
2665 req->num_inputResultSetNames = 1;
2666 req->inputResultSetNames = (Z_InternationalString **)
2667 odr_malloc (out, sizeof(*req->inputResultSetNames));
2668 req->inputResultSetNames[0] = odr_strdup (out, setstring);
2670 if (newset && setnumber >= 0)
2671 sprintf (setstring, "%d", ++setnumber);
2673 req->sortedResultSetName = odr_strdup (out, setstring);
2675 req->sortSequence = yaz_sort_spec (out, arg);
2676 if (!req->sortSequence)
2678 printf ("Missing sort specifications\n");
2685 void display_term(Z_TermInfo *t)
2688 printf("%s", t->displayTerm);
2689 else if (t->term->which == Z_Term_general)
2691 printf("%.*s", t->term->u.general->len, t->term->u.general->buf);
2692 sprintf(last_scan_line, "%.*s", t->term->u.general->len,
2693 t->term->u.general->buf);
2696 printf("Term (not general)");
2697 if (t->globalOccurrences)
2698 printf (" (%d)\n", *t->globalOccurrences);
2703 void process_scanResponse(Z_ScanResponse *res)
2706 Z_Entry **entries = NULL;
2707 int num_entries = 0;
2709 printf("Received ScanResponse\n");
2710 print_refid (res->referenceId);
2711 printf("%d entries", *res->numberOfEntriesReturned);
2712 if (res->positionOfTerm)
2713 printf (", position=%d", *res->positionOfTerm);
2715 if (*res->scanStatus != Z_Scan_success)
2716 printf("Scan returned code %d\n", *res->scanStatus);
2719 if ((entries = res->entries->entries))
2720 num_entries = res->entries->num_entries;
2721 for (i = 0; i < num_entries; i++)
2723 int pos_term = res->positionOfTerm ? *res->positionOfTerm : -1;
2724 if (entries[i]->which == Z_Entry_termInfo)
2726 printf("%c ", i + 1 == pos_term ? '*' : ' ');
2727 display_term(entries[i]->u.termInfo);
2730 display_diagrecs(&entries[i]->u.surrogateDiagnostic, 1);
2732 if (res->entries->nonsurrogateDiagnostics)
2733 display_diagrecs (res->entries->nonsurrogateDiagnostics,
2734 res->entries->num_nonsurrogateDiagnostics);
2737 void process_sortResponse(Z_SortResponse *res)
2739 printf("Received SortResponse: status=");
2740 switch (*res->sortStatus)
2742 case Z_SortResponse_success:
2743 printf ("success"); break;
2744 case Z_SortResponse_partial_1:
2745 printf ("partial"); break;
2746 case Z_SortResponse_failure:
2747 printf ("failure"); break;
2749 printf ("unknown (%d)", *res->sortStatus);
2752 print_refid (res->referenceId);
2753 if (res->diagnostics)
2754 display_diagrecs(res->diagnostics,
2755 res->num_diagnostics);
2758 void process_deleteResultSetResponse (Z_DeleteResultSetResponse *res)
2760 printf("Got deleteResultSetResponse status=%d\n",
2761 *res->deleteOperationStatus);
2762 if (res->deleteListStatuses)
2765 for (i = 0; i < res->deleteListStatuses->num; i++)
2767 printf ("%s status=%d\n", res->deleteListStatuses->elements[i]->id,
2768 *res->deleteListStatuses->elements[i]->status);
2773 int cmd_sort_generic(const char *arg, int newset)
2777 printf("Session not initialized yet\n");
2782 if (!ODR_MASK_GET(session->options, Z_Options_sort))
2784 printf("Target doesn't support sort\n");
2789 if (send_sortrequest(arg, newset) < 0)
2796 int cmd_sort(const char *arg)
2798 return cmd_sort_generic (arg, 0);
2801 int cmd_sort_newset (const char *arg)
2803 return cmd_sort_generic (arg, 1);
2806 int cmd_scanstep(const char *arg)
2808 scan_stepSize = atoi(arg);
2812 int cmd_scanpos(const char *arg)
2814 int r = sscanf(arg, "%d", &scan_position);
2820 int cmd_scan(const char *arg)
2829 printf("Session not initialized yet\n");
2833 if (!ODR_MASK_GET(session->options, Z_Options_scan))
2835 printf("Target doesn't support scan\n");
2840 strcpy (last_scan_query, arg);
2841 if (send_scanrequest(arg, scan_position, 20, 0) < 0)
2846 if (send_scanrequest(last_scan_query, 1, 20, last_scan_line) < 0)
2852 int cmd_schema(const char *arg)
2854 xfree(record_schema);
2857 record_schema = xstrdup(arg);
2861 int cmd_format(const char *arg)
2866 printf("Usage: format <recordsyntax>\n");
2869 nsyntax = oid_getvalbyname (arg);
2870 if (strcmp(arg, "none") && nsyntax == VAL_NONE)
2872 printf ("unknown record syntax\n");
2875 recordsyntax = nsyntax;
2879 int cmd_elements(const char *arg)
2881 static Z_ElementSetNames esn;
2882 static char what[100];
2886 elementSetNames = 0;
2890 esn.which = Z_ElementSetNames_generic;
2891 esn.u.generic = what;
2892 elementSetNames = &esn;
2896 int cmd_attributeset(const char *arg)
2902 printf("Usage: attributeset <setname>\n");
2905 sscanf(arg, "%s", what);
2906 if (p_query_attset (what))
2908 printf("Unknown attribute set name\n");
2914 int cmd_querytype (const char *arg)
2916 if (!strcmp (arg, "ccl"))
2917 queryType = QueryType_CCL;
2918 else if (!strcmp (arg, "prefix") || !strcmp(arg, "rpn"))
2919 queryType = QueryType_Prefix;
2920 else if (!strcmp (arg, "ccl2rpn") || !strcmp (arg, "cclrpn"))
2921 queryType = QueryType_CCL2RPN;
2922 else if (!strcmp(arg, "cql"))
2923 queryType = QueryType_CQL;
2924 else if (!strcmp (arg, "cql2rpn") || !strcmp (arg, "cqlrpn"))
2925 queryType = QueryType_CQL2RPN;
2928 printf ("Querytype must be one of:\n");
2929 printf (" prefix - Prefix query\n");
2930 printf (" ccl - CCL query\n");
2931 printf (" ccl2rpn - CCL query converted to RPN\n");
2932 printf (" cql - CQL\n");
2933 printf (" cql2rpn - CQL query converted to RPN\n");
2939 int cmd_refid (const char *arg)
2944 refid = xstrdup (arg);
2948 int cmd_close(const char *arg)
2957 apdu = zget_APDU(out, Z_APDU_close);
2958 req = apdu->u.close;
2959 *req->closeReason = Z_Close_finished;
2961 printf("Sent close request.\n");
2966 int cmd_packagename(const char* arg)
2968 xfree (esPackageName);
2969 esPackageName = NULL;
2971 esPackageName = xstrdup(arg);
2975 int cmd_proxy(const char* arg)
2980 yazProxy = xstrdup (arg);
2984 int cmd_marccharset(const char *arg)
2989 if (sscanf(arg, "%29s", l1) < 1)
2991 xfree (marcCharset);
2993 if (strcmp(l1, "-"))
2994 marcCharset = xstrdup(l1);
2998 int cmd_charset(const char* arg)
3000 char l1[30], l2[30];
3003 if (sscanf(arg, "%29s %29s", l1, l2) < 1)
3005 printf("Current negotiation character set is `%s'\n",
3006 negotiationCharset ? negotiationCharset: "none");
3007 printf("Current output character set is `%s'\n",
3008 outputCharset ? outputCharset: "none");
3011 xfree (negotiationCharset);
3012 negotiationCharset = NULL;
3013 if (*l1 && strcmp(l1, "-"))
3015 negotiationCharset = xstrdup(l1);
3016 printf ("Character set negotiation : %s\n", negotiationCharset);
3019 printf ("Character set negotiation disabled\n");
3022 xfree (outputCharset);
3024 if (!strcmp(l2, "auto") && codeset)
3028 printf ("output charset: %s\n", codeset);
3029 outputCharset = xstrdup(codeset);
3034 printf ("No codeset found on this system\n");
3036 else if (strcmp(l2, "-"))
3037 outputCharset = xstrdup(l2);
3039 printf ("Output charset conversion disabled\n");
3045 int cmd_lang(const char* arg)
3048 printf("Current language is `%s'\n", (yazLang)?yazLang:NULL);
3054 yazLang = xstrdup(arg);
3058 int cmd_source(const char* arg, int echo )
3060 /* first should open the file and read one line at a time.. */
3062 char line[102400], *cp;
3065 fprintf(stderr,"Error in source command use a filename\n");
3069 includeFile = fopen (arg, "r");
3072 fprintf(stderr,"Unable to open file %s for reading\n",arg);
3076 while(!feof(includeFile)) {
3077 memset(line,0,sizeof(line));
3078 fgets(line,sizeof(line),includeFile);
3080 if(strlen(line) < 2) continue;
3081 if(line[0] == '#') continue;
3083 if ((cp = strrchr (line, '\n')))
3087 printf( "processing line: %s\n",line );
3089 process_cmd_line(line);
3092 if(fclose(includeFile)<0) {
3093 perror("unable to close include file");
3099 int cmd_source_echo(const char* arg) {
3100 cmd_source( arg, 1);
3103 int cmd_source_noecho(const char* arg) {
3104 cmd_source( arg, 0 );
3108 int cmd_subshell(const char* args)
3113 system(getenv("SHELL"));
3119 int cmd_set_berfile(const char *arg)
3121 if (ber_file && ber_file != stdout && ber_file != stderr)
3123 if (!strcmp(arg, ""))
3125 else if (!strcmp(arg, "-"))
3128 ber_file = fopen(arg, "a");
3132 int cmd_set_apdufile(const char *arg)
3134 if(apdu_file && apdu_file != stderr && apdu_file != stderr)
3136 if (!strcmp(arg, ""))
3138 else if (!strcmp(arg, "-"))
3142 apdu_file = fopen(arg, "a");
3144 perror("unable to open apdu log file");
3147 odr_setprint(print, apdu_file);
3151 int cmd_set_cclfile(const char* arg)
3155 bibset = ccl_qual_mk ();
3156 inf = fopen (arg, "r");
3158 perror("unable to open CCL file");
3161 ccl_qual_file (bibset, inf);
3164 strcpy(ccl_fields,arg);
3168 int cmd_set_cqlfile(const char* arg)
3170 cql_transform_t newcqltrans;
3172 if ((newcqltrans = cql_transform_open_fname(arg)) == 0) {
3173 perror("unable to open CQL file");
3177 cql_transform_close(cqltrans);
3179 cqltrans = newcqltrans;
3180 strcpy(cql_fields, arg);
3184 int cmd_set_auto_reconnect(const char* arg)
3186 if(strlen(arg)==0) {
3187 auto_reconnect = ! auto_reconnect;
3188 } else if(strcmp(arg,"on")==0) {
3190 } else if(strcmp(arg,"off")==0) {
3193 printf("Error use on or off\n");
3198 printf("Set auto reconnect enabled.\n");
3200 printf("Set auto reconnect disabled.\n");
3205 int cmd_set_marcdump(const char* arg)
3207 if(marc_file && marc_file != stderr) { /* don't close stdout*/
3211 if (!strcmp(arg, ""))
3213 else if (!strcmp(arg, "-"))
3217 marc_file = fopen(arg, "a");
3219 perror("unable to open marc log file");
3225 this command takes 3 arge {name class oid}
3227 int cmd_register_oid(const char* args) {
3232 {"appctx",CLASS_APPCTX},
3233 {"absyn",CLASS_ABSYN},
3234 {"attset",CLASS_ATTSET},
3235 {"transyn",CLASS_TRANSYN},
3236 {"diagset",CLASS_DIAGSET},
3237 {"recsyn",CLASS_RECSYN},
3238 {"resform",CLASS_RESFORM},
3239 {"accform",CLASS_ACCFORM},
3240 {"extserv",CLASS_EXTSERV},
3241 {"userinfo",CLASS_USERINFO},
3242 {"elemspec",CLASS_ELEMSPEC},
3243 {"varset",CLASS_VARSET},
3244 {"schema",CLASS_SCHEMA},
3245 {"tagset",CLASS_TAGSET},
3246 {"general",CLASS_GENERAL},
3247 {0,(enum oid_class) 0}
3249 char oname_str[101], oclass_str[101], oid_str[101];
3252 oid_class oidclass = CLASS_GENERAL;
3253 int val = 0, oid[OID_SIZE];
3254 struct oident * new_oident=NULL;
3256 if (sscanf (args, "%100[^ ] %100[^ ] %100s",
3257 oname_str,oclass_str, oid_str) < 1) {
3258 printf("Error in register command \n");
3262 for (i = 0; oid_classes[i].className; i++) {
3263 if (!strcmp(oid_classes[i].className, oclass_str))
3265 oidclass=oid_classes[i].oclass;
3270 if(!(oid_classes[i].className)) {
3271 printf("Unknown oid class %s\n",oclass_str);
3279 while (isdigit (*(unsigned char *) name))
3281 val = val*10 + (*name - '0');
3294 new_oident = oid_addent (oid, PROTO_GENERAL, oidclass, oname_str,
3296 if(strcmp(new_oident->desc,oname_str))
3298 fprintf(stderr,"oid is already named as %s, registration failed\n",
3304 int cmd_push_command(const char* arg)
3306 #if HAVE_READLINE_HISTORY_H
3310 fprintf(stderr,"Not compiled with the readline/history module\n");
3315 void source_rcfile()
3317 /* Look for a $HOME/.yazclientrc and source it if it exists */
3318 struct stat statbuf;
3320 char* homedir=getenv("HOME");
3324 sprintf(buffer,"%s/.yazclientrc",homedir);
3326 if(stat(buffer,&statbuf)==0) {
3327 cmd_source(buffer, 0 );
3332 if(stat(".yazclientrc",&statbuf)==0) {
3333 cmd_source(".yazclientrc", 0 );
3338 static void initialize(void)
3343 if (!(out = odr_createmem(ODR_ENCODE)) ||
3344 !(in = odr_createmem(ODR_DECODE)) ||
3345 !(print = odr_createmem(ODR_PRINT)))
3347 fprintf(stderr, "failed to allocate ODR streams\n");
3352 setvbuf(stdout, 0, _IONBF, 0);
3354 odr_setprint(print, apdu_file);
3356 bibset = ccl_qual_mk ();
3357 inf = fopen (ccl_fields, "r");
3360 ccl_qual_file (bibset, inf);
3364 cqltrans = cql_transform_open_fname(cql_fields);
3365 /* If this fails, no problem: we detect cqltrans == 0 later */
3367 #if HAVE_READLINE_READLINE_H
3368 rl_attempted_completion_function = (CPPFunction*)readline_completer;
3372 for(i=0; i<maxOtherInfosSupported; ++i) {
3373 extraOtherInfos[i].oidval = -1;
3380 #if HAVE_GETTIMEOFDAY
3381 struct timeval tv_start, tv_end;
3385 static void handle_srw_record(Z_SRW_record *rec)
3387 if (rec->recordPosition)
3389 printf ("pos=%d", *rec->recordPosition);
3390 setno = *rec->recordPosition + 1;
3392 if (rec->recordSchema)
3393 printf (" schema=%s", rec->recordSchema);
3395 if (rec->recordData_buf && rec->recordData_len)
3397 fwrite(rec->recordData_buf, 1, rec->recordData_len, stdout);
3399 fwrite (rec->recordData_buf, 1, rec->recordData_len, marc_file);
3402 printf ("No data!");
3406 static void handle_srw_explain_response(Z_SRW_explainResponse *res)
3408 handle_srw_record(&res->record);
3411 static void handle_srw_response(Z_SRW_searchRetrieveResponse *res)
3415 printf ("Received SRW SearchRetrieve Response\n");
3417 for (i = 0; i<res->num_diagnostics; i++)
3419 if (res->diagnostics[i].uri)
3420 printf ("SRW diagnostic %s\n",
3421 res->diagnostics[i].uri);
3423 printf ("SRW diagnostic missing or could not be decoded\n");
3424 if (res->diagnostics[i].message)
3425 printf ("Message: %s\n", res->diagnostics[i].message);
3426 if (res->diagnostics[i].details)
3427 printf ("Details: %s\n", res->diagnostics[i].details);
3429 if (res->numberOfRecords)
3430 printf ("Number of hits: %d\n", *res->numberOfRecords);
3431 for (i = 0; i<res->num_records; i++)
3432 handle_srw_record(res->records + i);
3435 static void http_response(Z_HTTP_Response *hres)
3438 const char *content_type = z_HTTP_header_lookup(hres->headers,
3440 const char *connection_head = z_HTTP_header_lookup(hres->headers,
3442 if (content_type && !yaz_strcmp_del("text/xml", content_type, "; "))
3444 Z_SOAP *soap_package = 0;
3445 ODR o = odr_createmem(ODR_DECODE);
3446 Z_SOAP_Handler soap_handlers[2] = {
3447 {"http://www.loc.gov/zing/srw/", 0,
3448 (Z_SOAP_fun) yaz_srw_codec},
3451 ret = z_soap_codec(o, &soap_package,
3452 &hres->content_buf, &hres->content_len,
3454 if (!ret && soap_package->which == Z_SOAP_generic &&
3455 soap_package->u.generic->no == 0)
3457 Z_SRW_PDU *sr = soap_package->u.generic->p;
3458 if (sr->which == Z_SRW_searchRetrieve_response)
3459 handle_srw_response(sr->u.response);
3460 else if (sr->which == Z_SRW_explain_response)
3461 handle_srw_explain_response(sr->u.explain_response);
3465 else if (soap_package && (soap_package->which == Z_SOAP_fault
3466 || soap_package->which == Z_SOAP_error))
3468 printf ("HTTP Error Status=%d\n", hres->code);
3469 printf ("SOAP Fault code %s\n",
3470 soap_package->u.fault->fault_code);
3471 printf ("SOAP Fault string %s\n",
3472 soap_package->u.fault->fault_string);
3473 if (soap_package->u.fault->details)
3474 printf ("SOAP Details %s\n",
3475 soap_package->u.fault->details);
3483 if (hres->code != 200)
3485 printf ("HTTP Error Status=%d\n", hres->code);
3489 printf ("Decoding of SRW package failed\n");
3495 if (!strcmp(hres->version, "1.0"))
3497 /* HTTP 1.0: only if Keep-Alive we stay alive.. */
3498 if (!connection_head || strcmp(connection_head, "Keep-Alive"))
3503 /* HTTP 1.1: only if no close we stay alive .. */
3504 if (connection_head && !strcmp(connection_head, "close"))
3511 void wait_and_handle_response()
3513 int reconnect_ok = 1;
3516 int netbufferlen = 0;
3521 res = cs_get(conn, &netbuffer, &netbufferlen);
3522 if (reconnect_ok && res <= 0 && protocol == PROTO_HTTP)
3533 buf_out = odr_getbuf(out, &len_out, 0);
3535 do_hex_dump(buf_out, len_out);
3537 cs_put(conn, buf_out, len_out);
3545 printf("Target closed connection\n");
3550 odr_reset(in); /* release APDU from last round */
3552 do_hex_dump(netbuffer, res);
3553 odr_setbuf(in, netbuffer, res, 0);
3555 if (!z_GDU(in, &gdu, 0, 0))
3557 FILE *f = ber_file ? ber_file : stdout;
3558 odr_perror(in, "Decoding incoming APDU");
3559 fprintf(f, "[Near %d]\n", odr_offset(in));
3560 fprintf(f, "Packet dump:\n---------\n");
3561 odr_dumpBER(f, netbuffer, res);
3562 fprintf(f, "---------\n");
3565 z_GDU(print, &gdu, 0, 0);
3568 if (conn && cs_more(conn))
3573 odr_dumpBER(ber_file, netbuffer, res);
3574 if (apdu_file && !z_GDU(print, &gdu, 0, 0))
3576 odr_perror(print, "Failed to print incoming APDU");
3580 if (gdu->which == Z_GDU_Z3950)
3582 Z_APDU *apdu = gdu->u.z3950;
3585 case Z_APDU_initResponse:
3586 process_initResponse(apdu->u.initResponse);
3588 case Z_APDU_searchResponse:
3589 process_searchResponse(apdu->u.searchResponse);
3591 case Z_APDU_scanResponse:
3592 process_scanResponse(apdu->u.scanResponse);
3594 case Z_APDU_presentResponse:
3595 print_refid (apdu->u.presentResponse->referenceId);
3597 *apdu->u.presentResponse->numberOfRecordsReturned;
3598 if (apdu->u.presentResponse->records)
3599 display_records(apdu->u.presentResponse->records);
3601 printf("No records.\n");
3602 printf ("nextResultSetPosition = %d\n",
3603 *apdu->u.presentResponse->nextResultSetPosition);
3605 case Z_APDU_sortResponse:
3606 process_sortResponse(apdu->u.sortResponse);
3608 case Z_APDU_extendedServicesResponse:
3609 printf("Got extended services response\n");
3610 process_ESResponse(apdu->u.extendedServicesResponse);
3613 printf("Target has closed the association.\n");
3614 process_close(apdu->u.close);
3616 case Z_APDU_resourceControlRequest:
3617 process_resourceControlRequest
3618 (apdu->u.resourceControlRequest);
3620 case Z_APDU_deleteResultSetResponse:
3621 process_deleteResultSetResponse(apdu->u.
3622 deleteResultSetResponse);
3625 printf("Received unknown APDU type (%d).\n",
3631 else if (gdu->which == Z_GDU_HTTP_Response)
3633 http_response(gdu->u.HTTP_Response);
3636 if (conn && !cs_more(conn))
3641 #if HAVE_GETTIMEOFDAY
3642 gettimeofday (&tv_end, 0);
3644 printf ("S/U S/U=%ld/%ld %ld/%ld",
3645 (long) tv_start.tv_sec,
3646 (long) tv_start.tv_usec,
3647 (long) tv_end.tv_sec,
3648 (long) tv_end.tv_usec);
3650 printf ("Elapsed: %.6f\n",
3651 (double) tv_end.tv_usec / 1e6 + tv_end.tv_sec -
3652 ((double) tv_start.tv_usec / 1e6 + tv_start.tv_sec));
3659 int cmd_cclparse(const char* arg)
3662 struct ccl_rpn_node *rpn=NULL;
3665 rpn = ccl_find_str (bibset, arg, &error, &pos);
3668 printf ("%*s^ - ", 3+strlen(last_cmd)+1+pos, " ");
3669 printf ("%s\n", ccl_err_msg (error));
3675 ccl_pr_tree(rpn, stdout);
3679 ccl_rpn_delete(rpn);
3687 int cmd_set_otherinfo(const char* args)
3689 char oidstr[101], otherinfoString[101];
3694 sscan_res = sscanf (args, "%d %100[^ ] %100s", &otherinfoNo, oidstr, otherinfoString);
3696 /* reset this otherinfo */
3697 if(otherinfoNo>=maxOtherInfosSupported) {
3698 printf("Error otherinfo index to large (%d>%d)\n",
3699 otherinfoNo,maxOtherInfosSupported);
3701 extraOtherInfos[otherinfoNo].oidval = -1;
3702 if (extraOtherInfos[otherinfoNo].value)
3703 free(extraOtherInfos[otherinfoNo].value);
3707 printf("Error in set_otherinfo command \n");
3711 if (otherinfoNo>=maxOtherInfosSupported) {
3712 printf("Error otherinfo index to large (%d>%d)\n",
3713 otherinfoNo,maxOtherInfosSupported);
3716 oidval = oid_getvalbyname (oidstr);
3717 if (oidval == -1 ) {
3718 printf("Error in set_otherinfo command unknown oid %s \n",oidstr);
3721 extraOtherInfos[otherinfoNo].oidval = oidval;
3722 if(extraOtherInfos[otherinfoNo].value) free(extraOtherInfos[otherinfoNo].value);
3723 extraOtherInfos[otherinfoNo].value = strdup(otherinfoString);
3728 int cmd_sleep(const char* args )
3737 printf("Done sleeping %d seconds\n", sec);
3742 int cmd_list_otherinfo(const char* args)
3746 if(strlen(args)>0) {
3748 if( i >= maxOtherInfosSupported ) {
3749 printf("Error otherinfo index to large (%d>%d)\n",i,maxOtherInfosSupported);
3753 if(extraOtherInfos[i].oidval != -1)
3754 printf(" otherinfo %d %s %s\n",
3756 yaz_z3950_oid_value_to_str(
3757 (enum oid_value) extraOtherInfos[i].oidval,
3759 extraOtherInfos[i].value);
3762 for(i=0; i<maxOtherInfosSupported; ++i) {
3763 if(extraOtherInfos[i].oidval != -1)
3764 printf(" otherinfo %d %s %s\n",
3766 yaz_z3950_oid_value_to_str(
3767 (enum oid_value) extraOtherInfos[i].oidval,
3769 extraOtherInfos[i].value);
3777 int cmd_list_all(const char* args) {
3780 /* connection options */
3782 printf("Connected to : %s\n",last_open_command);
3784 if(last_open_command)
3785 printf("Not connected to : %s\n",last_open_command);
3787 printf("Not connected : \n");
3790 if(yazProxy) printf("using proxy : %s\n",yazProxy);
3792 printf("auto_reconnect : %s\n",auto_reconnect?"on":"off");
3795 printf("Authentication : none\n");
3797 switch(auth->which) {
3798 case Z_IdAuthentication_idPass:
3799 printf("Authentication : IdPass\n");
3800 printf(" Login User : %s\n",auth->u.idPass->userId?auth->u.idPass->userId:"");
3801 printf(" Login Group : %s\n",auth->u.idPass->groupId?auth->u.idPass->groupId:"");
3802 printf(" Password : %s\n",auth->u.idPass->password?auth->u.idPass->password:"");
3804 case Z_IdAuthentication_open:
3805 printf("Authentication : psOpen\n");
3806 printf(" Open string : %s\n",auth->u.open);
3809 printf("Authentication : Unknown\n");
3812 if (negotiationCharset)
3813 printf("Neg. Character set : `%s'\n", negotiationCharset);
3817 for (i = 0; i<num_databaseNames; i++) printf("%s ",databaseNames[i]);
3821 printf("CCL file : %s\n",ccl_fields);
3822 printf("CQL file : %s\n",cql_fields);
3823 printf("Query type : %s\n",query_type_as_string(queryType));
3825 printf("Named Result Sets : %s\n",setnumber==-1?"off":"on");
3827 /* piggy back options */
3828 printf("ssub/lslb/mspn : %d/%d/%d\n",smallSetUpperBound,largeSetLowerBound,mediumSetPresentNumber);
3830 /* print present related options */
3831 printf("Format : %s\n",yaz_z3950_oid_value_to_str(recordsyntax,CLASS_RECSYN));
3832 printf("Schema : %s\n",record_schema ? record_schema : "not set");
3833 printf("Elements : %s\n",elementSetNames?elementSetNames->u.generic:"");
3835 /* loging options */
3836 printf("APDU log : %s\n",apdu_file?"on":"off");
3837 printf("Record log : %s\n",marc_file?"on":"off");
3840 printf("Other Info: \n");
3841 cmd_list_otherinfo("");
3846 int cmd_clear_otherinfo(const char* args)
3848 if(strlen(args)>0) {
3850 otherinfoNo = atoi(args);
3851 if( otherinfoNo >= maxOtherInfosSupported ) {
3852 printf("Error otherinfo index to large (%d>%d)\n",otherinfoNo,maxOtherInfosSupported);
3856 if(extraOtherInfos[otherinfoNo].oidval != -1) {
3857 /* only clear if set. */
3858 extraOtherInfos[otherinfoNo].oidval=-1;
3859 free(extraOtherInfos[otherinfoNo].value);
3864 for(i=0; i<maxOtherInfosSupported; ++i) {
3865 if (extraOtherInfos[i].oidval!=-1 ) {
3866 extraOtherInfos[i].oidval=-1;
3867 free(extraOtherInfos[i].value);
3874 static int cmd_help (const char *line);
3876 typedef char *(*completerFunctionType)(const char *text, int state);
3880 int (*fun)(const char *arg);
3882 completerFunctionType rl_completerfunction;
3883 int complete_filenames;
3884 char **local_tabcompletes;
3886 {"open", cmd_open, "('tcp'|'ssl')':<host>[':'<port>][/<db>]",NULL,0,NULL},
3887 {"quit", cmd_quit, "",NULL,0,NULL},
3888 {"find", cmd_find, "<query>",NULL,0,NULL},
3889 {"delete", cmd_delete, "<setname>",NULL,0,NULL},
3890 {"base", cmd_base, "<base-name>",NULL,0,NULL},
3891 {"show", cmd_show, "<rec#>['+'<#recs>['+'<setname>]]",NULL,0,NULL},
3892 {"scan", cmd_scan, "<term>",NULL,0,NULL},
3893 {"scanstep", cmd_scanstep, "<size>",NULL,0,NULL},
3894 {"scanpos", cmd_scanpos, "<size>",NULL,0,NULL},
3895 {"sort", cmd_sort, "<sortkey> <flag> <sortkey> <flag> ...",NULL,0,NULL},
3896 {"sort+", cmd_sort_newset, "<sortkey> <flag> <sortkey> <flag> ...",NULL,0,NULL},
3897 {"authentication", cmd_authentication, "<acctstring>",NULL,0,NULL},
3898 {"lslb", cmd_lslb, "<largeSetLowerBound>",NULL,0,NULL},
3899 {"ssub", cmd_ssub, "<smallSetUpperBound>",NULL,0,NULL},
3900 {"mspn", cmd_mspn, "<mediumSetPresentNumber>",NULL,0,NULL},
3901 {"status", cmd_status, "",NULL,0,NULL},
3902 {"setnames", cmd_setnames, "",NULL,0,NULL},
3903 {"cancel", cmd_cancel, "",NULL,0,NULL},
3904 {"cancel_find", cmd_cancel_find, "<query>",NULL,0,NULL},
3905 {"format", cmd_format, "<recordsyntax>",complete_format,0,NULL},
3906 {"schema", cmd_schema, "<schema>",complete_schema,0,NULL},
3907 {"elements", cmd_elements, "<elementSetName>",NULL,0,NULL},
3908 {"close", cmd_close, "",NULL,0,NULL},
3909 {"attributeset", cmd_attributeset, "<attrset>",complete_attributeset,0,NULL},
3910 {"querytype", cmd_querytype, "<type>",complete_querytype,0,NULL},
3911 {"refid", cmd_refid, "<id>",NULL,0,NULL},
3912 {"itemorder", cmd_itemorder, "ill|item <itemno>",NULL,0,NULL},
3913 {"update", cmd_update, "<action> <recid> [<file>]",NULL,0,NULL},
3914 {"update0", cmd_update0, "<action> <recid> [<file>]",NULL,0,NULL},
3915 {"packagename", cmd_packagename, "<packagename>",NULL,0,NULL},
3916 {"proxy", cmd_proxy, "[('tcp'|'ssl')]<host>[':'<port>]",NULL,0,NULL},
3917 {"charset", cmd_charset, "<nego_charset> <output_charset>",NULL,0,NULL},
3918 {"marccharset", cmd_marccharset, "<charset_name>",NULL,0,NULL},
3919 {"lang", cmd_lang, "<language_code>",NULL,0,NULL},
3920 {".", cmd_source_echo, "<filename>",NULL,1,NULL},
3921 {"!", cmd_subshell, "Subshell command",NULL,1,NULL},
3922 {"set_apdufile", cmd_set_apdufile, "<filename>",NULL,1,NULL},
3923 {"set_berfile", cmd_set_berfile, "<filename>",NULL,1,NULL},
3924 {"set_marcdump", cmd_set_marcdump," <filename>",NULL,1,NULL},
3925 {"set_cclfile", cmd_set_cclfile," <filename>",NULL,1,NULL},
3926 {"set_cqlfile", cmd_set_cqlfile," <filename>",NULL,1,NULL},
3927 {"set_auto_reconnect", cmd_set_auto_reconnect," on|off",complete_auto_reconnect,1,NULL},
3928 {"set_otherinfo", cmd_set_otherinfo,"<otherinfoinddex> <oid> <string>",NULL,0,NULL},
3929 {"sleep", cmd_sleep,"<seconds>",NULL,0,NULL},
3930 {"register_oid", cmd_register_oid,"<name> <class> <oid>",NULL,0,NULL},
3931 {"push_command", cmd_push_command,"<command>",command_generator,0,NULL},
3932 {"register_tab", cmd_register_tab,"<commandname> <tab>",command_generator,0,NULL},
3933 {"cclparse", cmd_cclparse,"<ccl find command>",NULL,0,NULL},
3934 {"list_otherinfo",cmd_list_otherinfo,"[otherinfoinddex]",NULL,0,NULL},
3935 {"list_all",cmd_list_all,"",NULL,0,NULL},
3936 {"clear_otherinfo",cmd_clear_otherinfo,"",NULL,0,NULL},
3937 /* Server Admin Functions */
3938 {"adm-reindex", cmd_adm_reindex, "<database-name>",NULL,0,NULL},
3939 {"adm-truncate", cmd_adm_truncate, "('database'|'index')<object-name>",NULL,0,NULL},
3940 {"adm-create", cmd_adm_create, "",NULL,0,NULL},
3941 {"adm-drop", cmd_adm_drop, "('database'|'index')<object-name>",NULL,0,NULL},
3942 {"adm-import", cmd_adm_import, "<record-type> <dir> <pattern>",NULL,0,NULL},
3943 {"adm-refresh", cmd_adm_refresh, "",NULL,0,NULL},
3944 {"adm-commit", cmd_adm_commit, "",NULL,0,NULL},
3945 {"adm-shutdown", cmd_adm_shutdown, "",NULL,0,NULL},
3946 {"adm-startup", cmd_adm_startup, "",NULL,0,NULL},
3947 {"explain", cmd_explain, "", NULL, 0, NULL},
3948 {"options", cmd_options, "", NULL, 0, NULL},
3949 {"zversion", cmd_zversion, "", NULL, 0, NULL},
3950 {"help", cmd_help, "", NULL,0,NULL},
3951 {"init", cmd_init, "", NULL,0,NULL},
3955 static int cmd_help (const char *line)
3961 sscanf (line, "%20s", topic);
3964 printf("Commands:\n");
3965 for (i = 0; cmd_array[i].cmd; i++)
3966 if (*topic == 0 || strcmp (topic, cmd_array[i].cmd) == 0)
3967 printf(" %s %s\n", cmd_array[i].cmd, cmd_array[i].ad);
3968 if (strcmp (topic, "find") == 0)
3971 printf (" \"term\" Simple Term\n");
3972 printf (" @attr [attset] type=value op Attribute\n");
3973 printf (" @and opl opr And\n");
3974 printf (" @or opl opr Or\n");
3975 printf (" @not opl opr And-Not\n");
3976 printf (" @set set Result set\n");
3978 printf ("Bib-1 attribute types\n");
3980 printf ("4=Title 7=ISBN 8=ISSN 30=Date 62=Abstract 1003=Author 1016=Any\n");
3981 printf ("2=Relation: ");
3982 printf ("1< 2<= 3= 4>= 5> 6!= 102=Relevance\n");
3983 printf ("3=Position: ");
3984 printf ("1=First in Field 2=First in subfield 3=Any position\n");
3985 printf ("4=Structure: ");
3986 printf ("1=Phrase 2=Word 3=Key 4=Year 5=Date 6=WordList\n");
3987 printf ("5=Truncation: ");
3988 printf ("1=Right 2=Left 3=L&R 100=No 101=# 102=Re-1 103=Re-2\n");
3989 printf ("6=Completeness:");
3990 printf ("1=Incomplete subfield 2=Complete subfield 3=Complete field\n");
3995 int cmd_register_tab(const char* arg) {
3997 char command[101], tabargument[101];
4002 if (sscanf (arg, "%100s %100s", command, tabargument) < 1) {
4006 /* locate the amdn in the list */
4007 for (i = 0; cmd_array[i].cmd; i++) {
4008 if (!strncmp(cmd_array[i].cmd, command, strlen(command))) {
4013 if(!cmd_array[i].cmd) {
4014 fprintf(stderr,"Unknown command %s\n",command);
4019 if(!cmd_array[i].local_tabcompletes)
4020 cmd_array[i].local_tabcompletes = (char **) calloc(1,sizeof(char**));
4024 tabslist = cmd_array[i].local_tabcompletes;
4025 for(;tabslist && *tabslist;tabslist++) {
4029 cmd_array[i].local_tabcompletes = (char **)
4030 realloc(cmd_array[i].local_tabcompletes,(num_of_tabs+2)*sizeof(char**));
4031 tabslist=cmd_array[i].local_tabcompletes;
4032 tabslist[num_of_tabs]=strdup(tabargument);
4033 tabslist[num_of_tabs+1]=NULL;
4038 void process_cmd_line(char* line)
4041 char word[32], arg[10240];
4043 #if HAVE_GETTIMEOFDAY
4044 gettimeofday (&tv_start, 0);
4047 if ((res = sscanf(line, "%31s %10239[^;]", word, arg)) <= 0)
4049 strcpy(word, last_cmd);
4054 strcpy(last_cmd, word);
4056 /* removed tailing spaces from the arg command */
4059 char* lastnonspace=NULL;
4062 if(!isspace(*(unsigned char *) p)) {
4067 *(++lastnonspace) = 0;
4070 for (i = 0; cmd_array[i].cmd; i++)
4071 if (!strncmp(cmd_array[i].cmd, word, strlen(word)))
4073 res = (*cmd_array[i].fun)(arg);
4077 if (!cmd_array[i].cmd) /* dump our help-screen */
4079 printf("Unknown command: %s.\n", word);
4080 printf("use help for list of commands\n");
4081 /* cmd_help (""); */
4085 if(apdu_file) fflush(apdu_file);
4088 wait_and_handle_response();
4097 char *command_generator(const char *text, int state)
4103 for( ; cmd_array[idx].cmd; ++idx) {
4104 if (!strncmp(cmd_array[idx].cmd,text,strlen(text))) {
4105 ++idx; /* skip this entry on the next run */
4106 return strdup(cmd_array[idx-1].cmd);
4114 This function only known how to complete on the first word
4116 char ** readline_completer(char *text, int start, int end) {
4117 #if HAVE_READLINE_READLINE_H
4119 completerFunctionType completerToUse;
4122 #if HAVE_READLINE_RL_COMPLETION_MATCHES
4123 char** res=rl_completion_matches(text,
4126 char** res=completion_matches(text,
4127 (CPFunction*)command_generator);
4129 rl_attempted_completion_over = 1;
4132 char arg[10240],word[32];
4134 if ((res = sscanf(rl_line_buffer, "%31s %10239[^;]", word, arg)) <= 0) {
4135 rl_attempted_completion_over = 1;
4139 for (i = 0; cmd_array[i].cmd; i++) {
4140 if (!strncmp(cmd_array[i].cmd, word, strlen(word))) {
4145 if(!cmd_array[i].cmd) return NULL;
4147 curret_global_list = cmd_array[i].local_tabcompletes;
4149 completerToUse = cmd_array[i].rl_completerfunction;
4150 if(completerToUse==NULL) /* if no pr. command completer is defined use the default completer */
4151 completerToUse = default_completer;
4153 if(completerToUse) {
4154 #ifdef HAVE_READLINE_RL_COMPLETION_MATCHES
4156 rl_completion_matches(text,
4160 completion_matches(text,
4161 (CPFunction*)completerToUse);
4163 if(!cmd_array[i].complete_filenames)
4164 rl_attempted_completion_over = 1;
4167 if(!cmd_array[i].complete_filenames)
4168 rl_attempted_completion_over = 1;
4178 static void client(void)
4184 #if HAVE_GETTIMEOFDAY
4185 gettimeofday (&tv_start, 0);
4190 char *line_in = NULL;
4191 #if HAVE_READLINE_READLINE_H
4194 line_in=readline(C_PROMPT);
4197 #if HAVE_READLINE_HISTORY_H
4199 add_history(line_in);
4201 strncpy(line, line_in, 10239);
4210 if (!fgets(line, 10239, stdin))
4212 if ((end_p = strchr (line, '\n')))
4215 process_cmd_line(line);
4219 static void show_version(void)
4223 yaz_version(vstr, 0);
4224 printf ("YAZ version: %s\n", YAZ_VERSION);
4225 if (strcmp(vstr, YAZ_VERSION))
4226 printf ("YAZ DLL/SO: %s\n", vstr);
4230 int main(int argc, char **argv)
4233 char *open_command = 0;
4234 char *auth_command = 0;
4239 if (!setlocale(LC_CTYPE, ""))
4240 fprintf (stderr, "setlocale failed\n");
4244 codeset = nl_langinfo(CODESET);
4248 outputCharset = xstrdup(codeset);
4250 ODR_MASK_SET(&z3950_options, Z_Options_search);
4251 ODR_MASK_SET(&z3950_options, Z_Options_present);
4252 ODR_MASK_SET(&z3950_options, Z_Options_namedResultSets);
4253 ODR_MASK_SET(&z3950_options, Z_Options_triggerResourceCtrl);
4254 ODR_MASK_SET(&z3950_options, Z_Options_scan);
4255 ODR_MASK_SET(&z3950_options, Z_Options_sort);
4256 ODR_MASK_SET(&z3950_options, Z_Options_extendedServices);
4257 ODR_MASK_SET(&z3950_options, Z_Options_delSet);
4259 while ((ret = options("k:c:q:a:b:m:v:p:u:t:Vxd:", argv, argc, &arg)) != -2)
4266 open_command = (char *) xmalloc (strlen(arg)+6);
4267 strcpy (open_command, "open ");
4268 strcat (open_command, arg);
4272 dump_file_prefix = arg;
4275 kilobytes = atoi(arg);
4278 if (!(marc_file = fopen (arg, "a")))
4285 outputCharset = xstrdup(arg);
4288 strncpy (ccl_fields, arg, sizeof(ccl_fields)-1);
4289 ccl_fields[sizeof(ccl_fields)-1] = '\0';
4292 strncpy (cql_fields, arg, sizeof(cql_fields)-1);
4293 cql_fields[sizeof(cql_fields)-1] = '\0';
4296 if (!strcmp(arg, "-"))
4299 ber_file=fopen(arg, "a");
4302 if (!strcmp(arg, "-"))
4305 apdu_file=fopen(arg, "a");
4311 yazProxy=strdup(arg);
4316 auth_command = (char *) xmalloc (strlen(arg)+6);
4317 strcpy (auth_command, "auth ");
4318 strcat (auth_command, arg);
4322 yaz_log_init(yaz_log_mask_str(arg), "", 0);
4328 fprintf (stderr, "Usage: %s [-m <marclog>] [ -a <apdulog>] "
4329 "[-b berdump] [-c cclfields] \n"
4330 "[-q cqlfields] [-p <proxy-addr>] [-u <auth>] "
4331 "[-k size] [-d dump] [-V] [<server-addr>]\n",
4339 #ifdef HAVE_GETTIMEOFDAY
4340 gettimeofday (&tv_start, 0);
4342 process_cmd_line (auth_command);
4343 #if HAVE_READLINE_HISTORY_H
4344 add_history(auth_command);
4346 xfree(auth_command);
4350 #ifdef HAVE_GETTIMEOFDAY
4351 gettimeofday (&tv_start, 0);
4353 process_cmd_line (open_command);
4354 #if HAVE_READLINE_HISTORY_H
4355 add_history(open_command);
4357 xfree(open_command);
4368 * vim600: sw=4 ts=8 fdm=marker
4369 * vim<600: sw=4 ts=8