2 * Copyright (C) 1995-2005, Index Data ApS
3 * See the file LICENSE for details.
5 * $Id: client.c,v 1.275 2005-03-06 12:54:32 adam Exp $
14 #include <sys/types.h>
32 #if HAVE_OPENSSL_SSL_H
33 #include <openssl/bio.h>
34 #include <openssl/crypto.h>
35 #include <openssl/x509.h>
36 #include <openssl/pem.h>
37 #include <openssl/ssl.h>
38 #include <openssl/err.h>
45 #define S_ISREG(x) (x & _S_IFREG)
46 #define S_ISDIR(x) (x & _S_IFDIR)
49 #include <yaz/yaz-util.h>
51 #include <yaz/comstack.h>
53 #include <yaz/proto.h>
54 #include <yaz/marcdisp.h>
55 #include <yaz/diagbib1.h>
56 #include <yaz/otherinfo.h>
57 #include <yaz/charneg.h>
59 #include <yaz/pquery.h>
60 #include <yaz/sortspec.h>
64 #include <yaz/yaz-ccl.h>
68 #if HAVE_READLINE_READLINE_H
69 #include <readline/readline.h>
71 #if HAVE_READLINE_HISTORY_H
72 #include <readline/history.h>
77 #include "tabcomplete.h"
79 #define C_PROMPT "Z> "
81 static char *codeset = 0; /* character set for output */
82 static int hex_dump = 0;
83 static char *dump_file_prefix = 0;
84 static ODR out, in, print; /* encoding and decoding streams */
86 static ODR srw_sr_odr_out = 0;
87 static Z_SRW_PDU *srw_sr = 0;
89 static FILE *apdu_file = 0;
90 static FILE *ber_file = 0;
91 static COMSTACK conn = 0; /* our z-association */
92 static Z_IdAuthentication *auth = 0; /* our current auth definition */
93 char *databaseNames[128];
94 int num_databaseNames = 0;
95 static Z_External *record_last = 0;
96 static int setnumber = -1; /* current result set number */
97 static int smallSetUpperBound = 0;
98 static int largeSetLowerBound = 1;
99 static int mediumSetPresentNumber = 0;
100 static Z_ElementSetNames *elementSetNames = 0;
101 static int setno = 1; /* current set offset */
102 static enum oid_proto protocol = PROTO_Z3950; /* current app protocol */
103 static enum oid_value recordsyntax = VAL_USMARC;
104 static char *record_schema = 0;
105 static int sent_close = 0;
106 static NMEM session_mem = NULL; /* memory handle for init-response */
107 static Z_InitResponse *session = 0; /* session parameters */
108 static char last_scan_line[512] = "0";
109 static char last_scan_query[512] = "0";
110 static char ccl_fields[512] = "default.bib";
111 /* ### How can I set this path to use wherever YAZ is installed? */
112 static char cql_fields[512] = "/usr/local/share/yaz/etc/pqf.properties";
113 static char *esPackageName = 0;
114 static char *yazProxy = 0;
115 static int kilobytes = 1024;
116 static char *negotiationCharset = 0;
117 static int negotiationCharsetRecords = 1;
118 static int negotiationCharsetVersion = 3;
119 static char *outputCharset = 0;
120 static char *marcCharset = 0;
121 static char* yazLang = 0;
122 static char* http_version = "1.1";
124 static char last_cmd[32] = "?";
125 static FILE *marc_file = 0;
126 static char *refid = NULL;
127 static char *last_open_command = NULL;
128 static int auto_reconnect = 0;
129 static Odr_bitmask z3950_options;
130 static int z3950_version = 3;
131 static int scan_stepSize = 0;
132 static int scan_position = 1;
133 static int scan_size = 20;
134 static char cur_host[200];
144 static QueryType queryType = QueryType_Prefix;
146 static CCL_bibset bibset; /* CCL bibset handle */
147 static cql_transform_t cqltrans; /* CQL context-set handle */
149 #if HAVE_READLINE_COMPLETION_OVER
152 /* readline doesn't have this var. Define it ourselves. */
153 int rl_attempted_completion_over = 0;
156 /* set this one to 1, to avoid decode of unknown MARCs */
157 #define AVOID_MARC_DECODE 1
159 #define maxOtherInfosSupported 10
163 } extraOtherInfos[maxOtherInfosSupported];
166 void process_cmd_line(char* line);
167 char ** readline_completer(char *text, int start, int end);
168 char *command_generator(const char *text, int state);
169 char** curret_global_list=NULL;
170 int cmd_register_tab(const char* arg);
172 static void close_session (void);
174 ODR getODROutputStream()
179 const char* query_type_as_string(QueryType q)
182 case QueryType_Prefix: return "prefix (RPN sent to server)";
183 case QueryType_CCL: return "CCL (CCL sent to server) ";
184 case QueryType_CCL2RPN: return "CCL -> RPN (RPN sent to server)";
185 case QueryType_CQL: return "CQL (CQL sent to server)";
186 case QueryType_CQL2RPN: return "CQL -> RPN (RPN sent to server)";
188 return "unknown Query type internal yaz-client error";
192 static void do_hex_dump(const char* buf, int len)
197 for( i=0; i<len ; i=i+16 )
200 for(x=0 ; i+x<len && x<16; ++x)
202 printf("%2.2X ",(unsigned int)((unsigned char)buf[i+x]));
207 if (dump_file_prefix)
210 if (++no < 1000 && strlen(dump_file_prefix) < 500)
214 sprintf (fname, "%s.%03d.raw", dump_file_prefix, no);
215 of = fopen(fname, "wb");
217 fwrite (buf, 1, len, of);
224 void add_otherInfos(Z_APDU *a)
226 Z_OtherInformation **oi;
230 for(i=0; i<maxOtherInfosSupported; ++i)
232 if(extraOtherInfos[i].oidval != -1)
233 yaz_oi_set_string_oidval(oi, out, extraOtherInfos[i].oidval,
234 1, extraOtherInfos[i].value);
238 int send_apdu(Z_APDU *a)
247 z_APDU(print, &a, 0, 0);
250 if (!z_APDU(out, &a, 0, 0))
252 odr_perror(out, "Encoding APDU");
256 buf = odr_getbuf(out, &len, 0);
258 odr_dumpBER(ber_file, buf, len);
259 /* printf ("sending APDU of size %d\n", len); */
260 do_hex_dump(buf, len);
261 if (cs_put(conn, buf, len) < 0)
263 fprintf(stderr, "cs_put: %s", cs_errmsg(cs_errno(conn)));
267 odr_reset(out); /* release the APDU structure */
271 static void print_stringn(const unsigned char *buf, size_t len)
274 for (i = 0; i<len; i++)
275 if ((buf[i] <= 126 && buf[i] >= 32) || strchr ("\n\r\t\f", buf[i]))
276 printf ("%c", buf[i]);
278 printf ("\\X%02X", buf[i]);
281 static void print_refid (Z_ReferenceId *id)
285 printf ("Reference Id: ");
286 print_stringn (id->buf, id->len);
291 static Z_ReferenceId *set_refid (ODR out)
296 id = (Z_ReferenceId *) odr_malloc (out, sizeof(*id));
297 id->size = id->len = strlen(refid);
298 id->buf = (unsigned char *) odr_malloc (out, id->len);
299 memcpy (id->buf, refid, id->len);
303 /* INIT SERVICE ------------------------------- */
305 static void send_initRequest(const char* type_and_host)
307 Z_APDU *apdu = zget_APDU(out, Z_APDU_initRequest);
308 Z_InitRequest *req = apdu->u.initRequest;
311 req->options = &z3950_options;
313 ODR_MASK_ZERO(req->protocolVersion);
314 for (i = 0; i<z3950_version; i++)
315 ODR_MASK_SET(req->protocolVersion, i);
317 *req->maximumRecordSize = 1024*kilobytes;
318 *req->preferredMessageSize = 1024*kilobytes;
320 req->idAuthentication = auth;
322 req->referenceId = set_refid (out);
324 if (yazProxy && type_and_host)
325 yaz_oi_set_string_oidval(&req->otherInfo, out, VAL_PROXY,
328 if (negotiationCharset || yazLang) {
329 Z_OtherInformation **p;
330 Z_OtherInformationUnit *p0;
332 yaz_oi_APDU(apdu, &p);
334 if ((p0=yaz_oi_update(p, out, NULL, 0, 0))) {
335 ODR_MASK_SET(req->options, Z_Options_negotiationModel);
337 p0->which = Z_OtherInfo_externallyDefinedInfo;
338 p0->information.externallyDefinedInfo =
339 yaz_set_proposal_charneg(
341 (const char**)&negotiationCharset,
342 negotiationCharset ? 1 : 0,
343 (const char**)&yazLang, yazLang ? 1 : 0,
344 negotiationCharsetRecords);
349 printf("Sent initrequest.\n");
353 /* These two are used only from process_initResponse() */
354 static void render_initUserInfo(Z_OtherInformation *ui1);
355 static void render_diag(Z_DiagnosticFormat *diag);
357 static void pr_opt(const char *opt, void *clientData)
362 static int process_initResponse(Z_InitResponse *res)
365 /* save session parameters for later use */
366 session_mem = odr_extract_mem(in);
369 for (ver = 0; ver < 8; ver++)
370 if (!ODR_MASK_GET(res->protocolVersion, ver))
374 printf("Connection rejected by v%d target.\n", ver);
376 printf("Connection accepted by v%d target.\n", ver);
377 if (res->implementationId)
378 printf("ID : %s\n", res->implementationId);
379 if (res->implementationName)
380 printf("Name : %s\n", res->implementationName);
381 if (res->implementationVersion)
382 printf("Version: %s\n", res->implementationVersion);
383 if (res->userInformationField)
385 Z_External *uif = res->userInformationField;
386 if (uif->which == Z_External_userInfo1) {
387 render_initUserInfo(uif->u.userInfo1);
389 printf("UserInformationfield:\n");
390 if (!z_External(print, (Z_External**)&uif, 0, 0))
392 odr_perror(print, "Printing userinfo\n");
395 if (uif->which == Z_External_octet) {
396 printf("Guessing visiblestring:\n");
397 printf("'%.*s'\n", uif->u.octet_aligned->len,
398 uif->u.octet_aligned->buf);
400 else if (uif->which == Z_External_single)
402 Odr_any *sat = uif->u.single_ASN1_type;
403 oident *oid = oid_getentbyoid(uif->direct_reference);
404 if (oid->value == VAL_OCLCUI) {
405 Z_OCLC_UserInformation *oclc_ui;
406 ODR decode = odr_createmem(ODR_DECODE);
407 odr_setbuf(decode, sat->buf, sat->len, 0);
408 if (!z_OCLC_UserInformation(decode, &oclc_ui, 0, 0))
409 printf ("Bad OCLC UserInformation:\n");
411 printf ("OCLC UserInformation:\n");
412 if (!z_OCLC_UserInformation(print, &oclc_ui, 0, 0))
413 printf ("Bad OCLC UserInformation spec\n");
418 /* Peek at any private Init-diagnostic APDUs */
419 printf("### NAUGHTY: External is '%.*s'\n",
427 yaz_init_opt_decode(res->options, pr_opt, 0);
430 if (ODR_MASK_GET(res->options, Z_Options_namedResultSets))
433 if (ODR_MASK_GET(res->options, Z_Options_negotiationModel)) {
435 Z_CharSetandLanguageNegotiation *p =
436 yaz_get_charneg_record(res->otherInfo);
440 char *charset=NULL, *lang=NULL;
443 yaz_get_response_charneg(session_mem, p, &charset, &lang,
446 if (outputCharset && negotiationCharset) {
447 odr_set_charset (out, charset, outputCharset);
448 odr_set_charset (in, outputCharset, charset);
451 odr_set_charset (out, 0, 0);
452 odr_set_charset (in, 0, 0);
455 printf("Accepted character set : %s\n", charset);
456 printf("Accepted code language : %s\n", lang ? lang : "none");
457 printf("Accepted records in ...: %d\n", selected );
465 static void render_initUserInfo(Z_OtherInformation *ui1) {
467 printf("Init response contains %d otherInfo unit%s:\n",
468 ui1->num_elements, ui1->num_elements == 1 ? "" : "s");
470 for (i = 0; i < ui1->num_elements; i++) {
471 Z_OtherInformationUnit *unit = ui1->list[i];
472 printf(" %d: otherInfo unit contains ", i+1);
473 if (unit->which == Z_OtherInfo_externallyDefinedInfo &&
474 unit->information.externallyDefinedInfo &&
475 unit->information.externallyDefinedInfo->which ==
477 render_diag(unit->information.externallyDefinedInfo->u.diag1);
479 else if (unit->which != Z_OtherInfo_externallyDefinedInfo)
481 printf("unsupported otherInfo unit->which = %d\n", unit->which);
485 printf("unsupported otherInfo unit external %d\n",
486 unit->information.externallyDefinedInfo ?
487 unit->information.externallyDefinedInfo->which : -2);
493 /* ### should this share code with display_diagrecs()? */
494 static void render_diag(Z_DiagnosticFormat *diag) {
497 printf("%d diagnostic%s:\n", diag->num, diag->num == 1 ? "" : "s");
498 for (i = 0; i < diag->num; i++) {
499 Z_DiagnosticFormat_s *ds = diag->elements[i];
500 printf(" %d: ", i+1);
502 case Z_DiagnosticFormat_s_defaultDiagRec: {
503 Z_DefaultDiagFormat *dd = ds->u.defaultDiagRec;
504 /* ### should check `dd->diagnosticSetId' */
505 printf("code=%d (%s)", *dd->condition,
506 diagbib1_str(*dd->condition));
507 /* Both types of addinfo are the same, so use type-pun */
508 if (dd->u.v2Addinfo != 0)
509 printf(",\n\taddinfo='%s'", dd->u.v2Addinfo);
512 case Z_DiagnosticFormat_s_explicitDiagnostic:
513 printf("Explicit diagnostic (not supported)");
516 printf("Unrecognised diagnostic type %d", ds->which);
520 if (ds->message != 0)
521 printf(", message='%s'", ds->message);
527 static int set_base(const char *arg)
532 for (i = 0; i<num_databaseNames; i++)
533 xfree (databaseNames[i]);
534 num_databaseNames = 0;
538 if (!(cp = strchr(arg, ' ')))
539 cp = arg + strlen(arg);
542 databaseNames[num_databaseNames] = (char *)xmalloc (1 + cp - arg);
543 memcpy (databaseNames[num_databaseNames], arg, cp - arg);
544 databaseNames[num_databaseNames][cp - arg] = '\0';
546 for (cp1 = databaseNames[num_databaseNames]; *cp1 ; cp1++)
555 if (num_databaseNames == 0)
557 num_databaseNames = 1;
558 databaseNames[0] = xstrdup("");
563 static int cmd_base(const char *arg)
567 printf("Usage: base <database> <database> ...\n");
570 return set_base(arg);
573 void cmd_open_remember_last_open_command(const char* arg, char* new_open_command)
575 if(last_open_command != arg)
577 if(last_open_command) xfree(last_open_command);
578 last_open_command = xstrdup(new_open_command);
582 int session_connect(const char *arg)
585 char type_and_host[101];
586 const char *basep = 0;
587 #if HAVE_OPENSSL_SSL_H
596 nmem_destroy (session_mem);
600 cs_get_host_args(arg, &basep);
602 strncpy(type_and_host, arg, sizeof(type_and_host)-1);
603 type_and_host[sizeof(type_and_host)-1] = '\0';
605 cmd_open_remember_last_open_command(arg, type_and_host);
608 conn = cs_create_host(yazProxy, 1, &add);
610 conn = cs_create_host(arg, 1, &add);
613 printf ("Couldn't create comstack\n");
617 if (conn->protocol == PROTO_HTTP)
618 queryType = QueryType_CQL;
620 if (conn->protocol == PROTO_HTTP)
622 printf ("SRW/HTTP not enabled in this YAZ\n");
628 protocol = conn->protocol;
629 if (conn->protocol == PROTO_HTTP)
633 printf("Connecting...");
635 if (cs_connect(conn, add) < 0)
637 printf ("error = %s\n", cs_strerror(conn));
638 if (conn->cerrno == CSYSERR)
641 yaz_strerror(msg, sizeof(msg));
642 printf ("%s\n", msg);
649 #if HAVE_OPENSSL_SSL_H
650 if ((ssl = (SSL *) cs_get_ssl(conn)))
652 X509 *server_cert = SSL_get_peer_certificate (ssl);
658 BIO *bio = BIO_new(BIO_s_mem());
660 /* get PEM buffer in memory */
661 PEM_write_bio_X509(bio, server_cert);
662 pem_len = BIO_get_mem_data(bio, &pem_buf);
663 fwrite(pem_buf, pem_len, 1, stdout);
665 /* print all info on screen .. */
666 X509_print_fp(stdout, server_cert);
669 X509_free (server_cert);
675 if (protocol == PROTO_Z3950)
677 send_initRequest(type_and_host);
683 int cmd_open(const char *arg)
687 strncpy (cur_host, arg, sizeof(cur_host)-1);
688 cur_host[sizeof(cur_host)-1] = 0;
690 return session_connect(cur_host);
697 if(!( auto_reconnect && last_open_command) ) return ;
699 open_command = (char *) xmalloc (strlen(last_open_command)+6);
700 strcpy (open_command, "open ");
702 strcat (open_command, last_open_command);
704 process_cmd_line(open_command);
709 int cmd_authentication(const char *arg)
711 static Z_IdAuthentication au;
712 static char user[40], group[40], pass[40];
713 static Z_IdPass idPass;
718 printf("Auth field set to null\n");
722 r = sscanf (arg, "%39s %39s %39s", user, group, pass);
725 printf("Authentication set to null\n");
731 if (!strcmp(user, "-")) {
732 au.which = Z_IdAuthentication_anonymous;
733 printf("Authentication set to Anonymous\n");
735 au.which = Z_IdAuthentication_open;
737 printf("Authentication set to Open (%s)\n", user);
743 au.which = Z_IdAuthentication_idPass;
744 au.u.idPass = &idPass;
745 idPass.groupId = NULL;
746 idPass.userId = user;
747 idPass.password = group;
748 printf("Authentication set to User (%s), Pass (%s)\n", user, group);
753 au.which = Z_IdAuthentication_idPass;
754 au.u.idPass = &idPass;
755 idPass.groupId = group;
756 idPass.userId = user;
757 idPass.password = pass;
758 printf("Authentication set to User (%s), Group (%s), Pass (%s)\n",
764 /* SEARCH SERVICE ------------------------------ */
765 static void display_record(Z_External *r);
767 static void print_record(const unsigned char *buf, size_t len)
770 print_stringn (buf, len);
771 /* add newline if not already added ... */
772 if (i <= 0 || buf[i-1] != '\n')
776 static void display_record(Z_External *r)
778 oident *ent = oid_getentbyoid(r->direct_reference);
782 * Tell the user what we got.
784 if (r->direct_reference)
786 printf("Record type: ");
788 printf("%s\n", ent->desc);
789 else if (!odr_oid(print, &r->direct_reference, 0, 0))
791 odr_perror(print, "print oid");
795 /* Check if this is a known, ASN.1 type tucked away in an octet string */
796 if (ent && r->which == Z_External_octet)
798 Z_ext_typeent *type = z_ext_getentbyref(ent->value);
804 * Call the given decoder to process the record.
806 odr_setbuf(in, (char*)r->u.octet_aligned->buf,
807 r->u.octet_aligned->len, 0);
808 if (!(*type->fun)(in, &rr, 0, 0))
810 odr_perror(in, "Decoding constructed record.");
811 fprintf(stdout, "[Near %d]\n", odr_offset(in));
812 fprintf(stdout, "Packet dump:\n---------\n");
813 odr_dumpBER(stdout, (char*)r->u.octet_aligned->buf,
814 r->u.octet_aligned->len);
815 fprintf(stdout, "---------\n");
817 /* note just ignores the error ant print the bytes form the octet_aligned later */
820 * Note: we throw away the original, BER-encoded record here.
821 * Do something else with it if you want to keep it.
823 r->u.sutrs = (Z_SUTRS *) rr; /* we don't actually check the type here. */
824 r->which = type->what;
828 if (ent && ent->value == VAL_SOIF)
830 print_record((const unsigned char *) r->u.octet_aligned->buf,
831 r->u.octet_aligned->len);
833 fwrite (r->u.octet_aligned->buf, 1, r->u.octet_aligned->len, marc_file);
835 else if (r->which == Z_External_octet)
837 const char *octet_buf = (char*)r->u.octet_aligned->buf;
838 if (ent->oclass == CLASS_RECSYN &&
839 (ent->value == VAL_TEXT_XML ||
840 ent->value == VAL_APPLICATION_XML ||
841 ent->value == VAL_HTML))
843 print_record((const unsigned char *) octet_buf,
844 r->u.octet_aligned->len);
846 else if (ent->value == VAL_POSTSCRIPT)
848 int size = r->u.octet_aligned->len;
851 print_record((const unsigned char *) octet_buf, size);
856 #if AVOID_MARC_DECODE
857 /* primitive check for a marc OID 5.1-29 except 16 */
858 ent->oidsuffix[0] == 5 && ent->oidsuffix[1] < 30 &&
859 ent->oidsuffix[1] != 16
868 yaz_marc_t mt = yaz_marc_create();
870 if (yaz_marc_decode_buf(mt, octet_buf,r->u.octet_aligned->len,
874 if (marcCharset && !strcmp(marcCharset, "auto"))
876 if (ent->value == VAL_USMARC)
878 if (octet_buf[9] == 'a')
886 else if (marcCharset)
888 if (outputCharset && from)
890 cd = yaz_iconv_open(outputCharset, from);
891 printf ("convert from %s to %s", from,
894 printf (" unsupported\n");
899 fwrite (result, 1, rlen, stdout);
903 size_t inbytesleft = rlen;
904 const char *inp = result;
908 size_t outbytesleft = sizeof(outbuf);
912 r = yaz_iconv (cd, (char**) &inp,
914 &outp, &outbytesleft);
915 if (r == (size_t) (-1))
917 int e = yaz_iconv_error(cd);
918 if (e != YAZ_ICONV_E2BIG)
921 fwrite (outbuf, outp - outbuf, 1, stdout);
927 printf ("bad MARC. Dumping as it is:\n");
928 print_record((const unsigned char*) octet_buf,
929 r->u.octet_aligned->len);
931 yaz_marc_destroy(mt);
937 print_record((const unsigned char*) octet_buf,
938 r->u.octet_aligned->len);
942 fwrite (octet_buf, 1, r->u.octet_aligned->len, marc_file);
944 else if (ent && ent->value == VAL_SUTRS)
946 if (r->which != Z_External_sutrs)
948 printf("Expecting single SUTRS type for SUTRS.\n");
951 print_record(r->u.sutrs->buf, r->u.sutrs->len);
953 fwrite (r->u.sutrs->buf, 1, r->u.sutrs->len, marc_file);
955 else if (ent && ent->value == VAL_GRS1)
958 if (r->which != Z_External_grs1)
960 printf("Expecting single GRS type for GRS.\n");
964 yaz_display_grs1(w, r->u.grs1, 0);
968 else if (ent && ent->value == VAL_OPAC)
971 if (r->u.opac->bibliographicRecord)
972 display_record(r->u.opac->bibliographicRecord);
973 for (i = 0; i<r->u.opac->num_holdingsData; i++)
975 Z_HoldingsRecord *h = r->u.opac->holdingsData[i];
976 if (h->which == Z_HoldingsRecord_marcHoldingsRecord)
978 printf ("MARC holdings %d\n", i);
979 display_record(h->u.marcHoldingsRecord);
981 else if (h->which == Z_HoldingsRecord_holdingsAndCirc)
985 Z_HoldingsAndCircData *data = h->u.holdingsAndCirc;
987 printf ("Data holdings %d\n", i);
988 if (data->typeOfRecord)
989 printf ("typeOfRecord: %s\n", data->typeOfRecord);
990 if (data->encodingLevel)
991 printf ("encodingLevel: %s\n", data->encodingLevel);
992 if (data->receiptAcqStatus)
993 printf ("receiptAcqStatus: %s\n", data->receiptAcqStatus);
994 if (data->generalRetention)
995 printf ("generalRetention: %s\n", data->generalRetention);
996 if (data->completeness)
997 printf ("completeness: %s\n", data->completeness);
998 if (data->dateOfReport)
999 printf ("dateOfReport: %s\n", data->dateOfReport);
1001 printf ("nucCode: %s\n", data->nucCode);
1002 if (data->localLocation)
1003 printf ("localLocation: %s\n", data->localLocation);
1004 if (data->shelvingLocation)
1005 printf ("shelvingLocation: %s\n", data->shelvingLocation);
1006 if (data->callNumber)
1007 printf ("callNumber: %s\n", data->callNumber);
1008 if (data->shelvingData)
1009 printf ("shelvingData: %s\n", data->shelvingData);
1010 if (data->copyNumber)
1011 printf ("copyNumber: %s\n", data->copyNumber);
1012 if (data->publicNote)
1013 printf ("publicNote: %s\n", data->publicNote);
1014 if (data->reproductionNote)
1015 printf ("reproductionNote: %s\n", data->reproductionNote);
1016 if (data->termsUseRepro)
1017 printf ("termsUseRepro: %s\n", data->termsUseRepro);
1018 if (data->enumAndChron)
1019 printf ("enumAndChron: %s\n", data->enumAndChron);
1020 for (j = 0; j<data->num_volumes; j++)
1022 printf ("volume %d\n", j);
1023 if (data->volumes[j]->enumeration)
1024 printf (" enumeration: %s\n",
1025 data->volumes[j]->enumeration);
1026 if (data->volumes[j]->chronology)
1027 printf (" chronology: %s\n",
1028 data->volumes[j]->chronology);
1029 if (data->volumes[j]->enumAndChron)
1030 printf (" enumAndChron: %s\n",
1031 data->volumes[j]->enumAndChron);
1033 for (j = 0; j<data->num_circulationData; j++)
1035 printf ("circulation %d\n", j);
1036 if (data->circulationData[j]->availableNow)
1037 printf (" availableNow: %d\n",
1038 *data->circulationData[j]->availableNow);
1039 if (data->circulationData[j]->availablityDate)
1040 printf (" availabiltyDate: %s\n",
1041 data->circulationData[j]->availablityDate);
1042 if (data->circulationData[j]->availableThru)
1043 printf (" availableThru: %s\n",
1044 data->circulationData[j]->availableThru);
1045 if (data->circulationData[j]->restrictions)
1046 printf (" restrictions: %s\n",
1047 data->circulationData[j]->restrictions);
1048 if (data->circulationData[j]->itemId)
1049 printf (" itemId: %s\n",
1050 data->circulationData[j]->itemId);
1051 if (data->circulationData[j]->renewable)
1052 printf (" renewable: %d\n",
1053 *data->circulationData[j]->renewable);
1054 if (data->circulationData[j]->onHold)
1055 printf (" onHold: %d\n",
1056 *data->circulationData[j]->onHold);
1057 if (data->circulationData[j]->enumAndChron)
1058 printf (" enumAndChron: %s\n",
1059 data->circulationData[j]->enumAndChron);
1060 if (data->circulationData[j]->midspine)
1061 printf (" midspine: %s\n",
1062 data->circulationData[j]->midspine);
1063 if (data->circulationData[j]->temporaryLocation)
1064 printf (" temporaryLocation: %s\n",
1065 data->circulationData[j]->temporaryLocation);
1072 printf("Unknown record representation.\n");
1073 if (!z_External(print, &r, 0, 0))
1075 odr_perror(print, "Printing external");
1081 static void display_diagrecs(Z_DiagRec **pp, int num)
1085 Z_DefaultDiagFormat *r;
1087 printf("Diagnostic message(s) from database:\n");
1088 for (i = 0; i<num; i++)
1090 Z_DiagRec *p = pp[i];
1091 if (p->which != Z_DiagRec_defaultFormat)
1093 printf("Diagnostic record not in default format.\n");
1097 r = p->u.defaultFormat;
1098 if (!(ent = oid_getentbyoid(r->diagnosticSetId)) ||
1099 ent->oclass != CLASS_DIAGSET || ent->value != VAL_BIB1)
1100 printf("Missing or unknown diagset\n");
1101 printf(" [%d] %s", *r->condition, diagbib1_str(*r->condition));
1104 case Z_DefaultDiagFormat_v2Addinfo:
1105 printf (" -- v2 addinfo '%s'\n", r->u.v2Addinfo);
1107 case Z_DefaultDiagFormat_v3Addinfo:
1108 printf (" -- v3 addinfo '%s'\n", r->u.v3Addinfo);
1115 static void display_nameplusrecord(Z_NamePlusRecord *p)
1117 if (p->databaseName)
1118 printf("[%s]", p->databaseName);
1119 if (p->which == Z_NamePlusRecord_surrogateDiagnostic)
1120 display_diagrecs(&p->u.surrogateDiagnostic, 1);
1121 else if (p->which == Z_NamePlusRecord_databaseRecord)
1122 display_record(p->u.databaseRecord);
1125 static void display_records(Z_Records *p)
1129 if (p->which == Z_Records_NSD)
1131 Z_DiagRec dr, *dr_p = &dr;
1132 dr.which = Z_DiagRec_defaultFormat;
1133 dr.u.defaultFormat = p->u.nonSurrogateDiagnostic;
1134 display_diagrecs (&dr_p, 1);
1136 else if (p->which == Z_Records_multipleNSD)
1137 display_diagrecs (p->u.multipleNonSurDiagnostics->diagRecs,
1138 p->u.multipleNonSurDiagnostics->num_diagRecs);
1141 printf("Records: %d\n", p->u.databaseOrSurDiagnostics->num_records);
1142 for (i = 0; i < p->u.databaseOrSurDiagnostics->num_records; i++)
1143 display_nameplusrecord(p->u.databaseOrSurDiagnostics->records[i]);
1147 static int send_deleteResultSetRequest(const char *arg)
1152 Z_APDU *apdu = zget_APDU(out, Z_APDU_deleteResultSetRequest);
1153 Z_DeleteResultSetRequest *req = apdu->u.deleteResultSetRequest;
1155 req->referenceId = set_refid (out);
1157 req->num_resultSetList =
1158 sscanf (arg, "%30s %30s %30s %30s %30s %30s %30s %30s",
1159 names[0], names[1], names[2], names[3],
1160 names[4], names[5], names[6], names[7]);
1162 req->deleteFunction = (int *)
1163 odr_malloc (out, sizeof(*req->deleteFunction));
1164 if (req->num_resultSetList > 0)
1166 *req->deleteFunction = Z_DeleteResultSetRequest_list;
1167 req->resultSetList = (char **)
1168 odr_malloc (out, sizeof(*req->resultSetList)*
1169 req->num_resultSetList);
1170 for (i = 0; i<req->num_resultSetList; i++)
1171 req->resultSetList[i] = names[i];
1175 *req->deleteFunction = Z_DeleteResultSetRequest_all;
1176 req->resultSetList = 0;
1180 printf("Sent deleteResultSetRequest.\n");
1185 static int send_srw(Z_SRW_PDU *sr)
1187 const char *charset = negotiationCharset;
1188 const char *host_port = cur_host;
1191 Z_SOAP_Handler h[2] = {
1192 {"http://www.loc.gov/zing/srw/", 0, (Z_SOAP_fun) yaz_srw_codec},
1195 ODR o = odr_createmem(ODR_ENCODE);
1197 Z_SOAP *p = odr_malloc(o, sizeof(*p));
1200 path = odr_malloc(out, strlen(databaseNames[0])+2);
1202 strcpy(path+1, databaseNames[0]);
1204 gdu = z_get_HTTP_Request(out);
1205 gdu->u.HTTP_Request->version = http_version;
1206 gdu->u.HTTP_Request->path = odr_strdup(out, path);
1210 const char *cp0 = strstr(host_port, "://");
1211 const char *cp1 = 0;
1217 cp1 = strchr(cp0, '/');
1219 cp1 = cp0+strlen(cp0);
1223 char *h = odr_malloc(out, cp1 - cp0 + 1);
1224 memcpy (h, cp0, cp1 - cp0);
1226 z_HTTP_header_add(out, &gdu->u.HTTP_Request->headers,
1231 strcpy(ctype, "text/xml");
1232 if (charset && strlen(charset) < 20)
1234 strcat(ctype, "; charset=");
1235 strcat(ctype, charset);
1237 z_HTTP_header_add(out, &gdu->u.HTTP_Request->headers,
1238 "Content-Type", ctype);
1239 z_HTTP_header_add(out, &gdu->u.HTTP_Request->headers,
1240 "SOAPAction", "\"\"");
1241 p->which = Z_SOAP_generic;
1242 p->u.generic = odr_malloc(o, sizeof(*p->u.generic));
1243 p->u.generic->no = 0;
1244 p->u.generic->ns = 0;
1245 p->u.generic->p = sr;
1246 p->ns = "http://schemas.xmlsoap.org/soap/envelope/";
1248 ret = z_soap_codec_enc(o, &p,
1249 &gdu->u.HTTP_Request->content_buf,
1250 &gdu->u.HTTP_Request->content_len, h,
1253 if (z_GDU(out, &gdu, 0, 0))
1261 if (!z_GDU(print, &gdu, 0, 0))
1262 printf ("Failed to print outgoing APDU\n");
1265 buf_out = odr_getbuf(out, &len_out, 0);
1267 /* we don't odr_reset(out), since we may need the buffer again */
1269 do_hex_dump(buf_out, len_out);
1271 r = cs_put(conn, buf_out, len_out);
1283 static int send_SRW_scanRequest(const char *arg, int pos, int num)
1287 /* regular requestse .. */
1288 sr = yaz_srw_get(out, Z_SRW_scan_request);
1293 sr->u.scan_request->query_type = Z_SRW_query_type_cql;
1294 sr->u.scan_request->scanClause.cql = odr_strdup(out, arg);
1296 case QueryType_Prefix:
1297 sr->u.scan_request->query_type = Z_SRW_query_type_pqf;
1298 sr->u.scan_request->scanClause.pqf = odr_strdup(out, arg);
1301 printf ("Only CQL and PQF supported in SRW\n");
1304 sr->u.scan_request->responsePosition = odr_intdup(out, pos);
1305 sr->u.scan_request->maximumTerms = odr_intdup(out, num);
1306 return send_srw(sr);
1309 static int send_SRW_searchRequest(const char *arg)
1315 assert(srw_sr_odr_out == 0);
1316 srw_sr_odr_out = odr_createmem(ODR_ENCODE);
1318 odr_reset(srw_sr_odr_out);
1322 /* save this for later .. when fetching individual records */
1323 srw_sr = yaz_srw_get(srw_sr_odr_out, Z_SRW_searchRetrieve_request);
1325 /* regular request .. */
1326 sr = yaz_srw_get(out, Z_SRW_searchRetrieve_request);
1331 srw_sr->u.request->query_type = Z_SRW_query_type_cql;
1332 srw_sr->u.request->query.cql = odr_strdup(srw_sr_odr_out, arg);
1334 sr->u.request->query_type = Z_SRW_query_type_cql;
1335 sr->u.request->query.cql = odr_strdup(out, arg);
1337 case QueryType_Prefix:
1338 srw_sr->u.request->query_type = Z_SRW_query_type_pqf;
1339 srw_sr->u.request->query.pqf = odr_strdup(srw_sr_odr_out, arg);
1341 sr->u.request->query_type = Z_SRW_query_type_pqf;
1342 sr->u.request->query.pqf = odr_strdup(out, arg);
1345 printf ("Only CQL and PQF supported in SRW\n");
1348 sr->u.request->maximumRecords = odr_intdup(out, 0);
1351 sr->u.request->recordSchema = record_schema;
1352 if (recordsyntax == VAL_TEXT_XML)
1353 sr->u.explain_request->recordPacking = "xml";
1354 return send_srw(sr);
1358 static int send_searchRequest(const char *arg)
1360 Z_APDU *apdu = zget_APDU(out, Z_APDU_searchRequest);
1361 Z_SearchRequest *req = apdu->u.searchRequest;
1363 struct ccl_rpn_node *rpn = NULL;
1365 char setstring[100];
1366 Z_RPNQuery *RPNquery;
1368 YAZ_PQF_Parser pqf_parser;
1370 QueryType myQueryType = queryType;
1373 if (myQueryType == QueryType_CCL2RPN)
1375 rpn = ccl_find_str(bibset, arg, &error, &pos);
1378 printf("CCL ERROR: %s\n", ccl_err_msg(error));
1381 } else if (myQueryType == QueryType_CQL2RPN) {
1382 /* ### All this code should be wrapped in a utility function */
1384 struct cql_node *node;
1385 const char *addinfo;
1386 if (cqltrans == 0) {
1387 printf("Can't use CQL: no translation file. Try set_cqlfile\n");
1390 parser = cql_parser_create();
1391 if ((error = cql_parser_string(parser, arg)) != 0) {
1392 printf("Can't parse CQL: must be a syntax error\n");
1395 node = cql_parser_result(parser);
1396 if ((error = cql_transform_buf(cqltrans, node, pqfbuf,
1397 sizeof pqfbuf)) != 0) {
1398 error = cql_transform_error(cqltrans, &addinfo);
1399 printf ("Can't convert CQL to PQF: %s (addinfo=%s)\n",
1400 cql_strerror(error), addinfo);
1404 myQueryType = QueryType_Prefix;
1407 req->referenceId = set_refid (out);
1408 if (!strcmp(arg, "@big")) /* strictly for troublemaking */
1410 static unsigned char big[2100];
1411 static Odr_oct bigo;
1413 /* send a very big referenceid to test transport stack etc. */
1414 memset(big, 'A', 2100);
1415 bigo.len = bigo.size = 2100;
1417 req->referenceId = &bigo;
1422 sprintf(setstring, "%d", ++setnumber);
1423 req->resultSetName = setstring;
1425 *req->smallSetUpperBound = smallSetUpperBound;
1426 *req->largeSetLowerBound = largeSetLowerBound;
1427 *req->mediumSetPresentNumber = mediumSetPresentNumber;
1428 if (smallSetUpperBound > 0 || (largeSetLowerBound > 1 &&
1429 mediumSetPresentNumber > 0))
1431 req->preferredRecordSyntax =
1432 yaz_oidval_to_z3950oid(out, CLASS_RECSYN, recordsyntax);
1434 req->smallSetElementSetNames =
1435 req->mediumSetElementSetNames = elementSetNames;
1437 req->num_databaseNames = num_databaseNames;
1438 req->databaseNames = databaseNames;
1440 req->query = &query;
1442 switch (myQueryType)
1444 case QueryType_Prefix:
1445 query.which = Z_Query_type_1;
1446 pqf_parser = yaz_pqf_create ();
1447 RPNquery = yaz_pqf_parse (pqf_parser, out, arg);
1450 const char *pqf_msg;
1452 int code = yaz_pqf_error (pqf_parser, &pqf_msg, &off);
1453 printf("%*s^\n", off+4, "");
1454 printf("Prefix query error: %s (code %d)\n", pqf_msg, code);
1456 yaz_pqf_destroy (pqf_parser);
1459 yaz_pqf_destroy (pqf_parser);
1460 query.u.type_1 = RPNquery;
1463 query.which = Z_Query_type_2;
1464 query.u.type_2 = &ccl_query;
1465 ccl_query.buf = (unsigned char*) arg;
1466 ccl_query.len = strlen(arg);
1468 case QueryType_CCL2RPN:
1469 query.which = Z_Query_type_1;
1470 RPNquery = ccl_rpn_query(out, rpn);
1473 printf ("Couldn't convert from CCL to RPN\n");
1476 query.u.type_1 = RPNquery;
1477 ccl_rpn_delete (rpn);
1480 query.which = Z_Query_type_104;
1481 ext = (Z_External *) odr_malloc(out, sizeof(*ext));
1482 ext->direct_reference = odr_getoidbystr(out, "1.2.840.10003.16.2");
1483 ext->indirect_reference = 0;
1484 ext->descriptor = 0;
1485 ext->which = Z_External_CQL;
1486 ext->u.cql = odr_strdup(out, arg);
1487 query.u.type_104 = ext;
1490 printf ("Unsupported query type\n");
1493 if (send_apdu(apdu))
1494 printf("Sent searchRequest.\n");
1499 /* display Query Expression as part of searchResult-1 */
1500 static void display_queryExpression (Z_QueryExpression *qe)
1504 if (qe->which == Z_QueryExpression_term)
1506 if (qe->u.term->queryTerm)
1508 Z_Term *term = qe->u.term->queryTerm;
1509 switch (term->which)
1511 case Z_Term_general:
1512 printf (" %.*s", term->u.general->len, term->u.general->buf);
1514 case Z_Term_characterString:
1515 printf (" %s", term->u.characterString);
1517 case Z_Term_numeric:
1518 printf (" %d", *term->u.numeric);
1528 /* see if we can find USR:SearchResult-1 */
1529 static void display_searchResult (Z_OtherInformation *o)
1534 for (i = 0; i < o->num_elements; i++)
1536 if (o->list[i]->which == Z_OtherInfo_externallyDefinedInfo)
1538 Z_External *ext = o->list[i]->information.externallyDefinedInfo;
1540 if (ext->which == Z_External_searchResult1)
1543 Z_SearchInfoReport *sr = ext->u.searchResult1;
1544 printf ("SearchResult-1:");
1545 for (j = 0; j < sr->num; j++)
1547 if (!sr->elements[j]->subqueryExpression)
1549 display_queryExpression (
1550 sr->elements[j]->subqueryExpression);
1551 display_queryExpression (
1552 sr->elements[j]->subqueryInterpretation);
1553 display_queryExpression (
1554 sr->elements[j]->subqueryRecommendation);
1555 if (sr->elements[j]->subqueryCount)
1556 printf ("(%d)", *sr->elements[j]->subqueryCount);
1564 static int process_searchResponse(Z_SearchResponse *res)
1566 printf ("Received SearchResponse.\n");
1567 print_refid (res->referenceId);
1568 if (*res->searchStatus)
1569 printf("Search was a success.\n");
1571 printf("Search was a bloomin' failure.\n");
1572 printf("Number of hits: %d", *res->resultCount);
1574 printf (", setno %d", setnumber);
1576 display_searchResult (res->additionalSearchInfo);
1577 printf("records returned: %d\n",
1578 *res->numberOfRecordsReturned);
1579 setno += *res->numberOfRecordsReturned;
1581 display_records(res->records);
1585 static void print_level(int iLevel)
1588 for (i = 0; i < iLevel * 4; i++)
1592 static void print_int(int iLevel, const char *pTag, int *pInt)
1596 print_level(iLevel);
1597 printf("%s: %d\n", pTag, *pInt);
1601 static void print_string(int iLevel, const char *pTag, const char *pString)
1603 if (pString != NULL)
1605 print_level(iLevel);
1606 printf("%s: %s\n", pTag, pString);
1610 static void print_oid(int iLevel, const char *pTag, Odr_oid *pOid)
1616 print_level(iLevel);
1617 printf("%s:", pTag);
1618 for (; *pInt != -1; pInt++)
1619 printf(" %d", *pInt);
1624 static void print_referenceId(int iLevel, Z_ReferenceId *referenceId)
1626 if (referenceId != NULL)
1630 print_level(iLevel);
1631 printf("Ref Id (%d, %d): ", referenceId->len, referenceId->size);
1632 for (i = 0; i < referenceId->len; i++)
1633 printf("%c", referenceId->buf[i]);
1638 static void print_string_or_numeric(int iLevel, const char *pTag, Z_StringOrNumeric *pStringNumeric)
1640 if (pStringNumeric != NULL)
1642 switch (pStringNumeric->which)
1644 case Z_StringOrNumeric_string:
1645 print_string(iLevel, pTag, pStringNumeric->u.string);
1648 case Z_StringOrNumeric_numeric:
1649 print_int(iLevel, pTag, pStringNumeric->u.numeric);
1653 print_level(iLevel);
1654 printf("%s: valid type for Z_StringOrNumeric\n", pTag);
1660 static void print_universe_report_duplicate(
1662 Z_UniverseReportDuplicate *pUniverseReportDuplicate)
1664 if (pUniverseReportDuplicate != NULL)
1666 print_level(iLevel);
1667 printf("Universe Report Duplicate: \n");
1669 print_string_or_numeric(iLevel, "Hit No",
1670 pUniverseReportDuplicate->hitno);
1674 static void print_universe_report_hits(
1676 Z_UniverseReportHits *pUniverseReportHits)
1678 if (pUniverseReportHits != NULL)
1680 print_level(iLevel);
1681 printf("Universe Report Hits: \n");
1683 print_string_or_numeric(iLevel, "Database",
1684 pUniverseReportHits->database);
1685 print_string_or_numeric(iLevel, "Hits", pUniverseReportHits->hits);
1689 static void print_universe_report(int iLevel, Z_UniverseReport *pUniverseReport)
1691 if (pUniverseReport != NULL)
1693 print_level(iLevel);
1694 printf("Universe Report: \n");
1696 print_int(iLevel, "Total Hits", pUniverseReport->totalHits);
1697 switch (pUniverseReport->which)
1699 case Z_UniverseReport_databaseHits:
1700 print_universe_report_hits(iLevel,
1701 pUniverseReport->u.databaseHits);
1704 case Z_UniverseReport_duplicate:
1705 print_universe_report_duplicate(iLevel,
1706 pUniverseReport->u.duplicate);
1710 print_level(iLevel);
1711 printf("Type: %d\n", pUniverseReport->which);
1717 static void print_external(int iLevel, Z_External *pExternal)
1719 if (pExternal != NULL)
1721 print_level(iLevel);
1722 printf("External: \n");
1724 print_oid(iLevel, "Direct Reference", pExternal->direct_reference);
1725 print_int(iLevel, "InDirect Reference", pExternal->indirect_reference);
1726 print_string(iLevel, "Descriptor", pExternal->descriptor);
1727 switch (pExternal->which)
1729 case Z_External_universeReport:
1730 print_universe_report(iLevel, pExternal->u.universeReport);
1734 print_level(iLevel);
1735 printf("Type: %d\n", pExternal->which);
1741 static int process_resourceControlRequest (Z_ResourceControlRequest *req)
1743 printf ("Received ResourceControlRequest.\n");
1744 print_referenceId(1, req->referenceId);
1745 print_int(1, "Suspended Flag", req->suspendedFlag);
1746 print_int(1, "Partial Results Available", req->partialResultsAvailable);
1747 print_int(1, "Response Required", req->responseRequired);
1748 print_int(1, "Triggered Request Flag", req->triggeredRequestFlag);
1749 print_external(1, req->resourceReport);
1753 void process_ESResponse(Z_ExtendedServicesResponse *res)
1756 switch (*res->operationStatus)
1758 case Z_ExtendedServicesResponse_done:
1761 case Z_ExtendedServicesResponse_accepted:
1762 printf ("accepted\n");
1764 case Z_ExtendedServicesResponse_failure:
1765 printf ("failure\n");
1766 display_diagrecs(res->diagnostics, res->num_diagnostics);
1769 printf ("unknown\n");
1771 if ( (*res->operationStatus != Z_ExtendedServicesResponse_failure) &&
1772 (res->num_diagnostics != 0) ) {
1773 display_diagrecs(res->diagnostics, res->num_diagnostics);
1775 print_refid (res->referenceId);
1776 if (res->taskPackage &&
1777 res->taskPackage->which == Z_External_extendedService)
1779 Z_TaskPackage *taskPackage = res->taskPackage->u.extendedService;
1780 Odr_oct *id = taskPackage->targetReference;
1781 Z_External *ext = taskPackage->taskSpecificParameters;
1785 printf ("Target Reference: ");
1786 print_stringn (id->buf, id->len);
1789 if (ext->which == Z_External_update)
1791 Z_IUUpdateTaskPackage *utp = ext->u.update->u.taskPackage;
1792 if (utp && utp->targetPart)
1794 Z_IUTargetPart *targetPart = utp->targetPart;
1797 for (i = 0; i<targetPart->num_taskPackageRecords; i++)
1800 Z_IUTaskPackageRecordStructure *tpr =
1801 targetPart->taskPackageRecords[i];
1802 printf ("task package record %d\n", i+1);
1803 if (tpr->which == Z_IUTaskPackageRecordStructure_record)
1805 display_record (tpr->u.record);
1809 printf ("other type\n");
1817 const char *get_ill_element (void *clientData, const char *element)
1822 static Z_External *create_external_itemRequest()
1824 struct ill_get_ctl ctl;
1825 ILL_ItemRequest *req;
1827 int item_request_size = 0;
1828 char *item_request_buf = 0;
1832 ctl.f = get_ill_element;
1834 req = ill_get_ItemRequest(&ctl, "ill", 0);
1836 printf ("ill_get_ItemRequest failed\n");
1838 if (!ill_ItemRequest (out, &req, 0, 0))
1842 ill_ItemRequest(print, &req, 0, 0);
1845 item_request_buf = odr_getbuf (out, &item_request_size, 0);
1846 if (item_request_buf)
1847 odr_setbuf (out, item_request_buf, item_request_size, 1);
1848 printf ("Couldn't encode ItemRequest, size %d\n", item_request_size);
1855 item_request_buf = odr_getbuf (out, &item_request_size, 0);
1856 oid.proto = PROTO_GENERAL;
1857 oid.oclass = CLASS_GENERAL;
1858 oid.value = VAL_ISO_ILL_1;
1860 r = (Z_External *) odr_malloc (out, sizeof(*r));
1861 r->direct_reference = odr_oiddup(out,oid_getoidbyent(&oid));
1862 r->indirect_reference = 0;
1864 r->which = Z_External_single;
1866 r->u.single_ASN1_type = (Odr_oct *)
1867 odr_malloc (out, sizeof(*r->u.single_ASN1_type));
1868 r->u.single_ASN1_type->buf = (unsigned char *)
1869 odr_malloc (out, item_request_size);
1870 r->u.single_ASN1_type->len = item_request_size;
1871 r->u.single_ASN1_type->size = item_request_size;
1872 memcpy (r->u.single_ASN1_type->buf, item_request_buf,
1875 do_hex_dump(item_request_buf,item_request_size);
1880 static Z_External *create_external_ILL_APDU(int which)
1882 struct ill_get_ctl ctl;
1885 int ill_request_size = 0;
1886 char *ill_request_buf = 0;
1890 ctl.f = get_ill_element;
1892 ill_apdu = ill_get_APDU(&ctl, "ill", 0);
1894 if (!ill_APDU (out, &ill_apdu, 0, 0))
1898 printf ("-------------------\n");
1899 ill_APDU(print, &ill_apdu, 0, 0);
1901 printf ("-------------------\n");
1903 ill_request_buf = odr_getbuf (out, &ill_request_size, 0);
1904 if (ill_request_buf)
1905 odr_setbuf (out, ill_request_buf, ill_request_size, 1);
1906 printf ("Couldn't encode ILL-Request, size %d\n", ill_request_size);
1912 ill_request_buf = odr_getbuf (out, &ill_request_size, 0);
1914 oid.proto = PROTO_GENERAL;
1915 oid.oclass = CLASS_GENERAL;
1916 oid.value = VAL_ISO_ILL_1;
1918 r = (Z_External *) odr_malloc (out, sizeof(*r));
1919 r->direct_reference = odr_oiddup(out,oid_getoidbyent(&oid));
1920 r->indirect_reference = 0;
1922 r->which = Z_External_single;
1924 r->u.single_ASN1_type = (Odr_oct *)
1925 odr_malloc (out, sizeof(*r->u.single_ASN1_type));
1926 r->u.single_ASN1_type->buf = (unsigned char *)
1927 odr_malloc (out, ill_request_size);
1928 r->u.single_ASN1_type->len = ill_request_size;
1929 r->u.single_ASN1_type->size = ill_request_size;
1930 memcpy (r->u.single_ASN1_type->buf, ill_request_buf, ill_request_size);
1931 /* printf ("len = %d\n", ill_request_size); */
1932 /* do_hex_dump(ill_request_buf,ill_request_size); */
1933 /* printf("--- end of extenal\n"); */
1940 static Z_External *create_ItemOrderExternal(const char *type, int itemno)
1942 Z_External *r = (Z_External *) odr_malloc(out, sizeof(Z_External));
1943 oident ItemOrderRequest;
1945 ItemOrderRequest.proto = PROTO_Z3950;
1946 ItemOrderRequest.oclass = CLASS_EXTSERV;
1947 ItemOrderRequest.value = VAL_ITEMORDER;
1949 r->direct_reference = odr_oiddup(out,oid_getoidbyent(&ItemOrderRequest));
1950 r->indirect_reference = 0;
1953 r->which = Z_External_itemOrder;
1955 r->u.itemOrder = (Z_ItemOrder *) odr_malloc(out,sizeof(Z_ItemOrder));
1956 memset(r->u.itemOrder, 0, sizeof(Z_ItemOrder));
1957 r->u.itemOrder->which=Z_IOItemOrder_esRequest;
1959 r->u.itemOrder->u.esRequest = (Z_IORequest *)
1960 odr_malloc(out,sizeof(Z_IORequest));
1961 memset(r->u.itemOrder->u.esRequest, 0, sizeof(Z_IORequest));
1963 r->u.itemOrder->u.esRequest->toKeep = (Z_IOOriginPartToKeep *)
1964 odr_malloc(out,sizeof(Z_IOOriginPartToKeep));
1965 memset(r->u.itemOrder->u.esRequest->toKeep, 0, sizeof(Z_IOOriginPartToKeep));
1966 r->u.itemOrder->u.esRequest->notToKeep = (Z_IOOriginPartNotToKeep *)
1967 odr_malloc(out,sizeof(Z_IOOriginPartNotToKeep));
1968 memset(r->u.itemOrder->u.esRequest->notToKeep, 0, sizeof(Z_IOOriginPartNotToKeep));
1970 r->u.itemOrder->u.esRequest->toKeep->supplDescription = NULL;
1971 r->u.itemOrder->u.esRequest->toKeep->contact = NULL;
1972 r->u.itemOrder->u.esRequest->toKeep->addlBilling = NULL;
1974 r->u.itemOrder->u.esRequest->notToKeep->resultSetItem =
1975 (Z_IOResultSetItem *) odr_malloc(out, sizeof(Z_IOResultSetItem));
1976 memset(r->u.itemOrder->u.esRequest->notToKeep->resultSetItem, 0, sizeof(Z_IOResultSetItem));
1977 r->u.itemOrder->u.esRequest->notToKeep->resultSetItem->resultSetId = "1";
1979 r->u.itemOrder->u.esRequest->notToKeep->resultSetItem->item =
1980 (int *) odr_malloc(out, sizeof(int));
1981 *r->u.itemOrder->u.esRequest->notToKeep->resultSetItem->item = itemno;
1983 if (!strcmp (type, "item") || !strcmp(type, "2"))
1985 printf ("using item-request\n");
1986 r->u.itemOrder->u.esRequest->notToKeep->itemRequest =
1987 create_external_itemRequest();
1989 else if (!strcmp(type, "ill") || !strcmp(type, "1"))
1991 printf ("using ILL-request\n");
1992 r->u.itemOrder->u.esRequest->notToKeep->itemRequest =
1993 create_external_ILL_APDU(ILL_APDU_ILL_Request);
1995 else if (!strcmp(type, "xml") || !strcmp(type, "3"))
1997 const char *xml_buf =
1999 " <type>request</type>\n"
2000 " <libraryNo>000200</libraryNo>\n"
2001 " <borrowerTicketNo> 1212 </borrowerTicketNo>\n"
2003 r->u.itemOrder->u.esRequest->notToKeep->itemRequest =
2004 z_ext_record (out, VAL_TEXT_XML, xml_buf, strlen(xml_buf));
2007 r->u.itemOrder->u.esRequest->notToKeep->itemRequest = 0;
2012 static int send_itemorder(const char *type, int itemno)
2014 Z_APDU *apdu = zget_APDU(out, Z_APDU_extendedServicesRequest);
2015 Z_ExtendedServicesRequest *req = apdu->u.extendedServicesRequest;
2016 oident ItemOrderRequest;
2018 ItemOrderRequest.proto = PROTO_Z3950;
2019 ItemOrderRequest.oclass = CLASS_EXTSERV;
2020 ItemOrderRequest.value = VAL_ITEMORDER;
2021 req->packageType = odr_oiddup(out,oid_getoidbyent(&ItemOrderRequest));
2022 req->packageName = esPackageName;
2024 req->taskSpecificParameters = create_ItemOrderExternal(type, itemno);
2030 static int only_z3950()
2032 if (protocol == PROTO_HTTP)
2034 printf ("Not supported by SRW\n");
2040 static int cmd_update_common(const char *arg, int version);
2042 static int cmd_update(const char *arg)
2044 return cmd_update_common(arg, 1);
2047 static int cmd_update0(const char *arg)
2049 return cmd_update_common(arg, 0);
2052 static int cmd_update_common(const char *arg, int version)
2054 Z_APDU *apdu = zget_APDU(out, Z_APDU_extendedServicesRequest );
2055 Z_ExtendedServicesRequest *req = apdu->u.extendedServicesRequest;
2057 char action[20], recid[20], fname[80];
2059 Z_External *record_this = 0;
2066 sscanf (arg, "%19s %19s %79s", action, recid, fname);
2068 if (!strcmp (action, "insert"))
2069 action_no = Z_IUOriginPartToKeep_recordInsert;
2070 else if (!strcmp (action, "replace"))
2071 action_no = Z_IUOriginPartToKeep_recordReplace;
2072 else if (!strcmp (action, "delete"))
2073 action_no = Z_IUOriginPartToKeep_recordDelete;
2074 else if (!strcmp (action, "update"))
2075 action_no = Z_IUOriginPartToKeep_specialUpdate;
2078 printf ("Bad action: %s\n", action);
2079 printf ("Possible values: insert, replace, delete, update\n");
2087 stat (fname, &status);
2088 if (S_ISREG(status.st_mode) && (inf = fopen(fname, "rb")))
2090 size_t len = status.st_size;
2091 char *buf = (char *) xmalloc (len);
2093 fread (buf, 1, len, inf);
2097 record_this = z_ext_record (out, VAL_TEXT_XML, buf, len);
2103 printf ("File %s doesn't exist\n", fname);
2111 printf ("No last record (update ignored)\n");
2114 record_this = record_last;
2118 yaz_oidval_to_z3950oid(out, CLASS_EXTSERV,
2119 version == 0 ? VAL_DBUPDATE0 : VAL_DBUPDATE);
2121 req->packageName = esPackageName;
2123 req->referenceId = set_refid (out);
2125 r = req->taskSpecificParameters = (Z_External *)
2126 odr_malloc (out, sizeof(*r));
2127 r->direct_reference = req->packageType;
2128 r->indirect_reference = 0;
2132 Z_IU0OriginPartToKeep *toKeep;
2133 Z_IU0SuppliedRecords *notToKeep;
2135 r->which = Z_External_update0;
2136 r->u.update0 = (Z_IU0Update *) odr_malloc(out, sizeof(*r->u.update0));
2137 r->u.update0->which = Z_IUUpdate_esRequest;
2138 r->u.update0->u.esRequest = (Z_IU0UpdateEsRequest *)
2139 odr_malloc(out, sizeof(*r->u.update0->u.esRequest));
2140 toKeep = r->u.update0->u.esRequest->toKeep = (Z_IU0OriginPartToKeep *)
2141 odr_malloc(out, sizeof(*r->u.update0->u.esRequest->toKeep));
2143 toKeep->databaseName = databaseNames[0];
2145 toKeep->elementSetName = 0;
2147 toKeep->action = (int *) odr_malloc(out, sizeof(*toKeep->action));
2148 *toKeep->action = action_no;
2150 notToKeep = r->u.update0->u.esRequest->notToKeep = (Z_IU0SuppliedRecords *)
2151 odr_malloc(out, sizeof(*r->u.update0->u.esRequest->notToKeep));
2153 notToKeep->elements = (Z_IU0SuppliedRecords_elem **)
2154 odr_malloc(out, sizeof(*notToKeep->elements));
2155 notToKeep->elements[0] = (Z_IU0SuppliedRecords_elem *)
2156 odr_malloc(out, sizeof(**notToKeep->elements));
2157 notToKeep->elements[0]->which = Z_IUSuppliedRecords_elem_opaque;
2160 notToKeep->elements[0]->u.opaque = (Odr_oct *)
2161 odr_malloc (out, sizeof(Odr_oct));
2162 notToKeep->elements[0]->u.opaque->buf = (unsigned char *) recid;
2163 notToKeep->elements[0]->u.opaque->size = strlen(recid);
2164 notToKeep->elements[0]->u.opaque->len = strlen(recid);
2167 notToKeep->elements[0]->u.opaque = 0;
2168 notToKeep->elements[0]->supplementalId = 0;
2169 notToKeep->elements[0]->correlationInfo = 0;
2170 notToKeep->elements[0]->record = record_this;
2174 Z_IUOriginPartToKeep *toKeep;
2175 Z_IUSuppliedRecords *notToKeep;
2177 r->which = Z_External_update;
2178 r->u.update = (Z_IUUpdate *) odr_malloc(out, sizeof(*r->u.update));
2179 r->u.update->which = Z_IUUpdate_esRequest;
2180 r->u.update->u.esRequest = (Z_IUUpdateEsRequest *)
2181 odr_malloc(out, sizeof(*r->u.update->u.esRequest));
2182 toKeep = r->u.update->u.esRequest->toKeep = (Z_IUOriginPartToKeep *)
2183 odr_malloc(out, sizeof(*r->u.update->u.esRequest->toKeep));
2185 toKeep->databaseName = databaseNames[0];
2187 toKeep->elementSetName = 0;
2188 toKeep->actionQualifier = 0;
2189 toKeep->action = (int *) odr_malloc(out, sizeof(*toKeep->action));
2190 *toKeep->action = action_no;
2192 notToKeep = r->u.update->u.esRequest->notToKeep = (Z_IUSuppliedRecords *)
2193 odr_malloc(out, sizeof(*r->u.update->u.esRequest->notToKeep));
2195 notToKeep->elements = (Z_IUSuppliedRecords_elem **)
2196 odr_malloc(out, sizeof(*notToKeep->elements));
2197 notToKeep->elements[0] = (Z_IUSuppliedRecords_elem *)
2198 odr_malloc(out, sizeof(**notToKeep->elements));
2199 notToKeep->elements[0]->which = Z_IUSuppliedRecords_elem_opaque;
2202 notToKeep->elements[0]->u.opaque = (Odr_oct *)
2203 odr_malloc (out, sizeof(Odr_oct));
2204 notToKeep->elements[0]->u.opaque->buf = (unsigned char *) recid;
2205 notToKeep->elements[0]->u.opaque->size = strlen(recid);
2206 notToKeep->elements[0]->u.opaque->len = strlen(recid);
2209 notToKeep->elements[0]->u.opaque = 0;
2210 notToKeep->elements[0]->supplementalId = 0;
2211 notToKeep->elements[0]->correlationInfo = 0;
2212 notToKeep->elements[0]->record = record_this;
2220 static int cmd_itemorder(const char *arg)
2227 if (sscanf (arg, "%10s %d", type, &itemno) != 2)
2230 printf("Item order request\n");
2232 send_itemorder(type, itemno);
2236 static void show_opt(const char *arg, void *clientData)
2238 printf ("%s ", arg);
2241 static int cmd_zversion(const char *arg)
2244 z3950_version = atoi(arg);
2246 printf ("version is %d\n", z3950_version);
2250 static int cmd_options(const char *arg)
2256 r = yaz_init_opt_encode(&z3950_options, arg, &pos);
2260 yaz_init_opt_decode(&z3950_options, show_opt, 0);
2266 static int cmd_explain(const char *arg)
2268 if (protocol != PROTO_HTTP)
2279 /* save this for later .. when fetching individual records */
2280 sr = yaz_srw_get(out, Z_SRW_explain_request);
2281 if (recordsyntax == VAL_TEXT_XML)
2282 sr->u.explain_request->recordPacking = "xml";
2290 static int cmd_init(const char *arg)
2294 strncpy (cur_host, arg, sizeof(cur_host)-1);
2295 cur_host[sizeof(cur_host)-1] = 0;
2297 if (!conn || protocol != PROTO_Z3950)
2299 send_initRequest(cur_host);
2303 static int cmd_find(const char *arg)
2307 printf("Find what?\n");
2310 if (protocol == PROTO_HTTP)
2317 if (!send_SRW_searchRequest(arg))
2330 printf("Not connected yet\n");
2334 if (!send_searchRequest(arg))
2340 static int cmd_delete(const char *arg)
2344 printf("Not connected yet\n");
2349 if (!send_deleteResultSetRequest(arg))
2354 static int cmd_ssub(const char *arg)
2356 if (!(smallSetUpperBound = atoi(arg)))
2361 static int cmd_lslb(const char *arg)
2365 if (!(largeSetLowerBound = atoi(arg)))
2370 static int cmd_mspn(const char *arg)
2374 if (!(mediumSetPresentNumber = atoi(arg)))
2379 static int cmd_status(const char *arg)
2381 printf("smallSetUpperBound: %d\n", smallSetUpperBound);
2382 printf("largeSetLowerBound: %d\n", largeSetLowerBound);
2383 printf("mediumSetPresentNumber: %d\n", mediumSetPresentNumber);
2387 static int cmd_setnames(const char *arg)
2389 if (*arg == '1') /* enable ? */
2391 else if (*arg == '0') /* disable ? */
2393 else if (setnumber < 0) /* no args, toggle .. */
2399 printf("Set numbering enabled.\n");
2401 printf("Set numbering disabled.\n");
2405 /* PRESENT SERVICE ----------------------------- */
2407 static void parse_show_args(const char *arg_c, char *setstring,
2408 int *start, int *number)
2413 strncpy(arg, arg_c, sizeof(arg)-1);
2414 arg[sizeof(arg)-1] = '\0';
2416 if ((p = strchr(arg, '+')))
2418 *number = atoi(p + 1);
2423 if (p && (p=strchr(p+1, '+')))
2424 strcpy (setstring, p+1);
2425 else if (setnumber >= 0)
2426 sprintf(setstring, "%d", setnumber);
2431 static int send_presentRequest(const char *arg)
2433 Z_APDU *apdu = zget_APDU(out, Z_APDU_presentRequest);
2434 Z_PresentRequest *req = apdu->u.presentRequest;
2435 Z_RecordComposition compo;
2437 char setstring[100];
2439 req->referenceId = set_refid (out);
2441 parse_show_args(arg, setstring, &setno, &nos);
2443 req->resultSetId = setstring;
2445 req->resultSetStartPoint = &setno;
2446 req->numberOfRecordsRequested = &nos;
2448 req->preferredRecordSyntax =
2449 yaz_oidval_to_z3950oid(out, CLASS_RECSYN, recordsyntax);
2453 req->recordComposition = &compo;
2454 compo.which = Z_RecordComp_complex;
2455 compo.u.complex = (Z_CompSpec *)
2456 odr_malloc(out, sizeof(*compo.u.complex));
2457 compo.u.complex->selectAlternativeSyntax = (bool_t *)
2458 odr_malloc(out, sizeof(bool_t));
2459 *compo.u.complex->selectAlternativeSyntax = 0;
2461 compo.u.complex->generic = (Z_Specification *)
2462 odr_malloc(out, sizeof(*compo.u.complex->generic));
2463 compo.u.complex->generic->which = Z_Schema_oid;
2465 compo.u.complex->generic->schema.oid =
2466 yaz_str_to_z3950oid(out, CLASS_SCHEMA, record_schema);
2468 if (!compo.u.complex->generic->schema.oid)
2470 /* OID wasn't a schema! Try record syntax instead. */
2471 compo.u.complex->generic->schema.oid = (Odr_oid *)
2472 yaz_str_to_z3950oid(out, CLASS_RECSYN, record_schema);
2474 if (!elementSetNames)
2475 compo.u.complex->generic->elementSpec = 0;
2478 compo.u.complex->generic->elementSpec = (Z_ElementSpec *)
2479 odr_malloc(out, sizeof(Z_ElementSpec));
2480 compo.u.complex->generic->elementSpec->which =
2481 Z_ElementSpec_elementSetName;
2482 compo.u.complex->generic->elementSpec->u.elementSetName =
2483 elementSetNames->u.generic;
2485 compo.u.complex->num_dbSpecific = 0;
2486 compo.u.complex->dbSpecific = 0;
2487 compo.u.complex->num_recordSyntax = 0;
2488 compo.u.complex->recordSyntax = 0;
2490 else if (elementSetNames)
2492 req->recordComposition = &compo;
2493 compo.which = Z_RecordComp_simple;
2494 compo.u.simple = elementSetNames;
2497 printf("Sent presentRequest (%d+%d).\n", setno, nos);
2502 static int send_SRW_presentRequest(const char *arg)
2504 char setstring[100];
2506 Z_SRW_PDU *sr = srw_sr;
2510 parse_show_args(arg, setstring, &setno, &nos);
2511 sr->u.request->startRecord = odr_intdup(out, setno);
2512 sr->u.request->maximumRecords = odr_intdup(out, nos);
2514 sr->u.request->recordSchema = record_schema;
2515 if (recordsyntax == VAL_TEXT_XML)
2516 sr->u.request->recordPacking = "xml";
2517 return send_srw(sr);
2521 static void close_session (void)
2528 nmem_destroy (session_mem);
2537 void process_close(Z_Close *req)
2539 Z_APDU *apdu = zget_APDU(out, Z_APDU_close);
2540 Z_Close *res = apdu->u.close;
2542 static char *reasons[] =
2547 "cost limit reached",
2549 "security violation",
2556 printf("Reason: %s, message: %s\n", reasons[*req->closeReason],
2557 req->diagnosticInformation ? req->diagnosticInformation : "NULL");
2562 *res->closeReason = Z_Close_finished;
2564 printf("Sent response.\n");
2569 static int cmd_show(const char *arg)
2571 if (protocol == PROTO_HTTP)
2578 if (!send_SRW_presentRequest(arg))
2588 printf("Not connected yet\n");
2591 if (!send_presentRequest(arg))
2597 int cmd_quit(const char *arg)
2599 printf("See you later, alligator.\n");
2605 int cmd_cancel(const char *arg)
2607 Z_APDU *apdu = zget_APDU(out, Z_APDU_triggerResourceControlRequest);
2608 Z_TriggerResourceControlRequest *req =
2609 apdu->u.triggerResourceControlRequest;
2614 printf("Session not initialized yet\n");
2619 if (!ODR_MASK_GET(session->options, Z_Options_triggerResourceCtrl))
2621 printf("Target doesn't support cancel (trigger resource ctrl)\n");
2624 *req->requestedAction = Z_TriggerResourceControlRequest_cancel;
2625 req->resultSetWanted = &rfalse;
2626 req->referenceId = set_refid (out);
2629 printf("Sent cancel request\n");
2634 int cmd_cancel_find(const char *arg) {
2638 return cmd_cancel("");
2643 int send_scanrequest(const char *query, int pp, int num, const char *term)
2645 Z_APDU *apdu = zget_APDU(out, Z_APDU_scanRequest);
2646 Z_ScanRequest *req = apdu->u.scanRequest;
2650 if (queryType == QueryType_CCL2RPN)
2653 struct ccl_rpn_node *rpn;
2655 rpn = ccl_find_str (bibset, query, &error, &pos);
2658 printf("CCL ERROR: %s\n", ccl_err_msg(error));
2662 yaz_oidval_to_z3950oid(out, CLASS_ATTSET, VAL_BIB1);
2663 if (!(req->termListAndStartPoint = ccl_scan_query (out, rpn)))
2665 printf("Couldn't convert CCL to Scan term\n");
2668 ccl_rpn_delete (rpn);
2672 YAZ_PQF_Parser pqf_parser = yaz_pqf_create ();
2674 if (!(req->termListAndStartPoint =
2675 yaz_pqf_scan(pqf_parser, out, &req->attributeSet, query)))
2677 const char *pqf_msg;
2679 int code = yaz_pqf_error (pqf_parser, &pqf_msg, &off);
2680 printf("%*s^\n", off+7, "");
2681 printf("Prefix query error: %s (code %d)\n", pqf_msg, code);
2682 yaz_pqf_destroy (pqf_parser);
2685 yaz_pqf_destroy (pqf_parser);
2689 if (req->termListAndStartPoint->term &&
2690 req->termListAndStartPoint->term->which == Z_Term_general &&
2691 req->termListAndStartPoint->term->u.general)
2693 req->termListAndStartPoint->term->u.general->buf =
2694 (unsigned char *) odr_strdup(out, term);
2695 req->termListAndStartPoint->term->u.general->len =
2696 req->termListAndStartPoint->term->u.general->size =
2700 req->referenceId = set_refid (out);
2701 req->num_databaseNames = num_databaseNames;
2702 req->databaseNames = databaseNames;
2703 req->numberOfTermsRequested = #
2704 req->preferredPositionInResponse = &pp;
2705 req->stepSize = odr_intdup(out, scan_stepSize);
2710 int send_sortrequest(const char *arg, int newset)
2712 Z_APDU *apdu = zget_APDU(out, Z_APDU_sortRequest);
2713 Z_SortRequest *req = apdu->u.sortRequest;
2714 Z_SortKeySpecList *sksl = (Z_SortKeySpecList *)
2715 odr_malloc (out, sizeof(*sksl));
2721 sprintf (setstring, "%d", setnumber);
2723 sprintf (setstring, "default");
2725 req->referenceId = set_refid (out);
2727 req->num_inputResultSetNames = 1;
2728 req->inputResultSetNames = (Z_InternationalString **)
2729 odr_malloc (out, sizeof(*req->inputResultSetNames));
2730 req->inputResultSetNames[0] = odr_strdup (out, setstring);
2732 if (newset && setnumber >= 0)
2733 sprintf (setstring, "%d", ++setnumber);
2735 req->sortedResultSetName = odr_strdup (out, setstring);
2737 req->sortSequence = yaz_sort_spec (out, arg);
2738 if (!req->sortSequence)
2740 printf ("Missing sort specifications\n");
2747 void display_term(Z_TermInfo *t)
2750 printf("%s", t->displayTerm);
2751 else if (t->term->which == Z_Term_general)
2753 printf("%.*s", t->term->u.general->len, t->term->u.general->buf);
2754 sprintf(last_scan_line, "%.*s", t->term->u.general->len,
2755 t->term->u.general->buf);
2758 printf("Term (not general)");
2759 if (t->globalOccurrences)
2760 printf (" (%d)\n", *t->globalOccurrences);
2765 void process_scanResponse(Z_ScanResponse *res)
2768 Z_Entry **entries = NULL;
2769 int num_entries = 0;
2771 printf("Received ScanResponse\n");
2772 print_refid (res->referenceId);
2773 printf("%d entries", *res->numberOfEntriesReturned);
2774 if (res->positionOfTerm)
2775 printf (", position=%d", *res->positionOfTerm);
2777 if (*res->scanStatus != Z_Scan_success)
2778 printf("Scan returned code %d\n", *res->scanStatus);
2781 if ((entries = res->entries->entries))
2782 num_entries = res->entries->num_entries;
2783 for (i = 0; i < num_entries; i++)
2785 int pos_term = res->positionOfTerm ? *res->positionOfTerm : -1;
2786 if (entries[i]->which == Z_Entry_termInfo)
2788 printf("%c ", i + 1 == pos_term ? '*' : ' ');
2789 display_term(entries[i]->u.termInfo);
2792 display_diagrecs(&entries[i]->u.surrogateDiagnostic, 1);
2794 if (res->entries->nonsurrogateDiagnostics)
2795 display_diagrecs (res->entries->nonsurrogateDiagnostics,
2796 res->entries->num_nonsurrogateDiagnostics);
2799 void process_sortResponse(Z_SortResponse *res)
2801 printf("Received SortResponse: status=");
2802 switch (*res->sortStatus)
2804 case Z_SortResponse_success:
2805 printf ("success"); break;
2806 case Z_SortResponse_partial_1:
2807 printf ("partial"); break;
2808 case Z_SortResponse_failure:
2809 printf ("failure"); break;
2811 printf ("unknown (%d)", *res->sortStatus);
2814 print_refid (res->referenceId);
2815 if (res->diagnostics)
2816 display_diagrecs(res->diagnostics,
2817 res->num_diagnostics);
2820 void process_deleteResultSetResponse (Z_DeleteResultSetResponse *res)
2822 printf("Got deleteResultSetResponse status=%d\n",
2823 *res->deleteOperationStatus);
2824 if (res->deleteListStatuses)
2827 for (i = 0; i < res->deleteListStatuses->num; i++)
2829 printf ("%s status=%d\n", res->deleteListStatuses->elements[i]->id,
2830 *res->deleteListStatuses->elements[i]->status);
2835 int cmd_sort_generic(const char *arg, int newset)
2839 printf("Session not initialized yet\n");
2844 if (!ODR_MASK_GET(session->options, Z_Options_sort))
2846 printf("Target doesn't support sort\n");
2851 if (send_sortrequest(arg, newset) < 0)
2858 int cmd_sort(const char *arg)
2860 return cmd_sort_generic (arg, 0);
2863 int cmd_sort_newset (const char *arg)
2865 return cmd_sort_generic (arg, 1);
2868 int cmd_scanstep(const char *arg)
2870 scan_stepSize = atoi(arg);
2874 int cmd_scanpos(const char *arg)
2876 int r = sscanf(arg, "%d", &scan_position);
2882 int cmd_scansize(const char *arg)
2884 int r = sscanf(arg, "%d", &scan_size);
2890 int cmd_scan(const char *arg)
2892 if (protocol == PROTO_HTTP)
2901 if (send_SRW_scanRequest(arg, scan_position, scan_size) < 0)
2906 if (send_SRW_scanRequest(last_scan_line, 1, scan_size) < 0)
2921 printf("Session not initialized yet\n");
2925 if (!ODR_MASK_GET(session->options, Z_Options_scan))
2927 printf("Target doesn't support scan\n");
2932 strcpy (last_scan_query, arg);
2933 if (send_scanrequest(arg, scan_position, scan_size, 0) < 0)
2938 if (send_scanrequest(last_scan_query, 1, scan_size, last_scan_line) < 0)
2945 int cmd_schema(const char *arg)
2947 xfree(record_schema);
2950 record_schema = xstrdup(arg);
2954 int cmd_format(const char *arg)
2959 printf("Usage: format <recordsyntax>\n");
2962 nsyntax = oid_getvalbyname (arg);
2963 if (strcmp(arg, "none") && nsyntax == VAL_NONE)
2965 printf ("unknown record syntax\n");
2968 recordsyntax = nsyntax;
2972 int cmd_elements(const char *arg)
2974 static Z_ElementSetNames esn;
2975 static char what[100];
2979 elementSetNames = 0;
2983 esn.which = Z_ElementSetNames_generic;
2984 esn.u.generic = what;
2985 elementSetNames = &esn;
2989 int cmd_attributeset(const char *arg)
2995 printf("Usage: attributeset <setname>\n");
2998 sscanf(arg, "%s", what);
2999 if (p_query_attset (what))
3001 printf("Unknown attribute set name\n");
3007 int cmd_querytype (const char *arg)
3009 if (!strcmp (arg, "ccl"))
3010 queryType = QueryType_CCL;
3011 else if (!strcmp (arg, "prefix") || !strcmp(arg, "rpn"))
3012 queryType = QueryType_Prefix;
3013 else if (!strcmp (arg, "ccl2rpn") || !strcmp (arg, "cclrpn"))
3014 queryType = QueryType_CCL2RPN;
3015 else if (!strcmp(arg, "cql"))
3016 queryType = QueryType_CQL;
3017 else if (!strcmp (arg, "cql2rpn") || !strcmp (arg, "cqlrpn"))
3018 queryType = QueryType_CQL2RPN;
3021 printf ("Querytype must be one of:\n");
3022 printf (" prefix - Prefix query\n");
3023 printf (" ccl - CCL query\n");
3024 printf (" ccl2rpn - CCL query converted to RPN\n");
3025 printf (" cql - CQL\n");
3026 printf (" cql2rpn - CQL query converted to RPN\n");
3032 int cmd_refid (const char *arg)
3037 refid = xstrdup (arg);
3041 int cmd_close(const char *arg)
3050 apdu = zget_APDU(out, Z_APDU_close);
3051 req = apdu->u.close;
3052 *req->closeReason = Z_Close_finished;
3054 printf("Sent close request.\n");
3059 int cmd_packagename(const char* arg)
3061 xfree (esPackageName);
3062 esPackageName = NULL;
3064 esPackageName = xstrdup(arg);
3068 int cmd_proxy(const char* arg)
3073 yazProxy = xstrdup (arg);
3077 int cmd_marccharset(const char *arg)
3082 if (sscanf(arg, "%29s", l1) < 1)
3084 printf("MARC character set is `%s'\n",
3085 marcCharset ? marcCharset: "none");
3088 xfree (marcCharset);
3090 if (strcmp(l1, "-"))
3091 marcCharset = xstrdup(l1);
3095 int cmd_displaycharset(const char *arg)
3100 if (sscanf(arg, "%29s", l1) < 1)
3102 printf("Display character set is `%s'\n",
3103 outputCharset ? outputCharset: "none");
3107 xfree (outputCharset);
3109 if (!strcmp(l1, "auto") && codeset)
3113 printf ("Display character set: %s\n", codeset);
3114 outputCharset = xstrdup(codeset);
3117 printf ("No codeset found on this system\n");
3119 else if (strcmp(l1, "-") && strcmp(l1, "none"))
3120 outputCharset = xstrdup(l1);
3125 int cmd_negcharset(const char *arg)
3130 if (sscanf(arg, "%29s %d %d", l1, &negotiationCharsetRecords,
3131 &negotiationCharsetVersion) < 1)
3133 printf("Current negotiation character set is `%s'\n",
3134 negotiationCharset ? negotiationCharset: "none");
3135 printf("Records in charset %s\n", negotiationCharsetRecords ?
3137 printf("Charneg version %d\n", negotiationCharsetVersion);
3141 xfree (negotiationCharset);
3142 negotiationCharset = NULL;
3143 if (*l1 && strcmp(l1, "-") && strcmp(l1, "none"))
3145 negotiationCharset = xstrdup(l1);
3146 printf ("Character set negotiation : %s\n", negotiationCharset);
3152 int cmd_charset(const char* arg)
3154 char l1[30], l2[30], l3[30];
3156 *l1 = *l2 = *l3 = 0;
3157 if (sscanf(arg, "%29s %29s %29s", l1, l2, l3) < 1)
3160 cmd_displaycharset("");
3161 cmd_marccharset("");
3167 cmd_displaycharset(l2);
3169 cmd_marccharset(l3);
3174 int cmd_lang(const char* arg)
3177 printf("Current language is `%s'\n", (yazLang)?yazLang:NULL);
3183 yazLang = xstrdup(arg);
3187 int cmd_source(const char* arg, int echo )
3189 /* first should open the file and read one line at a time.. */
3191 char line[102400], *cp;
3194 fprintf(stderr,"Error in source command use a filename\n");
3198 includeFile = fopen (arg, "r");
3201 fprintf(stderr,"Unable to open file %s for reading\n",arg);
3205 while(!feof(includeFile)) {
3206 memset(line,0,sizeof(line));
3207 fgets(line,sizeof(line),includeFile);
3209 if(strlen(line) < 2) continue;
3210 if(line[0] == '#') continue;
3212 if ((cp = strrchr (line, '\n')))
3216 printf( "processing line: %s\n",line );
3218 process_cmd_line(line);
3221 if(fclose(includeFile)<0) {
3222 perror("unable to close include file");
3228 int cmd_source_echo(const char* arg)
3234 int cmd_source_noecho(const char* arg)
3241 int cmd_subshell(const char* args)
3246 system(getenv("SHELL"));
3252 int cmd_set_berfile(const char *arg)
3254 if (ber_file && ber_file != stdout && ber_file != stderr)
3256 if (!strcmp(arg, ""))
3258 else if (!strcmp(arg, "-"))
3261 ber_file = fopen(arg, "a");
3265 int cmd_set_apdufile(const char *arg)
3267 if(apdu_file && apdu_file != stderr && apdu_file != stderr)
3269 if (!strcmp(arg, ""))
3271 else if (!strcmp(arg, "-"))
3275 apdu_file = fopen(arg, "a");
3277 perror("unable to open apdu log file");
3280 odr_setprint(print, apdu_file);
3284 int cmd_set_cclfile(const char* arg)
3288 bibset = ccl_qual_mk ();
3289 inf = fopen (arg, "r");
3291 perror("unable to open CCL file");
3294 ccl_qual_file (bibset, inf);
3297 strcpy(ccl_fields,arg);
3301 int cmd_set_cqlfile(const char* arg)
3303 cql_transform_t newcqltrans;
3305 if ((newcqltrans = cql_transform_open_fname(arg)) == 0) {
3306 perror("unable to open CQL file");
3310 cql_transform_close(cqltrans);
3312 cqltrans = newcqltrans;
3313 strcpy(cql_fields, arg);
3317 int cmd_set_auto_reconnect(const char* arg)
3319 if(strlen(arg)==0) {
3320 auto_reconnect = ! auto_reconnect;
3321 } else if(strcmp(arg,"on")==0) {
3323 } else if(strcmp(arg,"off")==0) {
3326 printf("Error use on or off\n");
3331 printf("Set auto reconnect enabled.\n");
3333 printf("Set auto reconnect disabled.\n");
3338 int cmd_set_marcdump(const char* arg)
3340 if(marc_file && marc_file != stderr) { /* don't close stdout*/
3344 if (!strcmp(arg, ""))
3346 else if (!strcmp(arg, "-"))
3350 marc_file = fopen(arg, "a");
3352 perror("unable to open marc log file");
3358 this command takes 3 arge {name class oid}
3360 int cmd_register_oid(const char* args) {
3365 {"appctx",CLASS_APPCTX},
3366 {"absyn",CLASS_ABSYN},
3367 {"attset",CLASS_ATTSET},
3368 {"transyn",CLASS_TRANSYN},
3369 {"diagset",CLASS_DIAGSET},
3370 {"recsyn",CLASS_RECSYN},
3371 {"resform",CLASS_RESFORM},
3372 {"accform",CLASS_ACCFORM},
3373 {"extserv",CLASS_EXTSERV},
3374 {"userinfo",CLASS_USERINFO},
3375 {"elemspec",CLASS_ELEMSPEC},
3376 {"varset",CLASS_VARSET},
3377 {"schema",CLASS_SCHEMA},
3378 {"tagset",CLASS_TAGSET},
3379 {"general",CLASS_GENERAL},
3380 {0,(enum oid_class) 0}
3382 char oname_str[101], oclass_str[101], oid_str[101];
3385 oid_class oidclass = CLASS_GENERAL;
3386 int val = 0, oid[OID_SIZE];
3387 struct oident * new_oident=NULL;
3389 if (sscanf (args, "%100[^ ] %100[^ ] %100s",
3390 oname_str,oclass_str, oid_str) < 1) {
3391 printf("Error in register command \n");
3395 for (i = 0; oid_classes[i].className; i++) {
3396 if (!strcmp(oid_classes[i].className, oclass_str))
3398 oidclass=oid_classes[i].oclass;
3403 if(!(oid_classes[i].className)) {
3404 printf("Unknown oid class %s\n",oclass_str);
3412 while (isdigit (*(unsigned char *) name))
3414 val = val*10 + (*name - '0');
3427 new_oident = oid_addent (oid, PROTO_GENERAL, oidclass, oname_str,
3429 if(strcmp(new_oident->desc,oname_str))
3431 fprintf(stderr,"oid is already named as %s, registration failed\n",
3437 int cmd_push_command(const char* arg)
3439 #if HAVE_READLINE_HISTORY_H
3443 fprintf(stderr,"Not compiled with the readline/history module\n");
3448 void source_rcfile()
3450 /* Look for a $HOME/.yazclientrc and source it if it exists */
3451 struct stat statbuf;
3453 char* homedir=getenv("HOME");
3457 sprintf(buffer,"%s/.yazclientrc",homedir);
3459 if(stat(buffer,&statbuf)==0) {
3460 cmd_source(buffer, 0 );
3465 if(stat(".yazclientrc",&statbuf)==0) {
3466 cmd_source(".yazclientrc", 0 );
3471 static void initialize(void)
3476 if (!(out = odr_createmem(ODR_ENCODE)) ||
3477 !(in = odr_createmem(ODR_DECODE)) ||
3478 !(print = odr_createmem(ODR_PRINT)))
3480 fprintf(stderr, "failed to allocate ODR streams\n");
3485 setvbuf(stdout, 0, _IONBF, 0);
3487 odr_setprint(print, apdu_file);
3489 bibset = ccl_qual_mk ();
3490 inf = fopen (ccl_fields, "r");
3493 ccl_qual_file (bibset, inf);
3497 cqltrans = cql_transform_open_fname(cql_fields);
3498 /* If this fails, no problem: we detect cqltrans == 0 later */
3500 #if HAVE_READLINE_READLINE_H
3501 rl_attempted_completion_function = (CPPFunction*)readline_completer;
3505 for(i=0; i<maxOtherInfosSupported; ++i) {
3506 extraOtherInfos[i].oidval = -1;
3513 #if HAVE_GETTIMEOFDAY
3514 struct timeval tv_start, tv_end;
3518 static void handle_srw_record(Z_SRW_record *rec)
3520 if (rec->recordPosition)
3522 printf ("pos=%d", *rec->recordPosition);
3523 setno = *rec->recordPosition + 1;
3525 if (rec->recordSchema)
3526 printf (" schema=%s", rec->recordSchema);
3528 if (rec->recordData_buf && rec->recordData_len)
3530 fwrite(rec->recordData_buf, 1, rec->recordData_len, stdout);
3532 fwrite (rec->recordData_buf, 1, rec->recordData_len, marc_file);
3535 printf ("No data!");
3539 static void handle_srw_explain_response(Z_SRW_explainResponse *res)
3541 handle_srw_record(&res->record);
3544 static void handle_srw_response(Z_SRW_searchRetrieveResponse *res)
3548 printf ("Received SRW SearchRetrieve Response\n");
3550 for (i = 0; i<res->num_diagnostics; i++)
3552 if (res->diagnostics[i].uri)
3553 printf ("SRW diagnostic %s\n",
3554 res->diagnostics[i].uri);
3556 printf ("SRW diagnostic missing or could not be decoded\n");
3557 if (res->diagnostics[i].message)
3558 printf ("Message: %s\n", res->diagnostics[i].message);
3559 if (res->diagnostics[i].details)
3560 printf ("Details: %s\n", res->diagnostics[i].details);
3562 if (res->numberOfRecords)
3563 printf ("Number of hits: %d\n", *res->numberOfRecords);
3564 for (i = 0; i<res->num_records; i++)
3565 handle_srw_record(res->records + i);
3568 static void handle_srw_scan_term(Z_SRW_scanTerm *term)
3570 if (term->displayTerm)
3571 printf("%s:", term->displayTerm);
3572 else if (term->value)
3573 printf("%s:", term->value);
3575 printf("No value:");
3576 if (term->numberOfRecords)
3577 printf(" %d", *term->numberOfRecords);
3578 if (term->whereInList)
3579 printf(" %s", term->whereInList);
3580 if (term->value && term->displayTerm)
3581 printf(" %s", term->value);
3583 strcpy(last_scan_line, term->value);
3587 static void handle_srw_scan_response(Z_SRW_scanResponse *res)
3591 printf ("Received SRW Scan Response\n");
3593 for (i = 0; i<res->num_diagnostics; i++)
3595 if (res->diagnostics[i].uri)
3596 printf ("SRW diagnostic %s\n",
3597 res->diagnostics[i].uri);
3599 printf ("SRW diagnostic missing or could not be decoded\n");
3600 if (res->diagnostics[i].message)
3601 printf ("Message: %s\n", res->diagnostics[i].message);
3602 if (res->diagnostics[i].details)
3603 printf ("Details: %s\n", res->diagnostics[i].details);
3606 for (i = 0; i<res->num_terms; i++)
3607 handle_srw_scan_term(res->terms + i);
3610 static void http_response(Z_HTTP_Response *hres)
3613 const char *content_type = z_HTTP_header_lookup(hres->headers,
3615 const char *connection_head = z_HTTP_header_lookup(hres->headers,
3617 if (content_type && !yaz_strcmp_del("text/xml", content_type, "; "))
3619 Z_SOAP *soap_package = 0;
3620 ODR o = odr_createmem(ODR_DECODE);
3621 Z_SOAP_Handler soap_handlers[2] = {
3622 {"http://www.loc.gov/zing/srw/", 0,
3623 (Z_SOAP_fun) yaz_srw_codec},
3626 ret = z_soap_codec(o, &soap_package,
3627 &hres->content_buf, &hres->content_len,
3629 if (!ret && soap_package->which == Z_SOAP_generic &&
3630 soap_package->u.generic->no == 0)
3632 Z_SRW_PDU *sr = soap_package->u.generic->p;
3633 if (sr->which == Z_SRW_searchRetrieve_response)
3634 handle_srw_response(sr->u.response);
3635 else if (sr->which == Z_SRW_explain_response)
3636 handle_srw_explain_response(sr->u.explain_response);
3637 else if (sr->which == Z_SRW_scan_response)
3638 handle_srw_scan_response(sr->u.scan_response);
3642 else if (soap_package && (soap_package->which == Z_SOAP_fault
3643 || soap_package->which == Z_SOAP_error))
3645 printf ("HTTP Error Status=%d\n", hres->code);
3646 printf ("SOAP Fault code %s\n",
3647 soap_package->u.fault->fault_code);
3648 printf ("SOAP Fault string %s\n",
3649 soap_package->u.fault->fault_string);
3650 if (soap_package->u.fault->details)
3651 printf ("SOAP Details %s\n",
3652 soap_package->u.fault->details);
3660 if (hres->code != 200)
3662 printf ("HTTP Error Status=%d\n", hres->code);
3666 printf ("Decoding of SRW package failed\n");
3672 if (!strcmp(hres->version, "1.0"))
3674 /* HTTP 1.0: only if Keep-Alive we stay alive.. */
3675 if (!connection_head || strcmp(connection_head, "Keep-Alive"))
3680 /* HTTP 1.1: only if no close we stay alive .. */
3681 if (connection_head && !strcmp(connection_head, "close"))
3688 void wait_and_handle_response()
3690 int reconnect_ok = 1;
3693 int netbufferlen = 0;
3698 res = cs_get(conn, &netbuffer, &netbufferlen);
3699 if (reconnect_ok && res <= 0 && protocol == PROTO_HTTP)
3710 buf_out = odr_getbuf(out, &len_out, 0);
3712 do_hex_dump(buf_out, len_out);
3714 cs_put(conn, buf_out, len_out);
3722 printf("Target closed connection\n");
3727 odr_reset(in); /* release APDU from last round */
3729 do_hex_dump(netbuffer, res);
3730 odr_setbuf(in, netbuffer, res, 0);
3732 if (!z_GDU(in, &gdu, 0, 0))
3734 FILE *f = ber_file ? ber_file : stdout;
3735 odr_perror(in, "Decoding incoming APDU");
3736 fprintf(f, "[Near %d]\n", odr_offset(in));
3737 fprintf(f, "Packet dump:\n---------\n");
3738 odr_dumpBER(f, netbuffer, res);
3739 fprintf(f, "---------\n");
3742 z_GDU(print, &gdu, 0, 0);
3745 if (conn && cs_more(conn))
3750 odr_dumpBER(ber_file, netbuffer, res);
3751 if (apdu_file && !z_GDU(print, &gdu, 0, 0))
3753 odr_perror(print, "Failed to print incoming APDU");
3757 if (gdu->which == Z_GDU_Z3950)
3759 Z_APDU *apdu = gdu->u.z3950;
3762 case Z_APDU_initResponse:
3763 process_initResponse(apdu->u.initResponse);
3765 case Z_APDU_searchResponse:
3766 process_searchResponse(apdu->u.searchResponse);
3768 case Z_APDU_scanResponse:
3769 process_scanResponse(apdu->u.scanResponse);
3771 case Z_APDU_presentResponse:
3772 print_refid (apdu->u.presentResponse->referenceId);
3774 *apdu->u.presentResponse->numberOfRecordsReturned;
3775 if (apdu->u.presentResponse->records)
3776 display_records(apdu->u.presentResponse->records);
3778 printf("No records.\n");
3779 printf ("nextResultSetPosition = %d\n",
3780 *apdu->u.presentResponse->nextResultSetPosition);
3782 case Z_APDU_sortResponse:
3783 process_sortResponse(apdu->u.sortResponse);
3785 case Z_APDU_extendedServicesResponse:
3786 printf("Got extended services response\n");
3787 process_ESResponse(apdu->u.extendedServicesResponse);
3790 printf("Target has closed the association.\n");
3791 process_close(apdu->u.close);
3793 case Z_APDU_resourceControlRequest:
3794 process_resourceControlRequest
3795 (apdu->u.resourceControlRequest);
3797 case Z_APDU_deleteResultSetResponse:
3798 process_deleteResultSetResponse(apdu->u.
3799 deleteResultSetResponse);
3802 printf("Received unknown APDU type (%d).\n",
3808 else if (gdu->which == Z_GDU_HTTP_Response)
3810 http_response(gdu->u.HTTP_Response);
3813 if (conn && !cs_more(conn))
3818 #if HAVE_GETTIMEOFDAY
3819 gettimeofday (&tv_end, 0);
3821 printf ("S/U S/U=%ld/%ld %ld/%ld",
3822 (long) tv_start.tv_sec,
3823 (long) tv_start.tv_usec,
3824 (long) tv_end.tv_sec,
3825 (long) tv_end.tv_usec);
3827 printf ("Elapsed: %.6f\n",
3828 (double) tv_end.tv_usec / 1e6 + tv_end.tv_sec -
3829 ((double) tv_start.tv_usec / 1e6 + tv_start.tv_sec));
3836 int cmd_cclparse(const char* arg)
3839 struct ccl_rpn_node *rpn=NULL;
3842 rpn = ccl_find_str (bibset, arg, &error, &pos);
3845 printf ("%*s^ - ", 3+strlen(last_cmd)+1+pos, " ");
3846 printf ("%s\n", ccl_err_msg (error));
3852 ccl_pr_tree(rpn, stdout);
3856 ccl_rpn_delete(rpn);
3864 int cmd_set_otherinfo(const char* args)
3866 char oidstr[101], otherinfoString[101];
3871 sscan_res = sscanf (args, "%d %100[^ ] %100s", &otherinfoNo, oidstr, otherinfoString);
3873 /* reset this otherinfo */
3874 if(otherinfoNo>=maxOtherInfosSupported) {
3875 printf("Error otherinfo index to large (%d>%d)\n",
3876 otherinfoNo,maxOtherInfosSupported);
3878 extraOtherInfos[otherinfoNo].oidval = -1;
3879 if (extraOtherInfos[otherinfoNo].value)
3880 free(extraOtherInfos[otherinfoNo].value);
3884 printf("Error in set_otherinfo command \n");
3888 if (otherinfoNo>=maxOtherInfosSupported) {
3889 printf("Error otherinfo index to large (%d>%d)\n",
3890 otherinfoNo,maxOtherInfosSupported);
3893 oidval = oid_getvalbyname (oidstr);
3894 if (oidval == -1 ) {
3895 printf("Error in set_otherinfo command unknown oid %s \n",oidstr);
3898 extraOtherInfos[otherinfoNo].oidval = oidval;
3899 if(extraOtherInfos[otherinfoNo].value) free(extraOtherInfos[otherinfoNo].value);
3900 extraOtherInfos[otherinfoNo].value = strdup(otherinfoString);
3905 int cmd_sleep(const char* args )
3914 printf("Done sleeping %d seconds\n", sec);
3919 int cmd_list_otherinfo(const char* args)
3923 if(strlen(args)>0) {
3925 if( i >= maxOtherInfosSupported ) {
3926 printf("Error otherinfo index to large (%d>%d)\n",i,maxOtherInfosSupported);
3930 if(extraOtherInfos[i].oidval != -1)
3931 printf(" otherinfo %d %s %s\n",
3933 yaz_z3950_oid_value_to_str(
3934 (enum oid_value) extraOtherInfos[i].oidval,
3936 extraOtherInfos[i].value);
3939 for(i=0; i<maxOtherInfosSupported; ++i) {
3940 if(extraOtherInfos[i].oidval != -1)
3941 printf(" otherinfo %d %s %s\n",
3943 yaz_z3950_oid_value_to_str(
3944 (enum oid_value) extraOtherInfos[i].oidval,
3946 extraOtherInfos[i].value);
3954 int cmd_list_all(const char* args) {
3957 /* connection options */
3959 printf("Connected to : %s\n",last_open_command);
3961 if(last_open_command)
3962 printf("Not connected to : %s\n",last_open_command);
3964 printf("Not connected : \n");
3967 if(yazProxy) printf("using proxy : %s\n",yazProxy);
3969 printf("auto_reconnect : %s\n",auto_reconnect?"on":"off");
3972 printf("Authentication : none\n");
3974 switch(auth->which) {
3975 case Z_IdAuthentication_idPass:
3976 printf("Authentication : IdPass\n");
3977 printf(" Login User : %s\n",auth->u.idPass->userId?auth->u.idPass->userId:"");
3978 printf(" Login Group : %s\n",auth->u.idPass->groupId?auth->u.idPass->groupId:"");
3979 printf(" Password : %s\n",auth->u.idPass->password?auth->u.idPass->password:"");
3981 case Z_IdAuthentication_open:
3982 printf("Authentication : psOpen\n");
3983 printf(" Open string : %s\n",auth->u.open);
3986 printf("Authentication : Unknown\n");
3989 if (negotiationCharset)
3990 printf("Neg. Character set : `%s'\n", negotiationCharset);
3994 for (i = 0; i<num_databaseNames; i++) printf("%s ",databaseNames[i]);
3998 printf("CCL file : %s\n",ccl_fields);
3999 printf("CQL file : %s\n",cql_fields);
4000 printf("Query type : %s\n",query_type_as_string(queryType));
4002 printf("Named Result Sets : %s\n",setnumber==-1?"off":"on");
4004 /* piggy back options */
4005 printf("ssub/lslb/mspn : %d/%d/%d\n",smallSetUpperBound,largeSetLowerBound,mediumSetPresentNumber);
4007 /* print present related options */
4008 printf("Format : %s\n",yaz_z3950_oid_value_to_str(recordsyntax,CLASS_RECSYN));
4009 printf("Schema : %s\n",record_schema ? record_schema : "not set");
4010 printf("Elements : %s\n",elementSetNames?elementSetNames->u.generic:"");
4012 /* loging options */
4013 printf("APDU log : %s\n",apdu_file?"on":"off");
4014 printf("Record log : %s\n",marc_file?"on":"off");
4017 printf("Other Info: \n");
4018 cmd_list_otherinfo("");
4023 int cmd_clear_otherinfo(const char* args)
4025 if(strlen(args)>0) {
4027 otherinfoNo = atoi(args);
4028 if( otherinfoNo >= maxOtherInfosSupported ) {
4029 printf("Error otherinfo index to large (%d>%d)\n",otherinfoNo,maxOtherInfosSupported);
4033 if(extraOtherInfos[otherinfoNo].oidval != -1) {
4034 /* only clear if set. */
4035 extraOtherInfos[otherinfoNo].oidval=-1;
4036 free(extraOtherInfos[otherinfoNo].value);
4041 for(i=0; i<maxOtherInfosSupported; ++i) {
4042 if (extraOtherInfos[i].oidval!=-1 ) {
4043 extraOtherInfos[i].oidval=-1;
4044 free(extraOtherInfos[i].value);
4051 static int cmd_help (const char *line);
4053 typedef char *(*completerFunctionType)(const char *text, int state);
4057 int (*fun)(const char *arg);
4059 completerFunctionType rl_completerfunction;
4060 int complete_filenames;
4061 char **local_tabcompletes;
4063 {"open", cmd_open, "('tcp'|'ssl')':<host>[':'<port>][/<db>]",NULL,0,NULL},
4064 {"quit", cmd_quit, "",NULL,0,NULL},
4065 {"find", cmd_find, "<query>",NULL,0,NULL},
4066 {"delete", cmd_delete, "<setname>",NULL,0,NULL},
4067 {"base", cmd_base, "<base-name>",NULL,0,NULL},
4068 {"show", cmd_show, "<rec#>['+'<#recs>['+'<setname>]]",NULL,0,NULL},
4069 {"scan", cmd_scan, "<term>",NULL,0,NULL},
4070 {"scanstep", cmd_scanstep, "<size>",NULL,0,NULL},
4071 {"scanpos", cmd_scanpos, "<size>",NULL,0,NULL},
4072 {"scansize", cmd_scansize, "<size>",NULL,0,NULL},
4073 {"sort", cmd_sort, "<sortkey> <flag> <sortkey> <flag> ...",NULL,0,NULL},
4074 {"sort+", cmd_sort_newset, "<sortkey> <flag> <sortkey> <flag> ...",NULL,0,NULL},
4075 {"authentication", cmd_authentication, "<acctstring>",NULL,0,NULL},
4076 {"lslb", cmd_lslb, "<largeSetLowerBound>",NULL,0,NULL},
4077 {"ssub", cmd_ssub, "<smallSetUpperBound>",NULL,0,NULL},
4078 {"mspn", cmd_mspn, "<mediumSetPresentNumber>",NULL,0,NULL},
4079 {"status", cmd_status, "",NULL,0,NULL},
4080 {"setnames", cmd_setnames, "",NULL,0,NULL},
4081 {"cancel", cmd_cancel, "",NULL,0,NULL},
4082 {"cancel_find", cmd_cancel_find, "<query>",NULL,0,NULL},
4083 {"format", cmd_format, "<recordsyntax>",complete_format,0,NULL},
4084 {"schema", cmd_schema, "<schema>",complete_schema,0,NULL},
4085 {"elements", cmd_elements, "<elementSetName>",NULL,0,NULL},
4086 {"close", cmd_close, "",NULL,0,NULL},
4087 {"attributeset", cmd_attributeset, "<attrset>",complete_attributeset,0,NULL},
4088 {"querytype", cmd_querytype, "<type>",complete_querytype,0,NULL},
4089 {"refid", cmd_refid, "<id>",NULL,0,NULL},
4090 {"itemorder", cmd_itemorder, "ill|item <itemno>",NULL,0,NULL},
4091 {"update", cmd_update, "<action> <recid> [<file>]",NULL,0,NULL},
4092 {"update0", cmd_update0, "<action> <recid> [<file>]",NULL,0,NULL},
4093 {"packagename", cmd_packagename, "<packagename>",NULL,0,NULL},
4094 {"proxy", cmd_proxy, "[('tcp'|'ssl')]<host>[':'<port>]",NULL,0,NULL},
4095 {"charset", cmd_charset, "<nego_charset> <output_charset>",NULL,0,NULL},
4096 {"negcharset", cmd_negcharset, "<nego_charset>",NULL,0,NULL},
4097 {"displaycharset", cmd_displaycharset, "<output_charset>",NULL,0,NULL},
4098 {"marccharset", cmd_marccharset, "<charset_name>",NULL,0,NULL},
4099 {"lang", cmd_lang, "<language_code>",NULL,0,NULL},
4100 {".", cmd_source_echo, "<filename>",NULL,1,NULL},
4101 {"!", cmd_subshell, "Subshell command",NULL,1,NULL},
4102 {"set_apdufile", cmd_set_apdufile, "<filename>",NULL,1,NULL},
4103 {"set_berfile", cmd_set_berfile, "<filename>",NULL,1,NULL},
4104 {"set_marcdump", cmd_set_marcdump," <filename>",NULL,1,NULL},
4105 {"set_cclfile", cmd_set_cclfile," <filename>",NULL,1,NULL},
4106 {"set_cqlfile", cmd_set_cqlfile," <filename>",NULL,1,NULL},
4107 {"set_auto_reconnect", cmd_set_auto_reconnect," on|off",complete_auto_reconnect,1,NULL},
4108 {"set_otherinfo", cmd_set_otherinfo,"<otherinfoinddex> <oid> <string>",NULL,0,NULL},
4109 {"sleep", cmd_sleep,"<seconds>",NULL,0,NULL},
4110 {"register_oid", cmd_register_oid,"<name> <class> <oid>",NULL,0,NULL},
4111 {"push_command", cmd_push_command,"<command>",command_generator,0,NULL},
4112 {"register_tab", cmd_register_tab,"<commandname> <tab>",command_generator,0,NULL},
4113 {"cclparse", cmd_cclparse,"<ccl find command>",NULL,0,NULL},
4114 {"list_otherinfo",cmd_list_otherinfo,"[otherinfoinddex]",NULL,0,NULL},
4115 {"list_all",cmd_list_all,"",NULL,0,NULL},
4116 {"clear_otherinfo",cmd_clear_otherinfo,"",NULL,0,NULL},
4117 /* Server Admin Functions */
4118 {"adm-reindex", cmd_adm_reindex, "<database-name>",NULL,0,NULL},
4119 {"adm-truncate", cmd_adm_truncate, "('database'|'index')<object-name>",NULL,0,NULL},
4120 {"adm-create", cmd_adm_create, "",NULL,0,NULL},
4121 {"adm-drop", cmd_adm_drop, "('database'|'index')<object-name>",NULL,0,NULL},
4122 {"adm-import", cmd_adm_import, "<record-type> <dir> <pattern>",NULL,0,NULL},
4123 {"adm-refresh", cmd_adm_refresh, "",NULL,0,NULL},
4124 {"adm-commit", cmd_adm_commit, "",NULL,0,NULL},
4125 {"adm-shutdown", cmd_adm_shutdown, "",NULL,0,NULL},
4126 {"adm-startup", cmd_adm_startup, "",NULL,0,NULL},
4127 {"explain", cmd_explain, "", NULL, 0, NULL},
4128 {"options", cmd_options, "", NULL, 0, NULL},
4129 {"zversion", cmd_zversion, "", NULL, 0, NULL},
4130 {"help", cmd_help, "", NULL,0,NULL},
4131 {"init", cmd_init, "", NULL,0,NULL},
4135 static int cmd_help (const char *line)
4141 sscanf (line, "%20s", topic);
4144 printf("Commands:\n");
4145 for (i = 0; cmd_array[i].cmd; i++)
4146 if (*topic == 0 || strcmp (topic, cmd_array[i].cmd) == 0)
4147 printf(" %s %s\n", cmd_array[i].cmd, cmd_array[i].ad);
4148 if (strcmp (topic, "find") == 0)
4151 printf (" \"term\" Simple Term\n");
4152 printf (" @attr [attset] type=value op Attribute\n");
4153 printf (" @and opl opr And\n");
4154 printf (" @or opl opr Or\n");
4155 printf (" @not opl opr And-Not\n");
4156 printf (" @set set Result set\n");
4158 printf ("Bib-1 attribute types\n");
4160 printf ("4=Title 7=ISBN 8=ISSN 30=Date 62=Abstract 1003=Author 1016=Any\n");
4161 printf ("2=Relation: ");
4162 printf ("1< 2<= 3= 4>= 5> 6!= 102=Relevance\n");
4163 printf ("3=Position: ");
4164 printf ("1=First in Field 2=First in subfield 3=Any position\n");
4165 printf ("4=Structure: ");
4166 printf ("1=Phrase 2=Word 3=Key 4=Year 5=Date 6=WordList\n");
4167 printf ("5=Truncation: ");
4168 printf ("1=Right 2=Left 3=L&R 100=No 101=# 102=Re-1 103=Re-2\n");
4169 printf ("6=Completeness:");
4170 printf ("1=Incomplete subfield 2=Complete subfield 3=Complete field\n");
4175 int cmd_register_tab(const char* arg) {
4177 char command[101], tabargument[101];
4182 if (sscanf (arg, "%100s %100s", command, tabargument) < 1) {
4186 /* locate the amdn in the list */
4187 for (i = 0; cmd_array[i].cmd; i++) {
4188 if (!strncmp(cmd_array[i].cmd, command, strlen(command))) {
4193 if(!cmd_array[i].cmd) {
4194 fprintf(stderr,"Unknown command %s\n",command);
4199 if(!cmd_array[i].local_tabcompletes)
4200 cmd_array[i].local_tabcompletes = (char **) calloc(1,sizeof(char**));
4204 tabslist = cmd_array[i].local_tabcompletes;
4205 for(;tabslist && *tabslist;tabslist++) {
4209 cmd_array[i].local_tabcompletes = (char **)
4210 realloc(cmd_array[i].local_tabcompletes,(num_of_tabs+2)*sizeof(char**));
4211 tabslist=cmd_array[i].local_tabcompletes;
4212 tabslist[num_of_tabs]=strdup(tabargument);
4213 tabslist[num_of_tabs+1]=NULL;
4218 void process_cmd_line(char* line)
4221 char word[32], arg[10240];
4223 #if HAVE_GETTIMEOFDAY
4224 gettimeofday (&tv_start, 0);
4227 if ((res = sscanf(line, "%31s %10239[^;]", word, arg)) <= 0)
4229 strcpy(word, last_cmd);
4234 strcpy(last_cmd, word);
4236 /* removed tailing spaces from the arg command */
4239 char* lastnonspace=NULL;
4242 if(!isspace(*(unsigned char *) p)) {
4247 *(++lastnonspace) = 0;
4250 for (i = 0; cmd_array[i].cmd; i++)
4251 if (!strncmp(cmd_array[i].cmd, word, strlen(word)))
4253 res = (*cmd_array[i].fun)(arg);
4257 if (!cmd_array[i].cmd) /* dump our help-screen */
4259 printf("Unknown command: %s.\n", word);
4260 printf("use help for list of commands\n");
4261 /* cmd_help (""); */
4265 if(apdu_file) fflush(apdu_file);
4268 wait_and_handle_response();
4277 char *command_generator(const char *text, int state)
4283 for( ; cmd_array[idx].cmd; ++idx) {
4284 if (!strncmp(cmd_array[idx].cmd,text,strlen(text))) {
4285 ++idx; /* skip this entry on the next run */
4286 return strdup(cmd_array[idx-1].cmd);
4294 This function only known how to complete on the first word
4296 char ** readline_completer(char *text, int start, int end) {
4297 #if HAVE_READLINE_READLINE_H
4299 completerFunctionType completerToUse;
4302 #if HAVE_READLINE_RL_COMPLETION_MATCHES
4303 char** res=rl_completion_matches(text,
4306 char** res=completion_matches(text,
4307 (CPFunction*)command_generator);
4309 rl_attempted_completion_over = 1;
4312 char arg[10240],word[32];
4314 if ((res = sscanf(rl_line_buffer, "%31s %10239[^;]", word, arg)) <= 0) {
4315 rl_attempted_completion_over = 1;
4319 for (i = 0; cmd_array[i].cmd; i++) {
4320 if (!strncmp(cmd_array[i].cmd, word, strlen(word))) {
4325 if(!cmd_array[i].cmd) return NULL;
4327 curret_global_list = cmd_array[i].local_tabcompletes;
4329 completerToUse = cmd_array[i].rl_completerfunction;
4330 if(completerToUse==NULL) /* if no pr. command completer is defined use the default completer */
4331 completerToUse = default_completer;
4333 if(completerToUse) {
4334 #ifdef HAVE_READLINE_RL_COMPLETION_MATCHES
4336 rl_completion_matches(text,
4340 completion_matches(text,
4341 (CPFunction*)completerToUse);
4343 if(!cmd_array[i].complete_filenames)
4344 rl_attempted_completion_over = 1;
4347 if(!cmd_array[i].complete_filenames)
4348 rl_attempted_completion_over = 1;
4358 static void client(void)
4364 #if HAVE_GETTIMEOFDAY
4365 gettimeofday (&tv_start, 0);
4370 char *line_in = NULL;
4371 #if HAVE_READLINE_READLINE_H
4374 line_in=readline(C_PROMPT);
4377 #if HAVE_READLINE_HISTORY_H
4379 add_history(line_in);
4381 strncpy(line, line_in, 10239);
4390 if (!fgets(line, 10239, stdin))
4392 if ((end_p = strchr (line, '\n')))
4395 process_cmd_line(line);
4399 static void show_version(void)
4403 yaz_version(vstr, 0);
4404 printf ("YAZ version: %s\n", YAZ_VERSION);
4405 if (strcmp(vstr, YAZ_VERSION))
4406 printf ("YAZ DLL/SO: %s\n", vstr);
4410 int main(int argc, char **argv)
4413 char *open_command = 0;
4414 char *auth_command = 0;
4419 if (!setlocale(LC_CTYPE, ""))
4420 fprintf (stderr, "setlocale failed\n");
4424 codeset = nl_langinfo(CODESET);
4428 outputCharset = xstrdup(codeset);
4430 ODR_MASK_SET(&z3950_options, Z_Options_search);
4431 ODR_MASK_SET(&z3950_options, Z_Options_present);
4432 ODR_MASK_SET(&z3950_options, Z_Options_namedResultSets);
4433 ODR_MASK_SET(&z3950_options, Z_Options_triggerResourceCtrl);
4434 ODR_MASK_SET(&z3950_options, Z_Options_scan);
4435 ODR_MASK_SET(&z3950_options, Z_Options_sort);
4436 ODR_MASK_SET(&z3950_options, Z_Options_extendedServices);
4437 ODR_MASK_SET(&z3950_options, Z_Options_delSet);
4439 while ((ret = options("k:c:q:a:b:m:v:p:u:t:Vxd:", argv, argc, &arg)) != -2)
4446 open_command = (char *) xmalloc (strlen(arg)+6);
4447 strcpy (open_command, "open ");
4448 strcat (open_command, arg);
4452 dump_file_prefix = arg;
4455 kilobytes = atoi(arg);
4458 if (!(marc_file = fopen (arg, "a")))
4465 outputCharset = xstrdup(arg);
4468 strncpy (ccl_fields, arg, sizeof(ccl_fields)-1);
4469 ccl_fields[sizeof(ccl_fields)-1] = '\0';
4472 strncpy (cql_fields, arg, sizeof(cql_fields)-1);
4473 cql_fields[sizeof(cql_fields)-1] = '\0';
4476 if (!strcmp(arg, "-"))
4479 ber_file=fopen(arg, "a");
4482 if (!strcmp(arg, "-"))
4485 apdu_file=fopen(arg, "a");
4491 yazProxy=strdup(arg);
4496 auth_command = (char *) xmalloc (strlen(arg)+6);
4497 strcpy (auth_command, "auth ");
4498 strcat (auth_command, arg);
4502 yaz_log_init(yaz_log_mask_str(arg), "", 0);
4508 fprintf (stderr, "Usage: %s [-m <marclog>] [ -a <apdulog>] "
4509 "[-b berdump] [-c cclfields] \n"
4510 "[-q cqlfields] [-p <proxy-addr>] [-u <auth>] "
4511 "[-k size] [-d dump] [-V] [<server-addr>]\n",
4519 #ifdef HAVE_GETTIMEOFDAY
4520 gettimeofday (&tv_start, 0);
4522 process_cmd_line (auth_command);
4523 #if HAVE_READLINE_HISTORY_H
4524 add_history(auth_command);
4526 xfree(auth_command);
4530 #ifdef HAVE_GETTIMEOFDAY
4531 gettimeofday (&tv_start, 0);
4533 process_cmd_line (open_command);
4534 #if HAVE_READLINE_HISTORY_H
4535 add_history(open_command);
4537 xfree(open_command);
4548 * vim600: sw=4 ts=8 fdm=marker
4549 * vim<600: sw=4 ts=8