2 * Copyright (C) 1995-2005, Index Data ApS
3 * See the file LICENSE for details.
5 * $Id: client.c,v 1.271 2005-01-19 08:26:44 adam Exp $
14 #include <sys/types.h>
32 #if HAVE_OPENSSL_SSL_H
33 #include <openssl/bio.h>
34 #include <openssl/crypto.h>
35 #include <openssl/x509.h>
36 #include <openssl/pem.h>
37 #include <openssl/ssl.h>
38 #include <openssl/err.h>
45 #define S_ISREG(x) (x & _S_IFREG)
46 #define S_ISDIR(x) (x & _S_IFDIR)
49 #include <yaz/yaz-util.h>
51 #include <yaz/comstack.h>
53 #include <yaz/proto.h>
54 #include <yaz/marcdisp.h>
55 #include <yaz/diagbib1.h>
56 #include <yaz/otherinfo.h>
57 #include <yaz/charneg.h>
59 #include <yaz/pquery.h>
60 #include <yaz/sortspec.h>
64 #include <yaz/yaz-ccl.h>
68 #if HAVE_READLINE_READLINE_H
69 #include <readline/readline.h>
71 #if HAVE_READLINE_HISTORY_H
72 #include <readline/history.h>
77 #include "tabcomplete.h"
79 #define C_PROMPT "Z> "
81 static char *codeset = 0; /* character set for output */
82 static int hex_dump = 0;
83 static char *dump_file_prefix = 0;
84 static ODR out, in, print; /* encoding and decoding streams */
86 static ODR srw_sr_odr_out = 0;
87 static Z_SRW_PDU *srw_sr = 0;
89 static FILE *apdu_file = 0;
90 static FILE *ber_file = 0;
91 static COMSTACK conn = 0; /* our z-association */
92 static Z_IdAuthentication *auth = 0; /* our current auth definition */
93 char *databaseNames[128];
94 int num_databaseNames = 0;
95 static Z_External *record_last = 0;
96 static int setnumber = -1; /* current result set number */
97 static int smallSetUpperBound = 0;
98 static int largeSetLowerBound = 1;
99 static int mediumSetPresentNumber = 0;
100 static Z_ElementSetNames *elementSetNames = 0;
101 static int setno = 1; /* current set offset */
102 static enum oid_proto protocol = PROTO_Z3950; /* current app protocol */
103 static enum oid_value recordsyntax = VAL_USMARC;
104 static char *record_schema = 0;
105 static int sent_close = 0;
106 static NMEM session_mem = NULL; /* memory handle for init-response */
107 static Z_InitResponse *session = 0; /* session parameters */
108 static char last_scan_line[512] = "0";
109 static char last_scan_query[512] = "0";
110 static char ccl_fields[512] = "default.bib";
111 /* ### How can I set this path to use wherever YAZ is installed? */
112 static char cql_fields[512] = "/usr/local/share/yaz/etc/pqf.properties";
113 static char *esPackageName = 0;
114 static char *yazProxy = 0;
115 static int kilobytes = 1024;
116 static char *negotiationCharset = 0;
117 static int negotiationCharsetRecords = 1;
118 static int negotiationCharsetVersion = 3;
119 static char *outputCharset = 0;
120 static char *marcCharset = 0;
121 static char* yazLang = 0;
122 static char* http_version = "1.1";
124 static char last_cmd[32] = "?";
125 static FILE *marc_file = 0;
126 static char *refid = NULL;
127 static char *last_open_command = NULL;
128 static int auto_reconnect = 0;
129 static Odr_bitmask z3950_options;
130 static int z3950_version = 3;
131 static int scan_stepSize = 0;
132 static int scan_position = 1;
133 static char cur_host[200];
143 static QueryType queryType = QueryType_Prefix;
145 static CCL_bibset bibset; /* CCL bibset handle */
146 static cql_transform_t cqltrans; /* CQL context-set handle */
148 #if HAVE_READLINE_COMPLETION_OVER
151 /* readline doesn't have this var. Define it ourselves. */
152 int rl_attempted_completion_over = 0;
155 /* set this one to 1, to avoid decode of unknown MARCs */
156 #define AVOID_MARC_DECODE 1
158 #define maxOtherInfosSupported 10
162 } extraOtherInfos[maxOtherInfosSupported];
165 void process_cmd_line(char* line);
166 char ** readline_completer(char *text, int start, int end);
167 char *command_generator(const char *text, int state);
168 char** curret_global_list=NULL;
169 int cmd_register_tab(const char* arg);
171 static void close_session (void);
173 ODR getODROutputStream()
178 const char* query_type_as_string(QueryType q)
181 case QueryType_Prefix: return "prefix (RPN sent to server)";
182 case QueryType_CCL: return "CCL (CCL sent to server) ";
183 case QueryType_CCL2RPN: return "CCL -> RPN (RPN sent to server)";
184 case QueryType_CQL: return "CQL (CQL sent to server)";
185 case QueryType_CQL2RPN: return "CQL -> RPN (RPN sent to server)";
187 return "unknown Query type internal yaz-client error";
191 static void do_hex_dump(const char* buf, int len)
196 for( i=0; i<len ; i=i+16 )
199 for(x=0 ; i+x<len && x<16; ++x)
201 printf("%2.2X ",(unsigned int)((unsigned char)buf[i+x]));
206 if (dump_file_prefix)
209 if (++no < 1000 && strlen(dump_file_prefix) < 500)
213 sprintf (fname, "%s.%03d.raw", dump_file_prefix, no);
214 of = fopen(fname, "wb");
216 fwrite (buf, 1, len, of);
223 void add_otherInfos(Z_APDU *a)
225 Z_OtherInformation **oi;
229 for(i=0; i<maxOtherInfosSupported; ++i)
231 if(extraOtherInfos[i].oidval != -1)
232 yaz_oi_set_string_oidval(oi, out, extraOtherInfos[i].oidval,
233 1, extraOtherInfos[i].value);
237 int send_apdu(Z_APDU *a)
246 z_APDU(print, &a, 0, 0);
249 if (!z_APDU(out, &a, 0, 0))
251 odr_perror(out, "Encoding APDU");
255 buf = odr_getbuf(out, &len, 0);
257 odr_dumpBER(ber_file, buf, len);
258 /* printf ("sending APDU of size %d\n", len); */
259 do_hex_dump(buf, len);
260 if (cs_put(conn, buf, len) < 0)
262 fprintf(stderr, "cs_put: %s", cs_errmsg(cs_errno(conn)));
266 odr_reset(out); /* release the APDU structure */
270 static void print_stringn(const unsigned char *buf, size_t len)
273 for (i = 0; i<len; i++)
274 if ((buf[i] <= 126 && buf[i] >= 32) || strchr ("\n\r\t\f", buf[i]))
275 printf ("%c", buf[i]);
277 printf ("\\X%02X", buf[i]);
280 static void print_refid (Z_ReferenceId *id)
284 printf ("Reference Id: ");
285 print_stringn (id->buf, id->len);
290 static Z_ReferenceId *set_refid (ODR out)
295 id = (Z_ReferenceId *) odr_malloc (out, sizeof(*id));
296 id->size = id->len = strlen(refid);
297 id->buf = (unsigned char *) odr_malloc (out, id->len);
298 memcpy (id->buf, refid, id->len);
302 /* INIT SERVICE ------------------------------- */
304 static void send_initRequest(const char* type_and_host)
306 Z_APDU *apdu = zget_APDU(out, Z_APDU_initRequest);
307 Z_InitRequest *req = apdu->u.initRequest;
310 req->options = &z3950_options;
312 ODR_MASK_ZERO(req->protocolVersion);
313 for (i = 0; i<z3950_version; i++)
314 ODR_MASK_SET(req->protocolVersion, i);
316 *req->maximumRecordSize = 1024*kilobytes;
317 *req->preferredMessageSize = 1024*kilobytes;
319 req->idAuthentication = auth;
321 req->referenceId = set_refid (out);
323 if (yazProxy && type_and_host)
324 yaz_oi_set_string_oidval(&req->otherInfo, out, VAL_PROXY,
327 if (negotiationCharset || yazLang) {
328 Z_OtherInformation **p;
329 Z_OtherInformationUnit *p0;
331 yaz_oi_APDU(apdu, &p);
333 if ((p0=yaz_oi_update(p, out, NULL, 0, 0))) {
334 ODR_MASK_SET(req->options, Z_Options_negotiationModel);
336 p0->which = Z_OtherInfo_externallyDefinedInfo;
337 p0->information.externallyDefinedInfo =
338 yaz_set_proposal_charneg(
340 (const char**)&negotiationCharset,
341 negotiationCharset ? 1 : 0,
342 (const char**)&yazLang, yazLang ? 1 : 0,
343 negotiationCharsetRecords);
348 printf("Sent initrequest.\n");
352 /* These two are used only from process_initResponse() */
353 static void render_initUserInfo(Z_OtherInformation *ui1);
354 static void render_diag(Z_DiagnosticFormat *diag);
356 static void pr_opt(const char *opt, void *clientData)
361 static int process_initResponse(Z_InitResponse *res)
364 /* save session parameters for later use */
365 session_mem = odr_extract_mem(in);
368 for (ver = 0; ver < 8; ver++)
369 if (!ODR_MASK_GET(res->protocolVersion, ver))
373 printf("Connection rejected by v%d target.\n", ver);
375 printf("Connection accepted by v%d target.\n", ver);
376 if (res->implementationId)
377 printf("ID : %s\n", res->implementationId);
378 if (res->implementationName)
379 printf("Name : %s\n", res->implementationName);
380 if (res->implementationVersion)
381 printf("Version: %s\n", res->implementationVersion);
382 if (res->userInformationField)
384 Z_External *uif = res->userInformationField;
385 if (uif->which == Z_External_userInfo1) {
386 render_initUserInfo(uif->u.userInfo1);
388 printf("UserInformationfield:\n");
389 if (!z_External(print, (Z_External**)&uif, 0, 0)) {
390 odr_perror(print, "Printing userinfo\n");
393 if (uif->which == Z_External_octet) {
394 printf("Guessing visiblestring:\n");
395 printf("'%s'\n", uif->u. octet_aligned->buf);
396 } else if (uif->which == Z_External_single) {
397 Odr_any *sat = uif->u.single_ASN1_type;
398 oident *oid = oid_getentbyoid(uif->direct_reference);
399 if (oid->value == VAL_OCLCUI) {
400 Z_OCLC_UserInformation *oclc_ui;
401 ODR decode = odr_createmem(ODR_DECODE);
402 odr_setbuf(decode, sat->buf, sat->len, 0);
403 if (!z_OCLC_UserInformation(decode, &oclc_ui, 0, 0))
404 printf ("Bad OCLC UserInformation:\n");
406 printf ("OCLC UserInformation:\n");
407 if (!z_OCLC_UserInformation(print, &oclc_ui, 0, 0))
408 printf ("Bad OCLC UserInformation spec\n");
413 /* Peek at any private Init-diagnostic APDUs */
414 printf("### NAUGHTY: External is '%.*s'\n", sat->len, sat->buf);
421 yaz_init_opt_decode(res->options, pr_opt, 0);
424 if (ODR_MASK_GET(res->options, Z_Options_namedResultSets))
427 if (ODR_MASK_GET(res->options, Z_Options_negotiationModel)) {
429 Z_CharSetandLanguageNegotiation *p =
430 yaz_get_charneg_record(res->otherInfo);
434 char *charset=NULL, *lang=NULL;
437 yaz_get_response_charneg(session_mem, p, &charset, &lang,
440 if (outputCharset && negotiationCharset) {
441 odr_set_charset (out, charset, outputCharset);
442 odr_set_charset (in, outputCharset, charset);
445 odr_set_charset (out, 0, 0);
446 odr_set_charset (in, 0, 0);
449 printf("Accepted character set : %s\n", charset);
450 printf("Accepted code language : %s\n", lang ? lang : "none");
451 printf("Accepted records in ...: %d\n", selected );
459 static void render_initUserInfo(Z_OtherInformation *ui1) {
461 printf("Init response contains %d otherInfo unit%s:\n",
462 ui1->num_elements, ui1->num_elements == 1 ? "" : "s");
464 for (i = 0; i < ui1->num_elements; i++) {
465 Z_OtherInformationUnit *unit = ui1->list[i];
466 printf(" %d: otherInfo unit contains ", i+1);
467 if (unit->which == Z_OtherInfo_externallyDefinedInfo &&
468 unit->information.externallyDefinedInfo->which ==
470 render_diag(unit->information.externallyDefinedInfo->u.diag1);
472 printf("unsupported otherInfo unit type %d\n", unit->which);
478 /* ### should this share code with display_diagrecs()? */
479 static void render_diag(Z_DiagnosticFormat *diag) {
482 printf("%d diagnostic%s:\n", diag->num, diag->num == 1 ? "" : "s");
483 for (i = 0; i < diag->num; i++) {
484 Z_DiagnosticFormat_s *ds = diag->elements[i];
485 printf(" %d: ", i+1);
487 case Z_DiagnosticFormat_s_defaultDiagRec: {
488 Z_DefaultDiagFormat *dd = ds->u.defaultDiagRec;
489 /* ### should check `dd->diagnosticSetId' */
490 printf("code=%d (%s)", *dd->condition,
491 diagbib1_str(*dd->condition));
492 /* Both types of addinfo are the same, so use type-pun */
493 if (dd->u.v2Addinfo != 0)
494 printf(",\n\taddinfo='%s'", dd->u.v2Addinfo);
497 case Z_DiagnosticFormat_s_explicitDiagnostic:
498 printf("Explicit diagnostic (not supported)");
501 printf("Unrecognised diagnostic type %d", ds->which);
505 if (ds->message != 0)
506 printf(", message='%s'", ds->message);
512 static int set_base(const char *arg)
517 for (i = 0; i<num_databaseNames; i++)
518 xfree (databaseNames[i]);
519 num_databaseNames = 0;
523 if (!(cp = strchr(arg, ' ')))
524 cp = arg + strlen(arg);
527 databaseNames[num_databaseNames] = (char *)xmalloc (1 + cp - arg);
528 memcpy (databaseNames[num_databaseNames], arg, cp - arg);
529 databaseNames[num_databaseNames][cp - arg] = '\0';
531 for (cp1 = databaseNames[num_databaseNames]; *cp1 ; cp1++)
540 if (num_databaseNames == 0)
542 num_databaseNames = 1;
543 databaseNames[0] = xstrdup("");
548 static int cmd_base(const char *arg)
552 printf("Usage: base <database> <database> ...\n");
555 return set_base(arg);
558 void cmd_open_remember_last_open_command(const char* arg, char* new_open_command)
560 if(last_open_command != arg)
562 if(last_open_command) xfree(last_open_command);
563 last_open_command = xstrdup(new_open_command);
567 int session_connect(const char *arg)
570 char type_and_host[101];
571 const char *basep = 0;
572 #if HAVE_OPENSSL_SSL_H
581 nmem_destroy (session_mem);
585 cs_get_host_args(arg, &basep);
587 strncpy(type_and_host, arg, sizeof(type_and_host)-1);
588 type_and_host[sizeof(type_and_host)-1] = '\0';
590 cmd_open_remember_last_open_command(arg,type_and_host);
593 conn = cs_create_host(yazProxy, 1, &add);
595 conn = cs_create_host(arg, 1, &add);
598 printf ("Couldn't create comstack\n");
602 if (conn->protocol == PROTO_HTTP)
603 queryType = QueryType_CQL;
605 if (conn->protocol == PROTO_HTTP)
607 printf ("SRW/HTTP not enabled in this YAZ\n");
613 protocol = conn->protocol;
614 if (conn->protocol == PROTO_HTTP)
618 printf("Connecting...");
620 if (cs_connect(conn, add) < 0)
622 printf ("error = %s\n", cs_strerror(conn));
623 if (conn->cerrno == CSYSERR)
626 yaz_strerror(msg, sizeof(msg));
627 printf ("%s\n", msg);
634 #if HAVE_OPENSSL_SSL_H
635 if ((ssl = (SSL *) cs_get_ssl(conn)))
637 X509 *server_cert = SSL_get_peer_certificate (ssl);
643 BIO *bio = BIO_new(BIO_s_mem());
645 /* get PEM buffer in memory */
646 PEM_write_bio_X509(bio, server_cert);
647 pem_len = BIO_get_mem_data(bio, &pem_buf);
648 fwrite(pem_buf, pem_len, 1, stdout);
650 /* print all info on screen .. */
651 X509_print_fp(stdout, server_cert);
654 X509_free (server_cert);
660 if (protocol == PROTO_Z3950)
662 send_initRequest(type_and_host);
668 int cmd_open(const char *arg)
672 strncpy (cur_host, arg, sizeof(cur_host)-1);
673 cur_host[sizeof(cur_host)-1] = 0;
675 return session_connect(cur_host);
682 if(!( auto_reconnect && last_open_command) ) return ;
684 open_command = (char *) xmalloc (strlen(last_open_command)+6);
685 strcpy (open_command, "open ");
687 strcat (open_command, last_open_command);
689 process_cmd_line(open_command);
694 int cmd_authentication(const char *arg)
696 static Z_IdAuthentication au;
697 static char user[40], group[40], pass[40];
698 static Z_IdPass idPass;
703 printf("Auth field set to null\n");
707 r = sscanf (arg, "%39s %39s %39s", user, group, pass);
710 printf("Authentication set to null\n");
716 if (!strcmp(user, "-")) {
717 au.which = Z_IdAuthentication_anonymous;
718 printf("Authentication set to Anonymous\n");
720 au.which = Z_IdAuthentication_open;
722 printf("Authentication set to Open (%s)\n", user);
728 au.which = Z_IdAuthentication_idPass;
729 au.u.idPass = &idPass;
730 idPass.groupId = NULL;
731 idPass.userId = user;
732 idPass.password = group;
733 printf("Authentication set to User (%s), Pass (%s)\n", user, group);
738 au.which = Z_IdAuthentication_idPass;
739 au.u.idPass = &idPass;
740 idPass.groupId = group;
741 idPass.userId = user;
742 idPass.password = pass;
743 printf("Authentication set to User (%s), Group (%s), Pass (%s)\n",
749 /* SEARCH SERVICE ------------------------------ */
750 static void display_record(Z_External *r);
752 static void print_record(const unsigned char *buf, size_t len)
755 print_stringn (buf, len);
756 /* add newline if not already added ... */
757 if (i <= 0 || buf[i-1] != '\n')
760 fwrite (buf, 1, len, marc_file);
763 static void display_record(Z_External *r)
765 oident *ent = oid_getentbyoid(r->direct_reference);
769 * Tell the user what we got.
771 if (r->direct_reference)
773 printf("Record type: ");
775 printf("%s\n", ent->desc);
776 else if (!odr_oid(print, &r->direct_reference, 0, 0))
778 odr_perror(print, "print oid");
782 /* Check if this is a known, ASN.1 type tucked away in an octet string */
783 if (ent && r->which == Z_External_octet)
785 Z_ext_typeent *type = z_ext_getentbyref(ent->value);
791 * Call the given decoder to process the record.
793 odr_setbuf(in, (char*)r->u.octet_aligned->buf,
794 r->u.octet_aligned->len, 0);
795 if (!(*type->fun)(in, &rr, 0, 0))
797 odr_perror(in, "Decoding constructed record.");
798 fprintf(stdout, "[Near %d]\n", odr_offset(in));
799 fprintf(stdout, "Packet dump:\n---------\n");
800 odr_dumpBER(stdout, (char*)r->u.octet_aligned->buf,
801 r->u.octet_aligned->len);
802 fprintf(stdout, "---------\n");
804 /* note just ignores the error ant print the bytes form the octet_aligned later */
807 * Note: we throw away the original, BER-encoded record here.
808 * Do something else with it if you want to keep it.
810 r->u.sutrs = (Z_SUTRS *) rr; /* we don't actually check the type here. */
811 r->which = type->what;
815 if (ent && ent->value == VAL_SOIF)
816 print_record((const unsigned char *) r->u.octet_aligned->buf,
817 r->u.octet_aligned->len);
818 else if (r->which == Z_External_octet)
820 const char *octet_buf = (char*)r->u.octet_aligned->buf;
821 if (ent->oclass == CLASS_RECSYN &&
822 (ent->value == VAL_TEXT_XML ||
823 ent->value == VAL_APPLICATION_XML ||
824 ent->value == VAL_HTML))
826 print_record((const unsigned char *) octet_buf,
827 r->u.octet_aligned->len);
829 else if (ent->value == VAL_POSTSCRIPT)
831 int size = r->u.octet_aligned->len;
834 print_record((const unsigned char *) octet_buf, size);
839 #if AVOID_MARC_DECODE
840 /* primitive check for a marc OID 5.1-29 except 16 */
841 ent->oidsuffix[0] == 5 && ent->oidsuffix[1] < 30 &&
842 ent->oidsuffix[1] != 16
851 yaz_marc_t mt = yaz_marc_create();
853 if (yaz_marc_decode_buf(mt, octet_buf,r->u.octet_aligned->len,
857 if (marcCharset && !strcmp(marcCharset, "auto"))
859 if (ent->value == VAL_USMARC)
861 if (octet_buf[9] == 'a')
869 else if (marcCharset)
871 if (outputCharset && from)
873 cd = yaz_iconv_open(outputCharset, from);
874 printf ("convert from %s to %s", from,
877 printf (" unsupported\n");
882 fwrite (result, 1, rlen, stdout);
886 size_t inbytesleft = rlen;
887 const char *inp = result;
891 size_t outbytesleft = sizeof(outbuf);
895 r = yaz_iconv (cd, (char**) &inp,
897 &outp, &outbytesleft);
898 if (r == (size_t) (-1))
900 int e = yaz_iconv_error(cd);
901 if (e != YAZ_ICONV_E2BIG)
904 fwrite (outbuf, outp - outbuf, 1, stdout);
910 printf ("bad MARC. Dumping as it is:\n");
911 print_record((const unsigned char*) octet_buf,
912 r->u.octet_aligned->len);
914 yaz_marc_destroy(mt);
920 print_record((const unsigned char*) octet_buf,
921 r->u.octet_aligned->len);
925 fwrite (octet_buf, 1, r->u.octet_aligned->len, marc_file);
927 else if (ent && ent->value == VAL_SUTRS)
929 if (r->which != Z_External_sutrs)
931 printf("Expecting single SUTRS type for SUTRS.\n");
934 print_record(r->u.sutrs->buf, r->u.sutrs->len);
936 else if (ent && ent->value == VAL_GRS1)
939 if (r->which != Z_External_grs1)
941 printf("Expecting single GRS type for GRS.\n");
945 yaz_display_grs1(w, r->u.grs1, 0);
949 else if ( /* OPAC display not complete yet .. */
950 ent && ent->value == VAL_OPAC)
953 if (r->u.opac->bibliographicRecord)
954 display_record(r->u.opac->bibliographicRecord);
955 for (i = 0; i<r->u.opac->num_holdingsData; i++)
957 Z_HoldingsRecord *h = r->u.opac->holdingsData[i];
958 if (h->which == Z_HoldingsRecord_marcHoldingsRecord)
960 printf ("MARC holdings %d\n", i);
961 display_record(h->u.marcHoldingsRecord);
963 else if (h->which == Z_HoldingsRecord_holdingsAndCirc)
967 Z_HoldingsAndCircData *data = h->u.holdingsAndCirc;
969 printf ("Data holdings %d\n", i);
970 if (data->typeOfRecord)
971 printf ("typeOfRecord: %s\n", data->typeOfRecord);
972 if (data->encodingLevel)
973 printf ("encodingLevel: %s\n", data->encodingLevel);
974 if (data->receiptAcqStatus)
975 printf ("receiptAcqStatus: %s\n", data->receiptAcqStatus);
976 if (data->generalRetention)
977 printf ("generalRetention: %s\n", data->generalRetention);
978 if (data->completeness)
979 printf ("completeness: %s\n", data->completeness);
980 if (data->dateOfReport)
981 printf ("dateOfReport: %s\n", data->dateOfReport);
983 printf ("nucCode: %s\n", data->nucCode);
984 if (data->localLocation)
985 printf ("localLocation: %s\n", data->localLocation);
986 if (data->shelvingLocation)
987 printf ("shelvingLocation: %s\n", data->shelvingLocation);
988 if (data->callNumber)
989 printf ("callNumber: %s\n", data->callNumber);
990 if (data->shelvingData)
991 printf ("shelvingData: %s\n", data->shelvingData);
992 if (data->copyNumber)
993 printf ("copyNumber: %s\n", data->copyNumber);
994 if (data->publicNote)
995 printf ("publicNote: %s\n", data->publicNote);
996 if (data->reproductionNote)
997 printf ("reproductionNote: %s\n", data->reproductionNote);
998 if (data->termsUseRepro)
999 printf ("termsUseRepro: %s\n", data->termsUseRepro);
1000 if (data->enumAndChron)
1001 printf ("enumAndChron: %s\n", data->enumAndChron);
1002 for (j = 0; j<data->num_volumes; j++)
1004 printf ("volume %d\n", j);
1005 if (data->volumes[j]->enumeration)
1006 printf (" enumeration: %s\n",
1007 data->volumes[j]->enumeration);
1008 if (data->volumes[j]->chronology)
1009 printf (" chronology: %s\n",
1010 data->volumes[j]->chronology);
1011 if (data->volumes[j]->enumAndChron)
1012 printf (" enumAndChron: %s\n",
1013 data->volumes[j]->enumAndChron);
1015 for (j = 0; j<data->num_circulationData; j++)
1017 printf ("circulation %d\n", j);
1018 if (data->circulationData[j]->availableNow)
1019 printf (" availableNow: %d\n",
1020 *data->circulationData[j]->availableNow);
1021 if (data->circulationData[j]->availablityDate)
1022 printf (" availabiltyDate: %s\n",
1023 data->circulationData[j]->availablityDate);
1024 if (data->circulationData[j]->availableThru)
1025 printf (" availableThru: %s\n",
1026 data->circulationData[j]->availableThru);
1027 if (data->circulationData[j]->restrictions)
1028 printf (" restrictions: %s\n",
1029 data->circulationData[j]->restrictions);
1030 if (data->circulationData[j]->itemId)
1031 printf (" itemId: %s\n",
1032 data->circulationData[j]->itemId);
1033 if (data->circulationData[j]->renewable)
1034 printf (" renewable: %d\n",
1035 *data->circulationData[j]->renewable);
1036 if (data->circulationData[j]->onHold)
1037 printf (" onHold: %d\n",
1038 *data->circulationData[j]->onHold);
1039 if (data->circulationData[j]->enumAndChron)
1040 printf (" enumAndChron: %s\n",
1041 data->circulationData[j]->enumAndChron);
1042 if (data->circulationData[j]->midspine)
1043 printf (" midspine: %s\n",
1044 data->circulationData[j]->midspine);
1045 if (data->circulationData[j]->temporaryLocation)
1046 printf (" temporaryLocation: %s\n",
1047 data->circulationData[j]->temporaryLocation);
1054 printf("Unknown record representation.\n");
1055 if (!z_External(print, &r, 0, 0))
1057 odr_perror(print, "Printing external");
1063 static void display_diagrecs(Z_DiagRec **pp, int num)
1067 Z_DefaultDiagFormat *r;
1069 printf("Diagnostic message(s) from database:\n");
1070 for (i = 0; i<num; i++)
1072 Z_DiagRec *p = pp[i];
1073 if (p->which != Z_DiagRec_defaultFormat)
1075 printf("Diagnostic record not in default format.\n");
1079 r = p->u.defaultFormat;
1080 if (!(ent = oid_getentbyoid(r->diagnosticSetId)) ||
1081 ent->oclass != CLASS_DIAGSET || ent->value != VAL_BIB1)
1082 printf("Missing or unknown diagset\n");
1083 printf(" [%d] %s", *r->condition, diagbib1_str(*r->condition));
1086 case Z_DefaultDiagFormat_v2Addinfo:
1087 printf (" -- v2 addinfo '%s'\n", r->u.v2Addinfo);
1089 case Z_DefaultDiagFormat_v3Addinfo:
1090 printf (" -- v3 addinfo '%s'\n", r->u.v3Addinfo);
1097 static void display_nameplusrecord(Z_NamePlusRecord *p)
1099 if (p->databaseName)
1100 printf("[%s]", p->databaseName);
1101 if (p->which == Z_NamePlusRecord_surrogateDiagnostic)
1102 display_diagrecs(&p->u.surrogateDiagnostic, 1);
1103 else if (p->which == Z_NamePlusRecord_databaseRecord)
1104 display_record(p->u.databaseRecord);
1107 static void display_records(Z_Records *p)
1111 if (p->which == Z_Records_NSD)
1113 Z_DiagRec dr, *dr_p = &dr;
1114 dr.which = Z_DiagRec_defaultFormat;
1115 dr.u.defaultFormat = p->u.nonSurrogateDiagnostic;
1116 display_diagrecs (&dr_p, 1);
1118 else if (p->which == Z_Records_multipleNSD)
1119 display_diagrecs (p->u.multipleNonSurDiagnostics->diagRecs,
1120 p->u.multipleNonSurDiagnostics->num_diagRecs);
1123 printf("Records: %d\n", p->u.databaseOrSurDiagnostics->num_records);
1124 for (i = 0; i < p->u.databaseOrSurDiagnostics->num_records; i++)
1125 display_nameplusrecord(p->u.databaseOrSurDiagnostics->records[i]);
1129 static int send_deleteResultSetRequest(const char *arg)
1134 Z_APDU *apdu = zget_APDU(out, Z_APDU_deleteResultSetRequest);
1135 Z_DeleteResultSetRequest *req = apdu->u.deleteResultSetRequest;
1137 req->referenceId = set_refid (out);
1139 req->num_resultSetList =
1140 sscanf (arg, "%30s %30s %30s %30s %30s %30s %30s %30s",
1141 names[0], names[1], names[2], names[3],
1142 names[4], names[5], names[6], names[7]);
1144 req->deleteFunction = (int *)
1145 odr_malloc (out, sizeof(*req->deleteFunction));
1146 if (req->num_resultSetList > 0)
1148 *req->deleteFunction = Z_DeleteResultSetRequest_list;
1149 req->resultSetList = (char **)
1150 odr_malloc (out, sizeof(*req->resultSetList)*
1151 req->num_resultSetList);
1152 for (i = 0; i<req->num_resultSetList; i++)
1153 req->resultSetList[i] = names[i];
1157 *req->deleteFunction = Z_DeleteResultSetRequest_all;
1158 req->resultSetList = 0;
1162 printf("Sent deleteResultSetRequest.\n");
1167 static int send_srw(Z_SRW_PDU *sr)
1169 const char *charset = negotiationCharset;
1170 const char *host_port = cur_host;
1173 Z_SOAP_Handler h[2] = {
1174 {"http://www.loc.gov/zing/srw/", 0, (Z_SOAP_fun) yaz_srw_codec},
1177 ODR o = odr_createmem(ODR_ENCODE);
1179 Z_SOAP *p = odr_malloc(o, sizeof(*p));
1182 path = odr_malloc(out, strlen(databaseNames[0])+2);
1184 strcpy(path+1, databaseNames[0]);
1186 gdu = z_get_HTTP_Request(out);
1187 gdu->u.HTTP_Request->version = http_version;
1188 gdu->u.HTTP_Request->path = odr_strdup(out, path);
1192 const char *cp0 = strstr(host_port, "://");
1193 const char *cp1 = 0;
1199 cp1 = strchr(cp0, '/');
1201 cp1 = cp0+strlen(cp0);
1205 char *h = odr_malloc(out, cp1 - cp0 + 1);
1206 memcpy (h, cp0, cp1 - cp0);
1208 z_HTTP_header_add(out, &gdu->u.HTTP_Request->headers,
1213 strcpy(ctype, "text/xml");
1214 if (charset && strlen(charset) < 20)
1216 strcat(ctype, "; charset=");
1217 strcat(ctype, charset);
1219 z_HTTP_header_add(out, &gdu->u.HTTP_Request->headers,
1220 "Content-Type", ctype);
1221 z_HTTP_header_add(out, &gdu->u.HTTP_Request->headers,
1222 "SOAPAction", "\"\"");
1223 p->which = Z_SOAP_generic;
1224 p->u.generic = odr_malloc(o, sizeof(*p->u.generic));
1225 p->u.generic->no = 0;
1226 p->u.generic->ns = 0;
1227 p->u.generic->p = sr;
1228 p->ns = "http://schemas.xmlsoap.org/soap/envelope/";
1230 ret = z_soap_codec_enc(o, &p,
1231 &gdu->u.HTTP_Request->content_buf,
1232 &gdu->u.HTTP_Request->content_len, h,
1235 if (z_GDU(out, &gdu, 0, 0))
1243 if (!z_GDU(print, &gdu, 0, 0))
1244 printf ("Failed to print outgoing APDU\n");
1247 buf_out = odr_getbuf(out, &len_out, 0);
1249 /* we don't odr_reset(out), since we may need the buffer again */
1251 do_hex_dump(buf_out, len_out);
1253 r = cs_put(conn, buf_out, len_out);
1265 static int send_SRW_scanRequest(const char *arg, int pos, int num)
1269 /* regular requestse .. */
1270 sr = yaz_srw_get(out, Z_SRW_scan_request);
1275 sr->u.scan_request->query_type = Z_SRW_query_type_cql;
1276 sr->u.scan_request->scanClause.cql = odr_strdup(out, arg);
1278 case QueryType_Prefix:
1279 sr->u.scan_request->query_type = Z_SRW_query_type_pqf;
1280 sr->u.scan_request->scanClause.pqf = odr_strdup(out, arg);
1283 printf ("Only CQL and PQF supported in SRW\n");
1286 sr->u.scan_request->responsePosition = odr_intdup(out, pos);
1287 sr->u.scan_request->maximumTerms = odr_intdup(out, num);
1288 return send_srw(sr);
1291 static int send_SRW_searchRequest(const char *arg)
1297 assert(srw_sr_odr_out == 0);
1298 srw_sr_odr_out = odr_createmem(ODR_ENCODE);
1300 odr_reset(srw_sr_odr_out);
1304 /* save this for later .. when fetching individual records */
1305 srw_sr = yaz_srw_get(srw_sr_odr_out, Z_SRW_searchRetrieve_request);
1307 /* regular request .. */
1308 sr = yaz_srw_get(out, Z_SRW_searchRetrieve_request);
1313 srw_sr->u.request->query_type = Z_SRW_query_type_cql;
1314 srw_sr->u.request->query.cql = odr_strdup(srw_sr_odr_out, arg);
1316 sr->u.request->query_type = Z_SRW_query_type_cql;
1317 sr->u.request->query.cql = odr_strdup(out, arg);
1319 case QueryType_Prefix:
1320 srw_sr->u.request->query_type = Z_SRW_query_type_pqf;
1321 srw_sr->u.request->query.pqf = odr_strdup(srw_sr_odr_out, arg);
1323 sr->u.request->query_type = Z_SRW_query_type_pqf;
1324 sr->u.request->query.pqf = odr_strdup(out, arg);
1327 printf ("Only CQL and PQF supported in SRW\n");
1330 sr->u.request->maximumRecords = odr_intdup(out, 0);
1333 sr->u.request->recordSchema = record_schema;
1334 if (recordsyntax == VAL_TEXT_XML)
1335 sr->u.explain_request->recordPacking = "xml";
1336 return send_srw(sr);
1340 static int send_searchRequest(const char *arg)
1342 Z_APDU *apdu = zget_APDU(out, Z_APDU_searchRequest);
1343 Z_SearchRequest *req = apdu->u.searchRequest;
1345 struct ccl_rpn_node *rpn = NULL;
1347 char setstring[100];
1348 Z_RPNQuery *RPNquery;
1350 YAZ_PQF_Parser pqf_parser;
1352 QueryType myQueryType = queryType;
1355 if (myQueryType == QueryType_CCL2RPN)
1357 rpn = ccl_find_str(bibset, arg, &error, &pos);
1360 printf("CCL ERROR: %s\n", ccl_err_msg(error));
1363 } else if (myQueryType == QueryType_CQL2RPN) {
1364 /* ### All this code should be wrapped in a utility function */
1366 struct cql_node *node;
1367 const char *addinfo;
1368 if (cqltrans == 0) {
1369 printf("Can't use CQL: no translation file. Try set_cqlfile\n");
1372 parser = cql_parser_create();
1373 if ((error = cql_parser_string(parser, arg)) != 0) {
1374 printf("Can't parse CQL: must be a syntax error\n");
1377 node = cql_parser_result(parser);
1378 if ((error = cql_transform_buf(cqltrans, node, pqfbuf,
1379 sizeof pqfbuf)) != 0) {
1380 error = cql_transform_error(cqltrans, &addinfo);
1381 printf ("Can't convert CQL to PQF: %s (addinfo=%s)\n",
1382 cql_strerror(error), addinfo);
1386 myQueryType = QueryType_Prefix;
1389 req->referenceId = set_refid (out);
1390 if (!strcmp(arg, "@big")) /* strictly for troublemaking */
1392 static unsigned char big[2100];
1393 static Odr_oct bigo;
1395 /* send a very big referenceid to test transport stack etc. */
1396 memset(big, 'A', 2100);
1397 bigo.len = bigo.size = 2100;
1399 req->referenceId = &bigo;
1404 sprintf(setstring, "%d", ++setnumber);
1405 req->resultSetName = setstring;
1407 *req->smallSetUpperBound = smallSetUpperBound;
1408 *req->largeSetLowerBound = largeSetLowerBound;
1409 *req->mediumSetPresentNumber = mediumSetPresentNumber;
1410 if (smallSetUpperBound > 0 || (largeSetLowerBound > 1 &&
1411 mediumSetPresentNumber > 0))
1413 req->preferredRecordSyntax =
1414 yaz_oidval_to_z3950oid(out, CLASS_RECSYN, recordsyntax);
1416 req->smallSetElementSetNames =
1417 req->mediumSetElementSetNames = elementSetNames;
1419 req->num_databaseNames = num_databaseNames;
1420 req->databaseNames = databaseNames;
1422 req->query = &query;
1424 switch (myQueryType)
1426 case QueryType_Prefix:
1427 query.which = Z_Query_type_1;
1428 pqf_parser = yaz_pqf_create ();
1429 RPNquery = yaz_pqf_parse (pqf_parser, out, arg);
1432 const char *pqf_msg;
1434 int code = yaz_pqf_error (pqf_parser, &pqf_msg, &off);
1435 printf("%*s^\n", off+4, "");
1436 printf("Prefix query error: %s (code %d)\n", pqf_msg, code);
1438 yaz_pqf_destroy (pqf_parser);
1441 yaz_pqf_destroy (pqf_parser);
1442 query.u.type_1 = RPNquery;
1445 query.which = Z_Query_type_2;
1446 query.u.type_2 = &ccl_query;
1447 ccl_query.buf = (unsigned char*) arg;
1448 ccl_query.len = strlen(arg);
1450 case QueryType_CCL2RPN:
1451 query.which = Z_Query_type_1;
1452 RPNquery = ccl_rpn_query(out, rpn);
1455 printf ("Couldn't convert from CCL to RPN\n");
1458 query.u.type_1 = RPNquery;
1459 ccl_rpn_delete (rpn);
1462 query.which = Z_Query_type_104;
1463 ext = (Z_External *) odr_malloc(out, sizeof(*ext));
1464 ext->direct_reference = odr_getoidbystr(out, "1.2.840.10003.16.2");
1465 ext->indirect_reference = 0;
1466 ext->descriptor = 0;
1467 ext->which = Z_External_CQL;
1468 ext->u.cql = odr_strdup(out, arg);
1469 query.u.type_104 = ext;
1472 printf ("Unsupported query type\n");
1475 if (send_apdu(apdu))
1476 printf("Sent searchRequest.\n");
1481 /* display Query Expression as part of searchResult-1 */
1482 static void display_queryExpression (Z_QueryExpression *qe)
1486 if (qe->which == Z_QueryExpression_term)
1488 if (qe->u.term->queryTerm)
1490 Z_Term *term = qe->u.term->queryTerm;
1491 switch (term->which)
1493 case Z_Term_general:
1494 printf (" %.*s", term->u.general->len, term->u.general->buf);
1496 case Z_Term_characterString:
1497 printf (" %s", term->u.characterString);
1499 case Z_Term_numeric:
1500 printf (" %d", *term->u.numeric);
1510 /* see if we can find USR:SearchResult-1 */
1511 static void display_searchResult (Z_OtherInformation *o)
1516 for (i = 0; i < o->num_elements; i++)
1518 if (o->list[i]->which == Z_OtherInfo_externallyDefinedInfo)
1520 Z_External *ext = o->list[i]->information.externallyDefinedInfo;
1522 if (ext->which == Z_External_searchResult1)
1525 Z_SearchInfoReport *sr = ext->u.searchResult1;
1526 printf ("SearchResult-1:");
1527 for (j = 0; j < sr->num; j++)
1529 if (!sr->elements[j]->subqueryExpression)
1531 display_queryExpression (
1532 sr->elements[j]->subqueryExpression);
1533 display_queryExpression (
1534 sr->elements[j]->subqueryInterpretation);
1535 display_queryExpression (
1536 sr->elements[j]->subqueryRecommendation);
1537 if (sr->elements[j]->subqueryCount)
1538 printf ("(%d)", *sr->elements[j]->subqueryCount);
1546 static int process_searchResponse(Z_SearchResponse *res)
1548 printf ("Received SearchResponse.\n");
1549 print_refid (res->referenceId);
1550 if (*res->searchStatus)
1551 printf("Search was a success.\n");
1553 printf("Search was a bloomin' failure.\n");
1554 printf("Number of hits: %d", *res->resultCount);
1556 printf (", setno %d", setnumber);
1558 display_searchResult (res->additionalSearchInfo);
1559 printf("records returned: %d\n",
1560 *res->numberOfRecordsReturned);
1561 setno += *res->numberOfRecordsReturned;
1563 display_records(res->records);
1567 static void print_level(int iLevel)
1570 for (i = 0; i < iLevel * 4; i++)
1574 static void print_int(int iLevel, const char *pTag, int *pInt)
1578 print_level(iLevel);
1579 printf("%s: %d\n", pTag, *pInt);
1583 static void print_string(int iLevel, const char *pTag, const char *pString)
1585 if (pString != NULL)
1587 print_level(iLevel);
1588 printf("%s: %s\n", pTag, pString);
1592 static void print_oid(int iLevel, const char *pTag, Odr_oid *pOid)
1598 print_level(iLevel);
1599 printf("%s:", pTag);
1600 for (; *pInt != -1; pInt++)
1601 printf(" %d", *pInt);
1606 static void print_referenceId(int iLevel, Z_ReferenceId *referenceId)
1608 if (referenceId != NULL)
1612 print_level(iLevel);
1613 printf("Ref Id (%d, %d): ", referenceId->len, referenceId->size);
1614 for (i = 0; i < referenceId->len; i++)
1615 printf("%c", referenceId->buf[i]);
1620 static void print_string_or_numeric(int iLevel, const char *pTag, Z_StringOrNumeric *pStringNumeric)
1622 if (pStringNumeric != NULL)
1624 switch (pStringNumeric->which)
1626 case Z_StringOrNumeric_string:
1627 print_string(iLevel, pTag, pStringNumeric->u.string);
1630 case Z_StringOrNumeric_numeric:
1631 print_int(iLevel, pTag, pStringNumeric->u.numeric);
1635 print_level(iLevel);
1636 printf("%s: valid type for Z_StringOrNumeric\n", pTag);
1642 static void print_universe_report_duplicate(
1644 Z_UniverseReportDuplicate *pUniverseReportDuplicate)
1646 if (pUniverseReportDuplicate != NULL)
1648 print_level(iLevel);
1649 printf("Universe Report Duplicate: \n");
1651 print_string_or_numeric(iLevel, "Hit No",
1652 pUniverseReportDuplicate->hitno);
1656 static void print_universe_report_hits(
1658 Z_UniverseReportHits *pUniverseReportHits)
1660 if (pUniverseReportHits != NULL)
1662 print_level(iLevel);
1663 printf("Universe Report Hits: \n");
1665 print_string_or_numeric(iLevel, "Database",
1666 pUniverseReportHits->database);
1667 print_string_or_numeric(iLevel, "Hits", pUniverseReportHits->hits);
1671 static void print_universe_report(int iLevel, Z_UniverseReport *pUniverseReport)
1673 if (pUniverseReport != NULL)
1675 print_level(iLevel);
1676 printf("Universe Report: \n");
1678 print_int(iLevel, "Total Hits", pUniverseReport->totalHits);
1679 switch (pUniverseReport->which)
1681 case Z_UniverseReport_databaseHits:
1682 print_universe_report_hits(iLevel,
1683 pUniverseReport->u.databaseHits);
1686 case Z_UniverseReport_duplicate:
1687 print_universe_report_duplicate(iLevel,
1688 pUniverseReport->u.duplicate);
1692 print_level(iLevel);
1693 printf("Type: %d\n", pUniverseReport->which);
1699 static void print_external(int iLevel, Z_External *pExternal)
1701 if (pExternal != NULL)
1703 print_level(iLevel);
1704 printf("External: \n");
1706 print_oid(iLevel, "Direct Reference", pExternal->direct_reference);
1707 print_int(iLevel, "InDirect Reference", pExternal->indirect_reference);
1708 print_string(iLevel, "Descriptor", pExternal->descriptor);
1709 switch (pExternal->which)
1711 case Z_External_universeReport:
1712 print_universe_report(iLevel, pExternal->u.universeReport);
1716 print_level(iLevel);
1717 printf("Type: %d\n", pExternal->which);
1723 static int process_resourceControlRequest (Z_ResourceControlRequest *req)
1725 printf ("Received ResourceControlRequest.\n");
1726 print_referenceId(1, req->referenceId);
1727 print_int(1, "Suspended Flag", req->suspendedFlag);
1728 print_int(1, "Partial Results Available", req->partialResultsAvailable);
1729 print_int(1, "Response Required", req->responseRequired);
1730 print_int(1, "Triggered Request Flag", req->triggeredRequestFlag);
1731 print_external(1, req->resourceReport);
1735 void process_ESResponse(Z_ExtendedServicesResponse *res)
1738 switch (*res->operationStatus)
1740 case Z_ExtendedServicesResponse_done:
1743 case Z_ExtendedServicesResponse_accepted:
1744 printf ("accepted\n");
1746 case Z_ExtendedServicesResponse_failure:
1747 printf ("failure\n");
1748 display_diagrecs(res->diagnostics, res->num_diagnostics);
1751 printf ("unknown\n");
1753 if ( (*res->operationStatus != Z_ExtendedServicesResponse_failure) &&
1754 (res->num_diagnostics != 0) ) {
1755 display_diagrecs(res->diagnostics, res->num_diagnostics);
1757 print_refid (res->referenceId);
1758 if (res->taskPackage &&
1759 res->taskPackage->which == Z_External_extendedService)
1761 Z_TaskPackage *taskPackage = res->taskPackage->u.extendedService;
1762 Odr_oct *id = taskPackage->targetReference;
1763 Z_External *ext = taskPackage->taskSpecificParameters;
1767 printf ("Target Reference: ");
1768 print_stringn (id->buf, id->len);
1771 if (ext->which == Z_External_update)
1773 Z_IUUpdateTaskPackage *utp = ext->u.update->u.taskPackage;
1774 if (utp && utp->targetPart)
1776 Z_IUTargetPart *targetPart = utp->targetPart;
1779 for (i = 0; i<targetPart->num_taskPackageRecords; i++)
1782 Z_IUTaskPackageRecordStructure *tpr =
1783 targetPart->taskPackageRecords[i];
1784 printf ("task package record %d\n", i+1);
1785 if (tpr->which == Z_IUTaskPackageRecordStructure_record)
1787 display_record (tpr->u.record);
1791 printf ("other type\n");
1799 const char *get_ill_element (void *clientData, const char *element)
1804 static Z_External *create_external_itemRequest()
1806 struct ill_get_ctl ctl;
1807 ILL_ItemRequest *req;
1809 int item_request_size = 0;
1810 char *item_request_buf = 0;
1814 ctl.f = get_ill_element;
1816 req = ill_get_ItemRequest(&ctl, "ill", 0);
1818 printf ("ill_get_ItemRequest failed\n");
1820 if (!ill_ItemRequest (out, &req, 0, 0))
1824 ill_ItemRequest(print, &req, 0, 0);
1827 item_request_buf = odr_getbuf (out, &item_request_size, 0);
1828 if (item_request_buf)
1829 odr_setbuf (out, item_request_buf, item_request_size, 1);
1830 printf ("Couldn't encode ItemRequest, size %d\n", item_request_size);
1837 item_request_buf = odr_getbuf (out, &item_request_size, 0);
1838 oid.proto = PROTO_GENERAL;
1839 oid.oclass = CLASS_GENERAL;
1840 oid.value = VAL_ISO_ILL_1;
1842 r = (Z_External *) odr_malloc (out, sizeof(*r));
1843 r->direct_reference = odr_oiddup(out,oid_getoidbyent(&oid));
1844 r->indirect_reference = 0;
1846 r->which = Z_External_single;
1848 r->u.single_ASN1_type = (Odr_oct *)
1849 odr_malloc (out, sizeof(*r->u.single_ASN1_type));
1850 r->u.single_ASN1_type->buf = (unsigned char *)
1851 odr_malloc (out, item_request_size);
1852 r->u.single_ASN1_type->len = item_request_size;
1853 r->u.single_ASN1_type->size = item_request_size;
1854 memcpy (r->u.single_ASN1_type->buf, item_request_buf,
1857 do_hex_dump(item_request_buf,item_request_size);
1862 static Z_External *create_external_ILL_APDU(int which)
1864 struct ill_get_ctl ctl;
1867 int ill_request_size = 0;
1868 char *ill_request_buf = 0;
1872 ctl.f = get_ill_element;
1874 ill_apdu = ill_get_APDU(&ctl, "ill", 0);
1876 if (!ill_APDU (out, &ill_apdu, 0, 0))
1880 printf ("-------------------\n");
1881 ill_APDU(print, &ill_apdu, 0, 0);
1883 printf ("-------------------\n");
1885 ill_request_buf = odr_getbuf (out, &ill_request_size, 0);
1886 if (ill_request_buf)
1887 odr_setbuf (out, ill_request_buf, ill_request_size, 1);
1888 printf ("Couldn't encode ILL-Request, size %d\n", ill_request_size);
1894 ill_request_buf = odr_getbuf (out, &ill_request_size, 0);
1896 oid.proto = PROTO_GENERAL;
1897 oid.oclass = CLASS_GENERAL;
1898 oid.value = VAL_ISO_ILL_1;
1900 r = (Z_External *) odr_malloc (out, sizeof(*r));
1901 r->direct_reference = odr_oiddup(out,oid_getoidbyent(&oid));
1902 r->indirect_reference = 0;
1904 r->which = Z_External_single;
1906 r->u.single_ASN1_type = (Odr_oct *)
1907 odr_malloc (out, sizeof(*r->u.single_ASN1_type));
1908 r->u.single_ASN1_type->buf = (unsigned char *)
1909 odr_malloc (out, ill_request_size);
1910 r->u.single_ASN1_type->len = ill_request_size;
1911 r->u.single_ASN1_type->size = ill_request_size;
1912 memcpy (r->u.single_ASN1_type->buf, ill_request_buf, ill_request_size);
1913 /* printf ("len = %d\n", ill_request_size); */
1914 /* do_hex_dump(ill_request_buf,ill_request_size); */
1915 /* printf("--- end of extenal\n"); */
1922 static Z_External *create_ItemOrderExternal(const char *type, int itemno)
1924 Z_External *r = (Z_External *) odr_malloc(out, sizeof(Z_External));
1925 oident ItemOrderRequest;
1927 ItemOrderRequest.proto = PROTO_Z3950;
1928 ItemOrderRequest.oclass = CLASS_EXTSERV;
1929 ItemOrderRequest.value = VAL_ITEMORDER;
1931 r->direct_reference = odr_oiddup(out,oid_getoidbyent(&ItemOrderRequest));
1932 r->indirect_reference = 0;
1935 r->which = Z_External_itemOrder;
1937 r->u.itemOrder = (Z_ItemOrder *) odr_malloc(out,sizeof(Z_ItemOrder));
1938 memset(r->u.itemOrder, 0, sizeof(Z_ItemOrder));
1939 r->u.itemOrder->which=Z_IOItemOrder_esRequest;
1941 r->u.itemOrder->u.esRequest = (Z_IORequest *)
1942 odr_malloc(out,sizeof(Z_IORequest));
1943 memset(r->u.itemOrder->u.esRequest, 0, sizeof(Z_IORequest));
1945 r->u.itemOrder->u.esRequest->toKeep = (Z_IOOriginPartToKeep *)
1946 odr_malloc(out,sizeof(Z_IOOriginPartToKeep));
1947 memset(r->u.itemOrder->u.esRequest->toKeep, 0, sizeof(Z_IOOriginPartToKeep));
1948 r->u.itemOrder->u.esRequest->notToKeep = (Z_IOOriginPartNotToKeep *)
1949 odr_malloc(out,sizeof(Z_IOOriginPartNotToKeep));
1950 memset(r->u.itemOrder->u.esRequest->notToKeep, 0, sizeof(Z_IOOriginPartNotToKeep));
1952 r->u.itemOrder->u.esRequest->toKeep->supplDescription = NULL;
1953 r->u.itemOrder->u.esRequest->toKeep->contact = NULL;
1954 r->u.itemOrder->u.esRequest->toKeep->addlBilling = NULL;
1956 r->u.itemOrder->u.esRequest->notToKeep->resultSetItem =
1957 (Z_IOResultSetItem *) odr_malloc(out, sizeof(Z_IOResultSetItem));
1958 memset(r->u.itemOrder->u.esRequest->notToKeep->resultSetItem, 0, sizeof(Z_IOResultSetItem));
1959 r->u.itemOrder->u.esRequest->notToKeep->resultSetItem->resultSetId = "1";
1961 r->u.itemOrder->u.esRequest->notToKeep->resultSetItem->item =
1962 (int *) odr_malloc(out, sizeof(int));
1963 *r->u.itemOrder->u.esRequest->notToKeep->resultSetItem->item = itemno;
1965 if (!strcmp (type, "item") || !strcmp(type, "2"))
1967 printf ("using item-request\n");
1968 r->u.itemOrder->u.esRequest->notToKeep->itemRequest =
1969 create_external_itemRequest();
1971 else if (!strcmp(type, "ill") || !strcmp(type, "1"))
1973 printf ("using ILL-request\n");
1974 r->u.itemOrder->u.esRequest->notToKeep->itemRequest =
1975 create_external_ILL_APDU(ILL_APDU_ILL_Request);
1977 else if (!strcmp(type, "xml") || !strcmp(type, "3"))
1979 const char *xml_buf =
1981 " <type>request</type>\n"
1982 " <libraryNo>000200</libraryNo>\n"
1983 " <borrowerTicketNo> 1212 </borrowerTicketNo>\n"
1985 r->u.itemOrder->u.esRequest->notToKeep->itemRequest =
1986 z_ext_record (out, VAL_TEXT_XML, xml_buf, strlen(xml_buf));
1989 r->u.itemOrder->u.esRequest->notToKeep->itemRequest = 0;
1994 static int send_itemorder(const char *type, int itemno)
1996 Z_APDU *apdu = zget_APDU(out, Z_APDU_extendedServicesRequest);
1997 Z_ExtendedServicesRequest *req = apdu->u.extendedServicesRequest;
1998 oident ItemOrderRequest;
2000 ItemOrderRequest.proto = PROTO_Z3950;
2001 ItemOrderRequest.oclass = CLASS_EXTSERV;
2002 ItemOrderRequest.value = VAL_ITEMORDER;
2003 req->packageType = odr_oiddup(out,oid_getoidbyent(&ItemOrderRequest));
2004 req->packageName = esPackageName;
2006 req->taskSpecificParameters = create_ItemOrderExternal(type, itemno);
2012 static int only_z3950()
2014 if (protocol == PROTO_HTTP)
2016 printf ("Not supported by SRW\n");
2022 static int cmd_update_common(const char *arg, int version);
2024 static int cmd_update(const char *arg)
2026 return cmd_update_common(arg, 1);
2029 static int cmd_update0(const char *arg)
2031 return cmd_update_common(arg, 0);
2034 static int cmd_update_common(const char *arg, int version)
2036 Z_APDU *apdu = zget_APDU(out, Z_APDU_extendedServicesRequest );
2037 Z_ExtendedServicesRequest *req = apdu->u.extendedServicesRequest;
2039 char action[20], recid[20], fname[80];
2041 Z_External *record_this = 0;
2048 sscanf (arg, "%19s %19s %79s", action, recid, fname);
2050 if (!strcmp (action, "insert"))
2051 action_no = Z_IUOriginPartToKeep_recordInsert;
2052 else if (!strcmp (action, "replace"))
2053 action_no = Z_IUOriginPartToKeep_recordReplace;
2054 else if (!strcmp (action, "delete"))
2055 action_no = Z_IUOriginPartToKeep_recordDelete;
2056 else if (!strcmp (action, "update"))
2057 action_no = Z_IUOriginPartToKeep_specialUpdate;
2060 printf ("Bad action: %s\n", action);
2061 printf ("Possible values: insert, replace, delete, update\n");
2069 stat (fname, &status);
2070 if (S_ISREG(status.st_mode) && (inf = fopen(fname, "r")))
2072 size_t len = status.st_size;
2073 char *buf = (char *) xmalloc (len);
2075 fread (buf, 1, len, inf);
2079 record_this = z_ext_record (out, VAL_TEXT_XML, buf, len);
2085 printf ("File %s doesn't exist\n", fname);
2093 printf ("No last record (update ignored)\n");
2096 record_this = record_last;
2100 yaz_oidval_to_z3950oid(out, CLASS_EXTSERV,
2101 version == 0 ? VAL_DBUPDATE0 : VAL_DBUPDATE);
2103 req->packageName = esPackageName;
2105 req->referenceId = set_refid (out);
2107 r = req->taskSpecificParameters = (Z_External *)
2108 odr_malloc (out, sizeof(*r));
2109 r->direct_reference = req->packageType;
2110 r->indirect_reference = 0;
2114 Z_IU0OriginPartToKeep *toKeep;
2115 Z_IU0SuppliedRecords *notToKeep;
2117 r->which = Z_External_update0;
2118 r->u.update0 = (Z_IU0Update *) odr_malloc(out, sizeof(*r->u.update0));
2119 r->u.update0->which = Z_IUUpdate_esRequest;
2120 r->u.update0->u.esRequest = (Z_IU0UpdateEsRequest *)
2121 odr_malloc(out, sizeof(*r->u.update0->u.esRequest));
2122 toKeep = r->u.update0->u.esRequest->toKeep = (Z_IU0OriginPartToKeep *)
2123 odr_malloc(out, sizeof(*r->u.update0->u.esRequest->toKeep));
2125 toKeep->databaseName = databaseNames[0];
2127 toKeep->elementSetName = 0;
2129 toKeep->action = (int *) odr_malloc(out, sizeof(*toKeep->action));
2130 *toKeep->action = action_no;
2132 notToKeep = r->u.update0->u.esRequest->notToKeep = (Z_IU0SuppliedRecords *)
2133 odr_malloc(out, sizeof(*r->u.update0->u.esRequest->notToKeep));
2135 notToKeep->elements = (Z_IU0SuppliedRecords_elem **)
2136 odr_malloc(out, sizeof(*notToKeep->elements));
2137 notToKeep->elements[0] = (Z_IU0SuppliedRecords_elem *)
2138 odr_malloc(out, sizeof(**notToKeep->elements));
2139 notToKeep->elements[0]->which = Z_IUSuppliedRecords_elem_opaque;
2142 notToKeep->elements[0]->u.opaque = (Odr_oct *)
2143 odr_malloc (out, sizeof(Odr_oct));
2144 notToKeep->elements[0]->u.opaque->buf = (unsigned char *) recid;
2145 notToKeep->elements[0]->u.opaque->size = strlen(recid);
2146 notToKeep->elements[0]->u.opaque->len = strlen(recid);
2149 notToKeep->elements[0]->u.opaque = 0;
2150 notToKeep->elements[0]->supplementalId = 0;
2151 notToKeep->elements[0]->correlationInfo = 0;
2152 notToKeep->elements[0]->record = record_this;
2156 Z_IUOriginPartToKeep *toKeep;
2157 Z_IUSuppliedRecords *notToKeep;
2159 r->which = Z_External_update;
2160 r->u.update = (Z_IUUpdate *) odr_malloc(out, sizeof(*r->u.update));
2161 r->u.update->which = Z_IUUpdate_esRequest;
2162 r->u.update->u.esRequest = (Z_IUUpdateEsRequest *)
2163 odr_malloc(out, sizeof(*r->u.update->u.esRequest));
2164 toKeep = r->u.update->u.esRequest->toKeep = (Z_IUOriginPartToKeep *)
2165 odr_malloc(out, sizeof(*r->u.update->u.esRequest->toKeep));
2167 toKeep->databaseName = databaseNames[0];
2169 toKeep->elementSetName = 0;
2170 toKeep->actionQualifier = 0;
2171 toKeep->action = (int *) odr_malloc(out, sizeof(*toKeep->action));
2172 *toKeep->action = action_no;
2174 notToKeep = r->u.update->u.esRequest->notToKeep = (Z_IUSuppliedRecords *)
2175 odr_malloc(out, sizeof(*r->u.update->u.esRequest->notToKeep));
2177 notToKeep->elements = (Z_IUSuppliedRecords_elem **)
2178 odr_malloc(out, sizeof(*notToKeep->elements));
2179 notToKeep->elements[0] = (Z_IUSuppliedRecords_elem *)
2180 odr_malloc(out, sizeof(**notToKeep->elements));
2181 notToKeep->elements[0]->which = Z_IUSuppliedRecords_elem_opaque;
2184 notToKeep->elements[0]->u.opaque = (Odr_oct *)
2185 odr_malloc (out, sizeof(Odr_oct));
2186 notToKeep->elements[0]->u.opaque->buf = (unsigned char *) recid;
2187 notToKeep->elements[0]->u.opaque->size = strlen(recid);
2188 notToKeep->elements[0]->u.opaque->len = strlen(recid);
2191 notToKeep->elements[0]->u.opaque = 0;
2192 notToKeep->elements[0]->supplementalId = 0;
2193 notToKeep->elements[0]->correlationInfo = 0;
2194 notToKeep->elements[0]->record = record_this;
2202 static int cmd_itemorder(const char *arg)
2209 if (sscanf (arg, "%10s %d", type, &itemno) != 2)
2212 printf("Item order request\n");
2214 send_itemorder(type, itemno);
2218 static void show_opt(const char *arg, void *clientData)
2220 printf ("%s ", arg);
2223 static int cmd_zversion(const char *arg)
2226 z3950_version = atoi(arg);
2228 printf ("version is %d\n", z3950_version);
2232 static int cmd_options(const char *arg)
2238 r = yaz_init_opt_encode(&z3950_options, arg, &pos);
2242 yaz_init_opt_decode(&z3950_options, show_opt, 0);
2248 static int cmd_explain(const char *arg)
2250 if (protocol != PROTO_HTTP)
2261 /* save this for later .. when fetching individual records */
2262 sr = yaz_srw_get(out, Z_SRW_explain_request);
2263 if (recordsyntax == VAL_TEXT_XML)
2264 sr->u.explain_request->recordPacking = "xml";
2272 static int cmd_init(const char *arg)
2274 if (!conn || protocol != PROTO_Z3950)
2276 send_initRequest(0);
2280 static int cmd_find(const char *arg)
2284 printf("Find what?\n");
2287 if (protocol == PROTO_HTTP)
2294 if (!send_SRW_searchRequest(arg))
2307 printf("Not connected yet\n");
2311 if (!send_searchRequest(arg))
2317 static int cmd_delete(const char *arg)
2321 printf("Not connected yet\n");
2326 if (!send_deleteResultSetRequest(arg))
2331 static int cmd_ssub(const char *arg)
2333 if (!(smallSetUpperBound = atoi(arg)))
2338 static int cmd_lslb(const char *arg)
2342 if (!(largeSetLowerBound = atoi(arg)))
2347 static int cmd_mspn(const char *arg)
2351 if (!(mediumSetPresentNumber = atoi(arg)))
2356 static int cmd_status(const char *arg)
2358 printf("smallSetUpperBound: %d\n", smallSetUpperBound);
2359 printf("largeSetLowerBound: %d\n", largeSetLowerBound);
2360 printf("mediumSetPresentNumber: %d\n", mediumSetPresentNumber);
2364 static int cmd_setnames(const char *arg)
2366 if (*arg == '1') /* enable ? */
2368 else if (*arg == '0') /* disable ? */
2370 else if (setnumber < 0) /* no args, toggle .. */
2376 printf("Set numbering enabled.\n");
2378 printf("Set numbering disabled.\n");
2382 /* PRESENT SERVICE ----------------------------- */
2384 static void parse_show_args(const char *arg_c, char *setstring,
2385 int *start, int *number)
2390 strncpy(arg, arg_c, sizeof(arg)-1);
2391 arg[sizeof(arg)-1] = '\0';
2393 if ((p = strchr(arg, '+')))
2395 *number = atoi(p + 1);
2400 if (p && (p=strchr(p+1, '+')))
2401 strcpy (setstring, p+1);
2402 else if (setnumber >= 0)
2403 sprintf(setstring, "%d", setnumber);
2408 static int send_presentRequest(const char *arg)
2410 Z_APDU *apdu = zget_APDU(out, Z_APDU_presentRequest);
2411 Z_PresentRequest *req = apdu->u.presentRequest;
2412 Z_RecordComposition compo;
2414 char setstring[100];
2416 req->referenceId = set_refid (out);
2418 parse_show_args(arg, setstring, &setno, &nos);
2420 req->resultSetId = setstring;
2422 req->resultSetStartPoint = &setno;
2423 req->numberOfRecordsRequested = &nos;
2425 req->preferredRecordSyntax =
2426 yaz_oidval_to_z3950oid(out, CLASS_RECSYN, recordsyntax);
2430 req->recordComposition = &compo;
2431 compo.which = Z_RecordComp_complex;
2432 compo.u.complex = (Z_CompSpec *)
2433 odr_malloc(out, sizeof(*compo.u.complex));
2434 compo.u.complex->selectAlternativeSyntax = (bool_t *)
2435 odr_malloc(out, sizeof(bool_t));
2436 *compo.u.complex->selectAlternativeSyntax = 0;
2438 compo.u.complex->generic = (Z_Specification *)
2439 odr_malloc(out, sizeof(*compo.u.complex->generic));
2440 compo.u.complex->generic->which = Z_Schema_oid;
2442 compo.u.complex->generic->schema.oid =
2443 yaz_str_to_z3950oid(out, CLASS_SCHEMA, record_schema);
2445 if (!compo.u.complex->generic->schema.oid)
2447 /* OID wasn't a schema! Try record syntax instead. */
2448 compo.u.complex->generic->schema.oid = (Odr_oid *)
2449 yaz_str_to_z3950oid(out, CLASS_RECSYN, record_schema);
2451 if (!elementSetNames)
2452 compo.u.complex->generic->elementSpec = 0;
2455 compo.u.complex->generic->elementSpec = (Z_ElementSpec *)
2456 odr_malloc(out, sizeof(Z_ElementSpec));
2457 compo.u.complex->generic->elementSpec->which =
2458 Z_ElementSpec_elementSetName;
2459 compo.u.complex->generic->elementSpec->u.elementSetName =
2460 elementSetNames->u.generic;
2462 compo.u.complex->num_dbSpecific = 0;
2463 compo.u.complex->dbSpecific = 0;
2464 compo.u.complex->num_recordSyntax = 0;
2465 compo.u.complex->recordSyntax = 0;
2467 else if (elementSetNames)
2469 req->recordComposition = &compo;
2470 compo.which = Z_RecordComp_simple;
2471 compo.u.simple = elementSetNames;
2474 printf("Sent presentRequest (%d+%d).\n", setno, nos);
2479 static int send_SRW_presentRequest(const char *arg)
2481 char setstring[100];
2483 Z_SRW_PDU *sr = srw_sr;
2487 parse_show_args(arg, setstring, &setno, &nos);
2488 sr->u.request->startRecord = odr_intdup(out, setno);
2489 sr->u.request->maximumRecords = odr_intdup(out, nos);
2491 sr->u.request->recordSchema = record_schema;
2492 if (recordsyntax == VAL_TEXT_XML)
2493 sr->u.request->recordPacking = "xml";
2494 return send_srw(sr);
2498 static void close_session (void)
2505 nmem_destroy (session_mem);
2514 void process_close(Z_Close *req)
2516 Z_APDU *apdu = zget_APDU(out, Z_APDU_close);
2517 Z_Close *res = apdu->u.close;
2519 static char *reasons[] =
2524 "cost limit reached",
2526 "security violation",
2533 printf("Reason: %s, message: %s\n", reasons[*req->closeReason],
2534 req->diagnosticInformation ? req->diagnosticInformation : "NULL");
2539 *res->closeReason = Z_Close_finished;
2541 printf("Sent response.\n");
2546 static int cmd_show(const char *arg)
2548 if (protocol == PROTO_HTTP)
2555 if (!send_SRW_presentRequest(arg))
2565 printf("Not connected yet\n");
2568 if (!send_presentRequest(arg))
2574 int cmd_quit(const char *arg)
2576 printf("See you later, alligator.\n");
2582 int cmd_cancel(const char *arg)
2584 Z_APDU *apdu = zget_APDU(out, Z_APDU_triggerResourceControlRequest);
2585 Z_TriggerResourceControlRequest *req =
2586 apdu->u.triggerResourceControlRequest;
2591 printf("Session not initialized yet\n");
2596 if (!ODR_MASK_GET(session->options, Z_Options_triggerResourceCtrl))
2598 printf("Target doesn't support cancel (trigger resource ctrl)\n");
2601 *req->requestedAction = Z_TriggerResourceControlRequest_cancel;
2602 req->resultSetWanted = &rfalse;
2603 req->referenceId = set_refid (out);
2606 printf("Sent cancel request\n");
2611 int cmd_cancel_find(const char *arg) {
2615 return cmd_cancel("");
2620 int send_scanrequest(const char *query, int pp, int num, const char *term)
2622 Z_APDU *apdu = zget_APDU(out, Z_APDU_scanRequest);
2623 Z_ScanRequest *req = apdu->u.scanRequest;
2627 if (queryType == QueryType_CCL2RPN)
2630 struct ccl_rpn_node *rpn;
2632 rpn = ccl_find_str (bibset, query, &error, &pos);
2635 printf("CCL ERROR: %s\n", ccl_err_msg(error));
2639 yaz_oidval_to_z3950oid(out, CLASS_ATTSET, VAL_BIB1);
2640 if (!(req->termListAndStartPoint = ccl_scan_query (out, rpn)))
2642 printf("Couldn't convert CCL to Scan term\n");
2645 ccl_rpn_delete (rpn);
2649 YAZ_PQF_Parser pqf_parser = yaz_pqf_create ();
2651 if (!(req->termListAndStartPoint =
2652 yaz_pqf_scan(pqf_parser, out, &req->attributeSet, query)))
2654 const char *pqf_msg;
2656 int code = yaz_pqf_error (pqf_parser, &pqf_msg, &off);
2657 printf("%*s^\n", off+7, "");
2658 printf("Prefix query error: %s (code %d)\n", pqf_msg, code);
2659 yaz_pqf_destroy (pqf_parser);
2662 yaz_pqf_destroy (pqf_parser);
2666 if (req->termListAndStartPoint->term &&
2667 req->termListAndStartPoint->term->which == Z_Term_general &&
2668 req->termListAndStartPoint->term->u.general)
2670 req->termListAndStartPoint->term->u.general->buf =
2671 (unsigned char *) odr_strdup(out, term);
2672 req->termListAndStartPoint->term->u.general->len =
2673 req->termListAndStartPoint->term->u.general->size =
2677 req->referenceId = set_refid (out);
2678 req->num_databaseNames = num_databaseNames;
2679 req->databaseNames = databaseNames;
2680 req->numberOfTermsRequested = #
2681 req->preferredPositionInResponse = &pp;
2682 req->stepSize = odr_intdup(out, scan_stepSize);
2687 int send_sortrequest(const char *arg, int newset)
2689 Z_APDU *apdu = zget_APDU(out, Z_APDU_sortRequest);
2690 Z_SortRequest *req = apdu->u.sortRequest;
2691 Z_SortKeySpecList *sksl = (Z_SortKeySpecList *)
2692 odr_malloc (out, sizeof(*sksl));
2698 sprintf (setstring, "%d", setnumber);
2700 sprintf (setstring, "default");
2702 req->referenceId = set_refid (out);
2704 req->num_inputResultSetNames = 1;
2705 req->inputResultSetNames = (Z_InternationalString **)
2706 odr_malloc (out, sizeof(*req->inputResultSetNames));
2707 req->inputResultSetNames[0] = odr_strdup (out, setstring);
2709 if (newset && setnumber >= 0)
2710 sprintf (setstring, "%d", ++setnumber);
2712 req->sortedResultSetName = odr_strdup (out, setstring);
2714 req->sortSequence = yaz_sort_spec (out, arg);
2715 if (!req->sortSequence)
2717 printf ("Missing sort specifications\n");
2724 void display_term(Z_TermInfo *t)
2727 printf("%s", t->displayTerm);
2728 else if (t->term->which == Z_Term_general)
2730 printf("%.*s", t->term->u.general->len, t->term->u.general->buf);
2731 sprintf(last_scan_line, "%.*s", t->term->u.general->len,
2732 t->term->u.general->buf);
2735 printf("Term (not general)");
2736 if (t->globalOccurrences)
2737 printf (" (%d)\n", *t->globalOccurrences);
2742 void process_scanResponse(Z_ScanResponse *res)
2745 Z_Entry **entries = NULL;
2746 int num_entries = 0;
2748 printf("Received ScanResponse\n");
2749 print_refid (res->referenceId);
2750 printf("%d entries", *res->numberOfEntriesReturned);
2751 if (res->positionOfTerm)
2752 printf (", position=%d", *res->positionOfTerm);
2754 if (*res->scanStatus != Z_Scan_success)
2755 printf("Scan returned code %d\n", *res->scanStatus);
2758 if ((entries = res->entries->entries))
2759 num_entries = res->entries->num_entries;
2760 for (i = 0; i < num_entries; i++)
2762 int pos_term = res->positionOfTerm ? *res->positionOfTerm : -1;
2763 if (entries[i]->which == Z_Entry_termInfo)
2765 printf("%c ", i + 1 == pos_term ? '*' : ' ');
2766 display_term(entries[i]->u.termInfo);
2769 display_diagrecs(&entries[i]->u.surrogateDiagnostic, 1);
2771 if (res->entries->nonsurrogateDiagnostics)
2772 display_diagrecs (res->entries->nonsurrogateDiagnostics,
2773 res->entries->num_nonsurrogateDiagnostics);
2776 void process_sortResponse(Z_SortResponse *res)
2778 printf("Received SortResponse: status=");
2779 switch (*res->sortStatus)
2781 case Z_SortResponse_success:
2782 printf ("success"); break;
2783 case Z_SortResponse_partial_1:
2784 printf ("partial"); break;
2785 case Z_SortResponse_failure:
2786 printf ("failure"); break;
2788 printf ("unknown (%d)", *res->sortStatus);
2791 print_refid (res->referenceId);
2792 if (res->diagnostics)
2793 display_diagrecs(res->diagnostics,
2794 res->num_diagnostics);
2797 void process_deleteResultSetResponse (Z_DeleteResultSetResponse *res)
2799 printf("Got deleteResultSetResponse status=%d\n",
2800 *res->deleteOperationStatus);
2801 if (res->deleteListStatuses)
2804 for (i = 0; i < res->deleteListStatuses->num; i++)
2806 printf ("%s status=%d\n", res->deleteListStatuses->elements[i]->id,
2807 *res->deleteListStatuses->elements[i]->status);
2812 int cmd_sort_generic(const char *arg, int newset)
2816 printf("Session not initialized yet\n");
2821 if (!ODR_MASK_GET(session->options, Z_Options_sort))
2823 printf("Target doesn't support sort\n");
2828 if (send_sortrequest(arg, newset) < 0)
2835 int cmd_sort(const char *arg)
2837 return cmd_sort_generic (arg, 0);
2840 int cmd_sort_newset (const char *arg)
2842 return cmd_sort_generic (arg, 1);
2845 int cmd_scanstep(const char *arg)
2847 scan_stepSize = atoi(arg);
2851 int cmd_scanpos(const char *arg)
2853 int r = sscanf(arg, "%d", &scan_position);
2859 int cmd_scan(const char *arg)
2861 if (protocol == PROTO_HTTP)
2870 if (send_SRW_scanRequest(arg, scan_position, 20) < 0)
2875 if (send_SRW_scanRequest(last_scan_line, 1, 20) < 0)
2890 printf("Session not initialized yet\n");
2894 if (!ODR_MASK_GET(session->options, Z_Options_scan))
2896 printf("Target doesn't support scan\n");
2901 strcpy (last_scan_query, arg);
2902 if (send_scanrequest(arg, scan_position, 20, 0) < 0)
2907 if (send_scanrequest(last_scan_query, 1, 20, last_scan_line) < 0)
2914 int cmd_schema(const char *arg)
2916 xfree(record_schema);
2919 record_schema = xstrdup(arg);
2923 int cmd_format(const char *arg)
2928 printf("Usage: format <recordsyntax>\n");
2931 nsyntax = oid_getvalbyname (arg);
2932 if (strcmp(arg, "none") && nsyntax == VAL_NONE)
2934 printf ("unknown record syntax\n");
2937 recordsyntax = nsyntax;
2941 int cmd_elements(const char *arg)
2943 static Z_ElementSetNames esn;
2944 static char what[100];
2948 elementSetNames = 0;
2952 esn.which = Z_ElementSetNames_generic;
2953 esn.u.generic = what;
2954 elementSetNames = &esn;
2958 int cmd_attributeset(const char *arg)
2964 printf("Usage: attributeset <setname>\n");
2967 sscanf(arg, "%s", what);
2968 if (p_query_attset (what))
2970 printf("Unknown attribute set name\n");
2976 int cmd_querytype (const char *arg)
2978 if (!strcmp (arg, "ccl"))
2979 queryType = QueryType_CCL;
2980 else if (!strcmp (arg, "prefix") || !strcmp(arg, "rpn"))
2981 queryType = QueryType_Prefix;
2982 else if (!strcmp (arg, "ccl2rpn") || !strcmp (arg, "cclrpn"))
2983 queryType = QueryType_CCL2RPN;
2984 else if (!strcmp(arg, "cql"))
2985 queryType = QueryType_CQL;
2986 else if (!strcmp (arg, "cql2rpn") || !strcmp (arg, "cqlrpn"))
2987 queryType = QueryType_CQL2RPN;
2990 printf ("Querytype must be one of:\n");
2991 printf (" prefix - Prefix query\n");
2992 printf (" ccl - CCL query\n");
2993 printf (" ccl2rpn - CCL query converted to RPN\n");
2994 printf (" cql - CQL\n");
2995 printf (" cql2rpn - CQL query converted to RPN\n");
3001 int cmd_refid (const char *arg)
3006 refid = xstrdup (arg);
3010 int cmd_close(const char *arg)
3019 apdu = zget_APDU(out, Z_APDU_close);
3020 req = apdu->u.close;
3021 *req->closeReason = Z_Close_finished;
3023 printf("Sent close request.\n");
3028 int cmd_packagename(const char* arg)
3030 xfree (esPackageName);
3031 esPackageName = NULL;
3033 esPackageName = xstrdup(arg);
3037 int cmd_proxy(const char* arg)
3042 yazProxy = xstrdup (arg);
3046 int cmd_marccharset(const char *arg)
3051 if (sscanf(arg, "%29s", l1) < 1)
3053 printf("MARC character set is `%s'\n",
3054 marcCharset ? marcCharset: "none");
3057 xfree (marcCharset);
3059 if (strcmp(l1, "-"))
3060 marcCharset = xstrdup(l1);
3064 int cmd_displaycharset(const char *arg)
3069 if (sscanf(arg, "%29s", l1) < 1)
3071 printf("Display character set is `%s'\n",
3072 outputCharset ? outputCharset: "none");
3076 xfree (outputCharset);
3078 if (!strcmp(l1, "auto") && codeset)
3082 printf ("Display character set: %s\n", codeset);
3083 outputCharset = xstrdup(codeset);
3086 printf ("No codeset found on this system\n");
3088 else if (strcmp(l1, "-") && strcmp(l1, "none"))
3089 outputCharset = xstrdup(l1);
3094 int cmd_negcharset(const char *arg)
3099 if (sscanf(arg, "%29s %d %d", l1, &negotiationCharsetRecords,
3100 &negotiationCharsetVersion) < 1)
3102 printf("Current negotiation character set is `%s'\n",
3103 negotiationCharset ? negotiationCharset: "none");
3104 printf("Records in charset %s\n", negotiationCharsetRecords ?
3106 printf("Charneg version %d\n", negotiationCharsetVersion);
3110 xfree (negotiationCharset);
3111 negotiationCharset = NULL;
3112 if (*l1 && strcmp(l1, "-") && strcmp(l1, "none"))
3114 negotiationCharset = xstrdup(l1);
3115 printf ("Character set negotiation : %s\n", negotiationCharset);
3121 int cmd_charset(const char* arg)
3123 char l1[30], l2[30], l3[30];
3125 *l1 = *l2 = *l3 = 0;
3126 if (sscanf(arg, "%29s %29s %29s", l1, l2, l3) < 1)
3129 cmd_displaycharset("");
3130 cmd_marccharset("");
3136 cmd_displaycharset(l2);
3138 cmd_marccharset(l3);
3143 int cmd_lang(const char* arg)
3146 printf("Current language is `%s'\n", (yazLang)?yazLang:NULL);
3152 yazLang = xstrdup(arg);
3156 int cmd_source(const char* arg, int echo )
3158 /* first should open the file and read one line at a time.. */
3160 char line[102400], *cp;
3163 fprintf(stderr,"Error in source command use a filename\n");
3167 includeFile = fopen (arg, "r");
3170 fprintf(stderr,"Unable to open file %s for reading\n",arg);
3174 while(!feof(includeFile)) {
3175 memset(line,0,sizeof(line));
3176 fgets(line,sizeof(line),includeFile);
3178 if(strlen(line) < 2) continue;
3179 if(line[0] == '#') continue;
3181 if ((cp = strrchr (line, '\n')))
3185 printf( "processing line: %s\n",line );
3187 process_cmd_line(line);
3190 if(fclose(includeFile)<0) {
3191 perror("unable to close include file");
3197 int cmd_source_echo(const char* arg)
3203 int cmd_source_noecho(const char* arg)
3210 int cmd_subshell(const char* args)
3215 system(getenv("SHELL"));
3221 int cmd_set_berfile(const char *arg)
3223 if (ber_file && ber_file != stdout && ber_file != stderr)
3225 if (!strcmp(arg, ""))
3227 else if (!strcmp(arg, "-"))
3230 ber_file = fopen(arg, "a");
3234 int cmd_set_apdufile(const char *arg)
3236 if(apdu_file && apdu_file != stderr && apdu_file != stderr)
3238 if (!strcmp(arg, ""))
3240 else if (!strcmp(arg, "-"))
3244 apdu_file = fopen(arg, "a");
3246 perror("unable to open apdu log file");
3249 odr_setprint(print, apdu_file);
3253 int cmd_set_cclfile(const char* arg)
3257 bibset = ccl_qual_mk ();
3258 inf = fopen (arg, "r");
3260 perror("unable to open CCL file");
3263 ccl_qual_file (bibset, inf);
3266 strcpy(ccl_fields,arg);
3270 int cmd_set_cqlfile(const char* arg)
3272 cql_transform_t newcqltrans;
3274 if ((newcqltrans = cql_transform_open_fname(arg)) == 0) {
3275 perror("unable to open CQL file");
3279 cql_transform_close(cqltrans);
3281 cqltrans = newcqltrans;
3282 strcpy(cql_fields, arg);
3286 int cmd_set_auto_reconnect(const char* arg)
3288 if(strlen(arg)==0) {
3289 auto_reconnect = ! auto_reconnect;
3290 } else if(strcmp(arg,"on")==0) {
3292 } else if(strcmp(arg,"off")==0) {
3295 printf("Error use on or off\n");
3300 printf("Set auto reconnect enabled.\n");
3302 printf("Set auto reconnect disabled.\n");
3307 int cmd_set_marcdump(const char* arg)
3309 if(marc_file && marc_file != stderr) { /* don't close stdout*/
3313 if (!strcmp(arg, ""))
3315 else if (!strcmp(arg, "-"))
3319 marc_file = fopen(arg, "a");
3321 perror("unable to open marc log file");
3327 this command takes 3 arge {name class oid}
3329 int cmd_register_oid(const char* args) {
3334 {"appctx",CLASS_APPCTX},
3335 {"absyn",CLASS_ABSYN},
3336 {"attset",CLASS_ATTSET},
3337 {"transyn",CLASS_TRANSYN},
3338 {"diagset",CLASS_DIAGSET},
3339 {"recsyn",CLASS_RECSYN},
3340 {"resform",CLASS_RESFORM},
3341 {"accform",CLASS_ACCFORM},
3342 {"extserv",CLASS_EXTSERV},
3343 {"userinfo",CLASS_USERINFO},
3344 {"elemspec",CLASS_ELEMSPEC},
3345 {"varset",CLASS_VARSET},
3346 {"schema",CLASS_SCHEMA},
3347 {"tagset",CLASS_TAGSET},
3348 {"general",CLASS_GENERAL},
3349 {0,(enum oid_class) 0}
3351 char oname_str[101], oclass_str[101], oid_str[101];
3354 oid_class oidclass = CLASS_GENERAL;
3355 int val = 0, oid[OID_SIZE];
3356 struct oident * new_oident=NULL;
3358 if (sscanf (args, "%100[^ ] %100[^ ] %100s",
3359 oname_str,oclass_str, oid_str) < 1) {
3360 printf("Error in register command \n");
3364 for (i = 0; oid_classes[i].className; i++) {
3365 if (!strcmp(oid_classes[i].className, oclass_str))
3367 oidclass=oid_classes[i].oclass;
3372 if(!(oid_classes[i].className)) {
3373 printf("Unknown oid class %s\n",oclass_str);
3381 while (isdigit (*(unsigned char *) name))
3383 val = val*10 + (*name - '0');
3396 new_oident = oid_addent (oid, PROTO_GENERAL, oidclass, oname_str,
3398 if(strcmp(new_oident->desc,oname_str))
3400 fprintf(stderr,"oid is already named as %s, registration failed\n",
3406 int cmd_push_command(const char* arg)
3408 #if HAVE_READLINE_HISTORY_H
3412 fprintf(stderr,"Not compiled with the readline/history module\n");
3417 void source_rcfile()
3419 /* Look for a $HOME/.yazclientrc and source it if it exists */
3420 struct stat statbuf;
3422 char* homedir=getenv("HOME");
3426 sprintf(buffer,"%s/.yazclientrc",homedir);
3428 if(stat(buffer,&statbuf)==0) {
3429 cmd_source(buffer, 0 );
3434 if(stat(".yazclientrc",&statbuf)==0) {
3435 cmd_source(".yazclientrc", 0 );
3440 static void initialize(void)
3445 if (!(out = odr_createmem(ODR_ENCODE)) ||
3446 !(in = odr_createmem(ODR_DECODE)) ||
3447 !(print = odr_createmem(ODR_PRINT)))
3449 fprintf(stderr, "failed to allocate ODR streams\n");
3454 setvbuf(stdout, 0, _IONBF, 0);
3456 odr_setprint(print, apdu_file);
3458 bibset = ccl_qual_mk ();
3459 inf = fopen (ccl_fields, "r");
3462 ccl_qual_file (bibset, inf);
3466 cqltrans = cql_transform_open_fname(cql_fields);
3467 /* If this fails, no problem: we detect cqltrans == 0 later */
3469 #if HAVE_READLINE_READLINE_H
3470 rl_attempted_completion_function = (CPPFunction*)readline_completer;
3474 for(i=0; i<maxOtherInfosSupported; ++i) {
3475 extraOtherInfos[i].oidval = -1;
3482 #if HAVE_GETTIMEOFDAY
3483 struct timeval tv_start, tv_end;
3487 static void handle_srw_record(Z_SRW_record *rec)
3489 if (rec->recordPosition)
3491 printf ("pos=%d", *rec->recordPosition);
3492 setno = *rec->recordPosition + 1;
3494 if (rec->recordSchema)
3495 printf (" schema=%s", rec->recordSchema);
3497 if (rec->recordData_buf && rec->recordData_len)
3499 fwrite(rec->recordData_buf, 1, rec->recordData_len, stdout);
3501 fwrite (rec->recordData_buf, 1, rec->recordData_len, marc_file);
3504 printf ("No data!");
3508 static void handle_srw_explain_response(Z_SRW_explainResponse *res)
3510 handle_srw_record(&res->record);
3513 static void handle_srw_response(Z_SRW_searchRetrieveResponse *res)
3517 printf ("Received SRW SearchRetrieve Response\n");
3519 for (i = 0; i<res->num_diagnostics; i++)
3521 if (res->diagnostics[i].uri)
3522 printf ("SRW diagnostic %s\n",
3523 res->diagnostics[i].uri);
3525 printf ("SRW diagnostic missing or could not be decoded\n");
3526 if (res->diagnostics[i].message)
3527 printf ("Message: %s\n", res->diagnostics[i].message);
3528 if (res->diagnostics[i].details)
3529 printf ("Details: %s\n", res->diagnostics[i].details);
3531 if (res->numberOfRecords)
3532 printf ("Number of hits: %d\n", *res->numberOfRecords);
3533 for (i = 0; i<res->num_records; i++)
3534 handle_srw_record(res->records + i);
3537 static void handle_srw_scan_term(Z_SRW_scanTerm *term)
3539 if (term->displayTerm)
3540 printf("%s:", term->displayTerm);
3541 else if (term->value)
3542 printf("%s:", term->value);
3544 printf("No value:");
3545 if (term->numberOfRecords)
3546 printf(" %d", *term->numberOfRecords);
3547 if (term->whereInList)
3548 printf(" %s", term->whereInList);
3549 if (term->value && term->displayTerm)
3550 printf(" %s", term->value);
3552 strcpy(last_scan_line, term->value);
3556 static void handle_srw_scan_response(Z_SRW_scanResponse *res)
3560 printf ("Received SRW Scan Response\n");
3562 for (i = 0; i<res->num_diagnostics; i++)
3564 if (res->diagnostics[i].uri)
3565 printf ("SRW diagnostic %s\n",
3566 res->diagnostics[i].uri);
3568 printf ("SRW diagnostic missing or could not be decoded\n");
3569 if (res->diagnostics[i].message)
3570 printf ("Message: %s\n", res->diagnostics[i].message);
3571 if (res->diagnostics[i].details)
3572 printf ("Details: %s\n", res->diagnostics[i].details);
3575 for (i = 0; i<res->num_terms; i++)
3576 handle_srw_scan_term(res->terms + i);
3579 static void http_response(Z_HTTP_Response *hres)
3582 const char *content_type = z_HTTP_header_lookup(hres->headers,
3584 const char *connection_head = z_HTTP_header_lookup(hres->headers,
3586 if (content_type && !yaz_strcmp_del("text/xml", content_type, "; "))
3588 Z_SOAP *soap_package = 0;
3589 ODR o = odr_createmem(ODR_DECODE);
3590 Z_SOAP_Handler soap_handlers[2] = {
3591 {"http://www.loc.gov/zing/srw/", 0,
3592 (Z_SOAP_fun) yaz_srw_codec},
3595 ret = z_soap_codec(o, &soap_package,
3596 &hres->content_buf, &hres->content_len,
3598 if (!ret && soap_package->which == Z_SOAP_generic &&
3599 soap_package->u.generic->no == 0)
3601 Z_SRW_PDU *sr = soap_package->u.generic->p;
3602 if (sr->which == Z_SRW_searchRetrieve_response)
3603 handle_srw_response(sr->u.response);
3604 else if (sr->which == Z_SRW_explain_response)
3605 handle_srw_explain_response(sr->u.explain_response);
3606 else if (sr->which == Z_SRW_scan_response)
3607 handle_srw_scan_response(sr->u.scan_response);
3611 else if (soap_package && (soap_package->which == Z_SOAP_fault
3612 || soap_package->which == Z_SOAP_error))
3614 printf ("HTTP Error Status=%d\n", hres->code);
3615 printf ("SOAP Fault code %s\n",
3616 soap_package->u.fault->fault_code);
3617 printf ("SOAP Fault string %s\n",
3618 soap_package->u.fault->fault_string);
3619 if (soap_package->u.fault->details)
3620 printf ("SOAP Details %s\n",
3621 soap_package->u.fault->details);
3629 if (hres->code != 200)
3631 printf ("HTTP Error Status=%d\n", hres->code);
3635 printf ("Decoding of SRW package failed\n");
3641 if (!strcmp(hres->version, "1.0"))
3643 /* HTTP 1.0: only if Keep-Alive we stay alive.. */
3644 if (!connection_head || strcmp(connection_head, "Keep-Alive"))
3649 /* HTTP 1.1: only if no close we stay alive .. */
3650 if (connection_head && !strcmp(connection_head, "close"))
3657 void wait_and_handle_response()
3659 int reconnect_ok = 1;
3662 int netbufferlen = 0;
3667 res = cs_get(conn, &netbuffer, &netbufferlen);
3668 if (reconnect_ok && res <= 0 && protocol == PROTO_HTTP)
3679 buf_out = odr_getbuf(out, &len_out, 0);
3681 do_hex_dump(buf_out, len_out);
3683 cs_put(conn, buf_out, len_out);
3691 printf("Target closed connection\n");
3696 odr_reset(in); /* release APDU from last round */
3698 do_hex_dump(netbuffer, res);
3699 odr_setbuf(in, netbuffer, res, 0);
3701 if (!z_GDU(in, &gdu, 0, 0))
3703 FILE *f = ber_file ? ber_file : stdout;
3704 odr_perror(in, "Decoding incoming APDU");
3705 fprintf(f, "[Near %d]\n", odr_offset(in));
3706 fprintf(f, "Packet dump:\n---------\n");
3707 odr_dumpBER(f, netbuffer, res);
3708 fprintf(f, "---------\n");
3711 z_GDU(print, &gdu, 0, 0);
3714 if (conn && cs_more(conn))
3719 odr_dumpBER(ber_file, netbuffer, res);
3720 if (apdu_file && !z_GDU(print, &gdu, 0, 0))
3722 odr_perror(print, "Failed to print incoming APDU");
3726 if (gdu->which == Z_GDU_Z3950)
3728 Z_APDU *apdu = gdu->u.z3950;
3731 case Z_APDU_initResponse:
3732 process_initResponse(apdu->u.initResponse);
3734 case Z_APDU_searchResponse:
3735 process_searchResponse(apdu->u.searchResponse);
3737 case Z_APDU_scanResponse:
3738 process_scanResponse(apdu->u.scanResponse);
3740 case Z_APDU_presentResponse:
3741 print_refid (apdu->u.presentResponse->referenceId);
3743 *apdu->u.presentResponse->numberOfRecordsReturned;
3744 if (apdu->u.presentResponse->records)
3745 display_records(apdu->u.presentResponse->records);
3747 printf("No records.\n");
3748 printf ("nextResultSetPosition = %d\n",
3749 *apdu->u.presentResponse->nextResultSetPosition);
3751 case Z_APDU_sortResponse:
3752 process_sortResponse(apdu->u.sortResponse);
3754 case Z_APDU_extendedServicesResponse:
3755 printf("Got extended services response\n");
3756 process_ESResponse(apdu->u.extendedServicesResponse);
3759 printf("Target has closed the association.\n");
3760 process_close(apdu->u.close);
3762 case Z_APDU_resourceControlRequest:
3763 process_resourceControlRequest
3764 (apdu->u.resourceControlRequest);
3766 case Z_APDU_deleteResultSetResponse:
3767 process_deleteResultSetResponse(apdu->u.
3768 deleteResultSetResponse);
3771 printf("Received unknown APDU type (%d).\n",
3777 else if (gdu->which == Z_GDU_HTTP_Response)
3779 http_response(gdu->u.HTTP_Response);
3782 if (conn && !cs_more(conn))
3787 #if HAVE_GETTIMEOFDAY
3788 gettimeofday (&tv_end, 0);
3790 printf ("S/U S/U=%ld/%ld %ld/%ld",
3791 (long) tv_start.tv_sec,
3792 (long) tv_start.tv_usec,
3793 (long) tv_end.tv_sec,
3794 (long) tv_end.tv_usec);
3796 printf ("Elapsed: %.6f\n",
3797 (double) tv_end.tv_usec / 1e6 + tv_end.tv_sec -
3798 ((double) tv_start.tv_usec / 1e6 + tv_start.tv_sec));
3805 int cmd_cclparse(const char* arg)
3808 struct ccl_rpn_node *rpn=NULL;
3811 rpn = ccl_find_str (bibset, arg, &error, &pos);
3814 printf ("%*s^ - ", 3+strlen(last_cmd)+1+pos, " ");
3815 printf ("%s\n", ccl_err_msg (error));
3821 ccl_pr_tree(rpn, stdout);
3825 ccl_rpn_delete(rpn);
3833 int cmd_set_otherinfo(const char* args)
3835 char oidstr[101], otherinfoString[101];
3840 sscan_res = sscanf (args, "%d %100[^ ] %100s", &otherinfoNo, oidstr, otherinfoString);
3842 /* reset this otherinfo */
3843 if(otherinfoNo>=maxOtherInfosSupported) {
3844 printf("Error otherinfo index to large (%d>%d)\n",
3845 otherinfoNo,maxOtherInfosSupported);
3847 extraOtherInfos[otherinfoNo].oidval = -1;
3848 if (extraOtherInfos[otherinfoNo].value)
3849 free(extraOtherInfos[otherinfoNo].value);
3853 printf("Error in set_otherinfo command \n");
3857 if (otherinfoNo>=maxOtherInfosSupported) {
3858 printf("Error otherinfo index to large (%d>%d)\n",
3859 otherinfoNo,maxOtherInfosSupported);
3862 oidval = oid_getvalbyname (oidstr);
3863 if (oidval == -1 ) {
3864 printf("Error in set_otherinfo command unknown oid %s \n",oidstr);
3867 extraOtherInfos[otherinfoNo].oidval = oidval;
3868 if(extraOtherInfos[otherinfoNo].value) free(extraOtherInfos[otherinfoNo].value);
3869 extraOtherInfos[otherinfoNo].value = strdup(otherinfoString);
3874 int cmd_sleep(const char* args )
3883 printf("Done sleeping %d seconds\n", sec);
3888 int cmd_list_otherinfo(const char* args)
3892 if(strlen(args)>0) {
3894 if( i >= maxOtherInfosSupported ) {
3895 printf("Error otherinfo index to large (%d>%d)\n",i,maxOtherInfosSupported);
3899 if(extraOtherInfos[i].oidval != -1)
3900 printf(" otherinfo %d %s %s\n",
3902 yaz_z3950_oid_value_to_str(
3903 (enum oid_value) extraOtherInfos[i].oidval,
3905 extraOtherInfos[i].value);
3908 for(i=0; i<maxOtherInfosSupported; ++i) {
3909 if(extraOtherInfos[i].oidval != -1)
3910 printf(" otherinfo %d %s %s\n",
3912 yaz_z3950_oid_value_to_str(
3913 (enum oid_value) extraOtherInfos[i].oidval,
3915 extraOtherInfos[i].value);
3923 int cmd_list_all(const char* args) {
3926 /* connection options */
3928 printf("Connected to : %s\n",last_open_command);
3930 if(last_open_command)
3931 printf("Not connected to : %s\n",last_open_command);
3933 printf("Not connected : \n");
3936 if(yazProxy) printf("using proxy : %s\n",yazProxy);
3938 printf("auto_reconnect : %s\n",auto_reconnect?"on":"off");
3941 printf("Authentication : none\n");
3943 switch(auth->which) {
3944 case Z_IdAuthentication_idPass:
3945 printf("Authentication : IdPass\n");
3946 printf(" Login User : %s\n",auth->u.idPass->userId?auth->u.idPass->userId:"");
3947 printf(" Login Group : %s\n",auth->u.idPass->groupId?auth->u.idPass->groupId:"");
3948 printf(" Password : %s\n",auth->u.idPass->password?auth->u.idPass->password:"");
3950 case Z_IdAuthentication_open:
3951 printf("Authentication : psOpen\n");
3952 printf(" Open string : %s\n",auth->u.open);
3955 printf("Authentication : Unknown\n");
3958 if (negotiationCharset)
3959 printf("Neg. Character set : `%s'\n", negotiationCharset);
3963 for (i = 0; i<num_databaseNames; i++) printf("%s ",databaseNames[i]);
3967 printf("CCL file : %s\n",ccl_fields);
3968 printf("CQL file : %s\n",cql_fields);
3969 printf("Query type : %s\n",query_type_as_string(queryType));
3971 printf("Named Result Sets : %s\n",setnumber==-1?"off":"on");
3973 /* piggy back options */
3974 printf("ssub/lslb/mspn : %d/%d/%d\n",smallSetUpperBound,largeSetLowerBound,mediumSetPresentNumber);
3976 /* print present related options */
3977 printf("Format : %s\n",yaz_z3950_oid_value_to_str(recordsyntax,CLASS_RECSYN));
3978 printf("Schema : %s\n",record_schema ? record_schema : "not set");
3979 printf("Elements : %s\n",elementSetNames?elementSetNames->u.generic:"");
3981 /* loging options */
3982 printf("APDU log : %s\n",apdu_file?"on":"off");
3983 printf("Record log : %s\n",marc_file?"on":"off");
3986 printf("Other Info: \n");
3987 cmd_list_otherinfo("");
3992 int cmd_clear_otherinfo(const char* args)
3994 if(strlen(args)>0) {
3996 otherinfoNo = atoi(args);
3997 if( otherinfoNo >= maxOtherInfosSupported ) {
3998 printf("Error otherinfo index to large (%d>%d)\n",otherinfoNo,maxOtherInfosSupported);
4002 if(extraOtherInfos[otherinfoNo].oidval != -1) {
4003 /* only clear if set. */
4004 extraOtherInfos[otherinfoNo].oidval=-1;
4005 free(extraOtherInfos[otherinfoNo].value);
4010 for(i=0; i<maxOtherInfosSupported; ++i) {
4011 if (extraOtherInfos[i].oidval!=-1 ) {
4012 extraOtherInfos[i].oidval=-1;
4013 free(extraOtherInfos[i].value);
4020 static int cmd_help (const char *line);
4022 typedef char *(*completerFunctionType)(const char *text, int state);
4026 int (*fun)(const char *arg);
4028 completerFunctionType rl_completerfunction;
4029 int complete_filenames;
4030 char **local_tabcompletes;
4032 {"open", cmd_open, "('tcp'|'ssl')':<host>[':'<port>][/<db>]",NULL,0,NULL},
4033 {"quit", cmd_quit, "",NULL,0,NULL},
4034 {"find", cmd_find, "<query>",NULL,0,NULL},
4035 {"delete", cmd_delete, "<setname>",NULL,0,NULL},
4036 {"base", cmd_base, "<base-name>",NULL,0,NULL},
4037 {"show", cmd_show, "<rec#>['+'<#recs>['+'<setname>]]",NULL,0,NULL},
4038 {"scan", cmd_scan, "<term>",NULL,0,NULL},
4039 {"scanstep", cmd_scanstep, "<size>",NULL,0,NULL},
4040 {"scanpos", cmd_scanpos, "<size>",NULL,0,NULL},
4041 {"sort", cmd_sort, "<sortkey> <flag> <sortkey> <flag> ...",NULL,0,NULL},
4042 {"sort+", cmd_sort_newset, "<sortkey> <flag> <sortkey> <flag> ...",NULL,0,NULL},
4043 {"authentication", cmd_authentication, "<acctstring>",NULL,0,NULL},
4044 {"lslb", cmd_lslb, "<largeSetLowerBound>",NULL,0,NULL},
4045 {"ssub", cmd_ssub, "<smallSetUpperBound>",NULL,0,NULL},
4046 {"mspn", cmd_mspn, "<mediumSetPresentNumber>",NULL,0,NULL},
4047 {"status", cmd_status, "",NULL,0,NULL},
4048 {"setnames", cmd_setnames, "",NULL,0,NULL},
4049 {"cancel", cmd_cancel, "",NULL,0,NULL},
4050 {"cancel_find", cmd_cancel_find, "<query>",NULL,0,NULL},
4051 {"format", cmd_format, "<recordsyntax>",complete_format,0,NULL},
4052 {"schema", cmd_schema, "<schema>",complete_schema,0,NULL},
4053 {"elements", cmd_elements, "<elementSetName>",NULL,0,NULL},
4054 {"close", cmd_close, "",NULL,0,NULL},
4055 {"attributeset", cmd_attributeset, "<attrset>",complete_attributeset,0,NULL},
4056 {"querytype", cmd_querytype, "<type>",complete_querytype,0,NULL},
4057 {"refid", cmd_refid, "<id>",NULL,0,NULL},
4058 {"itemorder", cmd_itemorder, "ill|item <itemno>",NULL,0,NULL},
4059 {"update", cmd_update, "<action> <recid> [<file>]",NULL,0,NULL},
4060 {"update0", cmd_update0, "<action> <recid> [<file>]",NULL,0,NULL},
4061 {"packagename", cmd_packagename, "<packagename>",NULL,0,NULL},
4062 {"proxy", cmd_proxy, "[('tcp'|'ssl')]<host>[':'<port>]",NULL,0,NULL},
4063 {"charset", cmd_charset, "<nego_charset> <output_charset>",NULL,0,NULL},
4064 {"negcharset", cmd_negcharset, "<nego_charset>",NULL,0,NULL},
4065 {"displaycharset", cmd_displaycharset, "<output_charset>",NULL,0,NULL},
4066 {"marccharset", cmd_marccharset, "<charset_name>",NULL,0,NULL},
4067 {"lang", cmd_lang, "<language_code>",NULL,0,NULL},
4068 {".", cmd_source_echo, "<filename>",NULL,1,NULL},
4069 {"!", cmd_subshell, "Subshell command",NULL,1,NULL},
4070 {"set_apdufile", cmd_set_apdufile, "<filename>",NULL,1,NULL},
4071 {"set_berfile", cmd_set_berfile, "<filename>",NULL,1,NULL},
4072 {"set_marcdump", cmd_set_marcdump," <filename>",NULL,1,NULL},
4073 {"set_cclfile", cmd_set_cclfile," <filename>",NULL,1,NULL},
4074 {"set_cqlfile", cmd_set_cqlfile," <filename>",NULL,1,NULL},
4075 {"set_auto_reconnect", cmd_set_auto_reconnect," on|off",complete_auto_reconnect,1,NULL},
4076 {"set_otherinfo", cmd_set_otherinfo,"<otherinfoinddex> <oid> <string>",NULL,0,NULL},
4077 {"sleep", cmd_sleep,"<seconds>",NULL,0,NULL},
4078 {"register_oid", cmd_register_oid,"<name> <class> <oid>",NULL,0,NULL},
4079 {"push_command", cmd_push_command,"<command>",command_generator,0,NULL},
4080 {"register_tab", cmd_register_tab,"<commandname> <tab>",command_generator,0,NULL},
4081 {"cclparse", cmd_cclparse,"<ccl find command>",NULL,0,NULL},
4082 {"list_otherinfo",cmd_list_otherinfo,"[otherinfoinddex]",NULL,0,NULL},
4083 {"list_all",cmd_list_all,"",NULL,0,NULL},
4084 {"clear_otherinfo",cmd_clear_otherinfo,"",NULL,0,NULL},
4085 /* Server Admin Functions */
4086 {"adm-reindex", cmd_adm_reindex, "<database-name>",NULL,0,NULL},
4087 {"adm-truncate", cmd_adm_truncate, "('database'|'index')<object-name>",NULL,0,NULL},
4088 {"adm-create", cmd_adm_create, "",NULL,0,NULL},
4089 {"adm-drop", cmd_adm_drop, "('database'|'index')<object-name>",NULL,0,NULL},
4090 {"adm-import", cmd_adm_import, "<record-type> <dir> <pattern>",NULL,0,NULL},
4091 {"adm-refresh", cmd_adm_refresh, "",NULL,0,NULL},
4092 {"adm-commit", cmd_adm_commit, "",NULL,0,NULL},
4093 {"adm-shutdown", cmd_adm_shutdown, "",NULL,0,NULL},
4094 {"adm-startup", cmd_adm_startup, "",NULL,0,NULL},
4095 {"explain", cmd_explain, "", NULL, 0, NULL},
4096 {"options", cmd_options, "", NULL, 0, NULL},
4097 {"zversion", cmd_zversion, "", NULL, 0, NULL},
4098 {"help", cmd_help, "", NULL,0,NULL},
4099 {"init", cmd_init, "", NULL,0,NULL},
4103 static int cmd_help (const char *line)
4109 sscanf (line, "%20s", topic);
4112 printf("Commands:\n");
4113 for (i = 0; cmd_array[i].cmd; i++)
4114 if (*topic == 0 || strcmp (topic, cmd_array[i].cmd) == 0)
4115 printf(" %s %s\n", cmd_array[i].cmd, cmd_array[i].ad);
4116 if (strcmp (topic, "find") == 0)
4119 printf (" \"term\" Simple Term\n");
4120 printf (" @attr [attset] type=value op Attribute\n");
4121 printf (" @and opl opr And\n");
4122 printf (" @or opl opr Or\n");
4123 printf (" @not opl opr And-Not\n");
4124 printf (" @set set Result set\n");
4126 printf ("Bib-1 attribute types\n");
4128 printf ("4=Title 7=ISBN 8=ISSN 30=Date 62=Abstract 1003=Author 1016=Any\n");
4129 printf ("2=Relation: ");
4130 printf ("1< 2<= 3= 4>= 5> 6!= 102=Relevance\n");
4131 printf ("3=Position: ");
4132 printf ("1=First in Field 2=First in subfield 3=Any position\n");
4133 printf ("4=Structure: ");
4134 printf ("1=Phrase 2=Word 3=Key 4=Year 5=Date 6=WordList\n");
4135 printf ("5=Truncation: ");
4136 printf ("1=Right 2=Left 3=L&R 100=No 101=# 102=Re-1 103=Re-2\n");
4137 printf ("6=Completeness:");
4138 printf ("1=Incomplete subfield 2=Complete subfield 3=Complete field\n");
4143 int cmd_register_tab(const char* arg) {
4145 char command[101], tabargument[101];
4150 if (sscanf (arg, "%100s %100s", command, tabargument) < 1) {
4154 /* locate the amdn in the list */
4155 for (i = 0; cmd_array[i].cmd; i++) {
4156 if (!strncmp(cmd_array[i].cmd, command, strlen(command))) {
4161 if(!cmd_array[i].cmd) {
4162 fprintf(stderr,"Unknown command %s\n",command);
4167 if(!cmd_array[i].local_tabcompletes)
4168 cmd_array[i].local_tabcompletes = (char **) calloc(1,sizeof(char**));
4172 tabslist = cmd_array[i].local_tabcompletes;
4173 for(;tabslist && *tabslist;tabslist++) {
4177 cmd_array[i].local_tabcompletes = (char **)
4178 realloc(cmd_array[i].local_tabcompletes,(num_of_tabs+2)*sizeof(char**));
4179 tabslist=cmd_array[i].local_tabcompletes;
4180 tabslist[num_of_tabs]=strdup(tabargument);
4181 tabslist[num_of_tabs+1]=NULL;
4186 void process_cmd_line(char* line)
4189 char word[32], arg[10240];
4191 #if HAVE_GETTIMEOFDAY
4192 gettimeofday (&tv_start, 0);
4195 if ((res = sscanf(line, "%31s %10239[^;]", word, arg)) <= 0)
4197 strcpy(word, last_cmd);
4202 strcpy(last_cmd, word);
4204 /* removed tailing spaces from the arg command */
4207 char* lastnonspace=NULL;
4210 if(!isspace(*(unsigned char *) p)) {
4215 *(++lastnonspace) = 0;
4218 for (i = 0; cmd_array[i].cmd; i++)
4219 if (!strncmp(cmd_array[i].cmd, word, strlen(word)))
4221 res = (*cmd_array[i].fun)(arg);
4225 if (!cmd_array[i].cmd) /* dump our help-screen */
4227 printf("Unknown command: %s.\n", word);
4228 printf("use help for list of commands\n");
4229 /* cmd_help (""); */
4233 if(apdu_file) fflush(apdu_file);
4236 wait_and_handle_response();
4245 char *command_generator(const char *text, int state)
4251 for( ; cmd_array[idx].cmd; ++idx) {
4252 if (!strncmp(cmd_array[idx].cmd,text,strlen(text))) {
4253 ++idx; /* skip this entry on the next run */
4254 return strdup(cmd_array[idx-1].cmd);
4262 This function only known how to complete on the first word
4264 char ** readline_completer(char *text, int start, int end) {
4265 #if HAVE_READLINE_READLINE_H
4267 completerFunctionType completerToUse;
4270 #if HAVE_READLINE_RL_COMPLETION_MATCHES
4271 char** res=rl_completion_matches(text,
4274 char** res=completion_matches(text,
4275 (CPFunction*)command_generator);
4277 rl_attempted_completion_over = 1;
4280 char arg[10240],word[32];
4282 if ((res = sscanf(rl_line_buffer, "%31s %10239[^;]", word, arg)) <= 0) {
4283 rl_attempted_completion_over = 1;
4287 for (i = 0; cmd_array[i].cmd; i++) {
4288 if (!strncmp(cmd_array[i].cmd, word, strlen(word))) {
4293 if(!cmd_array[i].cmd) return NULL;
4295 curret_global_list = cmd_array[i].local_tabcompletes;
4297 completerToUse = cmd_array[i].rl_completerfunction;
4298 if(completerToUse==NULL) /* if no pr. command completer is defined use the default completer */
4299 completerToUse = default_completer;
4301 if(completerToUse) {
4302 #ifdef HAVE_READLINE_RL_COMPLETION_MATCHES
4304 rl_completion_matches(text,
4308 completion_matches(text,
4309 (CPFunction*)completerToUse);
4311 if(!cmd_array[i].complete_filenames)
4312 rl_attempted_completion_over = 1;
4315 if(!cmd_array[i].complete_filenames)
4316 rl_attempted_completion_over = 1;
4326 static void client(void)
4332 #if HAVE_GETTIMEOFDAY
4333 gettimeofday (&tv_start, 0);
4338 char *line_in = NULL;
4339 #if HAVE_READLINE_READLINE_H
4342 line_in=readline(C_PROMPT);
4345 #if HAVE_READLINE_HISTORY_H
4347 add_history(line_in);
4349 strncpy(line, line_in, 10239);
4358 if (!fgets(line, 10239, stdin))
4360 if ((end_p = strchr (line, '\n')))
4363 process_cmd_line(line);
4367 static void show_version(void)
4371 yaz_version(vstr, 0);
4372 printf ("YAZ version: %s\n", YAZ_VERSION);
4373 if (strcmp(vstr, YAZ_VERSION))
4374 printf ("YAZ DLL/SO: %s\n", vstr);
4378 int main(int argc, char **argv)
4381 char *open_command = 0;
4382 char *auth_command = 0;
4387 if (!setlocale(LC_CTYPE, ""))
4388 fprintf (stderr, "setlocale failed\n");
4392 codeset = nl_langinfo(CODESET);
4396 outputCharset = xstrdup(codeset);
4398 ODR_MASK_SET(&z3950_options, Z_Options_search);
4399 ODR_MASK_SET(&z3950_options, Z_Options_present);
4400 ODR_MASK_SET(&z3950_options, Z_Options_namedResultSets);
4401 ODR_MASK_SET(&z3950_options, Z_Options_triggerResourceCtrl);
4402 ODR_MASK_SET(&z3950_options, Z_Options_scan);
4403 ODR_MASK_SET(&z3950_options, Z_Options_sort);
4404 ODR_MASK_SET(&z3950_options, Z_Options_extendedServices);
4405 ODR_MASK_SET(&z3950_options, Z_Options_delSet);
4407 while ((ret = options("k:c:q:a:b:m:v:p:u:t:Vxd:", argv, argc, &arg)) != -2)
4414 open_command = (char *) xmalloc (strlen(arg)+6);
4415 strcpy (open_command, "open ");
4416 strcat (open_command, arg);
4420 dump_file_prefix = arg;
4423 kilobytes = atoi(arg);
4426 if (!(marc_file = fopen (arg, "a")))
4433 outputCharset = xstrdup(arg);
4436 strncpy (ccl_fields, arg, sizeof(ccl_fields)-1);
4437 ccl_fields[sizeof(ccl_fields)-1] = '\0';
4440 strncpy (cql_fields, arg, sizeof(cql_fields)-1);
4441 cql_fields[sizeof(cql_fields)-1] = '\0';
4444 if (!strcmp(arg, "-"))
4447 ber_file=fopen(arg, "a");
4450 if (!strcmp(arg, "-"))
4453 apdu_file=fopen(arg, "a");
4459 yazProxy=strdup(arg);
4464 auth_command = (char *) xmalloc (strlen(arg)+6);
4465 strcpy (auth_command, "auth ");
4466 strcat (auth_command, arg);
4470 yaz_log_init(yaz_log_mask_str(arg), "", 0);
4476 fprintf (stderr, "Usage: %s [-m <marclog>] [ -a <apdulog>] "
4477 "[-b berdump] [-c cclfields] \n"
4478 "[-q cqlfields] [-p <proxy-addr>] [-u <auth>] "
4479 "[-k size] [-d dump] [-V] [<server-addr>]\n",
4487 #ifdef HAVE_GETTIMEOFDAY
4488 gettimeofday (&tv_start, 0);
4490 process_cmd_line (auth_command);
4491 #if HAVE_READLINE_HISTORY_H
4492 add_history(auth_command);
4494 xfree(auth_command);
4498 #ifdef HAVE_GETTIMEOFDAY
4499 gettimeofday (&tv_start, 0);
4501 process_cmd_line (open_command);
4502 #if HAVE_READLINE_HISTORY_H
4503 add_history(open_command);
4505 xfree(open_command);
4516 * vim600: sw=4 ts=8 fdm=marker
4517 * vim<600: sw=4 ts=8