2 * Copyright (c) 1995-2004, Index Data
3 * See the file LICENSE for details.
5 * $Id: client.c,v 1.248 2004-09-03 18:55:59 adam Exp $
19 #if HAVE_OPENSSL_SSL_H
20 #include <openssl/bio.h>
21 #include <openssl/crypto.h>
22 #include <openssl/x509.h>
23 #include <openssl/pem.h>
24 #include <openssl/ssl.h>
25 #include <openssl/err.h>
33 #define S_ISREG(x) (x & _S_IFREG)
34 #define S_ISDIR(x) (x & _S_IFDIR)
37 #include <yaz/yaz-util.h>
39 #include <yaz/comstack.h>
41 #include <yaz/proto.h>
42 #include <yaz/marcdisp.h>
43 #include <yaz/diagbib1.h>
44 #include <yaz/otherinfo.h>
45 #include <yaz/charneg.h>
47 #include <yaz/pquery.h>
48 #include <yaz/sortspec.h>
52 #include <yaz/yaz-ccl.h>
55 #if HAVE_READLINE_READLINE_H
56 #include <readline/readline.h>
59 #if HAVE_READLINE_HISTORY_H
60 #include <readline/history.h>
66 #include "tabcomplete.h"
68 #define C_PROMPT "Z> "
70 static char *codeset = 0; /* character set for output */
71 static int hex_dump = 0;
72 static char *dump_file_prefix = 0;
73 static ODR out, in, print; /* encoding and decoding streams */
75 static ODR srw_sr_odr_out = 0;
76 static Z_SRW_PDU *srw_sr = 0;
78 static FILE *apdu_file = 0;
79 static FILE *ber_file = 0;
80 static COMSTACK conn = 0; /* our z-association */
81 static Z_IdAuthentication *auth = 0; /* our current auth definition */
82 char *databaseNames[128];
83 int num_databaseNames = 0;
84 static Z_External *record_last = 0;
85 static int setnumber = -1; /* current result set number */
86 static int smallSetUpperBound = 0;
87 static int largeSetLowerBound = 1;
88 static int mediumSetPresentNumber = 0;
89 static Z_ElementSetNames *elementSetNames = 0;
90 static int setno = 1; /* current set offset */
91 static enum oid_proto protocol = PROTO_Z3950; /* current app protocol */
92 static enum oid_value recordsyntax = VAL_USMARC;
93 static char *record_schema = 0;
94 static int sent_close = 0;
95 static NMEM session_mem = NULL; /* memory handle for init-response */
96 static Z_InitResponse *session = 0; /* session parameters */
97 static char last_scan_line[512] = "0";
98 static char last_scan_query[512] = "0";
99 static char ccl_fields[512] = "default.bib";
100 /* ### How can I set this path to use wherever YAZ is installed? */
101 static char cql_fields[512] = "/usr/local/share/yaz/etc/pqf.properties";
102 static char *esPackageName = 0;
103 static char *yazProxy = 0;
104 static int kilobytes = 1024;
105 static char *negotiationCharset = 0;
106 static char *outputCharset = 0;
107 static char *marcCharset = 0;
108 static char* yazLang = 0;
109 static char* http_version = "1.1";
111 static char last_cmd[32] = "?";
112 static FILE *marc_file = 0;
113 static char *refid = NULL;
114 static char *last_open_command = NULL;
115 static int auto_reconnect = 0;
116 static Odr_bitmask z3950_options;
117 static int z3950_version = 3;
119 static char cur_host[200];
129 static QueryType queryType = QueryType_Prefix;
131 static CCL_bibset bibset; /* CCL bibset handle */
132 static cql_transform_t cqltrans; /* CQL context-set handle */
134 #if HAVE_READLINE_COMPLETION_OVER
137 /* readline doesn't have this var. Define it ourselves. */
138 int rl_attempted_completion_over = 0;
141 /* set this one to 1, to avoid decode of unknown MARCs */
142 #define AVOID_MARC_DECODE 1
144 #define maxOtherInfosSupported 10
148 } extraOtherInfos[maxOtherInfosSupported];
151 void process_cmd_line(char* line);
152 char ** readline_completer(char *text, int start, int end);
153 char *command_generator(const char *text, int state);
154 char** curret_global_list=NULL;
155 int cmd_register_tab(const char* arg);
157 static void close_session (void);
159 ODR getODROutputStream()
164 const char* query_type_as_string(QueryType q)
167 case QueryType_Prefix: return "prefix (RPN sent to server)";
168 case QueryType_CCL: return "CCL (CCL sent to server) ";
169 case QueryType_CCL2RPN: return "CCL -> RPN (RPN sent to server)";
170 case QueryType_CQL: return "CQL (CQL sent to server)";
171 case QueryType_CQL2RPN: return "CQL -> RPN (RPN sent to server)";
173 return "unknown Query type internal yaz-client error";
177 static void do_hex_dump(const char* buf, int len)
182 for( i=0; i<len ; i=i+16 )
185 for(x=0 ; i+x<len && x<16; ++x)
187 printf("%2.2X ",(unsigned int)((unsigned char)buf[i+x]));
192 if (dump_file_prefix)
195 if (++no < 1000 && strlen(dump_file_prefix) < 500)
199 sprintf (fname, "%s.%03d.raw", dump_file_prefix, no);
200 of = fopen(fname, "wb");
202 fwrite (buf, 1, len, of);
209 void add_otherInfos(Z_APDU *a)
211 Z_OtherInformation **oi;
215 for(i=0; i<maxOtherInfosSupported; ++i)
217 if(extraOtherInfos[i].oidval != -1)
218 yaz_oi_set_string_oidval(oi, out, extraOtherInfos[i].oidval,
219 1, extraOtherInfos[i].value);
223 int send_apdu(Z_APDU *a)
232 z_APDU(print, &a, 0, 0);
235 if (!z_APDU(out, &a, 0, 0))
237 odr_perror(out, "Encoding APDU");
241 buf = odr_getbuf(out, &len, 0);
243 odr_dumpBER(ber_file, buf, len);
244 /* printf ("sending APDU of size %d\n", len); */
245 do_hex_dump(buf, len);
246 if (cs_put(conn, buf, len) < 0)
248 fprintf(stderr, "cs_put: %s", cs_errmsg(cs_errno(conn)));
252 odr_reset(out); /* release the APDU structure */
256 static void print_stringn(const unsigned char *buf, size_t len)
259 for (i = 0; i<len; i++)
260 if ((buf[i] <= 126 && buf[i] >= 32) || strchr ("\n\r\t\f", buf[i]))
261 printf ("%c", buf[i]);
263 printf ("\\X%02X", buf[i]);
266 static void print_refid (Z_ReferenceId *id)
270 printf ("Reference Id: ");
271 print_stringn (id->buf, id->len);
276 static Z_ReferenceId *set_refid (ODR out)
281 id = (Z_ReferenceId *) odr_malloc (out, sizeof(*id));
282 id->size = id->len = strlen(refid);
283 id->buf = (unsigned char *) odr_malloc (out, id->len);
284 memcpy (id->buf, refid, id->len);
288 /* INIT SERVICE ------------------------------- */
290 static void send_initRequest(const char* type_and_host)
292 Z_APDU *apdu = zget_APDU(out, Z_APDU_initRequest);
293 Z_InitRequest *req = apdu->u.initRequest;
296 req->options = &z3950_options;
298 ODR_MASK_ZERO(req->protocolVersion);
299 for (i = 0; i<z3950_version; i++)
300 ODR_MASK_SET(req->protocolVersion, i);
302 *req->maximumRecordSize = 1024*kilobytes;
303 *req->preferredMessageSize = 1024*kilobytes;
305 req->idAuthentication = auth;
307 req->referenceId = set_refid (out);
309 if (yazProxy && type_and_host)
310 yaz_oi_set_string_oidval(&req->otherInfo, out, VAL_PROXY,
313 if (negotiationCharset || yazLang) {
314 Z_OtherInformation **p;
315 Z_OtherInformationUnit *p0;
317 yaz_oi_APDU(apdu, &p);
319 if ((p0=yaz_oi_update(p, out, NULL, 0, 0))) {
320 ODR_MASK_SET(req->options, Z_Options_negotiationModel);
322 p0->which = Z_OtherInfo_externallyDefinedInfo;
323 p0->information.externallyDefinedInfo =
324 yaz_set_proposal_charneg(
326 (const char**)&negotiationCharset,
327 negotiationCharset ? 1 : 0,
328 (const char**)&yazLang, yazLang ? 1 : 0, 1);
333 printf("Sent initrequest.\n");
337 /* These two are used only from process_initResponse() */
338 static void render_initUserInfo(Z_OtherInformation *ui1);
339 static void render_diag(Z_DiagnosticFormat *diag);
341 static void pr_opt(const char *opt, void *clientData)
346 static int process_initResponse(Z_InitResponse *res)
349 /* save session parameters for later use */
350 session_mem = odr_extract_mem(in);
353 for (ver = 0; ver < 8; ver++)
354 if (!ODR_MASK_GET(res->protocolVersion, ver))
358 printf("Connection rejected by v%d target.\n", ver);
360 printf("Connection accepted by v%d target.\n", ver);
361 if (res->implementationId)
362 printf("ID : %s\n", res->implementationId);
363 if (res->implementationName)
364 printf("Name : %s\n", res->implementationName);
365 if (res->implementationVersion)
366 printf("Version: %s\n", res->implementationVersion);
367 if (res->userInformationField)
369 Z_External *uif = res->userInformationField;
370 if (uif->which == Z_External_userInfo1) {
371 render_initUserInfo(uif->u.userInfo1);
373 printf("UserInformationfield:\n");
374 if (!z_External(print, (Z_External**)&uif, 0, 0)) {
375 odr_perror(print, "Printing userinfo\n");
378 if (uif->which == Z_External_octet) {
379 printf("Guessing visiblestring:\n");
380 printf("'%s'\n", uif->u. octet_aligned->buf);
381 } else if (uif->which == Z_External_single) {
382 Odr_any *sat = uif->u.single_ASN1_type;
383 oident *oid = oid_getentbyoid(uif->direct_reference);
384 if (oid->value == VAL_OCLCUI) {
385 Z_OCLC_UserInformation *oclc_ui;
386 ODR decode = odr_createmem(ODR_DECODE);
387 odr_setbuf(decode, sat->buf, sat->len, 0);
388 if (!z_OCLC_UserInformation(decode, &oclc_ui, 0, 0))
389 printf ("Bad OCLC UserInformation:\n");
391 printf ("OCLC UserInformation:\n");
392 if (!z_OCLC_UserInformation(print, &oclc_ui, 0, 0))
393 printf ("Bad OCLC UserInformation spec\n");
398 /* Peek at any private Init-diagnostic APDUs */
399 printf("### NAUGHTY: External is '%.*s'\n", sat->len, sat->buf);
406 yaz_init_opt_decode(res->options, pr_opt, 0);
409 if (ODR_MASK_GET(res->options, Z_Options_namedResultSets))
412 if (ODR_MASK_GET(res->options, Z_Options_negotiationModel)) {
414 Z_CharSetandLanguageNegotiation *p =
415 yaz_get_charneg_record(res->otherInfo);
419 char *charset=NULL, *lang=NULL;
422 yaz_get_response_charneg(session_mem, p, &charset, &lang,
425 if (outputCharset && negotiationCharset) {
426 odr_set_charset (out, charset, outputCharset);
427 odr_set_charset (in, outputCharset, charset);
430 odr_set_charset (out, 0, 0);
431 odr_set_charset (in, 0, 0);
434 printf("Accepted character set : %s\n", charset);
435 printf("Accepted code language : %s\n", lang ? lang : "none");
436 printf("Accepted records in ...: %d\n", selected );
444 static void render_initUserInfo(Z_OtherInformation *ui1) {
446 printf("Init response contains %d otherInfo unit%s:\n",
447 ui1->num_elements, ui1->num_elements == 1 ? "" : "s");
449 for (i = 0; i < ui1->num_elements; i++) {
450 Z_OtherInformationUnit *unit = ui1->list[i];
451 printf(" %d: otherInfo unit contains ", i+1);
452 if (unit->which == Z_OtherInfo_externallyDefinedInfo &&
453 unit->information.externallyDefinedInfo->which ==
455 render_diag(unit->information.externallyDefinedInfo->u.diag1);
457 printf("unsupported otherInfo unit type %d\n", unit->which);
463 /* ### should this share code with display_diagrecs()? */
464 static void render_diag(Z_DiagnosticFormat *diag) {
467 printf("%d diagnostic%s:\n", diag->num, diag->num == 1 ? "" : "s");
468 for (i = 0; i < diag->num; i++) {
469 Z_DiagnosticFormat_s *ds = diag->elements[i];
470 printf(" %d: ", i+1);
472 case Z_DiagnosticFormat_s_defaultDiagRec: {
473 Z_DefaultDiagFormat *dd = ds->u.defaultDiagRec;
474 /* ### should check `dd->diagnosticSetId' */
475 printf("code=%d (%s)", *dd->condition,
476 diagbib1_str(*dd->condition));
477 /* Both types of addinfo are the same, so use type-pun */
478 if (dd->u.v2Addinfo != 0)
479 printf(",\n\taddinfo='%s'", dd->u.v2Addinfo);
482 case Z_DiagnosticFormat_s_explicitDiagnostic:
483 printf("Explicit diagnostic (not supported)");
486 printf("Unrecognised diagnostic type %d", ds->which);
490 if (ds->message != 0)
491 printf(", message='%s'", ds->message);
497 static int set_base(const char *arg)
502 for (i = 0; i<num_databaseNames; i++)
503 xfree (databaseNames[i]);
504 num_databaseNames = 0;
508 if (!(cp = strchr(arg, ' ')))
509 cp = arg + strlen(arg);
512 databaseNames[num_databaseNames] = (char *)xmalloc (1 + cp - arg);
513 memcpy (databaseNames[num_databaseNames], arg, cp - arg);
514 databaseNames[num_databaseNames][cp - arg] = '\0';
516 for (cp1 = databaseNames[num_databaseNames]; *cp1 ; cp1++)
525 if (num_databaseNames == 0)
527 num_databaseNames = 1;
528 databaseNames[0] = xstrdup("");
533 static int cmd_base(const char *arg)
537 printf("Usage: base <database> <database> ...\n");
540 return set_base(arg);
543 void cmd_open_remember_last_open_command(const char* arg, char* new_open_command)
545 if(last_open_command != arg)
547 if(last_open_command) xfree(last_open_command);
548 last_open_command = xstrdup(new_open_command);
552 int session_connect(const char *arg)
555 char type_and_host[101];
556 const char *basep = 0;
557 #if HAVE_OPENSSL_SSL_H
566 nmem_destroy (session_mem);
570 cs_get_host_args(arg, &basep);
572 strncpy(type_and_host, arg, sizeof(type_and_host)-1);
573 type_and_host[sizeof(type_and_host)-1] = '\0';
575 cmd_open_remember_last_open_command(arg,type_and_host);
578 conn = cs_create_host(yazProxy, 1, &add);
580 conn = cs_create_host(arg, 1, &add);
583 printf ("Couldn't create comstack\n");
588 if (conn->protocol == PROTO_HTTP)
590 printf ("SRW/HTTP not enabled in this YAZ\n");
596 protocol = conn->protocol;
597 if (conn->protocol == PROTO_HTTP)
601 printf("Connecting...");
603 if (cs_connect(conn, add) < 0)
605 printf ("error = %s\n", cs_strerror(conn));
606 if (conn->cerrno == CSYSERR)
609 yaz_strerror(msg, sizeof(msg));
610 printf ("%s\n", msg);
617 #if HAVE_OPENSSL_SSL_H
618 if ((ssl = (SSL *) cs_get_ssl(conn)))
620 X509 *server_cert = SSL_get_peer_certificate (ssl);
626 BIO *bio = BIO_new(BIO_s_mem());
628 /* get PEM buffer in memory */
629 PEM_write_bio_X509(bio, server_cert);
630 pem_len = BIO_get_mem_data(bio, &pem_buf);
631 fwrite(pem_buf, pem_len, 1, stdout);
633 /* print all info on screen .. */
634 X509_print_fp(stdout, server_cert);
637 X509_free (server_cert);
643 if (protocol == PROTO_Z3950)
645 send_initRequest(type_and_host);
651 int cmd_open(const char *arg)
655 strncpy (cur_host, arg, sizeof(cur_host)-1);
656 cur_host[sizeof(cur_host)-1] = 0;
658 return session_connect(cur_host);
665 if(!( auto_reconnect && last_open_command) ) return ;
667 open_command = (char *) xmalloc (strlen(last_open_command)+6);
668 strcpy (open_command, "open ");
670 strcat (open_command, last_open_command);
672 process_cmd_line(open_command);
677 int cmd_authentication(const char *arg)
679 static Z_IdAuthentication au;
680 static char user[40], group[40], pass[40];
681 static Z_IdPass idPass;
686 printf("Auth field set to null\n");
690 r = sscanf (arg, "%39s %39s %39s", user, group, pass);
693 printf("Authentication set to null\n");
699 if (!strcmp(user, "-")) {
700 au.which = Z_IdAuthentication_anonymous;
701 printf("Authentication set to Anonymous\n");
703 au.which = Z_IdAuthentication_open;
705 printf("Authentication set to Open (%s)\n", user);
711 au.which = Z_IdAuthentication_idPass;
712 au.u.idPass = &idPass;
713 idPass.groupId = NULL;
714 idPass.userId = user;
715 idPass.password = group;
716 printf("Authentication set to User (%s), Pass (%s)\n", user, group);
721 au.which = Z_IdAuthentication_idPass;
722 au.u.idPass = &idPass;
723 idPass.groupId = group;
724 idPass.userId = user;
725 idPass.password = pass;
726 printf("Authentication set to User (%s), Group (%s), Pass (%s)\n",
732 /* SEARCH SERVICE ------------------------------ */
733 static void display_record(Z_External *r);
735 static void print_record(const unsigned char *buf, size_t len)
738 print_stringn (buf, len);
739 /* add newline if not already added ... */
740 if (i <= 0 || buf[i-1] != '\n')
743 fwrite (buf, 1, len, marc_file);
746 static void display_record(Z_External *r)
748 oident *ent = oid_getentbyoid(r->direct_reference);
752 * Tell the user what we got.
754 if (r->direct_reference)
756 printf("Record type: ");
758 printf("%s\n", ent->desc);
759 else if (!odr_oid(print, &r->direct_reference, 0, 0))
761 odr_perror(print, "print oid");
765 /* Check if this is a known, ASN.1 type tucked away in an octet string */
766 if (ent && r->which == Z_External_octet)
768 Z_ext_typeent *type = z_ext_getentbyref(ent->value);
774 * Call the given decoder to process the record.
776 odr_setbuf(in, (char*)r->u.octet_aligned->buf,
777 r->u.octet_aligned->len, 0);
778 if (!(*type->fun)(in, &rr, 0, 0))
780 odr_perror(in, "Decoding constructed record.");
781 fprintf(stdout, "[Near %d]\n", odr_offset(in));
782 fprintf(stdout, "Packet dump:\n---------\n");
783 odr_dumpBER(stdout, (char*)r->u.octet_aligned->buf,
784 r->u.octet_aligned->len);
785 fprintf(stdout, "---------\n");
787 /* note just ignores the error ant print the bytes form the octet_aligned later */
790 * Note: we throw away the original, BER-encoded record here.
791 * Do something else with it if you want to keep it.
793 r->u.sutrs = (Z_SUTRS *) rr; /* we don't actually check the type here. */
794 r->which = type->what;
798 if (ent && ent->value == VAL_SOIF)
799 print_record((const unsigned char *) r->u.octet_aligned->buf,
800 r->u.octet_aligned->len);
801 else if (r->which == Z_External_octet)
803 const char *octet_buf = (char*)r->u.octet_aligned->buf;
804 if (ent->oclass == CLASS_RECSYN &&
805 (ent->value == VAL_TEXT_XML ||
806 ent->value == VAL_APPLICATION_XML ||
807 ent->value == VAL_HTML))
809 print_record((const unsigned char *) octet_buf,
810 r->u.octet_aligned->len);
812 else if (ent->value == VAL_POSTSCRIPT)
814 int size = r->u.octet_aligned->len;
817 print_record((const unsigned char *) octet_buf, size);
822 #if AVOID_MARC_DECODE
823 /* primitive check for a marc OID 5.1-29 except 16 */
824 ent->oidsuffix[0] == 5 && ent->oidsuffix[1] < 30 &&
825 ent->oidsuffix[1] != 16
834 yaz_marc_t mt = yaz_marc_create();
836 if (yaz_marc_decode_buf(mt, octet_buf,r->u.octet_aligned->len,
840 if (marcCharset && !strcmp(marcCharset, "auto"))
842 if (ent->value == VAL_USMARC)
844 if (octet_buf[9] == 'a')
852 else if (marcCharset)
854 if (outputCharset && from)
856 cd = yaz_iconv_open(outputCharset, from);
857 printf ("convert from %s to %s", from,
860 printf (" unsupported\n");
865 fwrite (result, 1, rlen, stdout);
869 size_t inbytesleft = rlen;
870 const char *inp = result;
874 size_t outbytesleft = sizeof(outbuf);
878 r = yaz_iconv (cd, (char**) &inp,
880 &outp, &outbytesleft);
881 if (r == (size_t) (-1))
883 int e = yaz_iconv_error(cd);
884 if (e != YAZ_ICONV_E2BIG)
887 fwrite (outbuf, outp - outbuf, 1, stdout);
893 printf ("bad MARC. Dumping as it is:\n");
894 print_record((const unsigned char*) octet_buf,
895 r->u.octet_aligned->len);
897 yaz_marc_destroy(mt);
903 print_record((const unsigned char*) octet_buf,
904 r->u.octet_aligned->len);
908 fwrite (octet_buf, 1, r->u.octet_aligned->len, marc_file);
910 else if (ent && ent->value == VAL_SUTRS)
912 if (r->which != Z_External_sutrs)
914 printf("Expecting single SUTRS type for SUTRS.\n");
917 print_record(r->u.sutrs->buf, r->u.sutrs->len);
919 else if (ent && ent->value == VAL_GRS1)
922 if (r->which != Z_External_grs1)
924 printf("Expecting single GRS type for GRS.\n");
928 yaz_display_grs1(w, r->u.grs1, 0);
932 else if ( /* OPAC display not complete yet .. */
933 ent && ent->value == VAL_OPAC)
936 if (r->u.opac->bibliographicRecord)
937 display_record(r->u.opac->bibliographicRecord);
938 for (i = 0; i<r->u.opac->num_holdingsData; i++)
940 Z_HoldingsRecord *h = r->u.opac->holdingsData[i];
941 if (h->which == Z_HoldingsRecord_marcHoldingsRecord)
943 printf ("MARC holdings %d\n", i);
944 display_record(h->u.marcHoldingsRecord);
946 else if (h->which == Z_HoldingsRecord_holdingsAndCirc)
950 Z_HoldingsAndCircData *data = h->u.holdingsAndCirc;
952 printf ("Data holdings %d\n", i);
953 if (data->typeOfRecord)
954 printf ("typeOfRecord: %s\n", data->typeOfRecord);
955 if (data->encodingLevel)
956 printf ("encodingLevel: %s\n", data->encodingLevel);
957 if (data->receiptAcqStatus)
958 printf ("receiptAcqStatus: %s\n", data->receiptAcqStatus);
959 if (data->generalRetention)
960 printf ("generalRetention: %s\n", data->generalRetention);
961 if (data->completeness)
962 printf ("completeness: %s\n", data->completeness);
963 if (data->dateOfReport)
964 printf ("dateOfReport: %s\n", data->dateOfReport);
966 printf ("nucCode: %s\n", data->nucCode);
967 if (data->localLocation)
968 printf ("localLocation: %s\n", data->localLocation);
969 if (data->shelvingLocation)
970 printf ("shelvingLocation: %s\n", data->shelvingLocation);
971 if (data->callNumber)
972 printf ("callNumber: %s\n", data->callNumber);
973 if (data->shelvingData)
974 printf ("shelvingData: %s\n", data->shelvingData);
975 if (data->copyNumber)
976 printf ("copyNumber: %s\n", data->copyNumber);
977 if (data->publicNote)
978 printf ("publicNote: %s\n", data->publicNote);
979 if (data->reproductionNote)
980 printf ("reproductionNote: %s\n", data->reproductionNote);
981 if (data->termsUseRepro)
982 printf ("termsUseRepro: %s\n", data->termsUseRepro);
983 if (data->enumAndChron)
984 printf ("enumAndChron: %s\n", data->enumAndChron);
985 for (j = 0; j<data->num_volumes; j++)
987 printf ("volume %d\n", j);
988 if (data->volumes[j]->enumeration)
989 printf (" enumeration: %s\n",
990 data->volumes[j]->enumeration);
991 if (data->volumes[j]->chronology)
992 printf (" chronology: %s\n",
993 data->volumes[j]->chronology);
994 if (data->volumes[j]->enumAndChron)
995 printf (" enumAndChron: %s\n",
996 data->volumes[j]->enumAndChron);
998 for (j = 0; j<data->num_circulationData; j++)
1000 printf ("circulation %d\n", j);
1001 if (data->circulationData[j]->availableNow)
1002 printf (" availableNow: %d\n",
1003 *data->circulationData[j]->availableNow);
1004 if (data->circulationData[j]->availablityDate)
1005 printf (" availabiltyDate: %s\n",
1006 data->circulationData[j]->availablityDate);
1007 if (data->circulationData[j]->availableThru)
1008 printf (" availableThru: %s\n",
1009 data->circulationData[j]->availableThru);
1010 if (data->circulationData[j]->restrictions)
1011 printf (" restrictions: %s\n",
1012 data->circulationData[j]->restrictions);
1013 if (data->circulationData[j]->itemId)
1014 printf (" itemId: %s\n",
1015 data->circulationData[j]->itemId);
1016 if (data->circulationData[j]->renewable)
1017 printf (" renewable: %d\n",
1018 *data->circulationData[j]->renewable);
1019 if (data->circulationData[j]->onHold)
1020 printf (" onHold: %d\n",
1021 *data->circulationData[j]->onHold);
1022 if (data->circulationData[j]->enumAndChron)
1023 printf (" enumAndChron: %s\n",
1024 data->circulationData[j]->enumAndChron);
1025 if (data->circulationData[j]->midspine)
1026 printf (" midspine: %s\n",
1027 data->circulationData[j]->midspine);
1028 if (data->circulationData[j]->temporaryLocation)
1029 printf (" temporaryLocation: %s\n",
1030 data->circulationData[j]->temporaryLocation);
1037 printf("Unknown record representation.\n");
1038 if (!z_External(print, &r, 0, 0))
1040 odr_perror(print, "Printing external");
1046 static void display_diagrecs(Z_DiagRec **pp, int num)
1050 Z_DefaultDiagFormat *r;
1052 printf("Diagnostic message(s) from database:\n");
1053 for (i = 0; i<num; i++)
1055 Z_DiagRec *p = pp[i];
1056 if (p->which != Z_DiagRec_defaultFormat)
1058 printf("Diagnostic record not in default format.\n");
1062 r = p->u.defaultFormat;
1063 if (!(ent = oid_getentbyoid(r->diagnosticSetId)) ||
1064 ent->oclass != CLASS_DIAGSET || ent->value != VAL_BIB1)
1065 printf("Missing or unknown diagset\n");
1066 printf(" [%d] %s", *r->condition, diagbib1_str(*r->condition));
1069 case Z_DefaultDiagFormat_v2Addinfo:
1070 printf (" -- v2 addinfo '%s'\n", r->u.v2Addinfo);
1072 case Z_DefaultDiagFormat_v3Addinfo:
1073 printf (" -- v3 addinfo '%s'\n", r->u.v3Addinfo);
1080 static void display_nameplusrecord(Z_NamePlusRecord *p)
1082 if (p->databaseName)
1083 printf("[%s]", p->databaseName);
1084 if (p->which == Z_NamePlusRecord_surrogateDiagnostic)
1085 display_diagrecs(&p->u.surrogateDiagnostic, 1);
1086 else if (p->which == Z_NamePlusRecord_databaseRecord)
1087 display_record(p->u.databaseRecord);
1090 static void display_records(Z_Records *p)
1094 if (p->which == Z_Records_NSD)
1096 Z_DiagRec dr, *dr_p = &dr;
1097 dr.which = Z_DiagRec_defaultFormat;
1098 dr.u.defaultFormat = p->u.nonSurrogateDiagnostic;
1099 display_diagrecs (&dr_p, 1);
1101 else if (p->which == Z_Records_multipleNSD)
1102 display_diagrecs (p->u.multipleNonSurDiagnostics->diagRecs,
1103 p->u.multipleNonSurDiagnostics->num_diagRecs);
1106 printf("Records: %d\n", p->u.databaseOrSurDiagnostics->num_records);
1107 for (i = 0; i < p->u.databaseOrSurDiagnostics->num_records; i++)
1108 display_nameplusrecord(p->u.databaseOrSurDiagnostics->records[i]);
1112 static int send_deleteResultSetRequest(const char *arg)
1117 Z_APDU *apdu = zget_APDU(out, Z_APDU_deleteResultSetRequest);
1118 Z_DeleteResultSetRequest *req = apdu->u.deleteResultSetRequest;
1120 req->referenceId = set_refid (out);
1122 req->num_resultSetList =
1123 sscanf (arg, "%30s %30s %30s %30s %30s %30s %30s %30s",
1124 names[0], names[1], names[2], names[3],
1125 names[4], names[5], names[6], names[7]);
1127 req->deleteFunction = (int *)
1128 odr_malloc (out, sizeof(*req->deleteFunction));
1129 if (req->num_resultSetList > 0)
1131 *req->deleteFunction = Z_DeleteResultSetRequest_list;
1132 req->resultSetList = (char **)
1133 odr_malloc (out, sizeof(*req->resultSetList)*
1134 req->num_resultSetList);
1135 for (i = 0; i<req->num_resultSetList; i++)
1136 req->resultSetList[i] = names[i];
1140 *req->deleteFunction = Z_DeleteResultSetRequest_all;
1141 req->resultSetList = 0;
1145 printf("Sent deleteResultSetRequest.\n");
1150 static int send_srw(Z_SRW_PDU *sr)
1152 const char *charset = negotiationCharset;
1153 const char *host_port = cur_host;
1156 Z_SOAP_Handler h[2] = {
1157 {"http://www.loc.gov/zing/srw/", 0, (Z_SOAP_fun) yaz_srw_codec},
1160 ODR o = odr_createmem(ODR_ENCODE);
1162 Z_SOAP *p = odr_malloc(o, sizeof(*p));
1165 path = odr_malloc(out, strlen(databaseNames[0])+2);
1167 strcpy(path+1, databaseNames[0]);
1169 gdu = z_get_HTTP_Request(out);
1170 gdu->u.HTTP_Request->version = http_version;
1171 gdu->u.HTTP_Request->path = odr_strdup(out, path);
1175 const char *cp0 = strstr(host_port, "://");
1176 const char *cp1 = 0;
1182 cp1 = strchr(cp0, '/');
1184 cp1 = cp0+strlen(cp0);
1188 char *h = odr_malloc(out, cp1 - cp0 + 1);
1189 memcpy (h, cp0, cp1 - cp0);
1191 z_HTTP_header_add(out, &gdu->u.HTTP_Request->headers,
1196 strcpy(ctype, "text/xml");
1197 if (charset && strlen(charset) < 20)
1199 strcat(ctype, "; charset=");
1200 strcat(ctype, charset);
1202 z_HTTP_header_add(out, &gdu->u.HTTP_Request->headers,
1203 "Content-Type", ctype);
1204 z_HTTP_header_add(out, &gdu->u.HTTP_Request->headers,
1205 "SOAPAction", "\"\"");
1206 p->which = Z_SOAP_generic;
1207 p->u.generic = odr_malloc(o, sizeof(*p->u.generic));
1208 p->u.generic->no = 0;
1209 p->u.generic->ns = 0;
1210 p->u.generic->p = sr;
1211 p->ns = "http://schemas.xmlsoap.org/soap/envelope/";
1213 ret = z_soap_codec_enc(o, &p,
1214 &gdu->u.HTTP_Request->content_buf,
1215 &gdu->u.HTTP_Request->content_len, h,
1218 if (z_GDU(out, &gdu, 0, 0))
1226 if (!z_GDU(print, &gdu, 0, 0))
1227 printf ("Failed to print outgoing APDU\n");
1230 buf_out = odr_getbuf(out, &len_out, 0);
1232 /* we don't odr_reset(out), since we may need the buffer again */
1234 do_hex_dump(buf_out, len_out);
1236 r = cs_put(conn, buf_out, len_out);
1248 static int send_SRW_searchRequest(const char *arg)
1254 assert(srw_sr_odr_out == 0);
1255 srw_sr_odr_out = odr_createmem(ODR_ENCODE);
1257 odr_reset(srw_sr_odr_out);
1261 /* save this for later .. when fetching individual records */
1262 srw_sr = sr = yaz_srw_get(srw_sr_odr_out, Z_SRW_searchRetrieve_request);
1263 sr->u.request->query_type = Z_SRW_query_type_cql;
1264 sr->u.request->query.cql = odr_strdup(srw_sr_odr_out, arg);
1266 sr = yaz_srw_get(out, Z_SRW_searchRetrieve_request);
1267 sr->u.request->query_type = Z_SRW_query_type_cql;
1268 sr->u.request->query.cql = odr_strdup(out, arg);
1270 sr->u.request->maximumRecords = odr_intdup(out, 0);
1273 sr->u.request->recordSchema = record_schema;
1274 if (recordsyntax == VAL_TEXT_XML)
1275 sr->u.explain_request->recordPacking = "xml";
1276 return send_srw(sr);
1280 static int send_searchRequest(const char *arg)
1282 Z_APDU *apdu = zget_APDU(out, Z_APDU_searchRequest);
1283 Z_SearchRequest *req = apdu->u.searchRequest;
1285 struct ccl_rpn_node *rpn = NULL;
1287 char setstring[100];
1288 Z_RPNQuery *RPNquery;
1290 YAZ_PQF_Parser pqf_parser;
1292 QueryType myQueryType = queryType;
1295 if (myQueryType == QueryType_CCL2RPN)
1297 rpn = ccl_find_str(bibset, arg, &error, &pos);
1300 printf("CCL ERROR: %s\n", ccl_err_msg(error));
1303 } else if (myQueryType == QueryType_CQL2RPN) {
1304 /* ### All this code should be wrapped in a utility function */
1306 struct cql_node *node;
1307 const char *addinfo;
1308 if (cqltrans == 0) {
1309 printf("Can't use CQL: no translation file. Try set_cqlfile\n");
1312 parser = cql_parser_create();
1313 if ((error = cql_parser_string(parser, arg)) != 0) {
1314 printf("Can't parse CQL: must be a syntax error\n");
1317 node = cql_parser_result(parser);
1318 if ((error = cql_transform_buf(cqltrans, node, pqfbuf,
1319 sizeof pqfbuf)) != 0) {
1320 error = cql_transform_error(cqltrans, &addinfo);
1321 printf ("Can't convert CQL to PQF: %s (addinfo=%s)\n",
1322 cql_strerror(error), addinfo);
1326 myQueryType = QueryType_Prefix;
1329 req->referenceId = set_refid (out);
1330 if (!strcmp(arg, "@big")) /* strictly for troublemaking */
1332 static unsigned char big[2100];
1333 static Odr_oct bigo;
1335 /* send a very big referenceid to test transport stack etc. */
1336 memset(big, 'A', 2100);
1337 bigo.len = bigo.size = 2100;
1339 req->referenceId = &bigo;
1344 sprintf(setstring, "%d", ++setnumber);
1345 req->resultSetName = setstring;
1347 *req->smallSetUpperBound = smallSetUpperBound;
1348 *req->largeSetLowerBound = largeSetLowerBound;
1349 *req->mediumSetPresentNumber = mediumSetPresentNumber;
1350 if (smallSetUpperBound > 0 || (largeSetLowerBound > 1 &&
1351 mediumSetPresentNumber > 0))
1353 req->preferredRecordSyntax =
1354 yaz_oidval_to_z3950oid(out, CLASS_RECSYN, recordsyntax);
1356 req->smallSetElementSetNames =
1357 req->mediumSetElementSetNames = elementSetNames;
1359 req->num_databaseNames = num_databaseNames;
1360 req->databaseNames = databaseNames;
1362 req->query = &query;
1364 switch (myQueryType)
1366 case QueryType_Prefix:
1367 query.which = Z_Query_type_1;
1368 pqf_parser = yaz_pqf_create ();
1369 RPNquery = yaz_pqf_parse (pqf_parser, out, arg);
1372 const char *pqf_msg;
1374 int code = yaz_pqf_error (pqf_parser, &pqf_msg, &off);
1375 printf("%*s^\n", off+4, "");
1376 printf("Prefix query error: %s (code %d)\n", pqf_msg, code);
1378 yaz_pqf_destroy (pqf_parser);
1381 yaz_pqf_destroy (pqf_parser);
1382 query.u.type_1 = RPNquery;
1385 query.which = Z_Query_type_2;
1386 query.u.type_2 = &ccl_query;
1387 ccl_query.buf = (unsigned char*) arg;
1388 ccl_query.len = strlen(arg);
1390 case QueryType_CCL2RPN:
1391 query.which = Z_Query_type_1;
1392 RPNquery = ccl_rpn_query(out, rpn);
1395 printf ("Couldn't convert from CCL to RPN\n");
1398 query.u.type_1 = RPNquery;
1399 ccl_rpn_delete (rpn);
1402 query.which = Z_Query_type_104;
1403 ext = (Z_External *) odr_malloc(out, sizeof(*ext));
1404 ext->direct_reference = odr_getoidbystr(out, "1.2.840.10003.16.2");
1405 ext->indirect_reference = 0;
1406 ext->descriptor = 0;
1407 ext->which = Z_External_CQL;
1408 ext->u.cql = odr_strdup(out, arg);
1409 query.u.type_104 = ext;
1412 printf ("Unsupported query type\n");
1415 if (send_apdu(apdu))
1416 printf("Sent searchRequest.\n");
1421 /* display Query Expression as part of searchResult-1 */
1422 static void display_queryExpression (Z_QueryExpression *qe)
1426 if (qe->which == Z_QueryExpression_term)
1428 if (qe->u.term->queryTerm)
1430 Z_Term *term = qe->u.term->queryTerm;
1431 switch (term->which)
1433 case Z_Term_general:
1434 printf (" %.*s", term->u.general->len, term->u.general->buf);
1436 case Z_Term_characterString:
1437 printf (" %s", term->u.characterString);
1439 case Z_Term_numeric:
1440 printf (" %d", *term->u.numeric);
1450 /* see if we can find USR:SearchResult-1 */
1451 static void display_searchResult (Z_OtherInformation *o)
1456 for (i = 0; i < o->num_elements; i++)
1458 if (o->list[i]->which == Z_OtherInfo_externallyDefinedInfo)
1460 Z_External *ext = o->list[i]->information.externallyDefinedInfo;
1462 if (ext->which == Z_External_searchResult1)
1465 Z_SearchInfoReport *sr = ext->u.searchResult1;
1466 printf ("SearchResult-1:");
1467 for (j = 0; j < sr->num; j++)
1469 if (!sr->elements[j]->subqueryExpression)
1471 display_queryExpression (
1472 sr->elements[j]->subqueryExpression);
1473 display_queryExpression (
1474 sr->elements[j]->subqueryInterpretation);
1475 display_queryExpression (
1476 sr->elements[j]->subqueryRecommendation);
1477 if (sr->elements[j]->subqueryCount)
1478 printf ("(%d)", *sr->elements[j]->subqueryCount);
1486 static int process_searchResponse(Z_SearchResponse *res)
1488 printf ("Received SearchResponse.\n");
1489 print_refid (res->referenceId);
1490 if (*res->searchStatus)
1491 printf("Search was a success.\n");
1493 printf("Search was a bloomin' failure.\n");
1494 printf("Number of hits: %d", *res->resultCount);
1496 printf (", setno %d", setnumber);
1498 display_searchResult (res->additionalSearchInfo);
1499 printf("records returned: %d\n",
1500 *res->numberOfRecordsReturned);
1501 setno += *res->numberOfRecordsReturned;
1503 display_records(res->records);
1507 static void print_level(int iLevel)
1510 for (i = 0; i < iLevel * 4; i++)
1514 static void print_int(int iLevel, const char *pTag, int *pInt)
1518 print_level(iLevel);
1519 printf("%s: %d\n", pTag, *pInt);
1523 static void print_string(int iLevel, const char *pTag, const char *pString)
1525 if (pString != NULL)
1527 print_level(iLevel);
1528 printf("%s: %s\n", pTag, pString);
1532 static void print_oid(int iLevel, const char *pTag, Odr_oid *pOid)
1538 print_level(iLevel);
1539 printf("%s:", pTag);
1540 for (; *pInt != -1; pInt++)
1541 printf(" %d", *pInt);
1546 static void print_referenceId(int iLevel, Z_ReferenceId *referenceId)
1548 if (referenceId != NULL)
1552 print_level(iLevel);
1553 printf("Ref Id (%d, %d): ", referenceId->len, referenceId->size);
1554 for (i = 0; i < referenceId->len; i++)
1555 printf("%c", referenceId->buf[i]);
1560 static void print_string_or_numeric(int iLevel, const char *pTag, Z_StringOrNumeric *pStringNumeric)
1562 if (pStringNumeric != NULL)
1564 switch (pStringNumeric->which)
1566 case Z_StringOrNumeric_string:
1567 print_string(iLevel, pTag, pStringNumeric->u.string);
1570 case Z_StringOrNumeric_numeric:
1571 print_int(iLevel, pTag, pStringNumeric->u.numeric);
1575 print_level(iLevel);
1576 printf("%s: valid type for Z_StringOrNumeric\n", pTag);
1582 static void print_universe_report_duplicate(
1584 Z_UniverseReportDuplicate *pUniverseReportDuplicate)
1586 if (pUniverseReportDuplicate != NULL)
1588 print_level(iLevel);
1589 printf("Universe Report Duplicate: \n");
1591 print_string_or_numeric(iLevel, "Hit No",
1592 pUniverseReportDuplicate->hitno);
1596 static void print_universe_report_hits(
1598 Z_UniverseReportHits *pUniverseReportHits)
1600 if (pUniverseReportHits != NULL)
1602 print_level(iLevel);
1603 printf("Universe Report Hits: \n");
1605 print_string_or_numeric(iLevel, "Database",
1606 pUniverseReportHits->database);
1607 print_string_or_numeric(iLevel, "Hits", pUniverseReportHits->hits);
1611 static void print_universe_report(int iLevel, Z_UniverseReport *pUniverseReport)
1613 if (pUniverseReport != NULL)
1615 print_level(iLevel);
1616 printf("Universe Report: \n");
1618 print_int(iLevel, "Total Hits", pUniverseReport->totalHits);
1619 switch (pUniverseReport->which)
1621 case Z_UniverseReport_databaseHits:
1622 print_universe_report_hits(iLevel,
1623 pUniverseReport->u.databaseHits);
1626 case Z_UniverseReport_duplicate:
1627 print_universe_report_duplicate(iLevel,
1628 pUniverseReport->u.duplicate);
1632 print_level(iLevel);
1633 printf("Type: %d\n", pUniverseReport->which);
1639 static void print_external(int iLevel, Z_External *pExternal)
1641 if (pExternal != NULL)
1643 print_level(iLevel);
1644 printf("External: \n");
1646 print_oid(iLevel, "Direct Reference", pExternal->direct_reference);
1647 print_int(iLevel, "InDirect Reference", pExternal->indirect_reference);
1648 print_string(iLevel, "Descriptor", pExternal->descriptor);
1649 switch (pExternal->which)
1651 case Z_External_universeReport:
1652 print_universe_report(iLevel, pExternal->u.universeReport);
1656 print_level(iLevel);
1657 printf("Type: %d\n", pExternal->which);
1663 static int process_resourceControlRequest (Z_ResourceControlRequest *req)
1665 printf ("Received ResourceControlRequest.\n");
1666 print_referenceId(1, req->referenceId);
1667 print_int(1, "Suspended Flag", req->suspendedFlag);
1668 print_int(1, "Partial Results Available", req->partialResultsAvailable);
1669 print_int(1, "Response Required", req->responseRequired);
1670 print_int(1, "Triggered Request Flag", req->triggeredRequestFlag);
1671 print_external(1, req->resourceReport);
1675 void process_ESResponse(Z_ExtendedServicesResponse *res)
1678 switch (*res->operationStatus)
1680 case Z_ExtendedServicesResponse_done:
1683 case Z_ExtendedServicesResponse_accepted:
1684 printf ("accepted\n");
1686 case Z_ExtendedServicesResponse_failure:
1687 printf ("failure\n");
1688 display_diagrecs(res->diagnostics, res->num_diagnostics);
1691 printf ("unknown\n");
1693 if ( (*res->operationStatus != Z_ExtendedServicesResponse_failure) &&
1694 (res->num_diagnostics != 0) ) {
1695 display_diagrecs(res->diagnostics, res->num_diagnostics);
1697 print_refid (res->referenceId);
1698 if (res->taskPackage &&
1699 res->taskPackage->which == Z_External_extendedService)
1701 Z_TaskPackage *taskPackage = res->taskPackage->u.extendedService;
1702 Odr_oct *id = taskPackage->targetReference;
1703 Z_External *ext = taskPackage->taskSpecificParameters;
1707 printf ("Target Reference: ");
1708 print_stringn (id->buf, id->len);
1711 if (ext->which == Z_External_update)
1713 Z_IUUpdateTaskPackage *utp = ext->u.update->u.taskPackage;
1714 if (utp && utp->targetPart)
1716 Z_IUTargetPart *targetPart = utp->targetPart;
1719 for (i = 0; i<targetPart->num_taskPackageRecords; i++)
1722 Z_IUTaskPackageRecordStructure *tpr =
1723 targetPart->taskPackageRecords[i];
1724 printf ("task package record %d\n", i+1);
1725 if (tpr->which == Z_IUTaskPackageRecordStructure_record)
1727 display_record (tpr->u.record);
1731 printf ("other type\n");
1739 const char *get_ill_element (void *clientData, const char *element)
1744 static Z_External *create_external_itemRequest()
1746 struct ill_get_ctl ctl;
1747 ILL_ItemRequest *req;
1749 int item_request_size = 0;
1750 char *item_request_buf = 0;
1754 ctl.f = get_ill_element;
1756 req = ill_get_ItemRequest(&ctl, "ill", 0);
1758 printf ("ill_get_ItemRequest failed\n");
1760 if (!ill_ItemRequest (out, &req, 0, 0))
1764 ill_ItemRequest(print, &req, 0, 0);
1767 item_request_buf = odr_getbuf (out, &item_request_size, 0);
1768 if (item_request_buf)
1769 odr_setbuf (out, item_request_buf, item_request_size, 1);
1770 printf ("Couldn't encode ItemRequest, size %d\n", item_request_size);
1777 item_request_buf = odr_getbuf (out, &item_request_size, 0);
1778 oid.proto = PROTO_GENERAL;
1779 oid.oclass = CLASS_GENERAL;
1780 oid.value = VAL_ISO_ILL_1;
1782 r = (Z_External *) odr_malloc (out, sizeof(*r));
1783 r->direct_reference = odr_oiddup(out,oid_getoidbyent(&oid));
1784 r->indirect_reference = 0;
1786 r->which = Z_External_single;
1788 r->u.single_ASN1_type = (Odr_oct *)
1789 odr_malloc (out, sizeof(*r->u.single_ASN1_type));
1790 r->u.single_ASN1_type->buf = (unsigned char *)
1791 odr_malloc (out, item_request_size);
1792 r->u.single_ASN1_type->len = item_request_size;
1793 r->u.single_ASN1_type->size = item_request_size;
1794 memcpy (r->u.single_ASN1_type->buf, item_request_buf,
1797 do_hex_dump(item_request_buf,item_request_size);
1802 static Z_External *create_external_ILL_APDU(int which)
1804 struct ill_get_ctl ctl;
1807 int ill_request_size = 0;
1808 char *ill_request_buf = 0;
1812 ctl.f = get_ill_element;
1814 ill_apdu = ill_get_APDU(&ctl, "ill", 0);
1816 if (!ill_APDU (out, &ill_apdu, 0, 0))
1820 printf ("-------------------\n");
1821 ill_APDU(print, &ill_apdu, 0, 0);
1823 printf ("-------------------\n");
1825 ill_request_buf = odr_getbuf (out, &ill_request_size, 0);
1826 if (ill_request_buf)
1827 odr_setbuf (out, ill_request_buf, ill_request_size, 1);
1828 printf ("Couldn't encode ILL-Request, size %d\n", ill_request_size);
1834 ill_request_buf = odr_getbuf (out, &ill_request_size, 0);
1836 oid.proto = PROTO_GENERAL;
1837 oid.oclass = CLASS_GENERAL;
1838 oid.value = VAL_ISO_ILL_1;
1840 r = (Z_External *) odr_malloc (out, sizeof(*r));
1841 r->direct_reference = odr_oiddup(out,oid_getoidbyent(&oid));
1842 r->indirect_reference = 0;
1844 r->which = Z_External_single;
1846 r->u.single_ASN1_type = (Odr_oct *)
1847 odr_malloc (out, sizeof(*r->u.single_ASN1_type));
1848 r->u.single_ASN1_type->buf = (unsigned char *)
1849 odr_malloc (out, ill_request_size);
1850 r->u.single_ASN1_type->len = ill_request_size;
1851 r->u.single_ASN1_type->size = ill_request_size;
1852 memcpy (r->u.single_ASN1_type->buf, ill_request_buf, ill_request_size);
1853 /* printf ("len = %d\n", ill_request_size); */
1854 /* do_hex_dump(ill_request_buf,ill_request_size); */
1855 /* printf("--- end of extenal\n"); */
1862 static Z_External *create_ItemOrderExternal(const char *type, int itemno)
1864 Z_External *r = (Z_External *) odr_malloc(out, sizeof(Z_External));
1865 oident ItemOrderRequest;
1867 ItemOrderRequest.proto = PROTO_Z3950;
1868 ItemOrderRequest.oclass = CLASS_EXTSERV;
1869 ItemOrderRequest.value = VAL_ITEMORDER;
1871 r->direct_reference = odr_oiddup(out,oid_getoidbyent(&ItemOrderRequest));
1872 r->indirect_reference = 0;
1875 r->which = Z_External_itemOrder;
1877 r->u.itemOrder = (Z_ItemOrder *) odr_malloc(out,sizeof(Z_ItemOrder));
1878 memset(r->u.itemOrder, 0, sizeof(Z_ItemOrder));
1879 r->u.itemOrder->which=Z_IOItemOrder_esRequest;
1881 r->u.itemOrder->u.esRequest = (Z_IORequest *)
1882 odr_malloc(out,sizeof(Z_IORequest));
1883 memset(r->u.itemOrder->u.esRequest, 0, sizeof(Z_IORequest));
1885 r->u.itemOrder->u.esRequest->toKeep = (Z_IOOriginPartToKeep *)
1886 odr_malloc(out,sizeof(Z_IOOriginPartToKeep));
1887 memset(r->u.itemOrder->u.esRequest->toKeep, 0, sizeof(Z_IOOriginPartToKeep));
1888 r->u.itemOrder->u.esRequest->notToKeep = (Z_IOOriginPartNotToKeep *)
1889 odr_malloc(out,sizeof(Z_IOOriginPartNotToKeep));
1890 memset(r->u.itemOrder->u.esRequest->notToKeep, 0, sizeof(Z_IOOriginPartNotToKeep));
1892 r->u.itemOrder->u.esRequest->toKeep->supplDescription = NULL;
1893 r->u.itemOrder->u.esRequest->toKeep->contact = NULL;
1894 r->u.itemOrder->u.esRequest->toKeep->addlBilling = NULL;
1896 r->u.itemOrder->u.esRequest->notToKeep->resultSetItem =
1897 (Z_IOResultSetItem *) odr_malloc(out, sizeof(Z_IOResultSetItem));
1898 memset(r->u.itemOrder->u.esRequest->notToKeep->resultSetItem, 0, sizeof(Z_IOResultSetItem));
1899 r->u.itemOrder->u.esRequest->notToKeep->resultSetItem->resultSetId = "1";
1901 r->u.itemOrder->u.esRequest->notToKeep->resultSetItem->item =
1902 (int *) odr_malloc(out, sizeof(int));
1903 *r->u.itemOrder->u.esRequest->notToKeep->resultSetItem->item = itemno;
1905 if (!strcmp (type, "item") || !strcmp(type, "2"))
1907 printf ("using item-request\n");
1908 r->u.itemOrder->u.esRequest->notToKeep->itemRequest =
1909 create_external_itemRequest();
1911 else if (!strcmp(type, "ill") || !strcmp(type, "1"))
1913 printf ("using ILL-request\n");
1914 r->u.itemOrder->u.esRequest->notToKeep->itemRequest =
1915 create_external_ILL_APDU(ILL_APDU_ILL_Request);
1917 else if (!strcmp(type, "xml") || !strcmp(type, "3"))
1919 const char *xml_buf =
1921 " <type>request</type>\n"
1922 " <libraryNo>000200</libraryNo>\n"
1923 " <borrowerTicketNo> 1212 </borrowerTicketNo>\n"
1925 r->u.itemOrder->u.esRequest->notToKeep->itemRequest =
1926 z_ext_record (out, VAL_TEXT_XML, xml_buf, strlen(xml_buf));
1929 r->u.itemOrder->u.esRequest->notToKeep->itemRequest = 0;
1934 static int send_itemorder(const char *type, int itemno)
1936 Z_APDU *apdu = zget_APDU(out, Z_APDU_extendedServicesRequest);
1937 Z_ExtendedServicesRequest *req = apdu->u.extendedServicesRequest;
1938 oident ItemOrderRequest;
1940 ItemOrderRequest.proto = PROTO_Z3950;
1941 ItemOrderRequest.oclass = CLASS_EXTSERV;
1942 ItemOrderRequest.value = VAL_ITEMORDER;
1943 req->packageType = odr_oiddup(out,oid_getoidbyent(&ItemOrderRequest));
1944 req->packageName = esPackageName;
1946 req->taskSpecificParameters = create_ItemOrderExternal(type, itemno);
1952 static int only_z3950()
1954 if (protocol == PROTO_HTTP)
1956 printf ("Not supported by SRW\n");
1962 static int cmd_update_common(const char *arg, int version);
1964 static int cmd_update(const char *arg)
1966 return cmd_update_common(arg, 1);
1969 static int cmd_update0(const char *arg)
1971 return cmd_update_common(arg, 0);
1974 static int cmd_update_common(const char *arg, int version)
1976 Z_APDU *apdu = zget_APDU(out, Z_APDU_extendedServicesRequest );
1977 Z_ExtendedServicesRequest *req = apdu->u.extendedServicesRequest;
1979 char action[20], recid[20], fname[80];
1981 Z_External *record_this = 0;
1988 sscanf (arg, "%19s %19s %79s", action, recid, fname);
1990 if (!strcmp (action, "insert"))
1991 action_no = Z_IUOriginPartToKeep_recordInsert;
1992 else if (!strcmp (action, "replace"))
1993 action_no = Z_IUOriginPartToKeep_recordReplace;
1994 else if (!strcmp (action, "delete"))
1995 action_no = Z_IUOriginPartToKeep_recordDelete;
1996 else if (!strcmp (action, "update"))
1997 action_no = Z_IUOriginPartToKeep_specialUpdate;
2000 printf ("Bad action: %s\n", action);
2001 printf ("Possible values: insert, replace, delete, update\n");
2009 stat (fname, &status);
2010 if (S_ISREG(status.st_mode) && (inf = fopen(fname, "r")))
2012 size_t len = status.st_size;
2013 char *buf = (char *) xmalloc (len);
2015 fread (buf, 1, len, inf);
2019 record_this = z_ext_record (out, VAL_TEXT_XML, buf, len);
2025 printf ("File %s doesn't exist\n", fname);
2033 printf ("No last record (update ignored)\n");
2036 record_this = record_last;
2040 yaz_oidval_to_z3950oid(out, CLASS_EXTSERV,
2041 version == 0 ? VAL_DBUPDATE0 : VAL_DBUPDATE);
2043 req->packageName = esPackageName;
2045 req->referenceId = set_refid (out);
2047 r = req->taskSpecificParameters = (Z_External *)
2048 odr_malloc (out, sizeof(*r));
2049 r->direct_reference = req->packageType;
2050 r->indirect_reference = 0;
2054 Z_IU0OriginPartToKeep *toKeep;
2055 Z_IU0SuppliedRecords *notToKeep;
2057 r->which = Z_External_update0;
2058 r->u.update0 = (Z_IU0Update *) odr_malloc(out, sizeof(*r->u.update0));
2059 r->u.update0->which = Z_IUUpdate_esRequest;
2060 r->u.update0->u.esRequest = (Z_IU0UpdateEsRequest *)
2061 odr_malloc(out, sizeof(*r->u.update0->u.esRequest));
2062 toKeep = r->u.update0->u.esRequest->toKeep = (Z_IU0OriginPartToKeep *)
2063 odr_malloc(out, sizeof(*r->u.update0->u.esRequest->toKeep));
2065 toKeep->databaseName = databaseNames[0];
2067 toKeep->elementSetName = 0;
2069 toKeep->action = (int *) odr_malloc(out, sizeof(*toKeep->action));
2070 *toKeep->action = action_no;
2072 notToKeep = r->u.update0->u.esRequest->notToKeep = (Z_IU0SuppliedRecords *)
2073 odr_malloc(out, sizeof(*r->u.update0->u.esRequest->notToKeep));
2075 notToKeep->elements = (Z_IU0SuppliedRecords_elem **)
2076 odr_malloc(out, sizeof(*notToKeep->elements));
2077 notToKeep->elements[0] = (Z_IU0SuppliedRecords_elem *)
2078 odr_malloc(out, sizeof(**notToKeep->elements));
2079 notToKeep->elements[0]->which = Z_IUSuppliedRecords_elem_opaque;
2082 notToKeep->elements[0]->u.opaque = (Odr_oct *)
2083 odr_malloc (out, sizeof(Odr_oct));
2084 notToKeep->elements[0]->u.opaque->buf = (unsigned char *) recid;
2085 notToKeep->elements[0]->u.opaque->size = strlen(recid);
2086 notToKeep->elements[0]->u.opaque->len = strlen(recid);
2089 notToKeep->elements[0]->u.opaque = 0;
2090 notToKeep->elements[0]->supplementalId = 0;
2091 notToKeep->elements[0]->correlationInfo = 0;
2092 notToKeep->elements[0]->record = record_this;
2096 Z_IUOriginPartToKeep *toKeep;
2097 Z_IUSuppliedRecords *notToKeep;
2099 r->which = Z_External_update;
2100 r->u.update = (Z_IUUpdate *) odr_malloc(out, sizeof(*r->u.update));
2101 r->u.update->which = Z_IUUpdate_esRequest;
2102 r->u.update->u.esRequest = (Z_IUUpdateEsRequest *)
2103 odr_malloc(out, sizeof(*r->u.update->u.esRequest));
2104 toKeep = r->u.update->u.esRequest->toKeep = (Z_IUOriginPartToKeep *)
2105 odr_malloc(out, sizeof(*r->u.update->u.esRequest->toKeep));
2107 toKeep->databaseName = databaseNames[0];
2109 toKeep->elementSetName = 0;
2110 toKeep->actionQualifier = 0;
2111 toKeep->action = (int *) odr_malloc(out, sizeof(*toKeep->action));
2112 *toKeep->action = action_no;
2114 notToKeep = r->u.update->u.esRequest->notToKeep = (Z_IUSuppliedRecords *)
2115 odr_malloc(out, sizeof(*r->u.update->u.esRequest->notToKeep));
2117 notToKeep->elements = (Z_IUSuppliedRecords_elem **)
2118 odr_malloc(out, sizeof(*notToKeep->elements));
2119 notToKeep->elements[0] = (Z_IUSuppliedRecords_elem *)
2120 odr_malloc(out, sizeof(**notToKeep->elements));
2121 notToKeep->elements[0]->which = Z_IUSuppliedRecords_elem_opaque;
2124 notToKeep->elements[0]->u.opaque = (Odr_oct *)
2125 odr_malloc (out, sizeof(Odr_oct));
2126 notToKeep->elements[0]->u.opaque->buf = (unsigned char *) recid;
2127 notToKeep->elements[0]->u.opaque->size = strlen(recid);
2128 notToKeep->elements[0]->u.opaque->len = strlen(recid);
2131 notToKeep->elements[0]->u.opaque = 0;
2132 notToKeep->elements[0]->supplementalId = 0;
2133 notToKeep->elements[0]->correlationInfo = 0;
2134 notToKeep->elements[0]->record = record_this;
2142 static int cmd_itemorder(const char *arg)
2149 if (sscanf (arg, "%10s %d", type, &itemno) != 2)
2152 printf("Item order request\n");
2154 send_itemorder(type, itemno);
2158 static void show_opt(const char *arg, void *clientData)
2160 printf ("%s ", arg);
2163 static int cmd_zversion(const char *arg)
2166 z3950_version = atoi(arg);
2168 printf ("version is %d\n", z3950_version);
2172 static int cmd_options(const char *arg)
2178 r = yaz_init_opt_encode(&z3950_options, arg, &pos);
2182 yaz_init_opt_decode(&z3950_options, show_opt, 0);
2188 static int cmd_explain(const char *arg)
2190 if (protocol != PROTO_HTTP)
2201 /* save this for later .. when fetching individual records */
2202 sr = yaz_srw_get(out, Z_SRW_explain_request);
2203 if (recordsyntax == VAL_TEXT_XML)
2204 sr->u.explain_request->recordPacking = "xml";
2212 static int cmd_init(const char *arg)
2214 if (!conn || protocol != PROTO_Z3950)
2216 send_initRequest(0);
2220 static int cmd_find(const char *arg)
2224 printf("Find what?\n");
2227 if (protocol == PROTO_HTTP)
2234 if (!send_SRW_searchRequest(arg))
2247 printf("Not connected yet\n");
2251 if (!send_searchRequest(arg))
2257 static int cmd_delete(const char *arg)
2261 printf("Not connected yet\n");
2266 if (!send_deleteResultSetRequest(arg))
2271 static int cmd_ssub(const char *arg)
2273 if (!(smallSetUpperBound = atoi(arg)))
2278 static int cmd_lslb(const char *arg)
2282 if (!(largeSetLowerBound = atoi(arg)))
2287 static int cmd_mspn(const char *arg)
2291 if (!(mediumSetPresentNumber = atoi(arg)))
2296 static int cmd_status(const char *arg)
2298 printf("smallSetUpperBound: %d\n", smallSetUpperBound);
2299 printf("largeSetLowerBound: %d\n", largeSetLowerBound);
2300 printf("mediumSetPresentNumber: %d\n", mediumSetPresentNumber);
2304 static int cmd_setnames(const char *arg)
2306 if (*arg == '1') /* enable ? */
2308 else if (*arg == '0') /* disable ? */
2310 else if (setnumber < 0) /* no args, toggle .. */
2316 printf("Set numbering enabled.\n");
2318 printf("Set numbering disabled.\n");
2322 /* PRESENT SERVICE ----------------------------- */
2324 static void parse_show_args(const char *arg_c, char *setstring,
2325 int *start, int *number)
2330 strncpy(arg, arg_c, sizeof(arg)-1);
2331 arg[sizeof(arg)-1] = '\0';
2333 if ((p = strchr(arg, '+')))
2335 *number = atoi(p + 1);
2340 if (p && (p=strchr(p+1, '+')))
2341 strcpy (setstring, p+1);
2342 else if (setnumber >= 0)
2343 sprintf(setstring, "%d", setnumber);
2348 static int send_presentRequest(const char *arg)
2350 Z_APDU *apdu = zget_APDU(out, Z_APDU_presentRequest);
2351 Z_PresentRequest *req = apdu->u.presentRequest;
2352 Z_RecordComposition compo;
2354 char setstring[100];
2356 req->referenceId = set_refid (out);
2358 parse_show_args(arg, setstring, &setno, &nos);
2360 req->resultSetId = setstring;
2362 req->resultSetStartPoint = &setno;
2363 req->numberOfRecordsRequested = &nos;
2365 req->preferredRecordSyntax =
2366 yaz_oidval_to_z3950oid(out, CLASS_RECSYN, recordsyntax);
2370 req->recordComposition = &compo;
2371 compo.which = Z_RecordComp_complex;
2372 compo.u.complex = (Z_CompSpec *)
2373 odr_malloc(out, sizeof(*compo.u.complex));
2374 compo.u.complex->selectAlternativeSyntax = (bool_t *)
2375 odr_malloc(out, sizeof(bool_t));
2376 *compo.u.complex->selectAlternativeSyntax = 0;
2378 compo.u.complex->generic = (Z_Specification *)
2379 odr_malloc(out, sizeof(*compo.u.complex->generic));
2380 compo.u.complex->generic->which = Z_Schema_oid;
2382 compo.u.complex->generic->schema.oid =
2383 yaz_str_to_z3950oid(out, CLASS_SCHEMA, record_schema);
2385 if (!compo.u.complex->generic->schema.oid)
2387 /* OID wasn't a schema! Try record syntax instead. */
2388 compo.u.complex->generic->schema.oid = (Odr_oid *)
2389 yaz_str_to_z3950oid(out, CLASS_RECSYN, record_schema);
2391 if (!elementSetNames)
2392 compo.u.complex->generic->elementSpec = 0;
2395 compo.u.complex->generic->elementSpec = (Z_ElementSpec *)
2396 odr_malloc(out, sizeof(Z_ElementSpec));
2397 compo.u.complex->generic->elementSpec->which =
2398 Z_ElementSpec_elementSetName;
2399 compo.u.complex->generic->elementSpec->u.elementSetName =
2400 elementSetNames->u.generic;
2402 compo.u.complex->num_dbSpecific = 0;
2403 compo.u.complex->dbSpecific = 0;
2404 compo.u.complex->num_recordSyntax = 0;
2405 compo.u.complex->recordSyntax = 0;
2407 else if (elementSetNames)
2409 req->recordComposition = &compo;
2410 compo.which = Z_RecordComp_simple;
2411 compo.u.simple = elementSetNames;
2414 printf("Sent presentRequest (%d+%d).\n", setno, nos);
2419 static int send_SRW_presentRequest(const char *arg)
2421 char setstring[100];
2423 Z_SRW_PDU *sr = srw_sr;
2427 parse_show_args(arg, setstring, &setno, &nos);
2428 sr->u.request->startRecord = odr_intdup(out, setno);
2429 sr->u.request->maximumRecords = odr_intdup(out, nos);
2431 sr->u.request->recordSchema = record_schema;
2432 if (recordsyntax == VAL_TEXT_XML)
2433 sr->u.request->recordPacking = "xml";
2434 return send_srw(sr);
2438 static void close_session (void)
2445 nmem_destroy (session_mem);
2454 void process_close(Z_Close *req)
2456 Z_APDU *apdu = zget_APDU(out, Z_APDU_close);
2457 Z_Close *res = apdu->u.close;
2459 static char *reasons[] =
2464 "cost limit reached",
2466 "security violation",
2473 printf("Reason: %s, message: %s\n", reasons[*req->closeReason],
2474 req->diagnosticInformation ? req->diagnosticInformation : "NULL");
2479 *res->closeReason = Z_Close_finished;
2481 printf("Sent response.\n");
2486 static int cmd_show(const char *arg)
2488 if (protocol == PROTO_HTTP)
2495 if (!send_SRW_presentRequest(arg))
2505 printf("Not connected yet\n");
2508 if (!send_presentRequest(arg))
2514 int cmd_quit(const char *arg)
2516 printf("See you later, alligator.\n");
2522 int cmd_cancel(const char *arg)
2524 Z_APDU *apdu = zget_APDU(out, Z_APDU_triggerResourceControlRequest);
2525 Z_TriggerResourceControlRequest *req =
2526 apdu->u.triggerResourceControlRequest;
2531 printf("Session not initialized yet\n");
2536 if (!ODR_MASK_GET(session->options, Z_Options_triggerResourceCtrl))
2538 printf("Target doesn't support cancel (trigger resource ctrl)\n");
2541 *req->requestedAction = Z_TriggerResourceControlRequest_cancel;
2542 req->resultSetWanted = &rfalse;
2543 req->referenceId = set_refid (out);
2546 printf("Sent cancel request\n");
2551 int cmd_cancel_find(const char *arg) {
2555 return cmd_cancel("");
2560 int send_scanrequest(const char *query, int pp, int num, const char *term)
2562 Z_APDU *apdu = zget_APDU(out, Z_APDU_scanRequest);
2563 Z_ScanRequest *req = apdu->u.scanRequest;
2567 if (queryType == QueryType_CCL2RPN)
2570 struct ccl_rpn_node *rpn;
2572 rpn = ccl_find_str (bibset, query, &error, &pos);
2575 printf("CCL ERROR: %s\n", ccl_err_msg(error));
2579 yaz_oidval_to_z3950oid(out, CLASS_ATTSET, VAL_BIB1);
2580 if (!(req->termListAndStartPoint = ccl_scan_query (out, rpn)))
2582 printf("Couldn't convert CCL to Scan term\n");
2585 ccl_rpn_delete (rpn);
2589 YAZ_PQF_Parser pqf_parser = yaz_pqf_create ();
2591 if (!(req->termListAndStartPoint =
2592 yaz_pqf_scan(pqf_parser, out, &req->attributeSet, query)))
2594 const char *pqf_msg;
2596 int code = yaz_pqf_error (pqf_parser, &pqf_msg, &off);
2597 printf("%*s^\n", off+7, "");
2598 printf("Prefix query error: %s (code %d)\n", pqf_msg, code);
2599 yaz_pqf_destroy (pqf_parser);
2602 yaz_pqf_destroy (pqf_parser);
2606 if (req->termListAndStartPoint->term &&
2607 req->termListAndStartPoint->term->which == Z_Term_general &&
2608 req->termListAndStartPoint->term->u.general)
2610 req->termListAndStartPoint->term->u.general->buf =
2611 (unsigned char *) odr_strdup(out, term);
2612 req->termListAndStartPoint->term->u.general->len =
2613 req->termListAndStartPoint->term->u.general->size =
2617 req->referenceId = set_refid (out);
2618 req->num_databaseNames = num_databaseNames;
2619 req->databaseNames = databaseNames;
2620 req->numberOfTermsRequested = #
2621 req->preferredPositionInResponse = &pp;
2626 int send_sortrequest(const char *arg, int newset)
2628 Z_APDU *apdu = zget_APDU(out, Z_APDU_sortRequest);
2629 Z_SortRequest *req = apdu->u.sortRequest;
2630 Z_SortKeySpecList *sksl = (Z_SortKeySpecList *)
2631 odr_malloc (out, sizeof(*sksl));
2637 sprintf (setstring, "%d", setnumber);
2639 sprintf (setstring, "default");
2641 req->referenceId = set_refid (out);
2643 req->num_inputResultSetNames = 1;
2644 req->inputResultSetNames = (Z_InternationalString **)
2645 odr_malloc (out, sizeof(*req->inputResultSetNames));
2646 req->inputResultSetNames[0] = odr_strdup (out, setstring);
2648 if (newset && setnumber >= 0)
2649 sprintf (setstring, "%d", ++setnumber);
2651 req->sortedResultSetName = odr_strdup (out, setstring);
2653 req->sortSequence = yaz_sort_spec (out, arg);
2654 if (!req->sortSequence)
2656 printf ("Missing sort specifications\n");
2663 void display_term(Z_TermInfo *t)
2666 printf("%s", t->displayTerm);
2667 else if (t->term->which == Z_Term_general)
2669 printf("%.*s", t->term->u.general->len, t->term->u.general->buf);
2670 sprintf(last_scan_line, "%.*s", t->term->u.general->len,
2671 t->term->u.general->buf);
2674 printf("Term (not general)");
2675 if (t->globalOccurrences)
2676 printf (" (%d)\n", *t->globalOccurrences);
2681 void process_scanResponse(Z_ScanResponse *res)
2684 Z_Entry **entries = NULL;
2685 int num_entries = 0;
2687 printf("Received ScanResponse\n");
2688 print_refid (res->referenceId);
2689 printf("%d entries", *res->numberOfEntriesReturned);
2690 if (res->positionOfTerm)
2691 printf (", position=%d", *res->positionOfTerm);
2693 if (*res->scanStatus != Z_Scan_success)
2694 printf("Scan returned code %d\n", *res->scanStatus);
2697 if ((entries = res->entries->entries))
2698 num_entries = res->entries->num_entries;
2699 for (i = 0; i < num_entries; i++)
2701 int pos_term = res->positionOfTerm ? *res->positionOfTerm : -1;
2702 if (entries[i]->which == Z_Entry_termInfo)
2704 printf("%c ", i + 1 == pos_term ? '*' : ' ');
2705 display_term(entries[i]->u.termInfo);
2708 display_diagrecs(&entries[i]->u.surrogateDiagnostic, 1);
2710 if (res->entries->nonsurrogateDiagnostics)
2711 display_diagrecs (res->entries->nonsurrogateDiagnostics,
2712 res->entries->num_nonsurrogateDiagnostics);
2715 void process_sortResponse(Z_SortResponse *res)
2717 printf("Received SortResponse: status=");
2718 switch (*res->sortStatus)
2720 case Z_SortResponse_success:
2721 printf ("success"); break;
2722 case Z_SortResponse_partial_1:
2723 printf ("partial"); break;
2724 case Z_SortResponse_failure:
2725 printf ("failure"); break;
2727 printf ("unknown (%d)", *res->sortStatus);
2730 print_refid (res->referenceId);
2731 if (res->diagnostics)
2732 display_diagrecs(res->diagnostics,
2733 res->num_diagnostics);
2736 void process_deleteResultSetResponse (Z_DeleteResultSetResponse *res)
2738 printf("Got deleteResultSetResponse status=%d\n",
2739 *res->deleteOperationStatus);
2740 if (res->deleteListStatuses)
2743 for (i = 0; i < res->deleteListStatuses->num; i++)
2745 printf ("%s status=%d\n", res->deleteListStatuses->elements[i]->id,
2746 *res->deleteListStatuses->elements[i]->status);
2751 int cmd_sort_generic(const char *arg, int newset)
2755 printf("Session not initialized yet\n");
2760 if (!ODR_MASK_GET(session->options, Z_Options_sort))
2762 printf("Target doesn't support sort\n");
2767 if (send_sortrequest(arg, newset) < 0)
2774 int cmd_sort(const char *arg)
2776 return cmd_sort_generic (arg, 0);
2779 int cmd_sort_newset (const char *arg)
2781 return cmd_sort_generic (arg, 1);
2784 int cmd_scan(const char *arg)
2793 printf("Session not initialized yet\n");
2797 if (!ODR_MASK_GET(session->options, Z_Options_scan))
2799 printf("Target doesn't support scan\n");
2804 strcpy (last_scan_query, arg);
2805 if (send_scanrequest(arg, 1, 20, 0) < 0)
2810 if (send_scanrequest(last_scan_query, 1, 20, last_scan_line) < 0)
2816 int cmd_schema(const char *arg)
2818 xfree(record_schema);
2821 record_schema = xstrdup(arg);
2825 int cmd_format(const char *arg)
2830 printf("Usage: format <recordsyntax>\n");
2833 nsyntax = oid_getvalbyname (arg);
2834 if (strcmp(arg, "none") && nsyntax == VAL_NONE)
2836 printf ("unknown record syntax\n");
2839 recordsyntax = nsyntax;
2843 int cmd_elements(const char *arg)
2845 static Z_ElementSetNames esn;
2846 static char what[100];
2850 elementSetNames = 0;
2854 esn.which = Z_ElementSetNames_generic;
2855 esn.u.generic = what;
2856 elementSetNames = &esn;
2860 int cmd_attributeset(const char *arg)
2866 printf("Usage: attributeset <setname>\n");
2869 sscanf(arg, "%s", what);
2870 if (p_query_attset (what))
2872 printf("Unknown attribute set name\n");
2878 int cmd_querytype (const char *arg)
2880 if (!strcmp (arg, "ccl"))
2881 queryType = QueryType_CCL;
2882 else if (!strcmp (arg, "prefix") || !strcmp(arg, "rpn"))
2883 queryType = QueryType_Prefix;
2884 else if (!strcmp (arg, "ccl2rpn") || !strcmp (arg, "cclrpn"))
2885 queryType = QueryType_CCL2RPN;
2886 else if (!strcmp(arg, "cql"))
2887 queryType = QueryType_CQL;
2888 else if (!strcmp (arg, "cql2rpn") || !strcmp (arg, "cqlrpn"))
2889 queryType = QueryType_CQL2RPN;
2892 printf ("Querytype must be one of:\n");
2893 printf (" prefix - Prefix query\n");
2894 printf (" ccl - CCL query\n");
2895 printf (" ccl2rpn - CCL query converted to RPN\n");
2896 printf (" cql - CQL\n");
2897 printf (" cql2rpn - CQL query converted to RPN\n");
2903 int cmd_refid (const char *arg)
2908 refid = xstrdup (arg);
2912 int cmd_close(const char *arg)
2921 apdu = zget_APDU(out, Z_APDU_close);
2922 req = apdu->u.close;
2923 *req->closeReason = Z_Close_finished;
2925 printf("Sent close request.\n");
2930 int cmd_packagename(const char* arg)
2932 xfree (esPackageName);
2933 esPackageName = NULL;
2935 esPackageName = xstrdup(arg);
2939 int cmd_proxy(const char* arg)
2944 yazProxy = xstrdup (arg);
2948 int cmd_marccharset(const char *arg)
2953 if (sscanf(arg, "%29s", l1) < 1)
2955 xfree (marcCharset);
2957 if (strcmp(l1, "-"))
2958 marcCharset = xstrdup(l1);
2962 int cmd_charset(const char* arg)
2964 char l1[30], l2[30];
2967 if (sscanf(arg, "%29s %29s", l1, l2) < 1)
2969 printf("Current negotiation character set is `%s'\n",
2970 negotiationCharset ? negotiationCharset: "none");
2971 printf("Current output character set is `%s'\n",
2972 outputCharset ? outputCharset: "none");
2975 xfree (negotiationCharset);
2976 negotiationCharset = NULL;
2977 if (*l1 && strcmp(l1, "-"))
2979 negotiationCharset = xstrdup(l1);
2980 printf ("Character set negotiation : %s\n", negotiationCharset);
2983 printf ("Character set negotiation disabled\n");
2986 xfree (outputCharset);
2988 if (!strcmp(l2, "auto") && codeset)
2992 printf ("output charset: %s\n", codeset);
2993 outputCharset = xstrdup(codeset);
2998 printf ("No codeset found on this system\n");
3000 else if (strcmp(l2, "-"))
3001 outputCharset = xstrdup(l2);
3003 printf ("Output charset conversion disabled\n");
3009 int cmd_lang(const char* arg)
3012 printf("Current language is `%s'\n", (yazLang)?yazLang:NULL);
3018 yazLang = xstrdup(arg);
3022 int cmd_source(const char* arg)
3024 /* first should open the file and read one line at a time.. */
3026 char line[102400], *cp;
3029 fprintf(stderr,"Error in source command use a filename\n");
3033 includeFile = fopen (arg, "r");
3036 fprintf(stderr,"Unable to open file %s for reading\n",arg);
3040 while(!feof(includeFile)) {
3041 memset(line,0,sizeof(line));
3042 fgets(line,sizeof(line),includeFile);
3044 if(strlen(line) < 2) continue;
3045 if(line[0] == '#') continue;
3047 if ((cp = strrchr (line, '\n')))
3050 process_cmd_line(line);
3053 if(fclose(includeFile)<0) {
3054 perror("unable to close include file");
3060 int cmd_subshell(const char* args)
3065 system(getenv("SHELL"));
3071 int cmd_set_berfile(const char *arg)
3073 if (ber_file && ber_file != stdout && ber_file != stderr)
3075 if (!strcmp(arg, ""))
3077 else if (!strcmp(arg, "-"))
3080 ber_file = fopen(arg, "a");
3084 int cmd_set_apdufile(const char *arg)
3086 if(apdu_file && apdu_file != stderr && apdu_file != stderr)
3088 if (!strcmp(arg, ""))
3090 else if (!strcmp(arg, "-"))
3094 apdu_file = fopen(arg, "a");
3096 perror("unable to open apdu log file");
3099 odr_setprint(print, apdu_file);
3103 int cmd_set_cclfile(const char* arg)
3107 bibset = ccl_qual_mk ();
3108 inf = fopen (arg, "r");
3110 perror("unable to open CCL file");
3113 ccl_qual_file (bibset, inf);
3116 strcpy(ccl_fields,arg);
3120 int cmd_set_cqlfile(const char* arg)
3122 cql_transform_t newcqltrans;
3124 if ((newcqltrans = cql_transform_open_fname(arg)) == 0) {
3125 perror("unable to open CQL file");
3129 cql_transform_close(cqltrans);
3131 cqltrans = newcqltrans;
3132 strcpy(cql_fields, arg);
3136 int cmd_set_auto_reconnect(const char* arg)
3138 if(strlen(arg)==0) {
3139 auto_reconnect = ! auto_reconnect;
3140 } else if(strcmp(arg,"on")==0) {
3142 } else if(strcmp(arg,"off")==0) {
3145 printf("Error use on or off\n");
3150 printf("Set auto reconnect enabled.\n");
3152 printf("Set auto reconnect disabled.\n");
3157 int cmd_set_marcdump(const char* arg)
3159 if(marc_file && marc_file != stderr) { /* don't close stdout*/
3163 if (!strcmp(arg, ""))
3165 else if (!strcmp(arg, "-"))
3169 marc_file = fopen(arg, "a");
3171 perror("unable to open marc log file");
3177 this command takes 3 arge {name class oid}
3179 int cmd_register_oid(const char* args) {
3184 {"appctx",CLASS_APPCTX},
3185 {"absyn",CLASS_ABSYN},
3186 {"attset",CLASS_ATTSET},
3187 {"transyn",CLASS_TRANSYN},
3188 {"diagset",CLASS_DIAGSET},
3189 {"recsyn",CLASS_RECSYN},
3190 {"resform",CLASS_RESFORM},
3191 {"accform",CLASS_ACCFORM},
3192 {"extserv",CLASS_EXTSERV},
3193 {"userinfo",CLASS_USERINFO},
3194 {"elemspec",CLASS_ELEMSPEC},
3195 {"varset",CLASS_VARSET},
3196 {"schema",CLASS_SCHEMA},
3197 {"tagset",CLASS_TAGSET},
3198 {"general",CLASS_GENERAL},
3199 {0,(enum oid_class) 0}
3201 char oname_str[101], oclass_str[101], oid_str[101];
3204 oid_class oidclass = CLASS_GENERAL;
3205 int val = 0, oid[OID_SIZE];
3206 struct oident * new_oident=NULL;
3208 if (sscanf (args, "%100[^ ] %100[^ ] %100s",
3209 oname_str,oclass_str, oid_str) < 1) {
3210 printf("Error in register command \n");
3214 for (i = 0; oid_classes[i].className; i++) {
3215 if (!strcmp(oid_classes[i].className, oclass_str))
3217 oidclass=oid_classes[i].oclass;
3222 if(!(oid_classes[i].className)) {
3223 printf("Unknown oid class %s\n",oclass_str);
3231 while (isdigit (*(unsigned char *) name))
3233 val = val*10 + (*name - '0');
3246 new_oident = oid_addent (oid, PROTO_GENERAL, oidclass, oname_str,
3248 if(strcmp(new_oident->desc,oname_str))
3250 fprintf(stderr,"oid is already named as %s, registration failed\n",
3256 int cmd_push_command(const char* arg)
3258 #if HAVE_READLINE_HISTORY_H
3262 fprintf(stderr,"Not compiled with the readline/history module\n");
3267 void source_rcfile()
3269 /* Look for a $HOME/.yazclientrc and source it if it exists */
3270 struct stat statbuf;
3272 char* homedir=getenv("HOME");
3274 if(!homedir) return;
3276 sprintf(buffer,"%s/.yazclientrc",homedir);
3278 if(stat(buffer,&statbuf)==0) {
3282 if(stat(".yazclientrc",&statbuf)==0) {
3283 cmd_source(".yazclientrc");
3288 static void initialize(void)
3293 if (!(out = odr_createmem(ODR_ENCODE)) ||
3294 !(in = odr_createmem(ODR_DECODE)) ||
3295 !(print = odr_createmem(ODR_PRINT)))
3297 fprintf(stderr, "failed to allocate ODR streams\n");
3302 setvbuf(stdout, 0, _IONBF, 0);
3304 odr_setprint(print, apdu_file);
3306 bibset = ccl_qual_mk ();
3307 inf = fopen (ccl_fields, "r");
3310 ccl_qual_file (bibset, inf);
3314 cqltrans = cql_transform_open_fname(cql_fields);
3315 /* If this fails, no problem: we detect cqltrans == 0 later */
3317 #if HAVE_READLINE_READLINE_H
3318 rl_attempted_completion_function = (CPPFunction*)readline_completer;
3322 for(i=0; i<maxOtherInfosSupported; ++i) {
3323 extraOtherInfos[i].oidval = -1;
3330 #if HAVE_GETTIMEOFDAY
3331 struct timeval tv_start, tv_end;
3335 static void handle_srw_record(Z_SRW_record *rec)
3337 if (rec->recordPosition)
3339 printf ("pos=%d", *rec->recordPosition);
3340 setno = *rec->recordPosition + 1;
3342 if (rec->recordSchema)
3343 printf (" schema=%s", rec->recordSchema);
3345 if (rec->recordData_buf && rec->recordData_len)
3347 fwrite(rec->recordData_buf, 1, rec->recordData_len, stdout);
3349 fwrite (rec->recordData_buf, 1, rec->recordData_len, marc_file);
3352 printf ("No data!");
3356 static void handle_srw_explain_response(Z_SRW_explainResponse *res)
3358 handle_srw_record(&res->record);
3361 static void handle_srw_response(Z_SRW_searchRetrieveResponse *res)
3365 printf ("Received SRW SearchRetrieve Response\n");
3367 for (i = 0; i<res->num_diagnostics; i++)
3369 if (res->diagnostics[i].uri)
3370 printf ("SRW diagnostic %s\n",
3371 res->diagnostics[i].uri);
3373 printf ("SRW diagnostic missing or could not be decoded\n");
3374 if (res->diagnostics[i].message)
3375 printf ("Message: %s\n", res->diagnostics[i].message);
3376 if (res->diagnostics[i].details)
3377 printf ("Details: %s\n", res->diagnostics[i].details);
3379 if (res->numberOfRecords)
3380 printf ("Number of hits: %d\n", *res->numberOfRecords);
3381 for (i = 0; i<res->num_records; i++)
3382 handle_srw_record(res->records + i);
3385 static void http_response(Z_HTTP_Response *hres)
3388 const char *content_type = z_HTTP_header_lookup(hres->headers,
3390 const char *connection_head = z_HTTP_header_lookup(hres->headers,
3392 if (content_type && !yaz_strcmp_del("text/xml", content_type, "; "))
3394 Z_SOAP *soap_package = 0;
3395 ODR o = odr_createmem(ODR_DECODE);
3396 Z_SOAP_Handler soap_handlers[2] = {
3397 {"http://www.loc.gov/zing/srw/", 0,
3398 (Z_SOAP_fun) yaz_srw_codec},
3401 ret = z_soap_codec(o, &soap_package,
3402 &hres->content_buf, &hres->content_len,
3404 if (!ret && soap_package->which == Z_SOAP_generic &&
3405 soap_package->u.generic->no == 0)
3407 Z_SRW_PDU *sr = soap_package->u.generic->p;
3408 if (sr->which == Z_SRW_searchRetrieve_response)
3409 handle_srw_response(sr->u.response);
3410 else if (sr->which == Z_SRW_explain_response)
3411 handle_srw_explain_response(sr->u.explain_response);
3415 else if (soap_package && (soap_package->which == Z_SOAP_fault
3416 || soap_package->which == Z_SOAP_error))
3418 printf ("HTTP Error Status=%d\n", hres->code);
3419 printf ("SOAP Fault code %s\n",
3420 soap_package->u.fault->fault_code);
3421 printf ("SOAP Fault string %s\n",
3422 soap_package->u.fault->fault_string);
3423 if (soap_package->u.fault->details)
3424 printf ("SOAP Details %s\n",
3425 soap_package->u.fault->details);
3433 if (hres->code != 200)
3435 printf ("HTTP Error Status=%d\n", hres->code);
3439 printf ("Decoding of SRW package failed\n");
3445 if (!strcmp(hres->version, "1.0"))
3447 /* HTTP 1.0: only if Keep-Alive we stay alive.. */
3448 if (!connection_head || strcmp(connection_head, "Keep-Alive"))
3453 /* HTTP 1.1: only if no close we stay alive .. */
3454 if (connection_head && !strcmp(connection_head, "close"))
3461 void wait_and_handle_response()
3463 int reconnect_ok = 1;
3466 int netbufferlen = 0;
3471 res = cs_get(conn, &netbuffer, &netbufferlen);
3472 if (reconnect_ok && res <= 0 && protocol == PROTO_HTTP)
3483 buf_out = odr_getbuf(out, &len_out, 0);
3485 do_hex_dump(buf_out, len_out);
3487 cs_put(conn, buf_out, len_out);
3495 printf("Target closed connection\n");
3500 odr_reset(in); /* release APDU from last round */
3502 do_hex_dump(netbuffer, res);
3503 odr_setbuf(in, netbuffer, res, 0);
3505 if (!z_GDU(in, &gdu, 0, 0))
3507 FILE *f = ber_file ? ber_file : stdout;
3508 odr_perror(in, "Decoding incoming APDU");
3509 fprintf(f, "[Near %d]\n", odr_offset(in));
3510 fprintf(f, "Packet dump:\n---------\n");
3511 odr_dumpBER(f, netbuffer, res);
3512 fprintf(f, "---------\n");
3515 z_GDU(print, &gdu, 0, 0);
3518 if (conn && cs_more(conn))
3523 odr_dumpBER(ber_file, netbuffer, res);
3524 if (apdu_file && !z_GDU(print, &gdu, 0, 0))
3526 odr_perror(print, "Failed to print incoming APDU");
3530 if (gdu->which == Z_GDU_Z3950)
3532 Z_APDU *apdu = gdu->u.z3950;
3535 case Z_APDU_initResponse:
3536 process_initResponse(apdu->u.initResponse);
3538 case Z_APDU_searchResponse:
3539 process_searchResponse(apdu->u.searchResponse);
3541 case Z_APDU_scanResponse:
3542 process_scanResponse(apdu->u.scanResponse);
3544 case Z_APDU_presentResponse:
3545 print_refid (apdu->u.presentResponse->referenceId);
3547 *apdu->u.presentResponse->numberOfRecordsReturned;
3548 if (apdu->u.presentResponse->records)
3549 display_records(apdu->u.presentResponse->records);
3551 printf("No records.\n");
3552 printf ("nextResultSetPosition = %d\n",
3553 *apdu->u.presentResponse->nextResultSetPosition);
3555 case Z_APDU_sortResponse:
3556 process_sortResponse(apdu->u.sortResponse);
3558 case Z_APDU_extendedServicesResponse:
3559 printf("Got extended services response\n");
3560 process_ESResponse(apdu->u.extendedServicesResponse);
3563 printf("Target has closed the association.\n");
3564 process_close(apdu->u.close);
3566 case Z_APDU_resourceControlRequest:
3567 process_resourceControlRequest
3568 (apdu->u.resourceControlRequest);
3570 case Z_APDU_deleteResultSetResponse:
3571 process_deleteResultSetResponse(apdu->u.
3572 deleteResultSetResponse);
3575 printf("Received unknown APDU type (%d).\n",
3581 else if (gdu->which == Z_GDU_HTTP_Response)
3583 http_response(gdu->u.HTTP_Response);
3586 if (conn && !cs_more(conn))
3591 #if HAVE_GETTIMEOFDAY
3592 gettimeofday (&tv_end, 0);
3594 printf ("S/U S/U=%ld/%ld %ld/%ld",
3595 (long) tv_start.tv_sec,
3596 (long) tv_start.tv_usec,
3597 (long) tv_end.tv_sec,
3598 (long) tv_end.tv_usec);
3600 printf ("Elapsed: %.6f\n",
3601 (double) tv_end.tv_usec / 1e6 + tv_end.tv_sec -
3602 ((double) tv_start.tv_usec / 1e6 + tv_start.tv_sec));
3609 int cmd_cclparse(const char* arg)
3612 struct ccl_rpn_node *rpn=NULL;
3615 rpn = ccl_find_str (bibset, arg, &error, &pos);
3618 printf ("%*s^ - ", 3+strlen(last_cmd)+1+pos, " ");
3619 printf ("%s\n", ccl_err_msg (error));
3625 ccl_pr_tree(rpn, stdout);
3629 ccl_rpn_delete(rpn);
3637 int cmd_set_otherinfo(const char* args)
3639 char oidstr[101], otherinfoString[101];
3644 sscan_res = sscanf (args, "%d %100[^ ] %100s", &otherinfoNo, oidstr, otherinfoString);
3646 /* reset this otherinfo */
3647 if(otherinfoNo>=maxOtherInfosSupported) {
3648 printf("Error otherinfo index to large (%d>%d)\n",
3649 otherinfoNo,maxOtherInfosSupported);
3651 extraOtherInfos[otherinfoNo].oidval = -1;
3652 if (extraOtherInfos[otherinfoNo].value)
3653 free(extraOtherInfos[otherinfoNo].value);
3657 printf("Error in set_otherinfo command \n");
3661 if (otherinfoNo>=maxOtherInfosSupported) {
3662 printf("Error otherinfo index to large (%d>%d)\n",
3663 otherinfoNo,maxOtherInfosSupported);
3666 oidval = oid_getvalbyname (oidstr);
3667 if (oidval == -1 ) {
3668 printf("Error in set_otherinfo command unknown oid %s \n",oidstr);
3671 extraOtherInfos[otherinfoNo].oidval = oidval;
3672 if(extraOtherInfos[otherinfoNo].value) free(extraOtherInfos[otherinfoNo].value);
3673 extraOtherInfos[otherinfoNo].value = strdup(otherinfoString);
3678 int cmd_list_otherinfo(const char* args)
3682 if(strlen(args)>0) {
3684 if( i >= maxOtherInfosSupported ) {
3685 printf("Error otherinfo index to large (%d>%d)\n",i,maxOtherInfosSupported);
3689 if(extraOtherInfos[i].oidval != -1)
3690 printf(" otherinfo %d %s %s\n",
3692 yaz_z3950_oid_value_to_str(
3693 (enum oid_value) extraOtherInfos[i].oidval,
3695 extraOtherInfos[i].value);
3698 for(i=0; i<maxOtherInfosSupported; ++i) {
3699 if(extraOtherInfos[i].oidval != -1)
3700 printf(" otherinfo %d %s %s\n",
3702 yaz_z3950_oid_value_to_str(
3703 (enum oid_value) extraOtherInfos[i].oidval,
3705 extraOtherInfos[i].value);
3713 int cmd_list_all(const char* args) {
3716 /* connection options */
3718 printf("Connected to : %s\n",last_open_command);
3720 if(last_open_command)
3721 printf("Not connected to : %s\n",last_open_command);
3723 printf("Not connected : \n");
3726 if(yazProxy) printf("using proxy : %s\n",yazProxy);
3728 printf("auto_reconnect : %s\n",auto_reconnect?"on":"off");
3731 printf("Authentication : none\n");
3733 switch(auth->which) {
3734 case Z_IdAuthentication_idPass:
3735 printf("Authentication : IdPass\n");
3736 printf(" Login User : %s\n",auth->u.idPass->userId?auth->u.idPass->userId:"");
3737 printf(" Login Group : %s\n",auth->u.idPass->groupId?auth->u.idPass->groupId:"");
3738 printf(" Password : %s\n",auth->u.idPass->password?auth->u.idPass->password:"");
3740 case Z_IdAuthentication_open:
3741 printf("Authentication : psOpen\n");
3742 printf(" Open string : %s\n",auth->u.open);
3745 printf("Authentication : Unknown\n");
3748 if (negotiationCharset)
3749 printf("Neg. Character set : `%s'\n", negotiationCharset);
3753 for (i = 0; i<num_databaseNames; i++) printf("%s ",databaseNames[i]);
3757 printf("CCL file : %s\n",ccl_fields);
3758 printf("CQL file : %s\n",cql_fields);
3759 printf("Query type : %s\n",query_type_as_string(queryType));
3761 printf("Named Result Sets : %s\n",setnumber==-1?"off":"on");
3763 /* piggy back options */
3764 printf("ssub/lslb/mspn : %d/%d/%d\n",smallSetUpperBound,largeSetLowerBound,mediumSetPresentNumber);
3766 /* print present related options */
3767 printf("Format : %s\n",yaz_z3950_oid_value_to_str(recordsyntax,CLASS_RECSYN));
3768 printf("Schema : %s\n",record_schema ? record_schema : "not set");
3769 printf("Elements : %s\n",elementSetNames?elementSetNames->u.generic:"");
3771 /* loging options */
3772 printf("APDU log : %s\n",apdu_file?"on":"off");
3773 printf("Record log : %s\n",marc_file?"on":"off");
3776 printf("Other Info: \n");
3777 cmd_list_otherinfo("");
3782 int cmd_clear_otherinfo(const char* args)
3784 if(strlen(args)>0) {
3786 otherinfoNo = atoi(args);
3787 if( otherinfoNo >= maxOtherInfosSupported ) {
3788 printf("Error otherinfo index to large (%d>%d)\n",otherinfoNo,maxOtherInfosSupported);
3792 if(extraOtherInfos[otherinfoNo].oidval != -1) {
3793 /* only clear if set. */
3794 extraOtherInfos[otherinfoNo].oidval=-1;
3795 free(extraOtherInfos[otherinfoNo].value);
3800 for(i=0; i<maxOtherInfosSupported; ++i) {
3801 if (extraOtherInfos[i].oidval!=-1 ) {
3802 extraOtherInfos[i].oidval=-1;
3803 free(extraOtherInfos[i].value);
3810 static int cmd_help (const char *line);
3812 typedef char *(*completerFunctionType)(const char *text, int state);
3816 int (*fun)(const char *arg);
3818 completerFunctionType rl_completerfunction;
3819 int complete_filenames;
3820 char **local_tabcompletes;
3822 {"open", cmd_open, "('tcp'|'ssl')':<host>[':'<port>][/<db>]",NULL,0,NULL},
3823 {"quit", cmd_quit, "",NULL,0,NULL},
3824 {"find", cmd_find, "<query>",NULL,0,NULL},
3825 {"delete", cmd_delete, "<setname>",NULL,0,NULL},
3826 {"base", cmd_base, "<base-name>",NULL,0,NULL},
3827 {"show", cmd_show, "<rec#>['+'<#recs>['+'<setname>]]",NULL,0,NULL},
3828 {"scan", cmd_scan, "<term>",NULL,0,NULL},
3829 {"sort", cmd_sort, "<sortkey> <flag> <sortkey> <flag> ...",NULL,0,NULL},
3830 {"sort+", cmd_sort_newset, "<sortkey> <flag> <sortkey> <flag> ...",NULL,0,NULL},
3831 {"authentication", cmd_authentication, "<acctstring>",NULL,0,NULL},
3832 {"lslb", cmd_lslb, "<largeSetLowerBound>",NULL,0,NULL},
3833 {"ssub", cmd_ssub, "<smallSetUpperBound>",NULL,0,NULL},
3834 {"mspn", cmd_mspn, "<mediumSetPresentNumber>",NULL,0,NULL},
3835 {"status", cmd_status, "",NULL,0,NULL},
3836 {"setnames", cmd_setnames, "",NULL,0,NULL},
3837 {"cancel", cmd_cancel, "",NULL,0,NULL},
3838 {"cancel_find", cmd_cancel_find, "<query>",NULL,0,NULL},
3839 {"format", cmd_format, "<recordsyntax>",complete_format,0,NULL},
3840 {"schema", cmd_schema, "<schema>",complete_schema,0,NULL},
3841 {"elements", cmd_elements, "<elementSetName>",NULL,0,NULL},
3842 {"close", cmd_close, "",NULL,0,NULL},
3843 {"attributeset", cmd_attributeset, "<attrset>",complete_attributeset,0,NULL},
3844 {"querytype", cmd_querytype, "<type>",complete_querytype,0,NULL},
3845 {"refid", cmd_refid, "<id>",NULL,0,NULL},
3846 {"itemorder", cmd_itemorder, "ill|item <itemno>",NULL,0,NULL},
3847 {"update", cmd_update, "<action> <recid> [<file>]",NULL,0,NULL},
3848 {"update0", cmd_update0, "<action> <recid> [<file>]",NULL,0,NULL},
3849 {"packagename", cmd_packagename, "<packagename>",NULL,0,NULL},
3850 {"proxy", cmd_proxy, "[('tcp'|'ssl')]<host>[':'<port>]",NULL,0,NULL},
3851 {"charset", cmd_charset, "<nego_charset> <output_charset>",NULL,0,NULL},
3852 {"marccharset", cmd_marccharset, "<charset_name>",NULL,0,NULL},
3853 {"lang", cmd_lang, "<language_code>",NULL,0,NULL},
3854 {".", cmd_source, "<filename>",NULL,1,NULL},
3855 {"!", cmd_subshell, "Subshell command",NULL,1,NULL},
3856 {"set_apdufile", cmd_set_apdufile, "<filename>",NULL,1,NULL},
3857 {"set_berfile", cmd_set_berfile, "<filename>",NULL,1,NULL},
3858 {"set_marcdump", cmd_set_marcdump," <filename>",NULL,1,NULL},
3859 {"set_cclfile", cmd_set_cclfile," <filename>",NULL,1,NULL},
3860 {"set_cqlfile", cmd_set_cqlfile," <filename>",NULL,1,NULL},
3861 {"set_auto_reconnect", cmd_set_auto_reconnect," on|off",complete_auto_reconnect,1,NULL},
3862 {"set_otherinfo", cmd_set_otherinfo,"<otherinfoinddex> <oid> <string>",NULL,0,NULL},
3863 {"register_oid", cmd_register_oid,"<name> <class> <oid>",NULL,0,NULL},
3864 {"push_command", cmd_push_command,"<command>",command_generator,0,NULL},
3865 {"register_tab", cmd_register_tab,"<commandname> <tab>",command_generator,0,NULL},
3866 {"cclparse", cmd_cclparse,"<ccl find command>",NULL,0,NULL},
3867 {"list_otherinfo",cmd_list_otherinfo,"[otherinfoinddex]",NULL,0,NULL},
3868 {"list_all",cmd_list_all,"",NULL,0,NULL},
3869 {"clear_otherinfo",cmd_clear_otherinfo,"",NULL,0,NULL},
3870 /* Server Admin Functions */
3871 {"adm-reindex", cmd_adm_reindex, "<database-name>",NULL,0,NULL},
3872 {"adm-truncate", cmd_adm_truncate, "('database'|'index')<object-name>",NULL,0,NULL},
3873 {"adm-create", cmd_adm_create, "",NULL,0,NULL},
3874 {"adm-drop", cmd_adm_drop, "('database'|'index')<object-name>",NULL,0,NULL},
3875 {"adm-import", cmd_adm_import, "<record-type> <dir> <pattern>",NULL,0,NULL},
3876 {"adm-refresh", cmd_adm_refresh, "",NULL,0,NULL},
3877 {"adm-commit", cmd_adm_commit, "",NULL,0,NULL},
3878 {"adm-shutdown", cmd_adm_shutdown, "",NULL,0,NULL},
3879 {"adm-startup", cmd_adm_startup, "",NULL,0,NULL},
3880 {"explain", cmd_explain, "", NULL, 0, NULL},
3881 {"options", cmd_options, "", NULL, 0, NULL},
3882 {"zversion", cmd_zversion, "", NULL, 0, NULL},
3883 {"help", cmd_help, "", NULL,0,NULL},
3884 {"init", cmd_init, "", NULL,0,NULL},
3888 static int cmd_help (const char *line)
3894 sscanf (line, "%20s", topic);
3897 printf("Commands:\n");
3898 for (i = 0; cmd_array[i].cmd; i++)
3899 if (*topic == 0 || strcmp (topic, cmd_array[i].cmd) == 0)
3900 printf(" %s %s\n", cmd_array[i].cmd, cmd_array[i].ad);
3901 if (strcmp (topic, "find") == 0)
3904 printf (" \"term\" Simple Term\n");
3905 printf (" @attr [attset] type=value op Attribute\n");
3906 printf (" @and opl opr And\n");
3907 printf (" @or opl opr Or\n");
3908 printf (" @not opl opr And-Not\n");
3909 printf (" @set set Result set\n");
3911 printf ("Bib-1 attribute types\n");
3913 printf ("4=Title 7=ISBN 8=ISSN 30=Date 62=Abstract 1003=Author 1016=Any\n");
3914 printf ("2=Relation: ");
3915 printf ("1< 2<= 3= 4>= 5> 6!= 102=Relevance\n");
3916 printf ("3=Position: ");
3917 printf ("1=First in Field 2=First in subfield 3=Any position\n");
3918 printf ("4=Structure: ");
3919 printf ("1=Phrase 2=Word 3=Key 4=Year 5=Date 6=WordList\n");
3920 printf ("5=Truncation: ");
3921 printf ("1=Right 2=Left 3=L&R 100=No 101=# 102=Re-1 103=Re-2\n");
3922 printf ("6=Completeness:");
3923 printf ("1=Incomplete subfield 2=Complete subfield 3=Complete field\n");
3928 int cmd_register_tab(const char* arg) {
3930 char command[101], tabargument[101];
3935 if (sscanf (arg, "%100s %100s", command, tabargument) < 1) {
3939 /* locate the amdn in the list */
3940 for (i = 0; cmd_array[i].cmd; i++) {
3941 if (!strncmp(cmd_array[i].cmd, command, strlen(command))) {
3946 if(!cmd_array[i].cmd) {
3947 fprintf(stderr,"Unknown command %s\n",command);
3952 if(!cmd_array[i].local_tabcompletes)
3953 cmd_array[i].local_tabcompletes = (char **) calloc(1,sizeof(char**));
3957 tabslist = cmd_array[i].local_tabcompletes;
3958 for(;tabslist && *tabslist;tabslist++) {
3962 cmd_array[i].local_tabcompletes = (char **)
3963 realloc(cmd_array[i].local_tabcompletes,(num_of_tabs+2)*sizeof(char**));
3964 tabslist=cmd_array[i].local_tabcompletes;
3965 tabslist[num_of_tabs]=strdup(tabargument);
3966 tabslist[num_of_tabs+1]=NULL;
3971 void process_cmd_line(char* line)
3974 char word[32], arg[10240];
3976 #if HAVE_GETTIMEOFDAY
3977 gettimeofday (&tv_start, 0);
3980 if ((res = sscanf(line, "%31s %10239[^;]", word, arg)) <= 0)
3982 strcpy(word, last_cmd);
3987 strcpy(last_cmd, word);
3989 /* removed tailing spaces from the arg command */
3992 char* lastnonspace=NULL;
3995 if(!isspace(*(unsigned char *) p)) {
4000 *(++lastnonspace) = 0;
4003 for (i = 0; cmd_array[i].cmd; i++)
4004 if (!strncmp(cmd_array[i].cmd, word, strlen(word)))
4006 res = (*cmd_array[i].fun)(arg);
4010 if (!cmd_array[i].cmd) /* dump our help-screen */
4012 printf("Unknown command: %s.\n", word);
4013 printf("use help for list of commands\n");
4014 /* cmd_help (""); */
4018 if(apdu_file) fflush(apdu_file);
4021 wait_and_handle_response();
4030 char *command_generator(const char *text, int state)
4036 for( ; cmd_array[idx].cmd; ++idx) {
4037 if (!strncmp(cmd_array[idx].cmd,text,strlen(text))) {
4038 ++idx; /* skip this entry on the next run */
4039 return strdup(cmd_array[idx-1].cmd);
4047 This function only known how to complete on the first word
4049 char ** readline_completer(char *text, int start, int end) {
4050 #if HAVE_READLINE_READLINE_H
4052 completerFunctionType completerToUse;
4055 #if HAVE_READLINE_RL_COMPLETION_MATCHES
4056 char** res=rl_completion_matches(text,
4059 char** res=completion_matches(text,
4060 (CPFunction*)command_generator);
4062 rl_attempted_completion_over = 1;
4065 char arg[10240],word[32];
4067 if ((res = sscanf(rl_line_buffer, "%31s %10239[^;]", word, arg)) <= 0) {
4068 rl_attempted_completion_over = 1;
4072 for (i = 0; cmd_array[i].cmd; i++) {
4073 if (!strncmp(cmd_array[i].cmd, word, strlen(word))) {
4078 if(!cmd_array[i].cmd) return NULL;
4080 curret_global_list = cmd_array[i].local_tabcompletes;
4082 completerToUse = cmd_array[i].rl_completerfunction;
4083 if(completerToUse==NULL) /* if no pr. command completer is defined use the default completer */
4084 completerToUse = default_completer;
4086 if(completerToUse) {
4087 #ifdef HAVE_READLINE_RL_COMPLETION_MATCHES
4089 rl_completion_matches(text,
4093 completion_matches(text,
4094 (CPFunction*)completerToUse);
4096 if(!cmd_array[i].complete_filenames)
4097 rl_attempted_completion_over = 1;
4100 if(!cmd_array[i].complete_filenames)
4101 rl_attempted_completion_over = 1;
4111 static void client(void)
4117 #if HAVE_GETTIMEOFDAY
4118 gettimeofday (&tv_start, 0);
4123 char *line_in = NULL;
4124 #if HAVE_READLINE_READLINE_H
4127 line_in=readline(C_PROMPT);
4130 #if HAVE_READLINE_HISTORY_H
4132 add_history(line_in);
4134 strncpy(line, line_in, 10239);
4143 if (!fgets(line, 10239, stdin))
4145 if ((end_p = strchr (line, '\n')))
4148 process_cmd_line(line);
4152 static void show_version(void)
4156 yaz_version(vstr, 0);
4157 printf ("YAZ version: %s\n", YAZ_VERSION);
4158 if (strcmp(vstr, YAZ_VERSION))
4159 printf ("YAZ DLL/SO: %s\n", vstr);
4163 int main(int argc, char **argv)
4166 char *open_command = 0;
4167 char *auth_command = 0;
4172 if (!setlocale(LC_CTYPE, ""))
4173 fprintf (stderr, "setlocale failed\n");
4177 codeset = nl_langinfo(CODESET);
4181 outputCharset = xstrdup(codeset);
4183 ODR_MASK_SET(&z3950_options, Z_Options_search);
4184 ODR_MASK_SET(&z3950_options, Z_Options_present);
4185 ODR_MASK_SET(&z3950_options, Z_Options_namedResultSets);
4186 ODR_MASK_SET(&z3950_options, Z_Options_triggerResourceCtrl);
4187 ODR_MASK_SET(&z3950_options, Z_Options_scan);
4188 ODR_MASK_SET(&z3950_options, Z_Options_sort);
4189 ODR_MASK_SET(&z3950_options, Z_Options_extendedServices);
4190 ODR_MASK_SET(&z3950_options, Z_Options_delSet);
4192 while ((ret = options("k:c:q:a:b:m:v:p:u:t:Vxd:", argv, argc, &arg)) != -2)
4199 open_command = (char *) xmalloc (strlen(arg)+6);
4200 strcpy (open_command, "open ");
4201 strcat (open_command, arg);
4205 dump_file_prefix = arg;
4208 kilobytes = atoi(arg);
4211 if (!(marc_file = fopen (arg, "a")))
4218 outputCharset = xstrdup(arg);
4221 strncpy (ccl_fields, arg, sizeof(ccl_fields)-1);
4222 ccl_fields[sizeof(ccl_fields)-1] = '\0';
4225 strncpy (cql_fields, arg, sizeof(cql_fields)-1);
4226 cql_fields[sizeof(cql_fields)-1] = '\0';
4229 if (!strcmp(arg, "-"))
4232 ber_file=fopen(arg, "a");
4235 if (!strcmp(arg, "-"))
4238 apdu_file=fopen(arg, "a");
4244 yazProxy=strdup(arg);
4249 auth_command = (char *) xmalloc (strlen(arg)+6);
4250 strcpy (auth_command, "auth ");
4251 strcat (auth_command, arg);
4255 yaz_log_init(yaz_log_mask_str(arg), "", 0);
4261 fprintf (stderr, "Usage: %s [-m <marclog>] [ -a <apdulog>] "
4262 "[-b berdump] [-c cclfields] \n"
4263 "[-q cqlfields] [-p <proxy-addr>] [-u <auth>] "
4264 "[-k size] [-d dump] [-V] [<server-addr>]\n",
4272 #ifdef HAVE_GETTIMEOFDAY
4273 gettimeofday (&tv_start, 0);
4275 process_cmd_line (auth_command);
4276 #if HAVE_READLINE_HISTORY_H
4277 add_history(auth_command);
4279 xfree(auth_command);
4283 #ifdef HAVE_GETTIMEOFDAY
4284 gettimeofday (&tv_start, 0);
4286 process_cmd_line (open_command);
4287 #if HAVE_READLINE_HISTORY_H
4288 add_history(open_command);
4290 xfree(open_command);
4301 * vim600: sw=4 ts=8 fdm=marker
4302 * vim<600: sw=4 ts=8