2 * Copyright (C) 1995-2005, Index Data ApS
3 * See the file LICENSE for details.
5 * $Id: client.c,v 1.273 2005-02-02 17:11:05 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 int scan_size = 20;
134 static char cur_host[200];
144 static QueryType queryType = QueryType_Prefix;
146 static CCL_bibset bibset; /* CCL bibset handle */
147 static cql_transform_t cqltrans; /* CQL context-set handle */
149 #if HAVE_READLINE_COMPLETION_OVER
152 /* readline doesn't have this var. Define it ourselves. */
153 int rl_attempted_completion_over = 0;
156 /* set this one to 1, to avoid decode of unknown MARCs */
157 #define AVOID_MARC_DECODE 1
159 #define maxOtherInfosSupported 10
163 } extraOtherInfos[maxOtherInfosSupported];
166 void process_cmd_line(char* line);
167 char ** readline_completer(char *text, int start, int end);
168 char *command_generator(const char *text, int state);
169 char** curret_global_list=NULL;
170 int cmd_register_tab(const char* arg);
172 static void close_session (void);
174 ODR getODROutputStream()
179 const char* query_type_as_string(QueryType q)
182 case QueryType_Prefix: return "prefix (RPN sent to server)";
183 case QueryType_CCL: return "CCL (CCL sent to server) ";
184 case QueryType_CCL2RPN: return "CCL -> RPN (RPN sent to server)";
185 case QueryType_CQL: return "CQL (CQL sent to server)";
186 case QueryType_CQL2RPN: return "CQL -> RPN (RPN sent to server)";
188 return "unknown Query type internal yaz-client error";
192 static void do_hex_dump(const char* buf, int len)
197 for( i=0; i<len ; i=i+16 )
200 for(x=0 ; i+x<len && x<16; ++x)
202 printf("%2.2X ",(unsigned int)((unsigned char)buf[i+x]));
207 if (dump_file_prefix)
210 if (++no < 1000 && strlen(dump_file_prefix) < 500)
214 sprintf (fname, "%s.%03d.raw", dump_file_prefix, no);
215 of = fopen(fname, "wb");
217 fwrite (buf, 1, len, of);
224 void add_otherInfos(Z_APDU *a)
226 Z_OtherInformation **oi;
230 for(i=0; i<maxOtherInfosSupported; ++i)
232 if(extraOtherInfos[i].oidval != -1)
233 yaz_oi_set_string_oidval(oi, out, extraOtherInfos[i].oidval,
234 1, extraOtherInfos[i].value);
238 int send_apdu(Z_APDU *a)
247 z_APDU(print, &a, 0, 0);
250 if (!z_APDU(out, &a, 0, 0))
252 odr_perror(out, "Encoding APDU");
256 buf = odr_getbuf(out, &len, 0);
258 odr_dumpBER(ber_file, buf, len);
259 /* printf ("sending APDU of size %d\n", len); */
260 do_hex_dump(buf, len);
261 if (cs_put(conn, buf, len) < 0)
263 fprintf(stderr, "cs_put: %s", cs_errmsg(cs_errno(conn)));
267 odr_reset(out); /* release the APDU structure */
271 static void print_stringn(const unsigned char *buf, size_t len)
274 for (i = 0; i<len; i++)
275 if ((buf[i] <= 126 && buf[i] >= 32) || strchr ("\n\r\t\f", buf[i]))
276 printf ("%c", buf[i]);
278 printf ("\\X%02X", buf[i]);
281 static void print_refid (Z_ReferenceId *id)
285 printf ("Reference Id: ");
286 print_stringn (id->buf, id->len);
291 static Z_ReferenceId *set_refid (ODR out)
296 id = (Z_ReferenceId *) odr_malloc (out, sizeof(*id));
297 id->size = id->len = strlen(refid);
298 id->buf = (unsigned char *) odr_malloc (out, id->len);
299 memcpy (id->buf, refid, id->len);
303 /* INIT SERVICE ------------------------------- */
305 static void send_initRequest(const char* type_and_host)
307 Z_APDU *apdu = zget_APDU(out, Z_APDU_initRequest);
308 Z_InitRequest *req = apdu->u.initRequest;
311 req->options = &z3950_options;
313 ODR_MASK_ZERO(req->protocolVersion);
314 for (i = 0; i<z3950_version; i++)
315 ODR_MASK_SET(req->protocolVersion, i);
317 *req->maximumRecordSize = 1024*kilobytes;
318 *req->preferredMessageSize = 1024*kilobytes;
320 req->idAuthentication = auth;
322 req->referenceId = set_refid (out);
324 if (yazProxy && type_and_host)
325 yaz_oi_set_string_oidval(&req->otherInfo, out, VAL_PROXY,
328 if (negotiationCharset || yazLang) {
329 Z_OtherInformation **p;
330 Z_OtherInformationUnit *p0;
332 yaz_oi_APDU(apdu, &p);
334 if ((p0=yaz_oi_update(p, out, NULL, 0, 0))) {
335 ODR_MASK_SET(req->options, Z_Options_negotiationModel);
337 p0->which = Z_OtherInfo_externallyDefinedInfo;
338 p0->information.externallyDefinedInfo =
339 yaz_set_proposal_charneg(
341 (const char**)&negotiationCharset,
342 negotiationCharset ? 1 : 0,
343 (const char**)&yazLang, yazLang ? 1 : 0,
344 negotiationCharsetRecords);
349 printf("Sent initrequest.\n");
353 /* These two are used only from process_initResponse() */
354 static void render_initUserInfo(Z_OtherInformation *ui1);
355 static void render_diag(Z_DiagnosticFormat *diag);
357 static void pr_opt(const char *opt, void *clientData)
362 static int process_initResponse(Z_InitResponse *res)
365 /* save session parameters for later use */
366 session_mem = odr_extract_mem(in);
369 for (ver = 0; ver < 8; ver++)
370 if (!ODR_MASK_GET(res->protocolVersion, ver))
374 printf("Connection rejected by v%d target.\n", ver);
376 printf("Connection accepted by v%d target.\n", ver);
377 if (res->implementationId)
378 printf("ID : %s\n", res->implementationId);
379 if (res->implementationName)
380 printf("Name : %s\n", res->implementationName);
381 if (res->implementationVersion)
382 printf("Version: %s\n", res->implementationVersion);
383 if (res->userInformationField)
385 Z_External *uif = res->userInformationField;
386 if (uif->which == Z_External_userInfo1) {
387 render_initUserInfo(uif->u.userInfo1);
389 printf("UserInformationfield:\n");
390 if (!z_External(print, (Z_External**)&uif, 0, 0))
392 odr_perror(print, "Printing userinfo\n");
395 if (uif->which == Z_External_octet) {
396 printf("Guessing visiblestring:\n");
397 printf("'%.*s'\n", uif->u.octet_aligned->len,
398 uif->u.octet_aligned->buf);
400 else if (uif->which == Z_External_single)
402 Odr_any *sat = uif->u.single_ASN1_type;
403 oident *oid = oid_getentbyoid(uif->direct_reference);
404 if (oid->value == VAL_OCLCUI) {
405 Z_OCLC_UserInformation *oclc_ui;
406 ODR decode = odr_createmem(ODR_DECODE);
407 odr_setbuf(decode, sat->buf, sat->len, 0);
408 if (!z_OCLC_UserInformation(decode, &oclc_ui, 0, 0))
409 printf ("Bad OCLC UserInformation:\n");
411 printf ("OCLC UserInformation:\n");
412 if (!z_OCLC_UserInformation(print, &oclc_ui, 0, 0))
413 printf ("Bad OCLC UserInformation spec\n");
418 /* Peek at any private Init-diagnostic APDUs */
419 printf("### NAUGHTY: External is '%.*s'\n",
427 yaz_init_opt_decode(res->options, pr_opt, 0);
430 if (ODR_MASK_GET(res->options, Z_Options_namedResultSets))
433 if (ODR_MASK_GET(res->options, Z_Options_negotiationModel)) {
435 Z_CharSetandLanguageNegotiation *p =
436 yaz_get_charneg_record(res->otherInfo);
440 char *charset=NULL, *lang=NULL;
443 yaz_get_response_charneg(session_mem, p, &charset, &lang,
446 if (outputCharset && negotiationCharset) {
447 odr_set_charset (out, charset, outputCharset);
448 odr_set_charset (in, outputCharset, charset);
451 odr_set_charset (out, 0, 0);
452 odr_set_charset (in, 0, 0);
455 printf("Accepted character set : %s\n", charset);
456 printf("Accepted code language : %s\n", lang ? lang : "none");
457 printf("Accepted records in ...: %d\n", selected );
465 static void render_initUserInfo(Z_OtherInformation *ui1) {
467 printf("Init response contains %d otherInfo unit%s:\n",
468 ui1->num_elements, ui1->num_elements == 1 ? "" : "s");
470 for (i = 0; i < ui1->num_elements; i++) {
471 Z_OtherInformationUnit *unit = ui1->list[i];
472 printf(" %d: otherInfo unit contains ", i+1);
473 if (unit->which == Z_OtherInfo_externallyDefinedInfo &&
474 unit->information.externallyDefinedInfo &&
475 unit->information.externallyDefinedInfo->which ==
477 render_diag(unit->information.externallyDefinedInfo->u.diag1);
479 else if (unit->which != Z_OtherInfo_externallyDefinedInfo)
481 printf("unsupported otherInfo unit->which = %d\n", unit->which);
485 printf("unsupported otherInfo unit external %d\n",
486 unit->information.externallyDefinedInfo ?
487 unit->information.externallyDefinedInfo->which : -2);
493 /* ### should this share code with display_diagrecs()? */
494 static void render_diag(Z_DiagnosticFormat *diag) {
497 printf("%d diagnostic%s:\n", diag->num, diag->num == 1 ? "" : "s");
498 for (i = 0; i < diag->num; i++) {
499 Z_DiagnosticFormat_s *ds = diag->elements[i];
500 printf(" %d: ", i+1);
502 case Z_DiagnosticFormat_s_defaultDiagRec: {
503 Z_DefaultDiagFormat *dd = ds->u.defaultDiagRec;
504 /* ### should check `dd->diagnosticSetId' */
505 printf("code=%d (%s)", *dd->condition,
506 diagbib1_str(*dd->condition));
507 /* Both types of addinfo are the same, so use type-pun */
508 if (dd->u.v2Addinfo != 0)
509 printf(",\n\taddinfo='%s'", dd->u.v2Addinfo);
512 case Z_DiagnosticFormat_s_explicitDiagnostic:
513 printf("Explicit diagnostic (not supported)");
516 printf("Unrecognised diagnostic type %d", ds->which);
520 if (ds->message != 0)
521 printf(", message='%s'", ds->message);
527 static int set_base(const char *arg)
532 for (i = 0; i<num_databaseNames; i++)
533 xfree (databaseNames[i]);
534 num_databaseNames = 0;
538 if (!(cp = strchr(arg, ' ')))
539 cp = arg + strlen(arg);
542 databaseNames[num_databaseNames] = (char *)xmalloc (1 + cp - arg);
543 memcpy (databaseNames[num_databaseNames], arg, cp - arg);
544 databaseNames[num_databaseNames][cp - arg] = '\0';
546 for (cp1 = databaseNames[num_databaseNames]; *cp1 ; cp1++)
555 if (num_databaseNames == 0)
557 num_databaseNames = 1;
558 databaseNames[0] = xstrdup("");
563 static int cmd_base(const char *arg)
567 printf("Usage: base <database> <database> ...\n");
570 return set_base(arg);
573 void cmd_open_remember_last_open_command(const char* arg, char* new_open_command)
575 if(last_open_command != arg)
577 if(last_open_command) xfree(last_open_command);
578 last_open_command = xstrdup(new_open_command);
582 int session_connect(const char *arg)
585 char type_and_host[101];
586 const char *basep = 0;
587 #if HAVE_OPENSSL_SSL_H
596 nmem_destroy (session_mem);
600 cs_get_host_args(arg, &basep);
602 strncpy(type_and_host, arg, sizeof(type_and_host)-1);
603 type_and_host[sizeof(type_and_host)-1] = '\0';
605 cmd_open_remember_last_open_command(arg, type_and_host);
608 conn = cs_create_host(yazProxy, 1, &add);
610 conn = cs_create_host(arg, 1, &add);
613 printf ("Couldn't create comstack\n");
617 if (conn->protocol == PROTO_HTTP)
618 queryType = QueryType_CQL;
620 if (conn->protocol == PROTO_HTTP)
622 printf ("SRW/HTTP not enabled in this YAZ\n");
628 protocol = conn->protocol;
629 if (conn->protocol == PROTO_HTTP)
633 printf("Connecting...");
635 if (cs_connect(conn, add) < 0)
637 printf ("error = %s\n", cs_strerror(conn));
638 if (conn->cerrno == CSYSERR)
641 yaz_strerror(msg, sizeof(msg));
642 printf ("%s\n", msg);
649 #if HAVE_OPENSSL_SSL_H
650 if ((ssl = (SSL *) cs_get_ssl(conn)))
652 X509 *server_cert = SSL_get_peer_certificate (ssl);
658 BIO *bio = BIO_new(BIO_s_mem());
660 /* get PEM buffer in memory */
661 PEM_write_bio_X509(bio, server_cert);
662 pem_len = BIO_get_mem_data(bio, &pem_buf);
663 fwrite(pem_buf, pem_len, 1, stdout);
665 /* print all info on screen .. */
666 X509_print_fp(stdout, server_cert);
669 X509_free (server_cert);
675 if (protocol == PROTO_Z3950)
677 send_initRequest(type_and_host);
683 int cmd_open(const char *arg)
687 strncpy (cur_host, arg, sizeof(cur_host)-1);
688 cur_host[sizeof(cur_host)-1] = 0;
690 return session_connect(cur_host);
697 if(!( auto_reconnect && last_open_command) ) return ;
699 open_command = (char *) xmalloc (strlen(last_open_command)+6);
700 strcpy (open_command, "open ");
702 strcat (open_command, last_open_command);
704 process_cmd_line(open_command);
709 int cmd_authentication(const char *arg)
711 static Z_IdAuthentication au;
712 static char user[40], group[40], pass[40];
713 static Z_IdPass idPass;
718 printf("Auth field set to null\n");
722 r = sscanf (arg, "%39s %39s %39s", user, group, pass);
725 printf("Authentication set to null\n");
731 if (!strcmp(user, "-")) {
732 au.which = Z_IdAuthentication_anonymous;
733 printf("Authentication set to Anonymous\n");
735 au.which = Z_IdAuthentication_open;
737 printf("Authentication set to Open (%s)\n", user);
743 au.which = Z_IdAuthentication_idPass;
744 au.u.idPass = &idPass;
745 idPass.groupId = NULL;
746 idPass.userId = user;
747 idPass.password = group;
748 printf("Authentication set to User (%s), Pass (%s)\n", user, group);
753 au.which = Z_IdAuthentication_idPass;
754 au.u.idPass = &idPass;
755 idPass.groupId = group;
756 idPass.userId = user;
757 idPass.password = pass;
758 printf("Authentication set to User (%s), Group (%s), Pass (%s)\n",
764 /* SEARCH SERVICE ------------------------------ */
765 static void display_record(Z_External *r);
767 static void print_record(const unsigned char *buf, size_t len)
770 print_stringn (buf, len);
771 /* add newline if not already added ... */
772 if (i <= 0 || buf[i-1] != '\n')
775 fwrite (buf, 1, len, marc_file);
778 static void display_record(Z_External *r)
780 oident *ent = oid_getentbyoid(r->direct_reference);
784 * Tell the user what we got.
786 if (r->direct_reference)
788 printf("Record type: ");
790 printf("%s\n", ent->desc);
791 else if (!odr_oid(print, &r->direct_reference, 0, 0))
793 odr_perror(print, "print oid");
797 /* Check if this is a known, ASN.1 type tucked away in an octet string */
798 if (ent && r->which == Z_External_octet)
800 Z_ext_typeent *type = z_ext_getentbyref(ent->value);
806 * Call the given decoder to process the record.
808 odr_setbuf(in, (char*)r->u.octet_aligned->buf,
809 r->u.octet_aligned->len, 0);
810 if (!(*type->fun)(in, &rr, 0, 0))
812 odr_perror(in, "Decoding constructed record.");
813 fprintf(stdout, "[Near %d]\n", odr_offset(in));
814 fprintf(stdout, "Packet dump:\n---------\n");
815 odr_dumpBER(stdout, (char*)r->u.octet_aligned->buf,
816 r->u.octet_aligned->len);
817 fprintf(stdout, "---------\n");
819 /* note just ignores the error ant print the bytes form the octet_aligned later */
822 * Note: we throw away the original, BER-encoded record here.
823 * Do something else with it if you want to keep it.
825 r->u.sutrs = (Z_SUTRS *) rr; /* we don't actually check the type here. */
826 r->which = type->what;
830 if (ent && ent->value == VAL_SOIF)
831 print_record((const unsigned char *) r->u.octet_aligned->buf,
832 r->u.octet_aligned->len);
833 else if (r->which == Z_External_octet)
835 const char *octet_buf = (char*)r->u.octet_aligned->buf;
836 if (ent->oclass == CLASS_RECSYN &&
837 (ent->value == VAL_TEXT_XML ||
838 ent->value == VAL_APPLICATION_XML ||
839 ent->value == VAL_HTML))
841 print_record((const unsigned char *) octet_buf,
842 r->u.octet_aligned->len);
844 else if (ent->value == VAL_POSTSCRIPT)
846 int size = r->u.octet_aligned->len;
849 print_record((const unsigned char *) octet_buf, size);
854 #if AVOID_MARC_DECODE
855 /* primitive check for a marc OID 5.1-29 except 16 */
856 ent->oidsuffix[0] == 5 && ent->oidsuffix[1] < 30 &&
857 ent->oidsuffix[1] != 16
866 yaz_marc_t mt = yaz_marc_create();
868 if (yaz_marc_decode_buf(mt, octet_buf,r->u.octet_aligned->len,
872 if (marcCharset && !strcmp(marcCharset, "auto"))
874 if (ent->value == VAL_USMARC)
876 if (octet_buf[9] == 'a')
884 else if (marcCharset)
886 if (outputCharset && from)
888 cd = yaz_iconv_open(outputCharset, from);
889 printf ("convert from %s to %s", from,
892 printf (" unsupported\n");
897 fwrite (result, 1, rlen, stdout);
901 size_t inbytesleft = rlen;
902 const char *inp = result;
906 size_t outbytesleft = sizeof(outbuf);
910 r = yaz_iconv (cd, (char**) &inp,
912 &outp, &outbytesleft);
913 if (r == (size_t) (-1))
915 int e = yaz_iconv_error(cd);
916 if (e != YAZ_ICONV_E2BIG)
919 fwrite (outbuf, outp - outbuf, 1, stdout);
925 printf ("bad MARC. Dumping as it is:\n");
926 print_record((const unsigned char*) octet_buf,
927 r->u.octet_aligned->len);
929 yaz_marc_destroy(mt);
935 print_record((const unsigned char*) octet_buf,
936 r->u.octet_aligned->len);
940 fwrite (octet_buf, 1, r->u.octet_aligned->len, marc_file);
942 else if (ent && ent->value == VAL_SUTRS)
944 if (r->which != Z_External_sutrs)
946 printf("Expecting single SUTRS type for SUTRS.\n");
949 print_record(r->u.sutrs->buf, r->u.sutrs->len);
951 else if (ent && ent->value == VAL_GRS1)
954 if (r->which != Z_External_grs1)
956 printf("Expecting single GRS type for GRS.\n");
960 yaz_display_grs1(w, r->u.grs1, 0);
964 else if ( /* OPAC display not complete yet .. */
965 ent && ent->value == VAL_OPAC)
968 if (r->u.opac->bibliographicRecord)
969 display_record(r->u.opac->bibliographicRecord);
970 for (i = 0; i<r->u.opac->num_holdingsData; i++)
972 Z_HoldingsRecord *h = r->u.opac->holdingsData[i];
973 if (h->which == Z_HoldingsRecord_marcHoldingsRecord)
975 printf ("MARC holdings %d\n", i);
976 display_record(h->u.marcHoldingsRecord);
978 else if (h->which == Z_HoldingsRecord_holdingsAndCirc)
982 Z_HoldingsAndCircData *data = h->u.holdingsAndCirc;
984 printf ("Data holdings %d\n", i);
985 if (data->typeOfRecord)
986 printf ("typeOfRecord: %s\n", data->typeOfRecord);
987 if (data->encodingLevel)
988 printf ("encodingLevel: %s\n", data->encodingLevel);
989 if (data->receiptAcqStatus)
990 printf ("receiptAcqStatus: %s\n", data->receiptAcqStatus);
991 if (data->generalRetention)
992 printf ("generalRetention: %s\n", data->generalRetention);
993 if (data->completeness)
994 printf ("completeness: %s\n", data->completeness);
995 if (data->dateOfReport)
996 printf ("dateOfReport: %s\n", data->dateOfReport);
998 printf ("nucCode: %s\n", data->nucCode);
999 if (data->localLocation)
1000 printf ("localLocation: %s\n", data->localLocation);
1001 if (data->shelvingLocation)
1002 printf ("shelvingLocation: %s\n", data->shelvingLocation);
1003 if (data->callNumber)
1004 printf ("callNumber: %s\n", data->callNumber);
1005 if (data->shelvingData)
1006 printf ("shelvingData: %s\n", data->shelvingData);
1007 if (data->copyNumber)
1008 printf ("copyNumber: %s\n", data->copyNumber);
1009 if (data->publicNote)
1010 printf ("publicNote: %s\n", data->publicNote);
1011 if (data->reproductionNote)
1012 printf ("reproductionNote: %s\n", data->reproductionNote);
1013 if (data->termsUseRepro)
1014 printf ("termsUseRepro: %s\n", data->termsUseRepro);
1015 if (data->enumAndChron)
1016 printf ("enumAndChron: %s\n", data->enumAndChron);
1017 for (j = 0; j<data->num_volumes; j++)
1019 printf ("volume %d\n", j);
1020 if (data->volumes[j]->enumeration)
1021 printf (" enumeration: %s\n",
1022 data->volumes[j]->enumeration);
1023 if (data->volumes[j]->chronology)
1024 printf (" chronology: %s\n",
1025 data->volumes[j]->chronology);
1026 if (data->volumes[j]->enumAndChron)
1027 printf (" enumAndChron: %s\n",
1028 data->volumes[j]->enumAndChron);
1030 for (j = 0; j<data->num_circulationData; j++)
1032 printf ("circulation %d\n", j);
1033 if (data->circulationData[j]->availableNow)
1034 printf (" availableNow: %d\n",
1035 *data->circulationData[j]->availableNow);
1036 if (data->circulationData[j]->availablityDate)
1037 printf (" availabiltyDate: %s\n",
1038 data->circulationData[j]->availablityDate);
1039 if (data->circulationData[j]->availableThru)
1040 printf (" availableThru: %s\n",
1041 data->circulationData[j]->availableThru);
1042 if (data->circulationData[j]->restrictions)
1043 printf (" restrictions: %s\n",
1044 data->circulationData[j]->restrictions);
1045 if (data->circulationData[j]->itemId)
1046 printf (" itemId: %s\n",
1047 data->circulationData[j]->itemId);
1048 if (data->circulationData[j]->renewable)
1049 printf (" renewable: %d\n",
1050 *data->circulationData[j]->renewable);
1051 if (data->circulationData[j]->onHold)
1052 printf (" onHold: %d\n",
1053 *data->circulationData[j]->onHold);
1054 if (data->circulationData[j]->enumAndChron)
1055 printf (" enumAndChron: %s\n",
1056 data->circulationData[j]->enumAndChron);
1057 if (data->circulationData[j]->midspine)
1058 printf (" midspine: %s\n",
1059 data->circulationData[j]->midspine);
1060 if (data->circulationData[j]->temporaryLocation)
1061 printf (" temporaryLocation: %s\n",
1062 data->circulationData[j]->temporaryLocation);
1069 printf("Unknown record representation.\n");
1070 if (!z_External(print, &r, 0, 0))
1072 odr_perror(print, "Printing external");
1078 static void display_diagrecs(Z_DiagRec **pp, int num)
1082 Z_DefaultDiagFormat *r;
1084 printf("Diagnostic message(s) from database:\n");
1085 for (i = 0; i<num; i++)
1087 Z_DiagRec *p = pp[i];
1088 if (p->which != Z_DiagRec_defaultFormat)
1090 printf("Diagnostic record not in default format.\n");
1094 r = p->u.defaultFormat;
1095 if (!(ent = oid_getentbyoid(r->diagnosticSetId)) ||
1096 ent->oclass != CLASS_DIAGSET || ent->value != VAL_BIB1)
1097 printf("Missing or unknown diagset\n");
1098 printf(" [%d] %s", *r->condition, diagbib1_str(*r->condition));
1101 case Z_DefaultDiagFormat_v2Addinfo:
1102 printf (" -- v2 addinfo '%s'\n", r->u.v2Addinfo);
1104 case Z_DefaultDiagFormat_v3Addinfo:
1105 printf (" -- v3 addinfo '%s'\n", r->u.v3Addinfo);
1112 static void display_nameplusrecord(Z_NamePlusRecord *p)
1114 if (p->databaseName)
1115 printf("[%s]", p->databaseName);
1116 if (p->which == Z_NamePlusRecord_surrogateDiagnostic)
1117 display_diagrecs(&p->u.surrogateDiagnostic, 1);
1118 else if (p->which == Z_NamePlusRecord_databaseRecord)
1119 display_record(p->u.databaseRecord);
1122 static void display_records(Z_Records *p)
1126 if (p->which == Z_Records_NSD)
1128 Z_DiagRec dr, *dr_p = &dr;
1129 dr.which = Z_DiagRec_defaultFormat;
1130 dr.u.defaultFormat = p->u.nonSurrogateDiagnostic;
1131 display_diagrecs (&dr_p, 1);
1133 else if (p->which == Z_Records_multipleNSD)
1134 display_diagrecs (p->u.multipleNonSurDiagnostics->diagRecs,
1135 p->u.multipleNonSurDiagnostics->num_diagRecs);
1138 printf("Records: %d\n", p->u.databaseOrSurDiagnostics->num_records);
1139 for (i = 0; i < p->u.databaseOrSurDiagnostics->num_records; i++)
1140 display_nameplusrecord(p->u.databaseOrSurDiagnostics->records[i]);
1144 static int send_deleteResultSetRequest(const char *arg)
1149 Z_APDU *apdu = zget_APDU(out, Z_APDU_deleteResultSetRequest);
1150 Z_DeleteResultSetRequest *req = apdu->u.deleteResultSetRequest;
1152 req->referenceId = set_refid (out);
1154 req->num_resultSetList =
1155 sscanf (arg, "%30s %30s %30s %30s %30s %30s %30s %30s",
1156 names[0], names[1], names[2], names[3],
1157 names[4], names[5], names[6], names[7]);
1159 req->deleteFunction = (int *)
1160 odr_malloc (out, sizeof(*req->deleteFunction));
1161 if (req->num_resultSetList > 0)
1163 *req->deleteFunction = Z_DeleteResultSetRequest_list;
1164 req->resultSetList = (char **)
1165 odr_malloc (out, sizeof(*req->resultSetList)*
1166 req->num_resultSetList);
1167 for (i = 0; i<req->num_resultSetList; i++)
1168 req->resultSetList[i] = names[i];
1172 *req->deleteFunction = Z_DeleteResultSetRequest_all;
1173 req->resultSetList = 0;
1177 printf("Sent deleteResultSetRequest.\n");
1182 static int send_srw(Z_SRW_PDU *sr)
1184 const char *charset = negotiationCharset;
1185 const char *host_port = cur_host;
1188 Z_SOAP_Handler h[2] = {
1189 {"http://www.loc.gov/zing/srw/", 0, (Z_SOAP_fun) yaz_srw_codec},
1192 ODR o = odr_createmem(ODR_ENCODE);
1194 Z_SOAP *p = odr_malloc(o, sizeof(*p));
1197 path = odr_malloc(out, strlen(databaseNames[0])+2);
1199 strcpy(path+1, databaseNames[0]);
1201 gdu = z_get_HTTP_Request(out);
1202 gdu->u.HTTP_Request->version = http_version;
1203 gdu->u.HTTP_Request->path = odr_strdup(out, path);
1207 const char *cp0 = strstr(host_port, "://");
1208 const char *cp1 = 0;
1214 cp1 = strchr(cp0, '/');
1216 cp1 = cp0+strlen(cp0);
1220 char *h = odr_malloc(out, cp1 - cp0 + 1);
1221 memcpy (h, cp0, cp1 - cp0);
1223 z_HTTP_header_add(out, &gdu->u.HTTP_Request->headers,
1228 strcpy(ctype, "text/xml");
1229 if (charset && strlen(charset) < 20)
1231 strcat(ctype, "; charset=");
1232 strcat(ctype, charset);
1234 z_HTTP_header_add(out, &gdu->u.HTTP_Request->headers,
1235 "Content-Type", ctype);
1236 z_HTTP_header_add(out, &gdu->u.HTTP_Request->headers,
1237 "SOAPAction", "\"\"");
1238 p->which = Z_SOAP_generic;
1239 p->u.generic = odr_malloc(o, sizeof(*p->u.generic));
1240 p->u.generic->no = 0;
1241 p->u.generic->ns = 0;
1242 p->u.generic->p = sr;
1243 p->ns = "http://schemas.xmlsoap.org/soap/envelope/";
1245 ret = z_soap_codec_enc(o, &p,
1246 &gdu->u.HTTP_Request->content_buf,
1247 &gdu->u.HTTP_Request->content_len, h,
1250 if (z_GDU(out, &gdu, 0, 0))
1258 if (!z_GDU(print, &gdu, 0, 0))
1259 printf ("Failed to print outgoing APDU\n");
1262 buf_out = odr_getbuf(out, &len_out, 0);
1264 /* we don't odr_reset(out), since we may need the buffer again */
1266 do_hex_dump(buf_out, len_out);
1268 r = cs_put(conn, buf_out, len_out);
1280 static int send_SRW_scanRequest(const char *arg, int pos, int num)
1284 /* regular requestse .. */
1285 sr = yaz_srw_get(out, Z_SRW_scan_request);
1290 sr->u.scan_request->query_type = Z_SRW_query_type_cql;
1291 sr->u.scan_request->scanClause.cql = odr_strdup(out, arg);
1293 case QueryType_Prefix:
1294 sr->u.scan_request->query_type = Z_SRW_query_type_pqf;
1295 sr->u.scan_request->scanClause.pqf = odr_strdup(out, arg);
1298 printf ("Only CQL and PQF supported in SRW\n");
1301 sr->u.scan_request->responsePosition = odr_intdup(out, pos);
1302 sr->u.scan_request->maximumTerms = odr_intdup(out, num);
1303 return send_srw(sr);
1306 static int send_SRW_searchRequest(const char *arg)
1312 assert(srw_sr_odr_out == 0);
1313 srw_sr_odr_out = odr_createmem(ODR_ENCODE);
1315 odr_reset(srw_sr_odr_out);
1319 /* save this for later .. when fetching individual records */
1320 srw_sr = yaz_srw_get(srw_sr_odr_out, Z_SRW_searchRetrieve_request);
1322 /* regular request .. */
1323 sr = yaz_srw_get(out, Z_SRW_searchRetrieve_request);
1328 srw_sr->u.request->query_type = Z_SRW_query_type_cql;
1329 srw_sr->u.request->query.cql = odr_strdup(srw_sr_odr_out, arg);
1331 sr->u.request->query_type = Z_SRW_query_type_cql;
1332 sr->u.request->query.cql = odr_strdup(out, arg);
1334 case QueryType_Prefix:
1335 srw_sr->u.request->query_type = Z_SRW_query_type_pqf;
1336 srw_sr->u.request->query.pqf = odr_strdup(srw_sr_odr_out, arg);
1338 sr->u.request->query_type = Z_SRW_query_type_pqf;
1339 sr->u.request->query.pqf = odr_strdup(out, arg);
1342 printf ("Only CQL and PQF supported in SRW\n");
1345 sr->u.request->maximumRecords = odr_intdup(out, 0);
1348 sr->u.request->recordSchema = record_schema;
1349 if (recordsyntax == VAL_TEXT_XML)
1350 sr->u.explain_request->recordPacking = "xml";
1351 return send_srw(sr);
1355 static int send_searchRequest(const char *arg)
1357 Z_APDU *apdu = zget_APDU(out, Z_APDU_searchRequest);
1358 Z_SearchRequest *req = apdu->u.searchRequest;
1360 struct ccl_rpn_node *rpn = NULL;
1362 char setstring[100];
1363 Z_RPNQuery *RPNquery;
1365 YAZ_PQF_Parser pqf_parser;
1367 QueryType myQueryType = queryType;
1370 if (myQueryType == QueryType_CCL2RPN)
1372 rpn = ccl_find_str(bibset, arg, &error, &pos);
1375 printf("CCL ERROR: %s\n", ccl_err_msg(error));
1378 } else if (myQueryType == QueryType_CQL2RPN) {
1379 /* ### All this code should be wrapped in a utility function */
1381 struct cql_node *node;
1382 const char *addinfo;
1383 if (cqltrans == 0) {
1384 printf("Can't use CQL: no translation file. Try set_cqlfile\n");
1387 parser = cql_parser_create();
1388 if ((error = cql_parser_string(parser, arg)) != 0) {
1389 printf("Can't parse CQL: must be a syntax error\n");
1392 node = cql_parser_result(parser);
1393 if ((error = cql_transform_buf(cqltrans, node, pqfbuf,
1394 sizeof pqfbuf)) != 0) {
1395 error = cql_transform_error(cqltrans, &addinfo);
1396 printf ("Can't convert CQL to PQF: %s (addinfo=%s)\n",
1397 cql_strerror(error), addinfo);
1401 myQueryType = QueryType_Prefix;
1404 req->referenceId = set_refid (out);
1405 if (!strcmp(arg, "@big")) /* strictly for troublemaking */
1407 static unsigned char big[2100];
1408 static Odr_oct bigo;
1410 /* send a very big referenceid to test transport stack etc. */
1411 memset(big, 'A', 2100);
1412 bigo.len = bigo.size = 2100;
1414 req->referenceId = &bigo;
1419 sprintf(setstring, "%d", ++setnumber);
1420 req->resultSetName = setstring;
1422 *req->smallSetUpperBound = smallSetUpperBound;
1423 *req->largeSetLowerBound = largeSetLowerBound;
1424 *req->mediumSetPresentNumber = mediumSetPresentNumber;
1425 if (smallSetUpperBound > 0 || (largeSetLowerBound > 1 &&
1426 mediumSetPresentNumber > 0))
1428 req->preferredRecordSyntax =
1429 yaz_oidval_to_z3950oid(out, CLASS_RECSYN, recordsyntax);
1431 req->smallSetElementSetNames =
1432 req->mediumSetElementSetNames = elementSetNames;
1434 req->num_databaseNames = num_databaseNames;
1435 req->databaseNames = databaseNames;
1437 req->query = &query;
1439 switch (myQueryType)
1441 case QueryType_Prefix:
1442 query.which = Z_Query_type_1;
1443 pqf_parser = yaz_pqf_create ();
1444 RPNquery = yaz_pqf_parse (pqf_parser, out, arg);
1447 const char *pqf_msg;
1449 int code = yaz_pqf_error (pqf_parser, &pqf_msg, &off);
1450 printf("%*s^\n", off+4, "");
1451 printf("Prefix query error: %s (code %d)\n", pqf_msg, code);
1453 yaz_pqf_destroy (pqf_parser);
1456 yaz_pqf_destroy (pqf_parser);
1457 query.u.type_1 = RPNquery;
1460 query.which = Z_Query_type_2;
1461 query.u.type_2 = &ccl_query;
1462 ccl_query.buf = (unsigned char*) arg;
1463 ccl_query.len = strlen(arg);
1465 case QueryType_CCL2RPN:
1466 query.which = Z_Query_type_1;
1467 RPNquery = ccl_rpn_query(out, rpn);
1470 printf ("Couldn't convert from CCL to RPN\n");
1473 query.u.type_1 = RPNquery;
1474 ccl_rpn_delete (rpn);
1477 query.which = Z_Query_type_104;
1478 ext = (Z_External *) odr_malloc(out, sizeof(*ext));
1479 ext->direct_reference = odr_getoidbystr(out, "1.2.840.10003.16.2");
1480 ext->indirect_reference = 0;
1481 ext->descriptor = 0;
1482 ext->which = Z_External_CQL;
1483 ext->u.cql = odr_strdup(out, arg);
1484 query.u.type_104 = ext;
1487 printf ("Unsupported query type\n");
1490 if (send_apdu(apdu))
1491 printf("Sent searchRequest.\n");
1496 /* display Query Expression as part of searchResult-1 */
1497 static void display_queryExpression (Z_QueryExpression *qe)
1501 if (qe->which == Z_QueryExpression_term)
1503 if (qe->u.term->queryTerm)
1505 Z_Term *term = qe->u.term->queryTerm;
1506 switch (term->which)
1508 case Z_Term_general:
1509 printf (" %.*s", term->u.general->len, term->u.general->buf);
1511 case Z_Term_characterString:
1512 printf (" %s", term->u.characterString);
1514 case Z_Term_numeric:
1515 printf (" %d", *term->u.numeric);
1525 /* see if we can find USR:SearchResult-1 */
1526 static void display_searchResult (Z_OtherInformation *o)
1531 for (i = 0; i < o->num_elements; i++)
1533 if (o->list[i]->which == Z_OtherInfo_externallyDefinedInfo)
1535 Z_External *ext = o->list[i]->information.externallyDefinedInfo;
1537 if (ext->which == Z_External_searchResult1)
1540 Z_SearchInfoReport *sr = ext->u.searchResult1;
1541 printf ("SearchResult-1:");
1542 for (j = 0; j < sr->num; j++)
1544 if (!sr->elements[j]->subqueryExpression)
1546 display_queryExpression (
1547 sr->elements[j]->subqueryExpression);
1548 display_queryExpression (
1549 sr->elements[j]->subqueryInterpretation);
1550 display_queryExpression (
1551 sr->elements[j]->subqueryRecommendation);
1552 if (sr->elements[j]->subqueryCount)
1553 printf ("(%d)", *sr->elements[j]->subqueryCount);
1561 static int process_searchResponse(Z_SearchResponse *res)
1563 printf ("Received SearchResponse.\n");
1564 print_refid (res->referenceId);
1565 if (*res->searchStatus)
1566 printf("Search was a success.\n");
1568 printf("Search was a bloomin' failure.\n");
1569 printf("Number of hits: %d", *res->resultCount);
1571 printf (", setno %d", setnumber);
1573 display_searchResult (res->additionalSearchInfo);
1574 printf("records returned: %d\n",
1575 *res->numberOfRecordsReturned);
1576 setno += *res->numberOfRecordsReturned;
1578 display_records(res->records);
1582 static void print_level(int iLevel)
1585 for (i = 0; i < iLevel * 4; i++)
1589 static void print_int(int iLevel, const char *pTag, int *pInt)
1593 print_level(iLevel);
1594 printf("%s: %d\n", pTag, *pInt);
1598 static void print_string(int iLevel, const char *pTag, const char *pString)
1600 if (pString != NULL)
1602 print_level(iLevel);
1603 printf("%s: %s\n", pTag, pString);
1607 static void print_oid(int iLevel, const char *pTag, Odr_oid *pOid)
1613 print_level(iLevel);
1614 printf("%s:", pTag);
1615 for (; *pInt != -1; pInt++)
1616 printf(" %d", *pInt);
1621 static void print_referenceId(int iLevel, Z_ReferenceId *referenceId)
1623 if (referenceId != NULL)
1627 print_level(iLevel);
1628 printf("Ref Id (%d, %d): ", referenceId->len, referenceId->size);
1629 for (i = 0; i < referenceId->len; i++)
1630 printf("%c", referenceId->buf[i]);
1635 static void print_string_or_numeric(int iLevel, const char *pTag, Z_StringOrNumeric *pStringNumeric)
1637 if (pStringNumeric != NULL)
1639 switch (pStringNumeric->which)
1641 case Z_StringOrNumeric_string:
1642 print_string(iLevel, pTag, pStringNumeric->u.string);
1645 case Z_StringOrNumeric_numeric:
1646 print_int(iLevel, pTag, pStringNumeric->u.numeric);
1650 print_level(iLevel);
1651 printf("%s: valid type for Z_StringOrNumeric\n", pTag);
1657 static void print_universe_report_duplicate(
1659 Z_UniverseReportDuplicate *pUniverseReportDuplicate)
1661 if (pUniverseReportDuplicate != NULL)
1663 print_level(iLevel);
1664 printf("Universe Report Duplicate: \n");
1666 print_string_or_numeric(iLevel, "Hit No",
1667 pUniverseReportDuplicate->hitno);
1671 static void print_universe_report_hits(
1673 Z_UniverseReportHits *pUniverseReportHits)
1675 if (pUniverseReportHits != NULL)
1677 print_level(iLevel);
1678 printf("Universe Report Hits: \n");
1680 print_string_or_numeric(iLevel, "Database",
1681 pUniverseReportHits->database);
1682 print_string_or_numeric(iLevel, "Hits", pUniverseReportHits->hits);
1686 static void print_universe_report(int iLevel, Z_UniverseReport *pUniverseReport)
1688 if (pUniverseReport != NULL)
1690 print_level(iLevel);
1691 printf("Universe Report: \n");
1693 print_int(iLevel, "Total Hits", pUniverseReport->totalHits);
1694 switch (pUniverseReport->which)
1696 case Z_UniverseReport_databaseHits:
1697 print_universe_report_hits(iLevel,
1698 pUniverseReport->u.databaseHits);
1701 case Z_UniverseReport_duplicate:
1702 print_universe_report_duplicate(iLevel,
1703 pUniverseReport->u.duplicate);
1707 print_level(iLevel);
1708 printf("Type: %d\n", pUniverseReport->which);
1714 static void print_external(int iLevel, Z_External *pExternal)
1716 if (pExternal != NULL)
1718 print_level(iLevel);
1719 printf("External: \n");
1721 print_oid(iLevel, "Direct Reference", pExternal->direct_reference);
1722 print_int(iLevel, "InDirect Reference", pExternal->indirect_reference);
1723 print_string(iLevel, "Descriptor", pExternal->descriptor);
1724 switch (pExternal->which)
1726 case Z_External_universeReport:
1727 print_universe_report(iLevel, pExternal->u.universeReport);
1731 print_level(iLevel);
1732 printf("Type: %d\n", pExternal->which);
1738 static int process_resourceControlRequest (Z_ResourceControlRequest *req)
1740 printf ("Received ResourceControlRequest.\n");
1741 print_referenceId(1, req->referenceId);
1742 print_int(1, "Suspended Flag", req->suspendedFlag);
1743 print_int(1, "Partial Results Available", req->partialResultsAvailable);
1744 print_int(1, "Response Required", req->responseRequired);
1745 print_int(1, "Triggered Request Flag", req->triggeredRequestFlag);
1746 print_external(1, req->resourceReport);
1750 void process_ESResponse(Z_ExtendedServicesResponse *res)
1753 switch (*res->operationStatus)
1755 case Z_ExtendedServicesResponse_done:
1758 case Z_ExtendedServicesResponse_accepted:
1759 printf ("accepted\n");
1761 case Z_ExtendedServicesResponse_failure:
1762 printf ("failure\n");
1763 display_diagrecs(res->diagnostics, res->num_diagnostics);
1766 printf ("unknown\n");
1768 if ( (*res->operationStatus != Z_ExtendedServicesResponse_failure) &&
1769 (res->num_diagnostics != 0) ) {
1770 display_diagrecs(res->diagnostics, res->num_diagnostics);
1772 print_refid (res->referenceId);
1773 if (res->taskPackage &&
1774 res->taskPackage->which == Z_External_extendedService)
1776 Z_TaskPackage *taskPackage = res->taskPackage->u.extendedService;
1777 Odr_oct *id = taskPackage->targetReference;
1778 Z_External *ext = taskPackage->taskSpecificParameters;
1782 printf ("Target Reference: ");
1783 print_stringn (id->buf, id->len);
1786 if (ext->which == Z_External_update)
1788 Z_IUUpdateTaskPackage *utp = ext->u.update->u.taskPackage;
1789 if (utp && utp->targetPart)
1791 Z_IUTargetPart *targetPart = utp->targetPart;
1794 for (i = 0; i<targetPart->num_taskPackageRecords; i++)
1797 Z_IUTaskPackageRecordStructure *tpr =
1798 targetPart->taskPackageRecords[i];
1799 printf ("task package record %d\n", i+1);
1800 if (tpr->which == Z_IUTaskPackageRecordStructure_record)
1802 display_record (tpr->u.record);
1806 printf ("other type\n");
1814 const char *get_ill_element (void *clientData, const char *element)
1819 static Z_External *create_external_itemRequest()
1821 struct ill_get_ctl ctl;
1822 ILL_ItemRequest *req;
1824 int item_request_size = 0;
1825 char *item_request_buf = 0;
1829 ctl.f = get_ill_element;
1831 req = ill_get_ItemRequest(&ctl, "ill", 0);
1833 printf ("ill_get_ItemRequest failed\n");
1835 if (!ill_ItemRequest (out, &req, 0, 0))
1839 ill_ItemRequest(print, &req, 0, 0);
1842 item_request_buf = odr_getbuf (out, &item_request_size, 0);
1843 if (item_request_buf)
1844 odr_setbuf (out, item_request_buf, item_request_size, 1);
1845 printf ("Couldn't encode ItemRequest, size %d\n", item_request_size);
1852 item_request_buf = odr_getbuf (out, &item_request_size, 0);
1853 oid.proto = PROTO_GENERAL;
1854 oid.oclass = CLASS_GENERAL;
1855 oid.value = VAL_ISO_ILL_1;
1857 r = (Z_External *) odr_malloc (out, sizeof(*r));
1858 r->direct_reference = odr_oiddup(out,oid_getoidbyent(&oid));
1859 r->indirect_reference = 0;
1861 r->which = Z_External_single;
1863 r->u.single_ASN1_type = (Odr_oct *)
1864 odr_malloc (out, sizeof(*r->u.single_ASN1_type));
1865 r->u.single_ASN1_type->buf = (unsigned char *)
1866 odr_malloc (out, item_request_size);
1867 r->u.single_ASN1_type->len = item_request_size;
1868 r->u.single_ASN1_type->size = item_request_size;
1869 memcpy (r->u.single_ASN1_type->buf, item_request_buf,
1872 do_hex_dump(item_request_buf,item_request_size);
1877 static Z_External *create_external_ILL_APDU(int which)
1879 struct ill_get_ctl ctl;
1882 int ill_request_size = 0;
1883 char *ill_request_buf = 0;
1887 ctl.f = get_ill_element;
1889 ill_apdu = ill_get_APDU(&ctl, "ill", 0);
1891 if (!ill_APDU (out, &ill_apdu, 0, 0))
1895 printf ("-------------------\n");
1896 ill_APDU(print, &ill_apdu, 0, 0);
1898 printf ("-------------------\n");
1900 ill_request_buf = odr_getbuf (out, &ill_request_size, 0);
1901 if (ill_request_buf)
1902 odr_setbuf (out, ill_request_buf, ill_request_size, 1);
1903 printf ("Couldn't encode ILL-Request, size %d\n", ill_request_size);
1909 ill_request_buf = odr_getbuf (out, &ill_request_size, 0);
1911 oid.proto = PROTO_GENERAL;
1912 oid.oclass = CLASS_GENERAL;
1913 oid.value = VAL_ISO_ILL_1;
1915 r = (Z_External *) odr_malloc (out, sizeof(*r));
1916 r->direct_reference = odr_oiddup(out,oid_getoidbyent(&oid));
1917 r->indirect_reference = 0;
1919 r->which = Z_External_single;
1921 r->u.single_ASN1_type = (Odr_oct *)
1922 odr_malloc (out, sizeof(*r->u.single_ASN1_type));
1923 r->u.single_ASN1_type->buf = (unsigned char *)
1924 odr_malloc (out, ill_request_size);
1925 r->u.single_ASN1_type->len = ill_request_size;
1926 r->u.single_ASN1_type->size = ill_request_size;
1927 memcpy (r->u.single_ASN1_type->buf, ill_request_buf, ill_request_size);
1928 /* printf ("len = %d\n", ill_request_size); */
1929 /* do_hex_dump(ill_request_buf,ill_request_size); */
1930 /* printf("--- end of extenal\n"); */
1937 static Z_External *create_ItemOrderExternal(const char *type, int itemno)
1939 Z_External *r = (Z_External *) odr_malloc(out, sizeof(Z_External));
1940 oident ItemOrderRequest;
1942 ItemOrderRequest.proto = PROTO_Z3950;
1943 ItemOrderRequest.oclass = CLASS_EXTSERV;
1944 ItemOrderRequest.value = VAL_ITEMORDER;
1946 r->direct_reference = odr_oiddup(out,oid_getoidbyent(&ItemOrderRequest));
1947 r->indirect_reference = 0;
1950 r->which = Z_External_itemOrder;
1952 r->u.itemOrder = (Z_ItemOrder *) odr_malloc(out,sizeof(Z_ItemOrder));
1953 memset(r->u.itemOrder, 0, sizeof(Z_ItemOrder));
1954 r->u.itemOrder->which=Z_IOItemOrder_esRequest;
1956 r->u.itemOrder->u.esRequest = (Z_IORequest *)
1957 odr_malloc(out,sizeof(Z_IORequest));
1958 memset(r->u.itemOrder->u.esRequest, 0, sizeof(Z_IORequest));
1960 r->u.itemOrder->u.esRequest->toKeep = (Z_IOOriginPartToKeep *)
1961 odr_malloc(out,sizeof(Z_IOOriginPartToKeep));
1962 memset(r->u.itemOrder->u.esRequest->toKeep, 0, sizeof(Z_IOOriginPartToKeep));
1963 r->u.itemOrder->u.esRequest->notToKeep = (Z_IOOriginPartNotToKeep *)
1964 odr_malloc(out,sizeof(Z_IOOriginPartNotToKeep));
1965 memset(r->u.itemOrder->u.esRequest->notToKeep, 0, sizeof(Z_IOOriginPartNotToKeep));
1967 r->u.itemOrder->u.esRequest->toKeep->supplDescription = NULL;
1968 r->u.itemOrder->u.esRequest->toKeep->contact = NULL;
1969 r->u.itemOrder->u.esRequest->toKeep->addlBilling = NULL;
1971 r->u.itemOrder->u.esRequest->notToKeep->resultSetItem =
1972 (Z_IOResultSetItem *) odr_malloc(out, sizeof(Z_IOResultSetItem));
1973 memset(r->u.itemOrder->u.esRequest->notToKeep->resultSetItem, 0, sizeof(Z_IOResultSetItem));
1974 r->u.itemOrder->u.esRequest->notToKeep->resultSetItem->resultSetId = "1";
1976 r->u.itemOrder->u.esRequest->notToKeep->resultSetItem->item =
1977 (int *) odr_malloc(out, sizeof(int));
1978 *r->u.itemOrder->u.esRequest->notToKeep->resultSetItem->item = itemno;
1980 if (!strcmp (type, "item") || !strcmp(type, "2"))
1982 printf ("using item-request\n");
1983 r->u.itemOrder->u.esRequest->notToKeep->itemRequest =
1984 create_external_itemRequest();
1986 else if (!strcmp(type, "ill") || !strcmp(type, "1"))
1988 printf ("using ILL-request\n");
1989 r->u.itemOrder->u.esRequest->notToKeep->itemRequest =
1990 create_external_ILL_APDU(ILL_APDU_ILL_Request);
1992 else if (!strcmp(type, "xml") || !strcmp(type, "3"))
1994 const char *xml_buf =
1996 " <type>request</type>\n"
1997 " <libraryNo>000200</libraryNo>\n"
1998 " <borrowerTicketNo> 1212 </borrowerTicketNo>\n"
2000 r->u.itemOrder->u.esRequest->notToKeep->itemRequest =
2001 z_ext_record (out, VAL_TEXT_XML, xml_buf, strlen(xml_buf));
2004 r->u.itemOrder->u.esRequest->notToKeep->itemRequest = 0;
2009 static int send_itemorder(const char *type, int itemno)
2011 Z_APDU *apdu = zget_APDU(out, Z_APDU_extendedServicesRequest);
2012 Z_ExtendedServicesRequest *req = apdu->u.extendedServicesRequest;
2013 oident ItemOrderRequest;
2015 ItemOrderRequest.proto = PROTO_Z3950;
2016 ItemOrderRequest.oclass = CLASS_EXTSERV;
2017 ItemOrderRequest.value = VAL_ITEMORDER;
2018 req->packageType = odr_oiddup(out,oid_getoidbyent(&ItemOrderRequest));
2019 req->packageName = esPackageName;
2021 req->taskSpecificParameters = create_ItemOrderExternal(type, itemno);
2027 static int only_z3950()
2029 if (protocol == PROTO_HTTP)
2031 printf ("Not supported by SRW\n");
2037 static int cmd_update_common(const char *arg, int version);
2039 static int cmd_update(const char *arg)
2041 return cmd_update_common(arg, 1);
2044 static int cmd_update0(const char *arg)
2046 return cmd_update_common(arg, 0);
2049 static int cmd_update_common(const char *arg, int version)
2051 Z_APDU *apdu = zget_APDU(out, Z_APDU_extendedServicesRequest );
2052 Z_ExtendedServicesRequest *req = apdu->u.extendedServicesRequest;
2054 char action[20], recid[20], fname[80];
2056 Z_External *record_this = 0;
2063 sscanf (arg, "%19s %19s %79s", action, recid, fname);
2065 if (!strcmp (action, "insert"))
2066 action_no = Z_IUOriginPartToKeep_recordInsert;
2067 else if (!strcmp (action, "replace"))
2068 action_no = Z_IUOriginPartToKeep_recordReplace;
2069 else if (!strcmp (action, "delete"))
2070 action_no = Z_IUOriginPartToKeep_recordDelete;
2071 else if (!strcmp (action, "update"))
2072 action_no = Z_IUOriginPartToKeep_specialUpdate;
2075 printf ("Bad action: %s\n", action);
2076 printf ("Possible values: insert, replace, delete, update\n");
2084 stat (fname, &status);
2085 if (S_ISREG(status.st_mode) && (inf = fopen(fname, "r")))
2087 size_t len = status.st_size;
2088 char *buf = (char *) xmalloc (len);
2090 fread (buf, 1, len, inf);
2094 record_this = z_ext_record (out, VAL_TEXT_XML, buf, len);
2100 printf ("File %s doesn't exist\n", fname);
2108 printf ("No last record (update ignored)\n");
2111 record_this = record_last;
2115 yaz_oidval_to_z3950oid(out, CLASS_EXTSERV,
2116 version == 0 ? VAL_DBUPDATE0 : VAL_DBUPDATE);
2118 req->packageName = esPackageName;
2120 req->referenceId = set_refid (out);
2122 r = req->taskSpecificParameters = (Z_External *)
2123 odr_malloc (out, sizeof(*r));
2124 r->direct_reference = req->packageType;
2125 r->indirect_reference = 0;
2129 Z_IU0OriginPartToKeep *toKeep;
2130 Z_IU0SuppliedRecords *notToKeep;
2132 r->which = Z_External_update0;
2133 r->u.update0 = (Z_IU0Update *) odr_malloc(out, sizeof(*r->u.update0));
2134 r->u.update0->which = Z_IUUpdate_esRequest;
2135 r->u.update0->u.esRequest = (Z_IU0UpdateEsRequest *)
2136 odr_malloc(out, sizeof(*r->u.update0->u.esRequest));
2137 toKeep = r->u.update0->u.esRequest->toKeep = (Z_IU0OriginPartToKeep *)
2138 odr_malloc(out, sizeof(*r->u.update0->u.esRequest->toKeep));
2140 toKeep->databaseName = databaseNames[0];
2142 toKeep->elementSetName = 0;
2144 toKeep->action = (int *) odr_malloc(out, sizeof(*toKeep->action));
2145 *toKeep->action = action_no;
2147 notToKeep = r->u.update0->u.esRequest->notToKeep = (Z_IU0SuppliedRecords *)
2148 odr_malloc(out, sizeof(*r->u.update0->u.esRequest->notToKeep));
2150 notToKeep->elements = (Z_IU0SuppliedRecords_elem **)
2151 odr_malloc(out, sizeof(*notToKeep->elements));
2152 notToKeep->elements[0] = (Z_IU0SuppliedRecords_elem *)
2153 odr_malloc(out, sizeof(**notToKeep->elements));
2154 notToKeep->elements[0]->which = Z_IUSuppliedRecords_elem_opaque;
2157 notToKeep->elements[0]->u.opaque = (Odr_oct *)
2158 odr_malloc (out, sizeof(Odr_oct));
2159 notToKeep->elements[0]->u.opaque->buf = (unsigned char *) recid;
2160 notToKeep->elements[0]->u.opaque->size = strlen(recid);
2161 notToKeep->elements[0]->u.opaque->len = strlen(recid);
2164 notToKeep->elements[0]->u.opaque = 0;
2165 notToKeep->elements[0]->supplementalId = 0;
2166 notToKeep->elements[0]->correlationInfo = 0;
2167 notToKeep->elements[0]->record = record_this;
2171 Z_IUOriginPartToKeep *toKeep;
2172 Z_IUSuppliedRecords *notToKeep;
2174 r->which = Z_External_update;
2175 r->u.update = (Z_IUUpdate *) odr_malloc(out, sizeof(*r->u.update));
2176 r->u.update->which = Z_IUUpdate_esRequest;
2177 r->u.update->u.esRequest = (Z_IUUpdateEsRequest *)
2178 odr_malloc(out, sizeof(*r->u.update->u.esRequest));
2179 toKeep = r->u.update->u.esRequest->toKeep = (Z_IUOriginPartToKeep *)
2180 odr_malloc(out, sizeof(*r->u.update->u.esRequest->toKeep));
2182 toKeep->databaseName = databaseNames[0];
2184 toKeep->elementSetName = 0;
2185 toKeep->actionQualifier = 0;
2186 toKeep->action = (int *) odr_malloc(out, sizeof(*toKeep->action));
2187 *toKeep->action = action_no;
2189 notToKeep = r->u.update->u.esRequest->notToKeep = (Z_IUSuppliedRecords *)
2190 odr_malloc(out, sizeof(*r->u.update->u.esRequest->notToKeep));
2192 notToKeep->elements = (Z_IUSuppliedRecords_elem **)
2193 odr_malloc(out, sizeof(*notToKeep->elements));
2194 notToKeep->elements[0] = (Z_IUSuppliedRecords_elem *)
2195 odr_malloc(out, sizeof(**notToKeep->elements));
2196 notToKeep->elements[0]->which = Z_IUSuppliedRecords_elem_opaque;
2199 notToKeep->elements[0]->u.opaque = (Odr_oct *)
2200 odr_malloc (out, sizeof(Odr_oct));
2201 notToKeep->elements[0]->u.opaque->buf = (unsigned char *) recid;
2202 notToKeep->elements[0]->u.opaque->size = strlen(recid);
2203 notToKeep->elements[0]->u.opaque->len = strlen(recid);
2206 notToKeep->elements[0]->u.opaque = 0;
2207 notToKeep->elements[0]->supplementalId = 0;
2208 notToKeep->elements[0]->correlationInfo = 0;
2209 notToKeep->elements[0]->record = record_this;
2217 static int cmd_itemorder(const char *arg)
2224 if (sscanf (arg, "%10s %d", type, &itemno) != 2)
2227 printf("Item order request\n");
2229 send_itemorder(type, itemno);
2233 static void show_opt(const char *arg, void *clientData)
2235 printf ("%s ", arg);
2238 static int cmd_zversion(const char *arg)
2241 z3950_version = atoi(arg);
2243 printf ("version is %d\n", z3950_version);
2247 static int cmd_options(const char *arg)
2253 r = yaz_init_opt_encode(&z3950_options, arg, &pos);
2257 yaz_init_opt_decode(&z3950_options, show_opt, 0);
2263 static int cmd_explain(const char *arg)
2265 if (protocol != PROTO_HTTP)
2276 /* save this for later .. when fetching individual records */
2277 sr = yaz_srw_get(out, Z_SRW_explain_request);
2278 if (recordsyntax == VAL_TEXT_XML)
2279 sr->u.explain_request->recordPacking = "xml";
2287 static int cmd_init(const char *arg)
2291 strncpy (cur_host, arg, sizeof(cur_host)-1);
2292 cur_host[sizeof(cur_host)-1] = 0;
2294 if (!conn || protocol != PROTO_Z3950)
2296 send_initRequest(cur_host);
2300 static int cmd_find(const char *arg)
2304 printf("Find what?\n");
2307 if (protocol == PROTO_HTTP)
2314 if (!send_SRW_searchRequest(arg))
2327 printf("Not connected yet\n");
2331 if (!send_searchRequest(arg))
2337 static int cmd_delete(const char *arg)
2341 printf("Not connected yet\n");
2346 if (!send_deleteResultSetRequest(arg))
2351 static int cmd_ssub(const char *arg)
2353 if (!(smallSetUpperBound = atoi(arg)))
2358 static int cmd_lslb(const char *arg)
2362 if (!(largeSetLowerBound = atoi(arg)))
2367 static int cmd_mspn(const char *arg)
2371 if (!(mediumSetPresentNumber = atoi(arg)))
2376 static int cmd_status(const char *arg)
2378 printf("smallSetUpperBound: %d\n", smallSetUpperBound);
2379 printf("largeSetLowerBound: %d\n", largeSetLowerBound);
2380 printf("mediumSetPresentNumber: %d\n", mediumSetPresentNumber);
2384 static int cmd_setnames(const char *arg)
2386 if (*arg == '1') /* enable ? */
2388 else if (*arg == '0') /* disable ? */
2390 else if (setnumber < 0) /* no args, toggle .. */
2396 printf("Set numbering enabled.\n");
2398 printf("Set numbering disabled.\n");
2402 /* PRESENT SERVICE ----------------------------- */
2404 static void parse_show_args(const char *arg_c, char *setstring,
2405 int *start, int *number)
2410 strncpy(arg, arg_c, sizeof(arg)-1);
2411 arg[sizeof(arg)-1] = '\0';
2413 if ((p = strchr(arg, '+')))
2415 *number = atoi(p + 1);
2420 if (p && (p=strchr(p+1, '+')))
2421 strcpy (setstring, p+1);
2422 else if (setnumber >= 0)
2423 sprintf(setstring, "%d", setnumber);
2428 static int send_presentRequest(const char *arg)
2430 Z_APDU *apdu = zget_APDU(out, Z_APDU_presentRequest);
2431 Z_PresentRequest *req = apdu->u.presentRequest;
2432 Z_RecordComposition compo;
2434 char setstring[100];
2436 req->referenceId = set_refid (out);
2438 parse_show_args(arg, setstring, &setno, &nos);
2440 req->resultSetId = setstring;
2442 req->resultSetStartPoint = &setno;
2443 req->numberOfRecordsRequested = &nos;
2445 req->preferredRecordSyntax =
2446 yaz_oidval_to_z3950oid(out, CLASS_RECSYN, recordsyntax);
2450 req->recordComposition = &compo;
2451 compo.which = Z_RecordComp_complex;
2452 compo.u.complex = (Z_CompSpec *)
2453 odr_malloc(out, sizeof(*compo.u.complex));
2454 compo.u.complex->selectAlternativeSyntax = (bool_t *)
2455 odr_malloc(out, sizeof(bool_t));
2456 *compo.u.complex->selectAlternativeSyntax = 0;
2458 compo.u.complex->generic = (Z_Specification *)
2459 odr_malloc(out, sizeof(*compo.u.complex->generic));
2460 compo.u.complex->generic->which = Z_Schema_oid;
2462 compo.u.complex->generic->schema.oid =
2463 yaz_str_to_z3950oid(out, CLASS_SCHEMA, record_schema);
2465 if (!compo.u.complex->generic->schema.oid)
2467 /* OID wasn't a schema! Try record syntax instead. */
2468 compo.u.complex->generic->schema.oid = (Odr_oid *)
2469 yaz_str_to_z3950oid(out, CLASS_RECSYN, record_schema);
2471 if (!elementSetNames)
2472 compo.u.complex->generic->elementSpec = 0;
2475 compo.u.complex->generic->elementSpec = (Z_ElementSpec *)
2476 odr_malloc(out, sizeof(Z_ElementSpec));
2477 compo.u.complex->generic->elementSpec->which =
2478 Z_ElementSpec_elementSetName;
2479 compo.u.complex->generic->elementSpec->u.elementSetName =
2480 elementSetNames->u.generic;
2482 compo.u.complex->num_dbSpecific = 0;
2483 compo.u.complex->dbSpecific = 0;
2484 compo.u.complex->num_recordSyntax = 0;
2485 compo.u.complex->recordSyntax = 0;
2487 else if (elementSetNames)
2489 req->recordComposition = &compo;
2490 compo.which = Z_RecordComp_simple;
2491 compo.u.simple = elementSetNames;
2494 printf("Sent presentRequest (%d+%d).\n", setno, nos);
2499 static int send_SRW_presentRequest(const char *arg)
2501 char setstring[100];
2503 Z_SRW_PDU *sr = srw_sr;
2507 parse_show_args(arg, setstring, &setno, &nos);
2508 sr->u.request->startRecord = odr_intdup(out, setno);
2509 sr->u.request->maximumRecords = odr_intdup(out, nos);
2511 sr->u.request->recordSchema = record_schema;
2512 if (recordsyntax == VAL_TEXT_XML)
2513 sr->u.request->recordPacking = "xml";
2514 return send_srw(sr);
2518 static void close_session (void)
2525 nmem_destroy (session_mem);
2534 void process_close(Z_Close *req)
2536 Z_APDU *apdu = zget_APDU(out, Z_APDU_close);
2537 Z_Close *res = apdu->u.close;
2539 static char *reasons[] =
2544 "cost limit reached",
2546 "security violation",
2553 printf("Reason: %s, message: %s\n", reasons[*req->closeReason],
2554 req->diagnosticInformation ? req->diagnosticInformation : "NULL");
2559 *res->closeReason = Z_Close_finished;
2561 printf("Sent response.\n");
2566 static int cmd_show(const char *arg)
2568 if (protocol == PROTO_HTTP)
2575 if (!send_SRW_presentRequest(arg))
2585 printf("Not connected yet\n");
2588 if (!send_presentRequest(arg))
2594 int cmd_quit(const char *arg)
2596 printf("See you later, alligator.\n");
2602 int cmd_cancel(const char *arg)
2604 Z_APDU *apdu = zget_APDU(out, Z_APDU_triggerResourceControlRequest);
2605 Z_TriggerResourceControlRequest *req =
2606 apdu->u.triggerResourceControlRequest;
2611 printf("Session not initialized yet\n");
2616 if (!ODR_MASK_GET(session->options, Z_Options_triggerResourceCtrl))
2618 printf("Target doesn't support cancel (trigger resource ctrl)\n");
2621 *req->requestedAction = Z_TriggerResourceControlRequest_cancel;
2622 req->resultSetWanted = &rfalse;
2623 req->referenceId = set_refid (out);
2626 printf("Sent cancel request\n");
2631 int cmd_cancel_find(const char *arg) {
2635 return cmd_cancel("");
2640 int send_scanrequest(const char *query, int pp, int num, const char *term)
2642 Z_APDU *apdu = zget_APDU(out, Z_APDU_scanRequest);
2643 Z_ScanRequest *req = apdu->u.scanRequest;
2647 if (queryType == QueryType_CCL2RPN)
2650 struct ccl_rpn_node *rpn;
2652 rpn = ccl_find_str (bibset, query, &error, &pos);
2655 printf("CCL ERROR: %s\n", ccl_err_msg(error));
2659 yaz_oidval_to_z3950oid(out, CLASS_ATTSET, VAL_BIB1);
2660 if (!(req->termListAndStartPoint = ccl_scan_query (out, rpn)))
2662 printf("Couldn't convert CCL to Scan term\n");
2665 ccl_rpn_delete (rpn);
2669 YAZ_PQF_Parser pqf_parser = yaz_pqf_create ();
2671 if (!(req->termListAndStartPoint =
2672 yaz_pqf_scan(pqf_parser, out, &req->attributeSet, query)))
2674 const char *pqf_msg;
2676 int code = yaz_pqf_error (pqf_parser, &pqf_msg, &off);
2677 printf("%*s^\n", off+7, "");
2678 printf("Prefix query error: %s (code %d)\n", pqf_msg, code);
2679 yaz_pqf_destroy (pqf_parser);
2682 yaz_pqf_destroy (pqf_parser);
2686 if (req->termListAndStartPoint->term &&
2687 req->termListAndStartPoint->term->which == Z_Term_general &&
2688 req->termListAndStartPoint->term->u.general)
2690 req->termListAndStartPoint->term->u.general->buf =
2691 (unsigned char *) odr_strdup(out, term);
2692 req->termListAndStartPoint->term->u.general->len =
2693 req->termListAndStartPoint->term->u.general->size =
2697 req->referenceId = set_refid (out);
2698 req->num_databaseNames = num_databaseNames;
2699 req->databaseNames = databaseNames;
2700 req->numberOfTermsRequested = #
2701 req->preferredPositionInResponse = &pp;
2702 req->stepSize = odr_intdup(out, scan_stepSize);
2707 int send_sortrequest(const char *arg, int newset)
2709 Z_APDU *apdu = zget_APDU(out, Z_APDU_sortRequest);
2710 Z_SortRequest *req = apdu->u.sortRequest;
2711 Z_SortKeySpecList *sksl = (Z_SortKeySpecList *)
2712 odr_malloc (out, sizeof(*sksl));
2718 sprintf (setstring, "%d", setnumber);
2720 sprintf (setstring, "default");
2722 req->referenceId = set_refid (out);
2724 req->num_inputResultSetNames = 1;
2725 req->inputResultSetNames = (Z_InternationalString **)
2726 odr_malloc (out, sizeof(*req->inputResultSetNames));
2727 req->inputResultSetNames[0] = odr_strdup (out, setstring);
2729 if (newset && setnumber >= 0)
2730 sprintf (setstring, "%d", ++setnumber);
2732 req->sortedResultSetName = odr_strdup (out, setstring);
2734 req->sortSequence = yaz_sort_spec (out, arg);
2735 if (!req->sortSequence)
2737 printf ("Missing sort specifications\n");
2744 void display_term(Z_TermInfo *t)
2747 printf("%s", t->displayTerm);
2748 else if (t->term->which == Z_Term_general)
2750 printf("%.*s", t->term->u.general->len, t->term->u.general->buf);
2751 sprintf(last_scan_line, "%.*s", t->term->u.general->len,
2752 t->term->u.general->buf);
2755 printf("Term (not general)");
2756 if (t->globalOccurrences)
2757 printf (" (%d)\n", *t->globalOccurrences);
2762 void process_scanResponse(Z_ScanResponse *res)
2765 Z_Entry **entries = NULL;
2766 int num_entries = 0;
2768 printf("Received ScanResponse\n");
2769 print_refid (res->referenceId);
2770 printf("%d entries", *res->numberOfEntriesReturned);
2771 if (res->positionOfTerm)
2772 printf (", position=%d", *res->positionOfTerm);
2774 if (*res->scanStatus != Z_Scan_success)
2775 printf("Scan returned code %d\n", *res->scanStatus);
2778 if ((entries = res->entries->entries))
2779 num_entries = res->entries->num_entries;
2780 for (i = 0; i < num_entries; i++)
2782 int pos_term = res->positionOfTerm ? *res->positionOfTerm : -1;
2783 if (entries[i]->which == Z_Entry_termInfo)
2785 printf("%c ", i + 1 == pos_term ? '*' : ' ');
2786 display_term(entries[i]->u.termInfo);
2789 display_diagrecs(&entries[i]->u.surrogateDiagnostic, 1);
2791 if (res->entries->nonsurrogateDiagnostics)
2792 display_diagrecs (res->entries->nonsurrogateDiagnostics,
2793 res->entries->num_nonsurrogateDiagnostics);
2796 void process_sortResponse(Z_SortResponse *res)
2798 printf("Received SortResponse: status=");
2799 switch (*res->sortStatus)
2801 case Z_SortResponse_success:
2802 printf ("success"); break;
2803 case Z_SortResponse_partial_1:
2804 printf ("partial"); break;
2805 case Z_SortResponse_failure:
2806 printf ("failure"); break;
2808 printf ("unknown (%d)", *res->sortStatus);
2811 print_refid (res->referenceId);
2812 if (res->diagnostics)
2813 display_diagrecs(res->diagnostics,
2814 res->num_diagnostics);
2817 void process_deleteResultSetResponse (Z_DeleteResultSetResponse *res)
2819 printf("Got deleteResultSetResponse status=%d\n",
2820 *res->deleteOperationStatus);
2821 if (res->deleteListStatuses)
2824 for (i = 0; i < res->deleteListStatuses->num; i++)
2826 printf ("%s status=%d\n", res->deleteListStatuses->elements[i]->id,
2827 *res->deleteListStatuses->elements[i]->status);
2832 int cmd_sort_generic(const char *arg, int newset)
2836 printf("Session not initialized yet\n");
2841 if (!ODR_MASK_GET(session->options, Z_Options_sort))
2843 printf("Target doesn't support sort\n");
2848 if (send_sortrequest(arg, newset) < 0)
2855 int cmd_sort(const char *arg)
2857 return cmd_sort_generic (arg, 0);
2860 int cmd_sort_newset (const char *arg)
2862 return cmd_sort_generic (arg, 1);
2865 int cmd_scanstep(const char *arg)
2867 scan_stepSize = atoi(arg);
2871 int cmd_scanpos(const char *arg)
2873 int r = sscanf(arg, "%d", &scan_position);
2879 int cmd_scansize(const char *arg)
2881 int r = sscanf(arg, "%d", &scan_size);
2887 int cmd_scan(const char *arg)
2889 if (protocol == PROTO_HTTP)
2898 if (send_SRW_scanRequest(arg, scan_position, scan_size) < 0)
2903 if (send_SRW_scanRequest(last_scan_line, 1, scan_size) < 0)
2918 printf("Session not initialized yet\n");
2922 if (!ODR_MASK_GET(session->options, Z_Options_scan))
2924 printf("Target doesn't support scan\n");
2929 strcpy (last_scan_query, arg);
2930 if (send_scanrequest(arg, scan_position, scan_size, 0) < 0)
2935 if (send_scanrequest(last_scan_query, 1, scan_size, last_scan_line) < 0)
2942 int cmd_schema(const char *arg)
2944 xfree(record_schema);
2947 record_schema = xstrdup(arg);
2951 int cmd_format(const char *arg)
2956 printf("Usage: format <recordsyntax>\n");
2959 nsyntax = oid_getvalbyname (arg);
2960 if (strcmp(arg, "none") && nsyntax == VAL_NONE)
2962 printf ("unknown record syntax\n");
2965 recordsyntax = nsyntax;
2969 int cmd_elements(const char *arg)
2971 static Z_ElementSetNames esn;
2972 static char what[100];
2976 elementSetNames = 0;
2980 esn.which = Z_ElementSetNames_generic;
2981 esn.u.generic = what;
2982 elementSetNames = &esn;
2986 int cmd_attributeset(const char *arg)
2992 printf("Usage: attributeset <setname>\n");
2995 sscanf(arg, "%s", what);
2996 if (p_query_attset (what))
2998 printf("Unknown attribute set name\n");
3004 int cmd_querytype (const char *arg)
3006 if (!strcmp (arg, "ccl"))
3007 queryType = QueryType_CCL;
3008 else if (!strcmp (arg, "prefix") || !strcmp(arg, "rpn"))
3009 queryType = QueryType_Prefix;
3010 else if (!strcmp (arg, "ccl2rpn") || !strcmp (arg, "cclrpn"))
3011 queryType = QueryType_CCL2RPN;
3012 else if (!strcmp(arg, "cql"))
3013 queryType = QueryType_CQL;
3014 else if (!strcmp (arg, "cql2rpn") || !strcmp (arg, "cqlrpn"))
3015 queryType = QueryType_CQL2RPN;
3018 printf ("Querytype must be one of:\n");
3019 printf (" prefix - Prefix query\n");
3020 printf (" ccl - CCL query\n");
3021 printf (" ccl2rpn - CCL query converted to RPN\n");
3022 printf (" cql - CQL\n");
3023 printf (" cql2rpn - CQL query converted to RPN\n");
3029 int cmd_refid (const char *arg)
3034 refid = xstrdup (arg);
3038 int cmd_close(const char *arg)
3047 apdu = zget_APDU(out, Z_APDU_close);
3048 req = apdu->u.close;
3049 *req->closeReason = Z_Close_finished;
3051 printf("Sent close request.\n");
3056 int cmd_packagename(const char* arg)
3058 xfree (esPackageName);
3059 esPackageName = NULL;
3061 esPackageName = xstrdup(arg);
3065 int cmd_proxy(const char* arg)
3070 yazProxy = xstrdup (arg);
3074 int cmd_marccharset(const char *arg)
3079 if (sscanf(arg, "%29s", l1) < 1)
3081 printf("MARC character set is `%s'\n",
3082 marcCharset ? marcCharset: "none");
3085 xfree (marcCharset);
3087 if (strcmp(l1, "-"))
3088 marcCharset = xstrdup(l1);
3092 int cmd_displaycharset(const char *arg)
3097 if (sscanf(arg, "%29s", l1) < 1)
3099 printf("Display character set is `%s'\n",
3100 outputCharset ? outputCharset: "none");
3104 xfree (outputCharset);
3106 if (!strcmp(l1, "auto") && codeset)
3110 printf ("Display character set: %s\n", codeset);
3111 outputCharset = xstrdup(codeset);
3114 printf ("No codeset found on this system\n");
3116 else if (strcmp(l1, "-") && strcmp(l1, "none"))
3117 outputCharset = xstrdup(l1);
3122 int cmd_negcharset(const char *arg)
3127 if (sscanf(arg, "%29s %d %d", l1, &negotiationCharsetRecords,
3128 &negotiationCharsetVersion) < 1)
3130 printf("Current negotiation character set is `%s'\n",
3131 negotiationCharset ? negotiationCharset: "none");
3132 printf("Records in charset %s\n", negotiationCharsetRecords ?
3134 printf("Charneg version %d\n", negotiationCharsetVersion);
3138 xfree (negotiationCharset);
3139 negotiationCharset = NULL;
3140 if (*l1 && strcmp(l1, "-") && strcmp(l1, "none"))
3142 negotiationCharset = xstrdup(l1);
3143 printf ("Character set negotiation : %s\n", negotiationCharset);
3149 int cmd_charset(const char* arg)
3151 char l1[30], l2[30], l3[30];
3153 *l1 = *l2 = *l3 = 0;
3154 if (sscanf(arg, "%29s %29s %29s", l1, l2, l3) < 1)
3157 cmd_displaycharset("");
3158 cmd_marccharset("");
3164 cmd_displaycharset(l2);
3166 cmd_marccharset(l3);
3171 int cmd_lang(const char* arg)
3174 printf("Current language is `%s'\n", (yazLang)?yazLang:NULL);
3180 yazLang = xstrdup(arg);
3184 int cmd_source(const char* arg, int echo )
3186 /* first should open the file and read one line at a time.. */
3188 char line[102400], *cp;
3191 fprintf(stderr,"Error in source command use a filename\n");
3195 includeFile = fopen (arg, "r");
3198 fprintf(stderr,"Unable to open file %s for reading\n",arg);
3202 while(!feof(includeFile)) {
3203 memset(line,0,sizeof(line));
3204 fgets(line,sizeof(line),includeFile);
3206 if(strlen(line) < 2) continue;
3207 if(line[0] == '#') continue;
3209 if ((cp = strrchr (line, '\n')))
3213 printf( "processing line: %s\n",line );
3215 process_cmd_line(line);
3218 if(fclose(includeFile)<0) {
3219 perror("unable to close include file");
3225 int cmd_source_echo(const char* arg)
3231 int cmd_source_noecho(const char* arg)
3238 int cmd_subshell(const char* args)
3243 system(getenv("SHELL"));
3249 int cmd_set_berfile(const char *arg)
3251 if (ber_file && ber_file != stdout && ber_file != stderr)
3253 if (!strcmp(arg, ""))
3255 else if (!strcmp(arg, "-"))
3258 ber_file = fopen(arg, "a");
3262 int cmd_set_apdufile(const char *arg)
3264 if(apdu_file && apdu_file != stderr && apdu_file != stderr)
3266 if (!strcmp(arg, ""))
3268 else if (!strcmp(arg, "-"))
3272 apdu_file = fopen(arg, "a");
3274 perror("unable to open apdu log file");
3277 odr_setprint(print, apdu_file);
3281 int cmd_set_cclfile(const char* arg)
3285 bibset = ccl_qual_mk ();
3286 inf = fopen (arg, "r");
3288 perror("unable to open CCL file");
3291 ccl_qual_file (bibset, inf);
3294 strcpy(ccl_fields,arg);
3298 int cmd_set_cqlfile(const char* arg)
3300 cql_transform_t newcqltrans;
3302 if ((newcqltrans = cql_transform_open_fname(arg)) == 0) {
3303 perror("unable to open CQL file");
3307 cql_transform_close(cqltrans);
3309 cqltrans = newcqltrans;
3310 strcpy(cql_fields, arg);
3314 int cmd_set_auto_reconnect(const char* arg)
3316 if(strlen(arg)==0) {
3317 auto_reconnect = ! auto_reconnect;
3318 } else if(strcmp(arg,"on")==0) {
3320 } else if(strcmp(arg,"off")==0) {
3323 printf("Error use on or off\n");
3328 printf("Set auto reconnect enabled.\n");
3330 printf("Set auto reconnect disabled.\n");
3335 int cmd_set_marcdump(const char* arg)
3337 if(marc_file && marc_file != stderr) { /* don't close stdout*/
3341 if (!strcmp(arg, ""))
3343 else if (!strcmp(arg, "-"))
3347 marc_file = fopen(arg, "a");
3349 perror("unable to open marc log file");
3355 this command takes 3 arge {name class oid}
3357 int cmd_register_oid(const char* args) {
3362 {"appctx",CLASS_APPCTX},
3363 {"absyn",CLASS_ABSYN},
3364 {"attset",CLASS_ATTSET},
3365 {"transyn",CLASS_TRANSYN},
3366 {"diagset",CLASS_DIAGSET},
3367 {"recsyn",CLASS_RECSYN},
3368 {"resform",CLASS_RESFORM},
3369 {"accform",CLASS_ACCFORM},
3370 {"extserv",CLASS_EXTSERV},
3371 {"userinfo",CLASS_USERINFO},
3372 {"elemspec",CLASS_ELEMSPEC},
3373 {"varset",CLASS_VARSET},
3374 {"schema",CLASS_SCHEMA},
3375 {"tagset",CLASS_TAGSET},
3376 {"general",CLASS_GENERAL},
3377 {0,(enum oid_class) 0}
3379 char oname_str[101], oclass_str[101], oid_str[101];
3382 oid_class oidclass = CLASS_GENERAL;
3383 int val = 0, oid[OID_SIZE];
3384 struct oident * new_oident=NULL;
3386 if (sscanf (args, "%100[^ ] %100[^ ] %100s",
3387 oname_str,oclass_str, oid_str) < 1) {
3388 printf("Error in register command \n");
3392 for (i = 0; oid_classes[i].className; i++) {
3393 if (!strcmp(oid_classes[i].className, oclass_str))
3395 oidclass=oid_classes[i].oclass;
3400 if(!(oid_classes[i].className)) {
3401 printf("Unknown oid class %s\n",oclass_str);
3409 while (isdigit (*(unsigned char *) name))
3411 val = val*10 + (*name - '0');
3424 new_oident = oid_addent (oid, PROTO_GENERAL, oidclass, oname_str,
3426 if(strcmp(new_oident->desc,oname_str))
3428 fprintf(stderr,"oid is already named as %s, registration failed\n",
3434 int cmd_push_command(const char* arg)
3436 #if HAVE_READLINE_HISTORY_H
3440 fprintf(stderr,"Not compiled with the readline/history module\n");
3445 void source_rcfile()
3447 /* Look for a $HOME/.yazclientrc and source it if it exists */
3448 struct stat statbuf;
3450 char* homedir=getenv("HOME");
3454 sprintf(buffer,"%s/.yazclientrc",homedir);
3456 if(stat(buffer,&statbuf)==0) {
3457 cmd_source(buffer, 0 );
3462 if(stat(".yazclientrc",&statbuf)==0) {
3463 cmd_source(".yazclientrc", 0 );
3468 static void initialize(void)
3473 if (!(out = odr_createmem(ODR_ENCODE)) ||
3474 !(in = odr_createmem(ODR_DECODE)) ||
3475 !(print = odr_createmem(ODR_PRINT)))
3477 fprintf(stderr, "failed to allocate ODR streams\n");
3482 setvbuf(stdout, 0, _IONBF, 0);
3484 odr_setprint(print, apdu_file);
3486 bibset = ccl_qual_mk ();
3487 inf = fopen (ccl_fields, "r");
3490 ccl_qual_file (bibset, inf);
3494 cqltrans = cql_transform_open_fname(cql_fields);
3495 /* If this fails, no problem: we detect cqltrans == 0 later */
3497 #if HAVE_READLINE_READLINE_H
3498 rl_attempted_completion_function = (CPPFunction*)readline_completer;
3502 for(i=0; i<maxOtherInfosSupported; ++i) {
3503 extraOtherInfos[i].oidval = -1;
3510 #if HAVE_GETTIMEOFDAY
3511 struct timeval tv_start, tv_end;
3515 static void handle_srw_record(Z_SRW_record *rec)
3517 if (rec->recordPosition)
3519 printf ("pos=%d", *rec->recordPosition);
3520 setno = *rec->recordPosition + 1;
3522 if (rec->recordSchema)
3523 printf (" schema=%s", rec->recordSchema);
3525 if (rec->recordData_buf && rec->recordData_len)
3527 fwrite(rec->recordData_buf, 1, rec->recordData_len, stdout);
3529 fwrite (rec->recordData_buf, 1, rec->recordData_len, marc_file);
3532 printf ("No data!");
3536 static void handle_srw_explain_response(Z_SRW_explainResponse *res)
3538 handle_srw_record(&res->record);
3541 static void handle_srw_response(Z_SRW_searchRetrieveResponse *res)
3545 printf ("Received SRW SearchRetrieve Response\n");
3547 for (i = 0; i<res->num_diagnostics; i++)
3549 if (res->diagnostics[i].uri)
3550 printf ("SRW diagnostic %s\n",
3551 res->diagnostics[i].uri);
3553 printf ("SRW diagnostic missing or could not be decoded\n");
3554 if (res->diagnostics[i].message)
3555 printf ("Message: %s\n", res->diagnostics[i].message);
3556 if (res->diagnostics[i].details)
3557 printf ("Details: %s\n", res->diagnostics[i].details);
3559 if (res->numberOfRecords)
3560 printf ("Number of hits: %d\n", *res->numberOfRecords);
3561 for (i = 0; i<res->num_records; i++)
3562 handle_srw_record(res->records + i);
3565 static void handle_srw_scan_term(Z_SRW_scanTerm *term)
3567 if (term->displayTerm)
3568 printf("%s:", term->displayTerm);
3569 else if (term->value)
3570 printf("%s:", term->value);
3572 printf("No value:");
3573 if (term->numberOfRecords)
3574 printf(" %d", *term->numberOfRecords);
3575 if (term->whereInList)
3576 printf(" %s", term->whereInList);
3577 if (term->value && term->displayTerm)
3578 printf(" %s", term->value);
3580 strcpy(last_scan_line, term->value);
3584 static void handle_srw_scan_response(Z_SRW_scanResponse *res)
3588 printf ("Received SRW Scan Response\n");
3590 for (i = 0; i<res->num_diagnostics; i++)
3592 if (res->diagnostics[i].uri)
3593 printf ("SRW diagnostic %s\n",
3594 res->diagnostics[i].uri);
3596 printf ("SRW diagnostic missing or could not be decoded\n");
3597 if (res->diagnostics[i].message)
3598 printf ("Message: %s\n", res->diagnostics[i].message);
3599 if (res->diagnostics[i].details)
3600 printf ("Details: %s\n", res->diagnostics[i].details);
3603 for (i = 0; i<res->num_terms; i++)
3604 handle_srw_scan_term(res->terms + i);
3607 static void http_response(Z_HTTP_Response *hres)
3610 const char *content_type = z_HTTP_header_lookup(hres->headers,
3612 const char *connection_head = z_HTTP_header_lookup(hres->headers,
3614 if (content_type && !yaz_strcmp_del("text/xml", content_type, "; "))
3616 Z_SOAP *soap_package = 0;
3617 ODR o = odr_createmem(ODR_DECODE);
3618 Z_SOAP_Handler soap_handlers[2] = {
3619 {"http://www.loc.gov/zing/srw/", 0,
3620 (Z_SOAP_fun) yaz_srw_codec},
3623 ret = z_soap_codec(o, &soap_package,
3624 &hres->content_buf, &hres->content_len,
3626 if (!ret && soap_package->which == Z_SOAP_generic &&
3627 soap_package->u.generic->no == 0)
3629 Z_SRW_PDU *sr = soap_package->u.generic->p;
3630 if (sr->which == Z_SRW_searchRetrieve_response)
3631 handle_srw_response(sr->u.response);
3632 else if (sr->which == Z_SRW_explain_response)
3633 handle_srw_explain_response(sr->u.explain_response);
3634 else if (sr->which == Z_SRW_scan_response)
3635 handle_srw_scan_response(sr->u.scan_response);
3639 else if (soap_package && (soap_package->which == Z_SOAP_fault
3640 || soap_package->which == Z_SOAP_error))
3642 printf ("HTTP Error Status=%d\n", hres->code);
3643 printf ("SOAP Fault code %s\n",
3644 soap_package->u.fault->fault_code);
3645 printf ("SOAP Fault string %s\n",
3646 soap_package->u.fault->fault_string);
3647 if (soap_package->u.fault->details)
3648 printf ("SOAP Details %s\n",
3649 soap_package->u.fault->details);
3657 if (hres->code != 200)
3659 printf ("HTTP Error Status=%d\n", hres->code);
3663 printf ("Decoding of SRW package failed\n");
3669 if (!strcmp(hres->version, "1.0"))
3671 /* HTTP 1.0: only if Keep-Alive we stay alive.. */
3672 if (!connection_head || strcmp(connection_head, "Keep-Alive"))
3677 /* HTTP 1.1: only if no close we stay alive .. */
3678 if (connection_head && !strcmp(connection_head, "close"))
3685 void wait_and_handle_response()
3687 int reconnect_ok = 1;
3690 int netbufferlen = 0;
3695 res = cs_get(conn, &netbuffer, &netbufferlen);
3696 if (reconnect_ok && res <= 0 && protocol == PROTO_HTTP)
3707 buf_out = odr_getbuf(out, &len_out, 0);
3709 do_hex_dump(buf_out, len_out);
3711 cs_put(conn, buf_out, len_out);
3719 printf("Target closed connection\n");
3724 odr_reset(in); /* release APDU from last round */
3726 do_hex_dump(netbuffer, res);
3727 odr_setbuf(in, netbuffer, res, 0);
3729 if (!z_GDU(in, &gdu, 0, 0))
3731 FILE *f = ber_file ? ber_file : stdout;
3732 odr_perror(in, "Decoding incoming APDU");
3733 fprintf(f, "[Near %d]\n", odr_offset(in));
3734 fprintf(f, "Packet dump:\n---------\n");
3735 odr_dumpBER(f, netbuffer, res);
3736 fprintf(f, "---------\n");
3739 z_GDU(print, &gdu, 0, 0);
3742 if (conn && cs_more(conn))
3747 odr_dumpBER(ber_file, netbuffer, res);
3748 if (apdu_file && !z_GDU(print, &gdu, 0, 0))
3750 odr_perror(print, "Failed to print incoming APDU");
3754 if (gdu->which == Z_GDU_Z3950)
3756 Z_APDU *apdu = gdu->u.z3950;
3759 case Z_APDU_initResponse:
3760 process_initResponse(apdu->u.initResponse);
3762 case Z_APDU_searchResponse:
3763 process_searchResponse(apdu->u.searchResponse);
3765 case Z_APDU_scanResponse:
3766 process_scanResponse(apdu->u.scanResponse);
3768 case Z_APDU_presentResponse:
3769 print_refid (apdu->u.presentResponse->referenceId);
3771 *apdu->u.presentResponse->numberOfRecordsReturned;
3772 if (apdu->u.presentResponse->records)
3773 display_records(apdu->u.presentResponse->records);
3775 printf("No records.\n");
3776 printf ("nextResultSetPosition = %d\n",
3777 *apdu->u.presentResponse->nextResultSetPosition);
3779 case Z_APDU_sortResponse:
3780 process_sortResponse(apdu->u.sortResponse);
3782 case Z_APDU_extendedServicesResponse:
3783 printf("Got extended services response\n");
3784 process_ESResponse(apdu->u.extendedServicesResponse);
3787 printf("Target has closed the association.\n");
3788 process_close(apdu->u.close);
3790 case Z_APDU_resourceControlRequest:
3791 process_resourceControlRequest
3792 (apdu->u.resourceControlRequest);
3794 case Z_APDU_deleteResultSetResponse:
3795 process_deleteResultSetResponse(apdu->u.
3796 deleteResultSetResponse);
3799 printf("Received unknown APDU type (%d).\n",
3805 else if (gdu->which == Z_GDU_HTTP_Response)
3807 http_response(gdu->u.HTTP_Response);
3810 if (conn && !cs_more(conn))
3815 #if HAVE_GETTIMEOFDAY
3816 gettimeofday (&tv_end, 0);
3818 printf ("S/U S/U=%ld/%ld %ld/%ld",
3819 (long) tv_start.tv_sec,
3820 (long) tv_start.tv_usec,
3821 (long) tv_end.tv_sec,
3822 (long) tv_end.tv_usec);
3824 printf ("Elapsed: %.6f\n",
3825 (double) tv_end.tv_usec / 1e6 + tv_end.tv_sec -
3826 ((double) tv_start.tv_usec / 1e6 + tv_start.tv_sec));
3833 int cmd_cclparse(const char* arg)
3836 struct ccl_rpn_node *rpn=NULL;
3839 rpn = ccl_find_str (bibset, arg, &error, &pos);
3842 printf ("%*s^ - ", 3+strlen(last_cmd)+1+pos, " ");
3843 printf ("%s\n", ccl_err_msg (error));
3849 ccl_pr_tree(rpn, stdout);
3853 ccl_rpn_delete(rpn);
3861 int cmd_set_otherinfo(const char* args)
3863 char oidstr[101], otherinfoString[101];
3868 sscan_res = sscanf (args, "%d %100[^ ] %100s", &otherinfoNo, oidstr, otherinfoString);
3870 /* reset this otherinfo */
3871 if(otherinfoNo>=maxOtherInfosSupported) {
3872 printf("Error otherinfo index to large (%d>%d)\n",
3873 otherinfoNo,maxOtherInfosSupported);
3875 extraOtherInfos[otherinfoNo].oidval = -1;
3876 if (extraOtherInfos[otherinfoNo].value)
3877 free(extraOtherInfos[otherinfoNo].value);
3881 printf("Error in set_otherinfo command \n");
3885 if (otherinfoNo>=maxOtherInfosSupported) {
3886 printf("Error otherinfo index to large (%d>%d)\n",
3887 otherinfoNo,maxOtherInfosSupported);
3890 oidval = oid_getvalbyname (oidstr);
3891 if (oidval == -1 ) {
3892 printf("Error in set_otherinfo command unknown oid %s \n",oidstr);
3895 extraOtherInfos[otherinfoNo].oidval = oidval;
3896 if(extraOtherInfos[otherinfoNo].value) free(extraOtherInfos[otherinfoNo].value);
3897 extraOtherInfos[otherinfoNo].value = strdup(otherinfoString);
3902 int cmd_sleep(const char* args )
3911 printf("Done sleeping %d seconds\n", sec);
3916 int cmd_list_otherinfo(const char* args)
3920 if(strlen(args)>0) {
3922 if( i >= maxOtherInfosSupported ) {
3923 printf("Error otherinfo index to large (%d>%d)\n",i,maxOtherInfosSupported);
3927 if(extraOtherInfos[i].oidval != -1)
3928 printf(" otherinfo %d %s %s\n",
3930 yaz_z3950_oid_value_to_str(
3931 (enum oid_value) extraOtherInfos[i].oidval,
3933 extraOtherInfos[i].value);
3936 for(i=0; i<maxOtherInfosSupported; ++i) {
3937 if(extraOtherInfos[i].oidval != -1)
3938 printf(" otherinfo %d %s %s\n",
3940 yaz_z3950_oid_value_to_str(
3941 (enum oid_value) extraOtherInfos[i].oidval,
3943 extraOtherInfos[i].value);
3951 int cmd_list_all(const char* args) {
3954 /* connection options */
3956 printf("Connected to : %s\n",last_open_command);
3958 if(last_open_command)
3959 printf("Not connected to : %s\n",last_open_command);
3961 printf("Not connected : \n");
3964 if(yazProxy) printf("using proxy : %s\n",yazProxy);
3966 printf("auto_reconnect : %s\n",auto_reconnect?"on":"off");
3969 printf("Authentication : none\n");
3971 switch(auth->which) {
3972 case Z_IdAuthentication_idPass:
3973 printf("Authentication : IdPass\n");
3974 printf(" Login User : %s\n",auth->u.idPass->userId?auth->u.idPass->userId:"");
3975 printf(" Login Group : %s\n",auth->u.idPass->groupId?auth->u.idPass->groupId:"");
3976 printf(" Password : %s\n",auth->u.idPass->password?auth->u.idPass->password:"");
3978 case Z_IdAuthentication_open:
3979 printf("Authentication : psOpen\n");
3980 printf(" Open string : %s\n",auth->u.open);
3983 printf("Authentication : Unknown\n");
3986 if (negotiationCharset)
3987 printf("Neg. Character set : `%s'\n", negotiationCharset);
3991 for (i = 0; i<num_databaseNames; i++) printf("%s ",databaseNames[i]);
3995 printf("CCL file : %s\n",ccl_fields);
3996 printf("CQL file : %s\n",cql_fields);
3997 printf("Query type : %s\n",query_type_as_string(queryType));
3999 printf("Named Result Sets : %s\n",setnumber==-1?"off":"on");
4001 /* piggy back options */
4002 printf("ssub/lslb/mspn : %d/%d/%d\n",smallSetUpperBound,largeSetLowerBound,mediumSetPresentNumber);
4004 /* print present related options */
4005 printf("Format : %s\n",yaz_z3950_oid_value_to_str(recordsyntax,CLASS_RECSYN));
4006 printf("Schema : %s\n",record_schema ? record_schema : "not set");
4007 printf("Elements : %s\n",elementSetNames?elementSetNames->u.generic:"");
4009 /* loging options */
4010 printf("APDU log : %s\n",apdu_file?"on":"off");
4011 printf("Record log : %s\n",marc_file?"on":"off");
4014 printf("Other Info: \n");
4015 cmd_list_otherinfo("");
4020 int cmd_clear_otherinfo(const char* args)
4022 if(strlen(args)>0) {
4024 otherinfoNo = atoi(args);
4025 if( otherinfoNo >= maxOtherInfosSupported ) {
4026 printf("Error otherinfo index to large (%d>%d)\n",otherinfoNo,maxOtherInfosSupported);
4030 if(extraOtherInfos[otherinfoNo].oidval != -1) {
4031 /* only clear if set. */
4032 extraOtherInfos[otherinfoNo].oidval=-1;
4033 free(extraOtherInfos[otherinfoNo].value);
4038 for(i=0; i<maxOtherInfosSupported; ++i) {
4039 if (extraOtherInfos[i].oidval!=-1 ) {
4040 extraOtherInfos[i].oidval=-1;
4041 free(extraOtherInfos[i].value);
4048 static int cmd_help (const char *line);
4050 typedef char *(*completerFunctionType)(const char *text, int state);
4054 int (*fun)(const char *arg);
4056 completerFunctionType rl_completerfunction;
4057 int complete_filenames;
4058 char **local_tabcompletes;
4060 {"open", cmd_open, "('tcp'|'ssl')':<host>[':'<port>][/<db>]",NULL,0,NULL},
4061 {"quit", cmd_quit, "",NULL,0,NULL},
4062 {"find", cmd_find, "<query>",NULL,0,NULL},
4063 {"delete", cmd_delete, "<setname>",NULL,0,NULL},
4064 {"base", cmd_base, "<base-name>",NULL,0,NULL},
4065 {"show", cmd_show, "<rec#>['+'<#recs>['+'<setname>]]",NULL,0,NULL},
4066 {"scan", cmd_scan, "<term>",NULL,0,NULL},
4067 {"scanstep", cmd_scanstep, "<size>",NULL,0,NULL},
4068 {"scanpos", cmd_scanpos, "<size>",NULL,0,NULL},
4069 {"scansize", cmd_scansize, "<size>",NULL,0,NULL},
4070 {"sort", cmd_sort, "<sortkey> <flag> <sortkey> <flag> ...",NULL,0,NULL},
4071 {"sort+", cmd_sort_newset, "<sortkey> <flag> <sortkey> <flag> ...",NULL,0,NULL},
4072 {"authentication", cmd_authentication, "<acctstring>",NULL,0,NULL},
4073 {"lslb", cmd_lslb, "<largeSetLowerBound>",NULL,0,NULL},
4074 {"ssub", cmd_ssub, "<smallSetUpperBound>",NULL,0,NULL},
4075 {"mspn", cmd_mspn, "<mediumSetPresentNumber>",NULL,0,NULL},
4076 {"status", cmd_status, "",NULL,0,NULL},
4077 {"setnames", cmd_setnames, "",NULL,0,NULL},
4078 {"cancel", cmd_cancel, "",NULL,0,NULL},
4079 {"cancel_find", cmd_cancel_find, "<query>",NULL,0,NULL},
4080 {"format", cmd_format, "<recordsyntax>",complete_format,0,NULL},
4081 {"schema", cmd_schema, "<schema>",complete_schema,0,NULL},
4082 {"elements", cmd_elements, "<elementSetName>",NULL,0,NULL},
4083 {"close", cmd_close, "",NULL,0,NULL},
4084 {"attributeset", cmd_attributeset, "<attrset>",complete_attributeset,0,NULL},
4085 {"querytype", cmd_querytype, "<type>",complete_querytype,0,NULL},
4086 {"refid", cmd_refid, "<id>",NULL,0,NULL},
4087 {"itemorder", cmd_itemorder, "ill|item <itemno>",NULL,0,NULL},
4088 {"update", cmd_update, "<action> <recid> [<file>]",NULL,0,NULL},
4089 {"update0", cmd_update0, "<action> <recid> [<file>]",NULL,0,NULL},
4090 {"packagename", cmd_packagename, "<packagename>",NULL,0,NULL},
4091 {"proxy", cmd_proxy, "[('tcp'|'ssl')]<host>[':'<port>]",NULL,0,NULL},
4092 {"charset", cmd_charset, "<nego_charset> <output_charset>",NULL,0,NULL},
4093 {"negcharset", cmd_negcharset, "<nego_charset>",NULL,0,NULL},
4094 {"displaycharset", cmd_displaycharset, "<output_charset>",NULL,0,NULL},
4095 {"marccharset", cmd_marccharset, "<charset_name>",NULL,0,NULL},
4096 {"lang", cmd_lang, "<language_code>",NULL,0,NULL},
4097 {".", cmd_source_echo, "<filename>",NULL,1,NULL},
4098 {"!", cmd_subshell, "Subshell command",NULL,1,NULL},
4099 {"set_apdufile", cmd_set_apdufile, "<filename>",NULL,1,NULL},
4100 {"set_berfile", cmd_set_berfile, "<filename>",NULL,1,NULL},
4101 {"set_marcdump", cmd_set_marcdump," <filename>",NULL,1,NULL},
4102 {"set_cclfile", cmd_set_cclfile," <filename>",NULL,1,NULL},
4103 {"set_cqlfile", cmd_set_cqlfile," <filename>",NULL,1,NULL},
4104 {"set_auto_reconnect", cmd_set_auto_reconnect," on|off",complete_auto_reconnect,1,NULL},
4105 {"set_otherinfo", cmd_set_otherinfo,"<otherinfoinddex> <oid> <string>",NULL,0,NULL},
4106 {"sleep", cmd_sleep,"<seconds>",NULL,0,NULL},
4107 {"register_oid", cmd_register_oid,"<name> <class> <oid>",NULL,0,NULL},
4108 {"push_command", cmd_push_command,"<command>",command_generator,0,NULL},
4109 {"register_tab", cmd_register_tab,"<commandname> <tab>",command_generator,0,NULL},
4110 {"cclparse", cmd_cclparse,"<ccl find command>",NULL,0,NULL},
4111 {"list_otherinfo",cmd_list_otherinfo,"[otherinfoinddex]",NULL,0,NULL},
4112 {"list_all",cmd_list_all,"",NULL,0,NULL},
4113 {"clear_otherinfo",cmd_clear_otherinfo,"",NULL,0,NULL},
4114 /* Server Admin Functions */
4115 {"adm-reindex", cmd_adm_reindex, "<database-name>",NULL,0,NULL},
4116 {"adm-truncate", cmd_adm_truncate, "('database'|'index')<object-name>",NULL,0,NULL},
4117 {"adm-create", cmd_adm_create, "",NULL,0,NULL},
4118 {"adm-drop", cmd_adm_drop, "('database'|'index')<object-name>",NULL,0,NULL},
4119 {"adm-import", cmd_adm_import, "<record-type> <dir> <pattern>",NULL,0,NULL},
4120 {"adm-refresh", cmd_adm_refresh, "",NULL,0,NULL},
4121 {"adm-commit", cmd_adm_commit, "",NULL,0,NULL},
4122 {"adm-shutdown", cmd_adm_shutdown, "",NULL,0,NULL},
4123 {"adm-startup", cmd_adm_startup, "",NULL,0,NULL},
4124 {"explain", cmd_explain, "", NULL, 0, NULL},
4125 {"options", cmd_options, "", NULL, 0, NULL},
4126 {"zversion", cmd_zversion, "", NULL, 0, NULL},
4127 {"help", cmd_help, "", NULL,0,NULL},
4128 {"init", cmd_init, "", NULL,0,NULL},
4132 static int cmd_help (const char *line)
4138 sscanf (line, "%20s", topic);
4141 printf("Commands:\n");
4142 for (i = 0; cmd_array[i].cmd; i++)
4143 if (*topic == 0 || strcmp (topic, cmd_array[i].cmd) == 0)
4144 printf(" %s %s\n", cmd_array[i].cmd, cmd_array[i].ad);
4145 if (strcmp (topic, "find") == 0)
4148 printf (" \"term\" Simple Term\n");
4149 printf (" @attr [attset] type=value op Attribute\n");
4150 printf (" @and opl opr And\n");
4151 printf (" @or opl opr Or\n");
4152 printf (" @not opl opr And-Not\n");
4153 printf (" @set set Result set\n");
4155 printf ("Bib-1 attribute types\n");
4157 printf ("4=Title 7=ISBN 8=ISSN 30=Date 62=Abstract 1003=Author 1016=Any\n");
4158 printf ("2=Relation: ");
4159 printf ("1< 2<= 3= 4>= 5> 6!= 102=Relevance\n");
4160 printf ("3=Position: ");
4161 printf ("1=First in Field 2=First in subfield 3=Any position\n");
4162 printf ("4=Structure: ");
4163 printf ("1=Phrase 2=Word 3=Key 4=Year 5=Date 6=WordList\n");
4164 printf ("5=Truncation: ");
4165 printf ("1=Right 2=Left 3=L&R 100=No 101=# 102=Re-1 103=Re-2\n");
4166 printf ("6=Completeness:");
4167 printf ("1=Incomplete subfield 2=Complete subfield 3=Complete field\n");
4172 int cmd_register_tab(const char* arg) {
4174 char command[101], tabargument[101];
4179 if (sscanf (arg, "%100s %100s", command, tabargument) < 1) {
4183 /* locate the amdn in the list */
4184 for (i = 0; cmd_array[i].cmd; i++) {
4185 if (!strncmp(cmd_array[i].cmd, command, strlen(command))) {
4190 if(!cmd_array[i].cmd) {
4191 fprintf(stderr,"Unknown command %s\n",command);
4196 if(!cmd_array[i].local_tabcompletes)
4197 cmd_array[i].local_tabcompletes = (char **) calloc(1,sizeof(char**));
4201 tabslist = cmd_array[i].local_tabcompletes;
4202 for(;tabslist && *tabslist;tabslist++) {
4206 cmd_array[i].local_tabcompletes = (char **)
4207 realloc(cmd_array[i].local_tabcompletes,(num_of_tabs+2)*sizeof(char**));
4208 tabslist=cmd_array[i].local_tabcompletes;
4209 tabslist[num_of_tabs]=strdup(tabargument);
4210 tabslist[num_of_tabs+1]=NULL;
4215 void process_cmd_line(char* line)
4218 char word[32], arg[10240];
4220 #if HAVE_GETTIMEOFDAY
4221 gettimeofday (&tv_start, 0);
4224 if ((res = sscanf(line, "%31s %10239[^;]", word, arg)) <= 0)
4226 strcpy(word, last_cmd);
4231 strcpy(last_cmd, word);
4233 /* removed tailing spaces from the arg command */
4236 char* lastnonspace=NULL;
4239 if(!isspace(*(unsigned char *) p)) {
4244 *(++lastnonspace) = 0;
4247 for (i = 0; cmd_array[i].cmd; i++)
4248 if (!strncmp(cmd_array[i].cmd, word, strlen(word)))
4250 res = (*cmd_array[i].fun)(arg);
4254 if (!cmd_array[i].cmd) /* dump our help-screen */
4256 printf("Unknown command: %s.\n", word);
4257 printf("use help for list of commands\n");
4258 /* cmd_help (""); */
4262 if(apdu_file) fflush(apdu_file);
4265 wait_and_handle_response();
4274 char *command_generator(const char *text, int state)
4280 for( ; cmd_array[idx].cmd; ++idx) {
4281 if (!strncmp(cmd_array[idx].cmd,text,strlen(text))) {
4282 ++idx; /* skip this entry on the next run */
4283 return strdup(cmd_array[idx-1].cmd);
4291 This function only known how to complete on the first word
4293 char ** readline_completer(char *text, int start, int end) {
4294 #if HAVE_READLINE_READLINE_H
4296 completerFunctionType completerToUse;
4299 #if HAVE_READLINE_RL_COMPLETION_MATCHES
4300 char** res=rl_completion_matches(text,
4303 char** res=completion_matches(text,
4304 (CPFunction*)command_generator);
4306 rl_attempted_completion_over = 1;
4309 char arg[10240],word[32];
4311 if ((res = sscanf(rl_line_buffer, "%31s %10239[^;]", word, arg)) <= 0) {
4312 rl_attempted_completion_over = 1;
4316 for (i = 0; cmd_array[i].cmd; i++) {
4317 if (!strncmp(cmd_array[i].cmd, word, strlen(word))) {
4322 if(!cmd_array[i].cmd) return NULL;
4324 curret_global_list = cmd_array[i].local_tabcompletes;
4326 completerToUse = cmd_array[i].rl_completerfunction;
4327 if(completerToUse==NULL) /* if no pr. command completer is defined use the default completer */
4328 completerToUse = default_completer;
4330 if(completerToUse) {
4331 #ifdef HAVE_READLINE_RL_COMPLETION_MATCHES
4333 rl_completion_matches(text,
4337 completion_matches(text,
4338 (CPFunction*)completerToUse);
4340 if(!cmd_array[i].complete_filenames)
4341 rl_attempted_completion_over = 1;
4344 if(!cmd_array[i].complete_filenames)
4345 rl_attempted_completion_over = 1;
4355 static void client(void)
4361 #if HAVE_GETTIMEOFDAY
4362 gettimeofday (&tv_start, 0);
4367 char *line_in = NULL;
4368 #if HAVE_READLINE_READLINE_H
4371 line_in=readline(C_PROMPT);
4374 #if HAVE_READLINE_HISTORY_H
4376 add_history(line_in);
4378 strncpy(line, line_in, 10239);
4387 if (!fgets(line, 10239, stdin))
4389 if ((end_p = strchr (line, '\n')))
4392 process_cmd_line(line);
4396 static void show_version(void)
4400 yaz_version(vstr, 0);
4401 printf ("YAZ version: %s\n", YAZ_VERSION);
4402 if (strcmp(vstr, YAZ_VERSION))
4403 printf ("YAZ DLL/SO: %s\n", vstr);
4407 int main(int argc, char **argv)
4410 char *open_command = 0;
4411 char *auth_command = 0;
4416 if (!setlocale(LC_CTYPE, ""))
4417 fprintf (stderr, "setlocale failed\n");
4421 codeset = nl_langinfo(CODESET);
4425 outputCharset = xstrdup(codeset);
4427 ODR_MASK_SET(&z3950_options, Z_Options_search);
4428 ODR_MASK_SET(&z3950_options, Z_Options_present);
4429 ODR_MASK_SET(&z3950_options, Z_Options_namedResultSets);
4430 ODR_MASK_SET(&z3950_options, Z_Options_triggerResourceCtrl);
4431 ODR_MASK_SET(&z3950_options, Z_Options_scan);
4432 ODR_MASK_SET(&z3950_options, Z_Options_sort);
4433 ODR_MASK_SET(&z3950_options, Z_Options_extendedServices);
4434 ODR_MASK_SET(&z3950_options, Z_Options_delSet);
4436 while ((ret = options("k:c:q:a:b:m:v:p:u:t:Vxd:", argv, argc, &arg)) != -2)
4443 open_command = (char *) xmalloc (strlen(arg)+6);
4444 strcpy (open_command, "open ");
4445 strcat (open_command, arg);
4449 dump_file_prefix = arg;
4452 kilobytes = atoi(arg);
4455 if (!(marc_file = fopen (arg, "a")))
4462 outputCharset = xstrdup(arg);
4465 strncpy (ccl_fields, arg, sizeof(ccl_fields)-1);
4466 ccl_fields[sizeof(ccl_fields)-1] = '\0';
4469 strncpy (cql_fields, arg, sizeof(cql_fields)-1);
4470 cql_fields[sizeof(cql_fields)-1] = '\0';
4473 if (!strcmp(arg, "-"))
4476 ber_file=fopen(arg, "a");
4479 if (!strcmp(arg, "-"))
4482 apdu_file=fopen(arg, "a");
4488 yazProxy=strdup(arg);
4493 auth_command = (char *) xmalloc (strlen(arg)+6);
4494 strcpy (auth_command, "auth ");
4495 strcat (auth_command, arg);
4499 yaz_log_init(yaz_log_mask_str(arg), "", 0);
4505 fprintf (stderr, "Usage: %s [-m <marclog>] [ -a <apdulog>] "
4506 "[-b berdump] [-c cclfields] \n"
4507 "[-q cqlfields] [-p <proxy-addr>] [-u <auth>] "
4508 "[-k size] [-d dump] [-V] [<server-addr>]\n",
4516 #ifdef HAVE_GETTIMEOFDAY
4517 gettimeofday (&tv_start, 0);
4519 process_cmd_line (auth_command);
4520 #if HAVE_READLINE_HISTORY_H
4521 add_history(auth_command);
4523 xfree(auth_command);
4527 #ifdef HAVE_GETTIMEOFDAY
4528 gettimeofday (&tv_start, 0);
4530 process_cmd_line (open_command);
4531 #if HAVE_READLINE_HISTORY_H
4532 add_history(open_command);
4534 xfree(open_command);
4545 * vim600: sw=4 ts=8 fdm=marker
4546 * vim<600: sw=4 ts=8