2 * Copyright (C) 1995-2005, Index Data ApS
3 * See the file LICENSE for details.
5 * $Id: client.c,v 1.270 2005-01-17 13:08:53 adam Exp $
29 #if HAVE_OPENSSL_SSL_H
30 #include <openssl/bio.h>
31 #include <openssl/crypto.h>
32 #include <openssl/x509.h>
33 #include <openssl/pem.h>
34 #include <openssl/ssl.h>
35 #include <openssl/err.h>
41 #define S_ISREG(x) (x & _S_IFREG)
42 #define S_ISDIR(x) (x & _S_IFDIR)
45 #include <yaz/yaz-util.h>
47 #include <yaz/comstack.h>
49 #include <yaz/proto.h>
50 #include <yaz/marcdisp.h>
51 #include <yaz/diagbib1.h>
52 #include <yaz/otherinfo.h>
53 #include <yaz/charneg.h>
55 #include <yaz/pquery.h>
56 #include <yaz/sortspec.h>
60 #include <yaz/yaz-ccl.h>
64 #if HAVE_READLINE_READLINE_H
65 #include <readline/readline.h>
67 #if HAVE_READLINE_HISTORY_H
68 #include <readline/history.h>
73 #include "tabcomplete.h"
75 #define C_PROMPT "Z> "
77 static char *codeset = 0; /* character set for output */
78 static int hex_dump = 0;
79 static char *dump_file_prefix = 0;
80 static ODR out, in, print; /* encoding and decoding streams */
82 static ODR srw_sr_odr_out = 0;
83 static Z_SRW_PDU *srw_sr = 0;
85 static FILE *apdu_file = 0;
86 static FILE *ber_file = 0;
87 static COMSTACK conn = 0; /* our z-association */
88 static Z_IdAuthentication *auth = 0; /* our current auth definition */
89 char *databaseNames[128];
90 int num_databaseNames = 0;
91 static Z_External *record_last = 0;
92 static int setnumber = -1; /* current result set number */
93 static int smallSetUpperBound = 0;
94 static int largeSetLowerBound = 1;
95 static int mediumSetPresentNumber = 0;
96 static Z_ElementSetNames *elementSetNames = 0;
97 static int setno = 1; /* current set offset */
98 static enum oid_proto protocol = PROTO_Z3950; /* current app protocol */
99 static enum oid_value recordsyntax = VAL_USMARC;
100 static char *record_schema = 0;
101 static int sent_close = 0;
102 static NMEM session_mem = NULL; /* memory handle for init-response */
103 static Z_InitResponse *session = 0; /* session parameters */
104 static char last_scan_line[512] = "0";
105 static char last_scan_query[512] = "0";
106 static char ccl_fields[512] = "default.bib";
107 /* ### How can I set this path to use wherever YAZ is installed? */
108 static char cql_fields[512] = "/usr/local/share/yaz/etc/pqf.properties";
109 static char *esPackageName = 0;
110 static char *yazProxy = 0;
111 static int kilobytes = 1024;
112 static char *negotiationCharset = 0;
113 static int negotiationCharsetRecords = 1;
114 static int negotiationCharsetVersion = 3;
115 static char *outputCharset = 0;
116 static char *marcCharset = 0;
117 static char* yazLang = 0;
118 static char* http_version = "1.1";
120 static char last_cmd[32] = "?";
121 static FILE *marc_file = 0;
122 static char *refid = NULL;
123 static char *last_open_command = NULL;
124 static int auto_reconnect = 0;
125 static Odr_bitmask z3950_options;
126 static int z3950_version = 3;
127 static int scan_stepSize = 0;
128 static int scan_position = 1;
129 static char cur_host[200];
139 static QueryType queryType = QueryType_Prefix;
141 static CCL_bibset bibset; /* CCL bibset handle */
142 static cql_transform_t cqltrans; /* CQL context-set handle */
144 #if HAVE_READLINE_COMPLETION_OVER
147 /* readline doesn't have this var. Define it ourselves. */
148 int rl_attempted_completion_over = 0;
151 /* set this one to 1, to avoid decode of unknown MARCs */
152 #define AVOID_MARC_DECODE 1
154 #define maxOtherInfosSupported 10
158 } extraOtherInfos[maxOtherInfosSupported];
161 void process_cmd_line(char* line);
162 char ** readline_completer(char *text, int start, int end);
163 char *command_generator(const char *text, int state);
164 char** curret_global_list=NULL;
165 int cmd_register_tab(const char* arg);
167 static void close_session (void);
169 ODR getODROutputStream()
174 const char* query_type_as_string(QueryType q)
177 case QueryType_Prefix: return "prefix (RPN sent to server)";
178 case QueryType_CCL: return "CCL (CCL sent to server) ";
179 case QueryType_CCL2RPN: return "CCL -> RPN (RPN sent to server)";
180 case QueryType_CQL: return "CQL (CQL sent to server)";
181 case QueryType_CQL2RPN: return "CQL -> RPN (RPN sent to server)";
183 return "unknown Query type internal yaz-client error";
187 static void do_hex_dump(const char* buf, int len)
192 for( i=0; i<len ; i=i+16 )
195 for(x=0 ; i+x<len && x<16; ++x)
197 printf("%2.2X ",(unsigned int)((unsigned char)buf[i+x]));
202 if (dump_file_prefix)
205 if (++no < 1000 && strlen(dump_file_prefix) < 500)
209 sprintf (fname, "%s.%03d.raw", dump_file_prefix, no);
210 of = fopen(fname, "wb");
212 fwrite (buf, 1, len, of);
219 void add_otherInfos(Z_APDU *a)
221 Z_OtherInformation **oi;
225 for(i=0; i<maxOtherInfosSupported; ++i)
227 if(extraOtherInfos[i].oidval != -1)
228 yaz_oi_set_string_oidval(oi, out, extraOtherInfos[i].oidval,
229 1, extraOtherInfos[i].value);
233 int send_apdu(Z_APDU *a)
242 z_APDU(print, &a, 0, 0);
245 if (!z_APDU(out, &a, 0, 0))
247 odr_perror(out, "Encoding APDU");
251 buf = odr_getbuf(out, &len, 0);
253 odr_dumpBER(ber_file, buf, len);
254 /* printf ("sending APDU of size %d\n", len); */
255 do_hex_dump(buf, len);
256 if (cs_put(conn, buf, len) < 0)
258 fprintf(stderr, "cs_put: %s", cs_errmsg(cs_errno(conn)));
262 odr_reset(out); /* release the APDU structure */
266 static void print_stringn(const unsigned char *buf, size_t len)
269 for (i = 0; i<len; i++)
270 if ((buf[i] <= 126 && buf[i] >= 32) || strchr ("\n\r\t\f", buf[i]))
271 printf ("%c", buf[i]);
273 printf ("\\X%02X", buf[i]);
276 static void print_refid (Z_ReferenceId *id)
280 printf ("Reference Id: ");
281 print_stringn (id->buf, id->len);
286 static Z_ReferenceId *set_refid (ODR out)
291 id = (Z_ReferenceId *) odr_malloc (out, sizeof(*id));
292 id->size = id->len = strlen(refid);
293 id->buf = (unsigned char *) odr_malloc (out, id->len);
294 memcpy (id->buf, refid, id->len);
298 /* INIT SERVICE ------------------------------- */
300 static void send_initRequest(const char* type_and_host)
302 Z_APDU *apdu = zget_APDU(out, Z_APDU_initRequest);
303 Z_InitRequest *req = apdu->u.initRequest;
306 req->options = &z3950_options;
308 ODR_MASK_ZERO(req->protocolVersion);
309 for (i = 0; i<z3950_version; i++)
310 ODR_MASK_SET(req->protocolVersion, i);
312 *req->maximumRecordSize = 1024*kilobytes;
313 *req->preferredMessageSize = 1024*kilobytes;
315 req->idAuthentication = auth;
317 req->referenceId = set_refid (out);
319 if (yazProxy && type_and_host)
320 yaz_oi_set_string_oidval(&req->otherInfo, out, VAL_PROXY,
323 if (negotiationCharset || yazLang) {
324 Z_OtherInformation **p;
325 Z_OtherInformationUnit *p0;
327 yaz_oi_APDU(apdu, &p);
329 if ((p0=yaz_oi_update(p, out, NULL, 0, 0))) {
330 ODR_MASK_SET(req->options, Z_Options_negotiationModel);
332 p0->which = Z_OtherInfo_externallyDefinedInfo;
333 p0->information.externallyDefinedInfo =
334 yaz_set_proposal_charneg(
336 (const char**)&negotiationCharset,
337 negotiationCharset ? 1 : 0,
338 (const char**)&yazLang, yazLang ? 1 : 0,
339 negotiationCharsetRecords);
344 printf("Sent initrequest.\n");
348 /* These two are used only from process_initResponse() */
349 static void render_initUserInfo(Z_OtherInformation *ui1);
350 static void render_diag(Z_DiagnosticFormat *diag);
352 static void pr_opt(const char *opt, void *clientData)
357 static int process_initResponse(Z_InitResponse *res)
360 /* save session parameters for later use */
361 session_mem = odr_extract_mem(in);
364 for (ver = 0; ver < 8; ver++)
365 if (!ODR_MASK_GET(res->protocolVersion, ver))
369 printf("Connection rejected by v%d target.\n", ver);
371 printf("Connection accepted by v%d target.\n", ver);
372 if (res->implementationId)
373 printf("ID : %s\n", res->implementationId);
374 if (res->implementationName)
375 printf("Name : %s\n", res->implementationName);
376 if (res->implementationVersion)
377 printf("Version: %s\n", res->implementationVersion);
378 if (res->userInformationField)
380 Z_External *uif = res->userInformationField;
381 if (uif->which == Z_External_userInfo1) {
382 render_initUserInfo(uif->u.userInfo1);
384 printf("UserInformationfield:\n");
385 if (!z_External(print, (Z_External**)&uif, 0, 0)) {
386 odr_perror(print, "Printing userinfo\n");
389 if (uif->which == Z_External_octet) {
390 printf("Guessing visiblestring:\n");
391 printf("'%s'\n", uif->u. octet_aligned->buf);
392 } else if (uif->which == Z_External_single) {
393 Odr_any *sat = uif->u.single_ASN1_type;
394 oident *oid = oid_getentbyoid(uif->direct_reference);
395 if (oid->value == VAL_OCLCUI) {
396 Z_OCLC_UserInformation *oclc_ui;
397 ODR decode = odr_createmem(ODR_DECODE);
398 odr_setbuf(decode, sat->buf, sat->len, 0);
399 if (!z_OCLC_UserInformation(decode, &oclc_ui, 0, 0))
400 printf ("Bad OCLC UserInformation:\n");
402 printf ("OCLC UserInformation:\n");
403 if (!z_OCLC_UserInformation(print, &oclc_ui, 0, 0))
404 printf ("Bad OCLC UserInformation spec\n");
409 /* Peek at any private Init-diagnostic APDUs */
410 printf("### NAUGHTY: External is '%.*s'\n", sat->len, sat->buf);
417 yaz_init_opt_decode(res->options, pr_opt, 0);
420 if (ODR_MASK_GET(res->options, Z_Options_namedResultSets))
423 if (ODR_MASK_GET(res->options, Z_Options_negotiationModel)) {
425 Z_CharSetandLanguageNegotiation *p =
426 yaz_get_charneg_record(res->otherInfo);
430 char *charset=NULL, *lang=NULL;
433 yaz_get_response_charneg(session_mem, p, &charset, &lang,
436 if (outputCharset && negotiationCharset) {
437 odr_set_charset (out, charset, outputCharset);
438 odr_set_charset (in, outputCharset, charset);
441 odr_set_charset (out, 0, 0);
442 odr_set_charset (in, 0, 0);
445 printf("Accepted character set : %s\n", charset);
446 printf("Accepted code language : %s\n", lang ? lang : "none");
447 printf("Accepted records in ...: %d\n", selected );
455 static void render_initUserInfo(Z_OtherInformation *ui1) {
457 printf("Init response contains %d otherInfo unit%s:\n",
458 ui1->num_elements, ui1->num_elements == 1 ? "" : "s");
460 for (i = 0; i < ui1->num_elements; i++) {
461 Z_OtherInformationUnit *unit = ui1->list[i];
462 printf(" %d: otherInfo unit contains ", i+1);
463 if (unit->which == Z_OtherInfo_externallyDefinedInfo &&
464 unit->information.externallyDefinedInfo->which ==
466 render_diag(unit->information.externallyDefinedInfo->u.diag1);
468 printf("unsupported otherInfo unit type %d\n", unit->which);
474 /* ### should this share code with display_diagrecs()? */
475 static void render_diag(Z_DiagnosticFormat *diag) {
478 printf("%d diagnostic%s:\n", diag->num, diag->num == 1 ? "" : "s");
479 for (i = 0; i < diag->num; i++) {
480 Z_DiagnosticFormat_s *ds = diag->elements[i];
481 printf(" %d: ", i+1);
483 case Z_DiagnosticFormat_s_defaultDiagRec: {
484 Z_DefaultDiagFormat *dd = ds->u.defaultDiagRec;
485 /* ### should check `dd->diagnosticSetId' */
486 printf("code=%d (%s)", *dd->condition,
487 diagbib1_str(*dd->condition));
488 /* Both types of addinfo are the same, so use type-pun */
489 if (dd->u.v2Addinfo != 0)
490 printf(",\n\taddinfo='%s'", dd->u.v2Addinfo);
493 case Z_DiagnosticFormat_s_explicitDiagnostic:
494 printf("Explicit diagnostic (not supported)");
497 printf("Unrecognised diagnostic type %d", ds->which);
501 if (ds->message != 0)
502 printf(", message='%s'", ds->message);
508 static int set_base(const char *arg)
513 for (i = 0; i<num_databaseNames; i++)
514 xfree (databaseNames[i]);
515 num_databaseNames = 0;
519 if (!(cp = strchr(arg, ' ')))
520 cp = arg + strlen(arg);
523 databaseNames[num_databaseNames] = (char *)xmalloc (1 + cp - arg);
524 memcpy (databaseNames[num_databaseNames], arg, cp - arg);
525 databaseNames[num_databaseNames][cp - arg] = '\0';
527 for (cp1 = databaseNames[num_databaseNames]; *cp1 ; cp1++)
536 if (num_databaseNames == 0)
538 num_databaseNames = 1;
539 databaseNames[0] = xstrdup("");
544 static int cmd_base(const char *arg)
548 printf("Usage: base <database> <database> ...\n");
551 return set_base(arg);
554 void cmd_open_remember_last_open_command(const char* arg, char* new_open_command)
556 if(last_open_command != arg)
558 if(last_open_command) xfree(last_open_command);
559 last_open_command = xstrdup(new_open_command);
563 int session_connect(const char *arg)
566 char type_and_host[101];
567 const char *basep = 0;
568 #if HAVE_OPENSSL_SSL_H
577 nmem_destroy (session_mem);
581 cs_get_host_args(arg, &basep);
583 strncpy(type_and_host, arg, sizeof(type_and_host)-1);
584 type_and_host[sizeof(type_and_host)-1] = '\0';
586 cmd_open_remember_last_open_command(arg,type_and_host);
589 conn = cs_create_host(yazProxy, 1, &add);
591 conn = cs_create_host(arg, 1, &add);
594 printf ("Couldn't create comstack\n");
598 if (conn->protocol == PROTO_HTTP)
599 queryType = QueryType_CQL;
601 if (conn->protocol == PROTO_HTTP)
603 printf ("SRW/HTTP not enabled in this YAZ\n");
609 protocol = conn->protocol;
610 if (conn->protocol == PROTO_HTTP)
614 printf("Connecting...");
616 if (cs_connect(conn, add) < 0)
618 printf ("error = %s\n", cs_strerror(conn));
619 if (conn->cerrno == CSYSERR)
622 yaz_strerror(msg, sizeof(msg));
623 printf ("%s\n", msg);
630 #if HAVE_OPENSSL_SSL_H
631 if ((ssl = (SSL *) cs_get_ssl(conn)))
633 X509 *server_cert = SSL_get_peer_certificate (ssl);
639 BIO *bio = BIO_new(BIO_s_mem());
641 /* get PEM buffer in memory */
642 PEM_write_bio_X509(bio, server_cert);
643 pem_len = BIO_get_mem_data(bio, &pem_buf);
644 fwrite(pem_buf, pem_len, 1, stdout);
646 /* print all info on screen .. */
647 X509_print_fp(stdout, server_cert);
650 X509_free (server_cert);
656 if (protocol == PROTO_Z3950)
658 send_initRequest(type_and_host);
664 int cmd_open(const char *arg)
668 strncpy (cur_host, arg, sizeof(cur_host)-1);
669 cur_host[sizeof(cur_host)-1] = 0;
671 return session_connect(cur_host);
678 if(!( auto_reconnect && last_open_command) ) return ;
680 open_command = (char *) xmalloc (strlen(last_open_command)+6);
681 strcpy (open_command, "open ");
683 strcat (open_command, last_open_command);
685 process_cmd_line(open_command);
690 int cmd_authentication(const char *arg)
692 static Z_IdAuthentication au;
693 static char user[40], group[40], pass[40];
694 static Z_IdPass idPass;
699 printf("Auth field set to null\n");
703 r = sscanf (arg, "%39s %39s %39s", user, group, pass);
706 printf("Authentication set to null\n");
712 if (!strcmp(user, "-")) {
713 au.which = Z_IdAuthentication_anonymous;
714 printf("Authentication set to Anonymous\n");
716 au.which = Z_IdAuthentication_open;
718 printf("Authentication set to Open (%s)\n", user);
724 au.which = Z_IdAuthentication_idPass;
725 au.u.idPass = &idPass;
726 idPass.groupId = NULL;
727 idPass.userId = user;
728 idPass.password = group;
729 printf("Authentication set to User (%s), Pass (%s)\n", user, group);
734 au.which = Z_IdAuthentication_idPass;
735 au.u.idPass = &idPass;
736 idPass.groupId = group;
737 idPass.userId = user;
738 idPass.password = pass;
739 printf("Authentication set to User (%s), Group (%s), Pass (%s)\n",
745 /* SEARCH SERVICE ------------------------------ */
746 static void display_record(Z_External *r);
748 static void print_record(const unsigned char *buf, size_t len)
751 print_stringn (buf, len);
752 /* add newline if not already added ... */
753 if (i <= 0 || buf[i-1] != '\n')
756 fwrite (buf, 1, len, marc_file);
759 static void display_record(Z_External *r)
761 oident *ent = oid_getentbyoid(r->direct_reference);
765 * Tell the user what we got.
767 if (r->direct_reference)
769 printf("Record type: ");
771 printf("%s\n", ent->desc);
772 else if (!odr_oid(print, &r->direct_reference, 0, 0))
774 odr_perror(print, "print oid");
778 /* Check if this is a known, ASN.1 type tucked away in an octet string */
779 if (ent && r->which == Z_External_octet)
781 Z_ext_typeent *type = z_ext_getentbyref(ent->value);
787 * Call the given decoder to process the record.
789 odr_setbuf(in, (char*)r->u.octet_aligned->buf,
790 r->u.octet_aligned->len, 0);
791 if (!(*type->fun)(in, &rr, 0, 0))
793 odr_perror(in, "Decoding constructed record.");
794 fprintf(stdout, "[Near %d]\n", odr_offset(in));
795 fprintf(stdout, "Packet dump:\n---------\n");
796 odr_dumpBER(stdout, (char*)r->u.octet_aligned->buf,
797 r->u.octet_aligned->len);
798 fprintf(stdout, "---------\n");
800 /* note just ignores the error ant print the bytes form the octet_aligned later */
803 * Note: we throw away the original, BER-encoded record here.
804 * Do something else with it if you want to keep it.
806 r->u.sutrs = (Z_SUTRS *) rr; /* we don't actually check the type here. */
807 r->which = type->what;
811 if (ent && ent->value == VAL_SOIF)
812 print_record((const unsigned char *) r->u.octet_aligned->buf,
813 r->u.octet_aligned->len);
814 else if (r->which == Z_External_octet)
816 const char *octet_buf = (char*)r->u.octet_aligned->buf;
817 if (ent->oclass == CLASS_RECSYN &&
818 (ent->value == VAL_TEXT_XML ||
819 ent->value == VAL_APPLICATION_XML ||
820 ent->value == VAL_HTML))
822 print_record((const unsigned char *) octet_buf,
823 r->u.octet_aligned->len);
825 else if (ent->value == VAL_POSTSCRIPT)
827 int size = r->u.octet_aligned->len;
830 print_record((const unsigned char *) octet_buf, size);
835 #if AVOID_MARC_DECODE
836 /* primitive check for a marc OID 5.1-29 except 16 */
837 ent->oidsuffix[0] == 5 && ent->oidsuffix[1] < 30 &&
838 ent->oidsuffix[1] != 16
847 yaz_marc_t mt = yaz_marc_create();
849 if (yaz_marc_decode_buf(mt, octet_buf,r->u.octet_aligned->len,
853 if (marcCharset && !strcmp(marcCharset, "auto"))
855 if (ent->value == VAL_USMARC)
857 if (octet_buf[9] == 'a')
865 else if (marcCharset)
867 if (outputCharset && from)
869 cd = yaz_iconv_open(outputCharset, from);
870 printf ("convert from %s to %s", from,
873 printf (" unsupported\n");
878 fwrite (result, 1, rlen, stdout);
882 size_t inbytesleft = rlen;
883 const char *inp = result;
887 size_t outbytesleft = sizeof(outbuf);
891 r = yaz_iconv (cd, (char**) &inp,
893 &outp, &outbytesleft);
894 if (r == (size_t) (-1))
896 int e = yaz_iconv_error(cd);
897 if (e != YAZ_ICONV_E2BIG)
900 fwrite (outbuf, outp - outbuf, 1, stdout);
906 printf ("bad MARC. Dumping as it is:\n");
907 print_record((const unsigned char*) octet_buf,
908 r->u.octet_aligned->len);
910 yaz_marc_destroy(mt);
916 print_record((const unsigned char*) octet_buf,
917 r->u.octet_aligned->len);
921 fwrite (octet_buf, 1, r->u.octet_aligned->len, marc_file);
923 else if (ent && ent->value == VAL_SUTRS)
925 if (r->which != Z_External_sutrs)
927 printf("Expecting single SUTRS type for SUTRS.\n");
930 print_record(r->u.sutrs->buf, r->u.sutrs->len);
932 else if (ent && ent->value == VAL_GRS1)
935 if (r->which != Z_External_grs1)
937 printf("Expecting single GRS type for GRS.\n");
941 yaz_display_grs1(w, r->u.grs1, 0);
945 else if ( /* OPAC display not complete yet .. */
946 ent && ent->value == VAL_OPAC)
949 if (r->u.opac->bibliographicRecord)
950 display_record(r->u.opac->bibliographicRecord);
951 for (i = 0; i<r->u.opac->num_holdingsData; i++)
953 Z_HoldingsRecord *h = r->u.opac->holdingsData[i];
954 if (h->which == Z_HoldingsRecord_marcHoldingsRecord)
956 printf ("MARC holdings %d\n", i);
957 display_record(h->u.marcHoldingsRecord);
959 else if (h->which == Z_HoldingsRecord_holdingsAndCirc)
963 Z_HoldingsAndCircData *data = h->u.holdingsAndCirc;
965 printf ("Data holdings %d\n", i);
966 if (data->typeOfRecord)
967 printf ("typeOfRecord: %s\n", data->typeOfRecord);
968 if (data->encodingLevel)
969 printf ("encodingLevel: %s\n", data->encodingLevel);
970 if (data->receiptAcqStatus)
971 printf ("receiptAcqStatus: %s\n", data->receiptAcqStatus);
972 if (data->generalRetention)
973 printf ("generalRetention: %s\n", data->generalRetention);
974 if (data->completeness)
975 printf ("completeness: %s\n", data->completeness);
976 if (data->dateOfReport)
977 printf ("dateOfReport: %s\n", data->dateOfReport);
979 printf ("nucCode: %s\n", data->nucCode);
980 if (data->localLocation)
981 printf ("localLocation: %s\n", data->localLocation);
982 if (data->shelvingLocation)
983 printf ("shelvingLocation: %s\n", data->shelvingLocation);
984 if (data->callNumber)
985 printf ("callNumber: %s\n", data->callNumber);
986 if (data->shelvingData)
987 printf ("shelvingData: %s\n", data->shelvingData);
988 if (data->copyNumber)
989 printf ("copyNumber: %s\n", data->copyNumber);
990 if (data->publicNote)
991 printf ("publicNote: %s\n", data->publicNote);
992 if (data->reproductionNote)
993 printf ("reproductionNote: %s\n", data->reproductionNote);
994 if (data->termsUseRepro)
995 printf ("termsUseRepro: %s\n", data->termsUseRepro);
996 if (data->enumAndChron)
997 printf ("enumAndChron: %s\n", data->enumAndChron);
998 for (j = 0; j<data->num_volumes; j++)
1000 printf ("volume %d\n", j);
1001 if (data->volumes[j]->enumeration)
1002 printf (" enumeration: %s\n",
1003 data->volumes[j]->enumeration);
1004 if (data->volumes[j]->chronology)
1005 printf (" chronology: %s\n",
1006 data->volumes[j]->chronology);
1007 if (data->volumes[j]->enumAndChron)
1008 printf (" enumAndChron: %s\n",
1009 data->volumes[j]->enumAndChron);
1011 for (j = 0; j<data->num_circulationData; j++)
1013 printf ("circulation %d\n", j);
1014 if (data->circulationData[j]->availableNow)
1015 printf (" availableNow: %d\n",
1016 *data->circulationData[j]->availableNow);
1017 if (data->circulationData[j]->availablityDate)
1018 printf (" availabiltyDate: %s\n",
1019 data->circulationData[j]->availablityDate);
1020 if (data->circulationData[j]->availableThru)
1021 printf (" availableThru: %s\n",
1022 data->circulationData[j]->availableThru);
1023 if (data->circulationData[j]->restrictions)
1024 printf (" restrictions: %s\n",
1025 data->circulationData[j]->restrictions);
1026 if (data->circulationData[j]->itemId)
1027 printf (" itemId: %s\n",
1028 data->circulationData[j]->itemId);
1029 if (data->circulationData[j]->renewable)
1030 printf (" renewable: %d\n",
1031 *data->circulationData[j]->renewable);
1032 if (data->circulationData[j]->onHold)
1033 printf (" onHold: %d\n",
1034 *data->circulationData[j]->onHold);
1035 if (data->circulationData[j]->enumAndChron)
1036 printf (" enumAndChron: %s\n",
1037 data->circulationData[j]->enumAndChron);
1038 if (data->circulationData[j]->midspine)
1039 printf (" midspine: %s\n",
1040 data->circulationData[j]->midspine);
1041 if (data->circulationData[j]->temporaryLocation)
1042 printf (" temporaryLocation: %s\n",
1043 data->circulationData[j]->temporaryLocation);
1050 printf("Unknown record representation.\n");
1051 if (!z_External(print, &r, 0, 0))
1053 odr_perror(print, "Printing external");
1059 static void display_diagrecs(Z_DiagRec **pp, int num)
1063 Z_DefaultDiagFormat *r;
1065 printf("Diagnostic message(s) from database:\n");
1066 for (i = 0; i<num; i++)
1068 Z_DiagRec *p = pp[i];
1069 if (p->which != Z_DiagRec_defaultFormat)
1071 printf("Diagnostic record not in default format.\n");
1075 r = p->u.defaultFormat;
1076 if (!(ent = oid_getentbyoid(r->diagnosticSetId)) ||
1077 ent->oclass != CLASS_DIAGSET || ent->value != VAL_BIB1)
1078 printf("Missing or unknown diagset\n");
1079 printf(" [%d] %s", *r->condition, diagbib1_str(*r->condition));
1082 case Z_DefaultDiagFormat_v2Addinfo:
1083 printf (" -- v2 addinfo '%s'\n", r->u.v2Addinfo);
1085 case Z_DefaultDiagFormat_v3Addinfo:
1086 printf (" -- v3 addinfo '%s'\n", r->u.v3Addinfo);
1093 static void display_nameplusrecord(Z_NamePlusRecord *p)
1095 if (p->databaseName)
1096 printf("[%s]", p->databaseName);
1097 if (p->which == Z_NamePlusRecord_surrogateDiagnostic)
1098 display_diagrecs(&p->u.surrogateDiagnostic, 1);
1099 else if (p->which == Z_NamePlusRecord_databaseRecord)
1100 display_record(p->u.databaseRecord);
1103 static void display_records(Z_Records *p)
1107 if (p->which == Z_Records_NSD)
1109 Z_DiagRec dr, *dr_p = &dr;
1110 dr.which = Z_DiagRec_defaultFormat;
1111 dr.u.defaultFormat = p->u.nonSurrogateDiagnostic;
1112 display_diagrecs (&dr_p, 1);
1114 else if (p->which == Z_Records_multipleNSD)
1115 display_diagrecs (p->u.multipleNonSurDiagnostics->diagRecs,
1116 p->u.multipleNonSurDiagnostics->num_diagRecs);
1119 printf("Records: %d\n", p->u.databaseOrSurDiagnostics->num_records);
1120 for (i = 0; i < p->u.databaseOrSurDiagnostics->num_records; i++)
1121 display_nameplusrecord(p->u.databaseOrSurDiagnostics->records[i]);
1125 static int send_deleteResultSetRequest(const char *arg)
1130 Z_APDU *apdu = zget_APDU(out, Z_APDU_deleteResultSetRequest);
1131 Z_DeleteResultSetRequest *req = apdu->u.deleteResultSetRequest;
1133 req->referenceId = set_refid (out);
1135 req->num_resultSetList =
1136 sscanf (arg, "%30s %30s %30s %30s %30s %30s %30s %30s",
1137 names[0], names[1], names[2], names[3],
1138 names[4], names[5], names[6], names[7]);
1140 req->deleteFunction = (int *)
1141 odr_malloc (out, sizeof(*req->deleteFunction));
1142 if (req->num_resultSetList > 0)
1144 *req->deleteFunction = Z_DeleteResultSetRequest_list;
1145 req->resultSetList = (char **)
1146 odr_malloc (out, sizeof(*req->resultSetList)*
1147 req->num_resultSetList);
1148 for (i = 0; i<req->num_resultSetList; i++)
1149 req->resultSetList[i] = names[i];
1153 *req->deleteFunction = Z_DeleteResultSetRequest_all;
1154 req->resultSetList = 0;
1158 printf("Sent deleteResultSetRequest.\n");
1163 static int send_srw(Z_SRW_PDU *sr)
1165 const char *charset = negotiationCharset;
1166 const char *host_port = cur_host;
1169 Z_SOAP_Handler h[2] = {
1170 {"http://www.loc.gov/zing/srw/", 0, (Z_SOAP_fun) yaz_srw_codec},
1173 ODR o = odr_createmem(ODR_ENCODE);
1175 Z_SOAP *p = odr_malloc(o, sizeof(*p));
1178 path = odr_malloc(out, strlen(databaseNames[0])+2);
1180 strcpy(path+1, databaseNames[0]);
1182 gdu = z_get_HTTP_Request(out);
1183 gdu->u.HTTP_Request->version = http_version;
1184 gdu->u.HTTP_Request->path = odr_strdup(out, path);
1188 const char *cp0 = strstr(host_port, "://");
1189 const char *cp1 = 0;
1195 cp1 = strchr(cp0, '/');
1197 cp1 = cp0+strlen(cp0);
1201 char *h = odr_malloc(out, cp1 - cp0 + 1);
1202 memcpy (h, cp0, cp1 - cp0);
1204 z_HTTP_header_add(out, &gdu->u.HTTP_Request->headers,
1209 strcpy(ctype, "text/xml");
1210 if (charset && strlen(charset) < 20)
1212 strcat(ctype, "; charset=");
1213 strcat(ctype, charset);
1215 z_HTTP_header_add(out, &gdu->u.HTTP_Request->headers,
1216 "Content-Type", ctype);
1217 z_HTTP_header_add(out, &gdu->u.HTTP_Request->headers,
1218 "SOAPAction", "\"\"");
1219 p->which = Z_SOAP_generic;
1220 p->u.generic = odr_malloc(o, sizeof(*p->u.generic));
1221 p->u.generic->no = 0;
1222 p->u.generic->ns = 0;
1223 p->u.generic->p = sr;
1224 p->ns = "http://schemas.xmlsoap.org/soap/envelope/";
1226 ret = z_soap_codec_enc(o, &p,
1227 &gdu->u.HTTP_Request->content_buf,
1228 &gdu->u.HTTP_Request->content_len, h,
1231 if (z_GDU(out, &gdu, 0, 0))
1239 if (!z_GDU(print, &gdu, 0, 0))
1240 printf ("Failed to print outgoing APDU\n");
1243 buf_out = odr_getbuf(out, &len_out, 0);
1245 /* we don't odr_reset(out), since we may need the buffer again */
1247 do_hex_dump(buf_out, len_out);
1249 r = cs_put(conn, buf_out, len_out);
1261 static int send_SRW_scanRequest(const char *arg, int pos, int num)
1265 /* regular requestse .. */
1266 sr = yaz_srw_get(out, Z_SRW_scan_request);
1271 sr->u.scan_request->query_type = Z_SRW_query_type_cql;
1272 sr->u.scan_request->scanClause.cql = odr_strdup(out, arg);
1274 case QueryType_Prefix:
1275 sr->u.scan_request->query_type = Z_SRW_query_type_pqf;
1276 sr->u.scan_request->scanClause.pqf = odr_strdup(out, arg);
1279 printf ("Only CQL and PQF supported in SRW\n");
1282 sr->u.scan_request->responsePosition = odr_intdup(out, pos);
1283 sr->u.scan_request->maximumTerms = odr_intdup(out, num);
1284 return send_srw(sr);
1287 static int send_SRW_searchRequest(const char *arg)
1293 assert(srw_sr_odr_out == 0);
1294 srw_sr_odr_out = odr_createmem(ODR_ENCODE);
1296 odr_reset(srw_sr_odr_out);
1300 /* save this for later .. when fetching individual records */
1301 srw_sr = yaz_srw_get(srw_sr_odr_out, Z_SRW_searchRetrieve_request);
1303 /* regular request .. */
1304 sr = yaz_srw_get(out, Z_SRW_searchRetrieve_request);
1309 srw_sr->u.request->query_type = Z_SRW_query_type_cql;
1310 srw_sr->u.request->query.cql = odr_strdup(srw_sr_odr_out, arg);
1312 sr->u.request->query_type = Z_SRW_query_type_cql;
1313 sr->u.request->query.cql = odr_strdup(out, arg);
1315 case QueryType_Prefix:
1316 srw_sr->u.request->query_type = Z_SRW_query_type_pqf;
1317 srw_sr->u.request->query.pqf = odr_strdup(srw_sr_odr_out, arg);
1319 sr->u.request->query_type = Z_SRW_query_type_pqf;
1320 sr->u.request->query.pqf = odr_strdup(out, arg);
1323 printf ("Only CQL and PQF supported in SRW\n");
1326 sr->u.request->maximumRecords = odr_intdup(out, 0);
1329 sr->u.request->recordSchema = record_schema;
1330 if (recordsyntax == VAL_TEXT_XML)
1331 sr->u.explain_request->recordPacking = "xml";
1332 return send_srw(sr);
1336 static int send_searchRequest(const char *arg)
1338 Z_APDU *apdu = zget_APDU(out, Z_APDU_searchRequest);
1339 Z_SearchRequest *req = apdu->u.searchRequest;
1341 struct ccl_rpn_node *rpn = NULL;
1343 char setstring[100];
1344 Z_RPNQuery *RPNquery;
1346 YAZ_PQF_Parser pqf_parser;
1348 QueryType myQueryType = queryType;
1351 if (myQueryType == QueryType_CCL2RPN)
1353 rpn = ccl_find_str(bibset, arg, &error, &pos);
1356 printf("CCL ERROR: %s\n", ccl_err_msg(error));
1359 } else if (myQueryType == QueryType_CQL2RPN) {
1360 /* ### All this code should be wrapped in a utility function */
1362 struct cql_node *node;
1363 const char *addinfo;
1364 if (cqltrans == 0) {
1365 printf("Can't use CQL: no translation file. Try set_cqlfile\n");
1368 parser = cql_parser_create();
1369 if ((error = cql_parser_string(parser, arg)) != 0) {
1370 printf("Can't parse CQL: must be a syntax error\n");
1373 node = cql_parser_result(parser);
1374 if ((error = cql_transform_buf(cqltrans, node, pqfbuf,
1375 sizeof pqfbuf)) != 0) {
1376 error = cql_transform_error(cqltrans, &addinfo);
1377 printf ("Can't convert CQL to PQF: %s (addinfo=%s)\n",
1378 cql_strerror(error), addinfo);
1382 myQueryType = QueryType_Prefix;
1385 req->referenceId = set_refid (out);
1386 if (!strcmp(arg, "@big")) /* strictly for troublemaking */
1388 static unsigned char big[2100];
1389 static Odr_oct bigo;
1391 /* send a very big referenceid to test transport stack etc. */
1392 memset(big, 'A', 2100);
1393 bigo.len = bigo.size = 2100;
1395 req->referenceId = &bigo;
1400 sprintf(setstring, "%d", ++setnumber);
1401 req->resultSetName = setstring;
1403 *req->smallSetUpperBound = smallSetUpperBound;
1404 *req->largeSetLowerBound = largeSetLowerBound;
1405 *req->mediumSetPresentNumber = mediumSetPresentNumber;
1406 if (smallSetUpperBound > 0 || (largeSetLowerBound > 1 &&
1407 mediumSetPresentNumber > 0))
1409 req->preferredRecordSyntax =
1410 yaz_oidval_to_z3950oid(out, CLASS_RECSYN, recordsyntax);
1412 req->smallSetElementSetNames =
1413 req->mediumSetElementSetNames = elementSetNames;
1415 req->num_databaseNames = num_databaseNames;
1416 req->databaseNames = databaseNames;
1418 req->query = &query;
1420 switch (myQueryType)
1422 case QueryType_Prefix:
1423 query.which = Z_Query_type_1;
1424 pqf_parser = yaz_pqf_create ();
1425 RPNquery = yaz_pqf_parse (pqf_parser, out, arg);
1428 const char *pqf_msg;
1430 int code = yaz_pqf_error (pqf_parser, &pqf_msg, &off);
1431 printf("%*s^\n", off+4, "");
1432 printf("Prefix query error: %s (code %d)\n", pqf_msg, code);
1434 yaz_pqf_destroy (pqf_parser);
1437 yaz_pqf_destroy (pqf_parser);
1438 query.u.type_1 = RPNquery;
1441 query.which = Z_Query_type_2;
1442 query.u.type_2 = &ccl_query;
1443 ccl_query.buf = (unsigned char*) arg;
1444 ccl_query.len = strlen(arg);
1446 case QueryType_CCL2RPN:
1447 query.which = Z_Query_type_1;
1448 RPNquery = ccl_rpn_query(out, rpn);
1451 printf ("Couldn't convert from CCL to RPN\n");
1454 query.u.type_1 = RPNquery;
1455 ccl_rpn_delete (rpn);
1458 query.which = Z_Query_type_104;
1459 ext = (Z_External *) odr_malloc(out, sizeof(*ext));
1460 ext->direct_reference = odr_getoidbystr(out, "1.2.840.10003.16.2");
1461 ext->indirect_reference = 0;
1462 ext->descriptor = 0;
1463 ext->which = Z_External_CQL;
1464 ext->u.cql = odr_strdup(out, arg);
1465 query.u.type_104 = ext;
1468 printf ("Unsupported query type\n");
1471 if (send_apdu(apdu))
1472 printf("Sent searchRequest.\n");
1477 /* display Query Expression as part of searchResult-1 */
1478 static void display_queryExpression (Z_QueryExpression *qe)
1482 if (qe->which == Z_QueryExpression_term)
1484 if (qe->u.term->queryTerm)
1486 Z_Term *term = qe->u.term->queryTerm;
1487 switch (term->which)
1489 case Z_Term_general:
1490 printf (" %.*s", term->u.general->len, term->u.general->buf);
1492 case Z_Term_characterString:
1493 printf (" %s", term->u.characterString);
1495 case Z_Term_numeric:
1496 printf (" %d", *term->u.numeric);
1506 /* see if we can find USR:SearchResult-1 */
1507 static void display_searchResult (Z_OtherInformation *o)
1512 for (i = 0; i < o->num_elements; i++)
1514 if (o->list[i]->which == Z_OtherInfo_externallyDefinedInfo)
1516 Z_External *ext = o->list[i]->information.externallyDefinedInfo;
1518 if (ext->which == Z_External_searchResult1)
1521 Z_SearchInfoReport *sr = ext->u.searchResult1;
1522 printf ("SearchResult-1:");
1523 for (j = 0; j < sr->num; j++)
1525 if (!sr->elements[j]->subqueryExpression)
1527 display_queryExpression (
1528 sr->elements[j]->subqueryExpression);
1529 display_queryExpression (
1530 sr->elements[j]->subqueryInterpretation);
1531 display_queryExpression (
1532 sr->elements[j]->subqueryRecommendation);
1533 if (sr->elements[j]->subqueryCount)
1534 printf ("(%d)", *sr->elements[j]->subqueryCount);
1542 static int process_searchResponse(Z_SearchResponse *res)
1544 printf ("Received SearchResponse.\n");
1545 print_refid (res->referenceId);
1546 if (*res->searchStatus)
1547 printf("Search was a success.\n");
1549 printf("Search was a bloomin' failure.\n");
1550 printf("Number of hits: %d", *res->resultCount);
1552 printf (", setno %d", setnumber);
1554 display_searchResult (res->additionalSearchInfo);
1555 printf("records returned: %d\n",
1556 *res->numberOfRecordsReturned);
1557 setno += *res->numberOfRecordsReturned;
1559 display_records(res->records);
1563 static void print_level(int iLevel)
1566 for (i = 0; i < iLevel * 4; i++)
1570 static void print_int(int iLevel, const char *pTag, int *pInt)
1574 print_level(iLevel);
1575 printf("%s: %d\n", pTag, *pInt);
1579 static void print_string(int iLevel, const char *pTag, const char *pString)
1581 if (pString != NULL)
1583 print_level(iLevel);
1584 printf("%s: %s\n", pTag, pString);
1588 static void print_oid(int iLevel, const char *pTag, Odr_oid *pOid)
1594 print_level(iLevel);
1595 printf("%s:", pTag);
1596 for (; *pInt != -1; pInt++)
1597 printf(" %d", *pInt);
1602 static void print_referenceId(int iLevel, Z_ReferenceId *referenceId)
1604 if (referenceId != NULL)
1608 print_level(iLevel);
1609 printf("Ref Id (%d, %d): ", referenceId->len, referenceId->size);
1610 for (i = 0; i < referenceId->len; i++)
1611 printf("%c", referenceId->buf[i]);
1616 static void print_string_or_numeric(int iLevel, const char *pTag, Z_StringOrNumeric *pStringNumeric)
1618 if (pStringNumeric != NULL)
1620 switch (pStringNumeric->which)
1622 case Z_StringOrNumeric_string:
1623 print_string(iLevel, pTag, pStringNumeric->u.string);
1626 case Z_StringOrNumeric_numeric:
1627 print_int(iLevel, pTag, pStringNumeric->u.numeric);
1631 print_level(iLevel);
1632 printf("%s: valid type for Z_StringOrNumeric\n", pTag);
1638 static void print_universe_report_duplicate(
1640 Z_UniverseReportDuplicate *pUniverseReportDuplicate)
1642 if (pUniverseReportDuplicate != NULL)
1644 print_level(iLevel);
1645 printf("Universe Report Duplicate: \n");
1647 print_string_or_numeric(iLevel, "Hit No",
1648 pUniverseReportDuplicate->hitno);
1652 static void print_universe_report_hits(
1654 Z_UniverseReportHits *pUniverseReportHits)
1656 if (pUniverseReportHits != NULL)
1658 print_level(iLevel);
1659 printf("Universe Report Hits: \n");
1661 print_string_or_numeric(iLevel, "Database",
1662 pUniverseReportHits->database);
1663 print_string_or_numeric(iLevel, "Hits", pUniverseReportHits->hits);
1667 static void print_universe_report(int iLevel, Z_UniverseReport *pUniverseReport)
1669 if (pUniverseReport != NULL)
1671 print_level(iLevel);
1672 printf("Universe Report: \n");
1674 print_int(iLevel, "Total Hits", pUniverseReport->totalHits);
1675 switch (pUniverseReport->which)
1677 case Z_UniverseReport_databaseHits:
1678 print_universe_report_hits(iLevel,
1679 pUniverseReport->u.databaseHits);
1682 case Z_UniverseReport_duplicate:
1683 print_universe_report_duplicate(iLevel,
1684 pUniverseReport->u.duplicate);
1688 print_level(iLevel);
1689 printf("Type: %d\n", pUniverseReport->which);
1695 static void print_external(int iLevel, Z_External *pExternal)
1697 if (pExternal != NULL)
1699 print_level(iLevel);
1700 printf("External: \n");
1702 print_oid(iLevel, "Direct Reference", pExternal->direct_reference);
1703 print_int(iLevel, "InDirect Reference", pExternal->indirect_reference);
1704 print_string(iLevel, "Descriptor", pExternal->descriptor);
1705 switch (pExternal->which)
1707 case Z_External_universeReport:
1708 print_universe_report(iLevel, pExternal->u.universeReport);
1712 print_level(iLevel);
1713 printf("Type: %d\n", pExternal->which);
1719 static int process_resourceControlRequest (Z_ResourceControlRequest *req)
1721 printf ("Received ResourceControlRequest.\n");
1722 print_referenceId(1, req->referenceId);
1723 print_int(1, "Suspended Flag", req->suspendedFlag);
1724 print_int(1, "Partial Results Available", req->partialResultsAvailable);
1725 print_int(1, "Response Required", req->responseRequired);
1726 print_int(1, "Triggered Request Flag", req->triggeredRequestFlag);
1727 print_external(1, req->resourceReport);
1731 void process_ESResponse(Z_ExtendedServicesResponse *res)
1734 switch (*res->operationStatus)
1736 case Z_ExtendedServicesResponse_done:
1739 case Z_ExtendedServicesResponse_accepted:
1740 printf ("accepted\n");
1742 case Z_ExtendedServicesResponse_failure:
1743 printf ("failure\n");
1744 display_diagrecs(res->diagnostics, res->num_diagnostics);
1747 printf ("unknown\n");
1749 if ( (*res->operationStatus != Z_ExtendedServicesResponse_failure) &&
1750 (res->num_diagnostics != 0) ) {
1751 display_diagrecs(res->diagnostics, res->num_diagnostics);
1753 print_refid (res->referenceId);
1754 if (res->taskPackage &&
1755 res->taskPackage->which == Z_External_extendedService)
1757 Z_TaskPackage *taskPackage = res->taskPackage->u.extendedService;
1758 Odr_oct *id = taskPackage->targetReference;
1759 Z_External *ext = taskPackage->taskSpecificParameters;
1763 printf ("Target Reference: ");
1764 print_stringn (id->buf, id->len);
1767 if (ext->which == Z_External_update)
1769 Z_IUUpdateTaskPackage *utp = ext->u.update->u.taskPackage;
1770 if (utp && utp->targetPart)
1772 Z_IUTargetPart *targetPart = utp->targetPart;
1775 for (i = 0; i<targetPart->num_taskPackageRecords; i++)
1778 Z_IUTaskPackageRecordStructure *tpr =
1779 targetPart->taskPackageRecords[i];
1780 printf ("task package record %d\n", i+1);
1781 if (tpr->which == Z_IUTaskPackageRecordStructure_record)
1783 display_record (tpr->u.record);
1787 printf ("other type\n");
1795 const char *get_ill_element (void *clientData, const char *element)
1800 static Z_External *create_external_itemRequest()
1802 struct ill_get_ctl ctl;
1803 ILL_ItemRequest *req;
1805 int item_request_size = 0;
1806 char *item_request_buf = 0;
1810 ctl.f = get_ill_element;
1812 req = ill_get_ItemRequest(&ctl, "ill", 0);
1814 printf ("ill_get_ItemRequest failed\n");
1816 if (!ill_ItemRequest (out, &req, 0, 0))
1820 ill_ItemRequest(print, &req, 0, 0);
1823 item_request_buf = odr_getbuf (out, &item_request_size, 0);
1824 if (item_request_buf)
1825 odr_setbuf (out, item_request_buf, item_request_size, 1);
1826 printf ("Couldn't encode ItemRequest, size %d\n", item_request_size);
1833 item_request_buf = odr_getbuf (out, &item_request_size, 0);
1834 oid.proto = PROTO_GENERAL;
1835 oid.oclass = CLASS_GENERAL;
1836 oid.value = VAL_ISO_ILL_1;
1838 r = (Z_External *) odr_malloc (out, sizeof(*r));
1839 r->direct_reference = odr_oiddup(out,oid_getoidbyent(&oid));
1840 r->indirect_reference = 0;
1842 r->which = Z_External_single;
1844 r->u.single_ASN1_type = (Odr_oct *)
1845 odr_malloc (out, sizeof(*r->u.single_ASN1_type));
1846 r->u.single_ASN1_type->buf = (unsigned char *)
1847 odr_malloc (out, item_request_size);
1848 r->u.single_ASN1_type->len = item_request_size;
1849 r->u.single_ASN1_type->size = item_request_size;
1850 memcpy (r->u.single_ASN1_type->buf, item_request_buf,
1853 do_hex_dump(item_request_buf,item_request_size);
1858 static Z_External *create_external_ILL_APDU(int which)
1860 struct ill_get_ctl ctl;
1863 int ill_request_size = 0;
1864 char *ill_request_buf = 0;
1868 ctl.f = get_ill_element;
1870 ill_apdu = ill_get_APDU(&ctl, "ill", 0);
1872 if (!ill_APDU (out, &ill_apdu, 0, 0))
1876 printf ("-------------------\n");
1877 ill_APDU(print, &ill_apdu, 0, 0);
1879 printf ("-------------------\n");
1881 ill_request_buf = odr_getbuf (out, &ill_request_size, 0);
1882 if (ill_request_buf)
1883 odr_setbuf (out, ill_request_buf, ill_request_size, 1);
1884 printf ("Couldn't encode ILL-Request, size %d\n", ill_request_size);
1890 ill_request_buf = odr_getbuf (out, &ill_request_size, 0);
1892 oid.proto = PROTO_GENERAL;
1893 oid.oclass = CLASS_GENERAL;
1894 oid.value = VAL_ISO_ILL_1;
1896 r = (Z_External *) odr_malloc (out, sizeof(*r));
1897 r->direct_reference = odr_oiddup(out,oid_getoidbyent(&oid));
1898 r->indirect_reference = 0;
1900 r->which = Z_External_single;
1902 r->u.single_ASN1_type = (Odr_oct *)
1903 odr_malloc (out, sizeof(*r->u.single_ASN1_type));
1904 r->u.single_ASN1_type->buf = (unsigned char *)
1905 odr_malloc (out, ill_request_size);
1906 r->u.single_ASN1_type->len = ill_request_size;
1907 r->u.single_ASN1_type->size = ill_request_size;
1908 memcpy (r->u.single_ASN1_type->buf, ill_request_buf, ill_request_size);
1909 /* printf ("len = %d\n", ill_request_size); */
1910 /* do_hex_dump(ill_request_buf,ill_request_size); */
1911 /* printf("--- end of extenal\n"); */
1918 static Z_External *create_ItemOrderExternal(const char *type, int itemno)
1920 Z_External *r = (Z_External *) odr_malloc(out, sizeof(Z_External));
1921 oident ItemOrderRequest;
1923 ItemOrderRequest.proto = PROTO_Z3950;
1924 ItemOrderRequest.oclass = CLASS_EXTSERV;
1925 ItemOrderRequest.value = VAL_ITEMORDER;
1927 r->direct_reference = odr_oiddup(out,oid_getoidbyent(&ItemOrderRequest));
1928 r->indirect_reference = 0;
1931 r->which = Z_External_itemOrder;
1933 r->u.itemOrder = (Z_ItemOrder *) odr_malloc(out,sizeof(Z_ItemOrder));
1934 memset(r->u.itemOrder, 0, sizeof(Z_ItemOrder));
1935 r->u.itemOrder->which=Z_IOItemOrder_esRequest;
1937 r->u.itemOrder->u.esRequest = (Z_IORequest *)
1938 odr_malloc(out,sizeof(Z_IORequest));
1939 memset(r->u.itemOrder->u.esRequest, 0, sizeof(Z_IORequest));
1941 r->u.itemOrder->u.esRequest->toKeep = (Z_IOOriginPartToKeep *)
1942 odr_malloc(out,sizeof(Z_IOOriginPartToKeep));
1943 memset(r->u.itemOrder->u.esRequest->toKeep, 0, sizeof(Z_IOOriginPartToKeep));
1944 r->u.itemOrder->u.esRequest->notToKeep = (Z_IOOriginPartNotToKeep *)
1945 odr_malloc(out,sizeof(Z_IOOriginPartNotToKeep));
1946 memset(r->u.itemOrder->u.esRequest->notToKeep, 0, sizeof(Z_IOOriginPartNotToKeep));
1948 r->u.itemOrder->u.esRequest->toKeep->supplDescription = NULL;
1949 r->u.itemOrder->u.esRequest->toKeep->contact = NULL;
1950 r->u.itemOrder->u.esRequest->toKeep->addlBilling = NULL;
1952 r->u.itemOrder->u.esRequest->notToKeep->resultSetItem =
1953 (Z_IOResultSetItem *) odr_malloc(out, sizeof(Z_IOResultSetItem));
1954 memset(r->u.itemOrder->u.esRequest->notToKeep->resultSetItem, 0, sizeof(Z_IOResultSetItem));
1955 r->u.itemOrder->u.esRequest->notToKeep->resultSetItem->resultSetId = "1";
1957 r->u.itemOrder->u.esRequest->notToKeep->resultSetItem->item =
1958 (int *) odr_malloc(out, sizeof(int));
1959 *r->u.itemOrder->u.esRequest->notToKeep->resultSetItem->item = itemno;
1961 if (!strcmp (type, "item") || !strcmp(type, "2"))
1963 printf ("using item-request\n");
1964 r->u.itemOrder->u.esRequest->notToKeep->itemRequest =
1965 create_external_itemRequest();
1967 else if (!strcmp(type, "ill") || !strcmp(type, "1"))
1969 printf ("using ILL-request\n");
1970 r->u.itemOrder->u.esRequest->notToKeep->itemRequest =
1971 create_external_ILL_APDU(ILL_APDU_ILL_Request);
1973 else if (!strcmp(type, "xml") || !strcmp(type, "3"))
1975 const char *xml_buf =
1977 " <type>request</type>\n"
1978 " <libraryNo>000200</libraryNo>\n"
1979 " <borrowerTicketNo> 1212 </borrowerTicketNo>\n"
1981 r->u.itemOrder->u.esRequest->notToKeep->itemRequest =
1982 z_ext_record (out, VAL_TEXT_XML, xml_buf, strlen(xml_buf));
1985 r->u.itemOrder->u.esRequest->notToKeep->itemRequest = 0;
1990 static int send_itemorder(const char *type, int itemno)
1992 Z_APDU *apdu = zget_APDU(out, Z_APDU_extendedServicesRequest);
1993 Z_ExtendedServicesRequest *req = apdu->u.extendedServicesRequest;
1994 oident ItemOrderRequest;
1996 ItemOrderRequest.proto = PROTO_Z3950;
1997 ItemOrderRequest.oclass = CLASS_EXTSERV;
1998 ItemOrderRequest.value = VAL_ITEMORDER;
1999 req->packageType = odr_oiddup(out,oid_getoidbyent(&ItemOrderRequest));
2000 req->packageName = esPackageName;
2002 req->taskSpecificParameters = create_ItemOrderExternal(type, itemno);
2008 static int only_z3950()
2010 if (protocol == PROTO_HTTP)
2012 printf ("Not supported by SRW\n");
2018 static int cmd_update_common(const char *arg, int version);
2020 static int cmd_update(const char *arg)
2022 return cmd_update_common(arg, 1);
2025 static int cmd_update0(const char *arg)
2027 return cmd_update_common(arg, 0);
2030 static int cmd_update_common(const char *arg, int version)
2032 Z_APDU *apdu = zget_APDU(out, Z_APDU_extendedServicesRequest );
2033 Z_ExtendedServicesRequest *req = apdu->u.extendedServicesRequest;
2035 char action[20], recid[20], fname[80];
2037 Z_External *record_this = 0;
2044 sscanf (arg, "%19s %19s %79s", action, recid, fname);
2046 if (!strcmp (action, "insert"))
2047 action_no = Z_IUOriginPartToKeep_recordInsert;
2048 else if (!strcmp (action, "replace"))
2049 action_no = Z_IUOriginPartToKeep_recordReplace;
2050 else if (!strcmp (action, "delete"))
2051 action_no = Z_IUOriginPartToKeep_recordDelete;
2052 else if (!strcmp (action, "update"))
2053 action_no = Z_IUOriginPartToKeep_specialUpdate;
2056 printf ("Bad action: %s\n", action);
2057 printf ("Possible values: insert, replace, delete, update\n");
2065 stat (fname, &status);
2066 if (S_ISREG(status.st_mode) && (inf = fopen(fname, "r")))
2068 size_t len = status.st_size;
2069 char *buf = (char *) xmalloc (len);
2071 fread (buf, 1, len, inf);
2075 record_this = z_ext_record (out, VAL_TEXT_XML, buf, len);
2081 printf ("File %s doesn't exist\n", fname);
2089 printf ("No last record (update ignored)\n");
2092 record_this = record_last;
2096 yaz_oidval_to_z3950oid(out, CLASS_EXTSERV,
2097 version == 0 ? VAL_DBUPDATE0 : VAL_DBUPDATE);
2099 req->packageName = esPackageName;
2101 req->referenceId = set_refid (out);
2103 r = req->taskSpecificParameters = (Z_External *)
2104 odr_malloc (out, sizeof(*r));
2105 r->direct_reference = req->packageType;
2106 r->indirect_reference = 0;
2110 Z_IU0OriginPartToKeep *toKeep;
2111 Z_IU0SuppliedRecords *notToKeep;
2113 r->which = Z_External_update0;
2114 r->u.update0 = (Z_IU0Update *) odr_malloc(out, sizeof(*r->u.update0));
2115 r->u.update0->which = Z_IUUpdate_esRequest;
2116 r->u.update0->u.esRequest = (Z_IU0UpdateEsRequest *)
2117 odr_malloc(out, sizeof(*r->u.update0->u.esRequest));
2118 toKeep = r->u.update0->u.esRequest->toKeep = (Z_IU0OriginPartToKeep *)
2119 odr_malloc(out, sizeof(*r->u.update0->u.esRequest->toKeep));
2121 toKeep->databaseName = databaseNames[0];
2123 toKeep->elementSetName = 0;
2125 toKeep->action = (int *) odr_malloc(out, sizeof(*toKeep->action));
2126 *toKeep->action = action_no;
2128 notToKeep = r->u.update0->u.esRequest->notToKeep = (Z_IU0SuppliedRecords *)
2129 odr_malloc(out, sizeof(*r->u.update0->u.esRequest->notToKeep));
2131 notToKeep->elements = (Z_IU0SuppliedRecords_elem **)
2132 odr_malloc(out, sizeof(*notToKeep->elements));
2133 notToKeep->elements[0] = (Z_IU0SuppliedRecords_elem *)
2134 odr_malloc(out, sizeof(**notToKeep->elements));
2135 notToKeep->elements[0]->which = Z_IUSuppliedRecords_elem_opaque;
2138 notToKeep->elements[0]->u.opaque = (Odr_oct *)
2139 odr_malloc (out, sizeof(Odr_oct));
2140 notToKeep->elements[0]->u.opaque->buf = (unsigned char *) recid;
2141 notToKeep->elements[0]->u.opaque->size = strlen(recid);
2142 notToKeep->elements[0]->u.opaque->len = strlen(recid);
2145 notToKeep->elements[0]->u.opaque = 0;
2146 notToKeep->elements[0]->supplementalId = 0;
2147 notToKeep->elements[0]->correlationInfo = 0;
2148 notToKeep->elements[0]->record = record_this;
2152 Z_IUOriginPartToKeep *toKeep;
2153 Z_IUSuppliedRecords *notToKeep;
2155 r->which = Z_External_update;
2156 r->u.update = (Z_IUUpdate *) odr_malloc(out, sizeof(*r->u.update));
2157 r->u.update->which = Z_IUUpdate_esRequest;
2158 r->u.update->u.esRequest = (Z_IUUpdateEsRequest *)
2159 odr_malloc(out, sizeof(*r->u.update->u.esRequest));
2160 toKeep = r->u.update->u.esRequest->toKeep = (Z_IUOriginPartToKeep *)
2161 odr_malloc(out, sizeof(*r->u.update->u.esRequest->toKeep));
2163 toKeep->databaseName = databaseNames[0];
2165 toKeep->elementSetName = 0;
2166 toKeep->actionQualifier = 0;
2167 toKeep->action = (int *) odr_malloc(out, sizeof(*toKeep->action));
2168 *toKeep->action = action_no;
2170 notToKeep = r->u.update->u.esRequest->notToKeep = (Z_IUSuppliedRecords *)
2171 odr_malloc(out, sizeof(*r->u.update->u.esRequest->notToKeep));
2173 notToKeep->elements = (Z_IUSuppliedRecords_elem **)
2174 odr_malloc(out, sizeof(*notToKeep->elements));
2175 notToKeep->elements[0] = (Z_IUSuppliedRecords_elem *)
2176 odr_malloc(out, sizeof(**notToKeep->elements));
2177 notToKeep->elements[0]->which = Z_IUSuppliedRecords_elem_opaque;
2180 notToKeep->elements[0]->u.opaque = (Odr_oct *)
2181 odr_malloc (out, sizeof(Odr_oct));
2182 notToKeep->elements[0]->u.opaque->buf = (unsigned char *) recid;
2183 notToKeep->elements[0]->u.opaque->size = strlen(recid);
2184 notToKeep->elements[0]->u.opaque->len = strlen(recid);
2187 notToKeep->elements[0]->u.opaque = 0;
2188 notToKeep->elements[0]->supplementalId = 0;
2189 notToKeep->elements[0]->correlationInfo = 0;
2190 notToKeep->elements[0]->record = record_this;
2198 static int cmd_itemorder(const char *arg)
2205 if (sscanf (arg, "%10s %d", type, &itemno) != 2)
2208 printf("Item order request\n");
2210 send_itemorder(type, itemno);
2214 static void show_opt(const char *arg, void *clientData)
2216 printf ("%s ", arg);
2219 static int cmd_zversion(const char *arg)
2222 z3950_version = atoi(arg);
2224 printf ("version is %d\n", z3950_version);
2228 static int cmd_options(const char *arg)
2234 r = yaz_init_opt_encode(&z3950_options, arg, &pos);
2238 yaz_init_opt_decode(&z3950_options, show_opt, 0);
2244 static int cmd_explain(const char *arg)
2246 if (protocol != PROTO_HTTP)
2257 /* save this for later .. when fetching individual records */
2258 sr = yaz_srw_get(out, Z_SRW_explain_request);
2259 if (recordsyntax == VAL_TEXT_XML)
2260 sr->u.explain_request->recordPacking = "xml";
2268 static int cmd_init(const char *arg)
2270 if (!conn || protocol != PROTO_Z3950)
2272 send_initRequest(0);
2276 static int cmd_find(const char *arg)
2280 printf("Find what?\n");
2283 if (protocol == PROTO_HTTP)
2290 if (!send_SRW_searchRequest(arg))
2303 printf("Not connected yet\n");
2307 if (!send_searchRequest(arg))
2313 static int cmd_delete(const char *arg)
2317 printf("Not connected yet\n");
2322 if (!send_deleteResultSetRequest(arg))
2327 static int cmd_ssub(const char *arg)
2329 if (!(smallSetUpperBound = atoi(arg)))
2334 static int cmd_lslb(const char *arg)
2338 if (!(largeSetLowerBound = atoi(arg)))
2343 static int cmd_mspn(const char *arg)
2347 if (!(mediumSetPresentNumber = atoi(arg)))
2352 static int cmd_status(const char *arg)
2354 printf("smallSetUpperBound: %d\n", smallSetUpperBound);
2355 printf("largeSetLowerBound: %d\n", largeSetLowerBound);
2356 printf("mediumSetPresentNumber: %d\n", mediumSetPresentNumber);
2360 static int cmd_setnames(const char *arg)
2362 if (*arg == '1') /* enable ? */
2364 else if (*arg == '0') /* disable ? */
2366 else if (setnumber < 0) /* no args, toggle .. */
2372 printf("Set numbering enabled.\n");
2374 printf("Set numbering disabled.\n");
2378 /* PRESENT SERVICE ----------------------------- */
2380 static void parse_show_args(const char *arg_c, char *setstring,
2381 int *start, int *number)
2386 strncpy(arg, arg_c, sizeof(arg)-1);
2387 arg[sizeof(arg)-1] = '\0';
2389 if ((p = strchr(arg, '+')))
2391 *number = atoi(p + 1);
2396 if (p && (p=strchr(p+1, '+')))
2397 strcpy (setstring, p+1);
2398 else if (setnumber >= 0)
2399 sprintf(setstring, "%d", setnumber);
2404 static int send_presentRequest(const char *arg)
2406 Z_APDU *apdu = zget_APDU(out, Z_APDU_presentRequest);
2407 Z_PresentRequest *req = apdu->u.presentRequest;
2408 Z_RecordComposition compo;
2410 char setstring[100];
2412 req->referenceId = set_refid (out);
2414 parse_show_args(arg, setstring, &setno, &nos);
2416 req->resultSetId = setstring;
2418 req->resultSetStartPoint = &setno;
2419 req->numberOfRecordsRequested = &nos;
2421 req->preferredRecordSyntax =
2422 yaz_oidval_to_z3950oid(out, CLASS_RECSYN, recordsyntax);
2426 req->recordComposition = &compo;
2427 compo.which = Z_RecordComp_complex;
2428 compo.u.complex = (Z_CompSpec *)
2429 odr_malloc(out, sizeof(*compo.u.complex));
2430 compo.u.complex->selectAlternativeSyntax = (bool_t *)
2431 odr_malloc(out, sizeof(bool_t));
2432 *compo.u.complex->selectAlternativeSyntax = 0;
2434 compo.u.complex->generic = (Z_Specification *)
2435 odr_malloc(out, sizeof(*compo.u.complex->generic));
2436 compo.u.complex->generic->which = Z_Schema_oid;
2438 compo.u.complex->generic->schema.oid =
2439 yaz_str_to_z3950oid(out, CLASS_SCHEMA, record_schema);
2441 if (!compo.u.complex->generic->schema.oid)
2443 /* OID wasn't a schema! Try record syntax instead. */
2444 compo.u.complex->generic->schema.oid = (Odr_oid *)
2445 yaz_str_to_z3950oid(out, CLASS_RECSYN, record_schema);
2447 if (!elementSetNames)
2448 compo.u.complex->generic->elementSpec = 0;
2451 compo.u.complex->generic->elementSpec = (Z_ElementSpec *)
2452 odr_malloc(out, sizeof(Z_ElementSpec));
2453 compo.u.complex->generic->elementSpec->which =
2454 Z_ElementSpec_elementSetName;
2455 compo.u.complex->generic->elementSpec->u.elementSetName =
2456 elementSetNames->u.generic;
2458 compo.u.complex->num_dbSpecific = 0;
2459 compo.u.complex->dbSpecific = 0;
2460 compo.u.complex->num_recordSyntax = 0;
2461 compo.u.complex->recordSyntax = 0;
2463 else if (elementSetNames)
2465 req->recordComposition = &compo;
2466 compo.which = Z_RecordComp_simple;
2467 compo.u.simple = elementSetNames;
2470 printf("Sent presentRequest (%d+%d).\n", setno, nos);
2475 static int send_SRW_presentRequest(const char *arg)
2477 char setstring[100];
2479 Z_SRW_PDU *sr = srw_sr;
2483 parse_show_args(arg, setstring, &setno, &nos);
2484 sr->u.request->startRecord = odr_intdup(out, setno);
2485 sr->u.request->maximumRecords = odr_intdup(out, nos);
2487 sr->u.request->recordSchema = record_schema;
2488 if (recordsyntax == VAL_TEXT_XML)
2489 sr->u.request->recordPacking = "xml";
2490 return send_srw(sr);
2494 static void close_session (void)
2501 nmem_destroy (session_mem);
2510 void process_close(Z_Close *req)
2512 Z_APDU *apdu = zget_APDU(out, Z_APDU_close);
2513 Z_Close *res = apdu->u.close;
2515 static char *reasons[] =
2520 "cost limit reached",
2522 "security violation",
2529 printf("Reason: %s, message: %s\n", reasons[*req->closeReason],
2530 req->diagnosticInformation ? req->diagnosticInformation : "NULL");
2535 *res->closeReason = Z_Close_finished;
2537 printf("Sent response.\n");
2542 static int cmd_show(const char *arg)
2544 if (protocol == PROTO_HTTP)
2551 if (!send_SRW_presentRequest(arg))
2561 printf("Not connected yet\n");
2564 if (!send_presentRequest(arg))
2570 int cmd_quit(const char *arg)
2572 printf("See you later, alligator.\n");
2578 int cmd_cancel(const char *arg)
2580 Z_APDU *apdu = zget_APDU(out, Z_APDU_triggerResourceControlRequest);
2581 Z_TriggerResourceControlRequest *req =
2582 apdu->u.triggerResourceControlRequest;
2587 printf("Session not initialized yet\n");
2592 if (!ODR_MASK_GET(session->options, Z_Options_triggerResourceCtrl))
2594 printf("Target doesn't support cancel (trigger resource ctrl)\n");
2597 *req->requestedAction = Z_TriggerResourceControlRequest_cancel;
2598 req->resultSetWanted = &rfalse;
2599 req->referenceId = set_refid (out);
2602 printf("Sent cancel request\n");
2607 int cmd_cancel_find(const char *arg) {
2611 return cmd_cancel("");
2616 int send_scanrequest(const char *query, int pp, int num, const char *term)
2618 Z_APDU *apdu = zget_APDU(out, Z_APDU_scanRequest);
2619 Z_ScanRequest *req = apdu->u.scanRequest;
2623 if (queryType == QueryType_CCL2RPN)
2626 struct ccl_rpn_node *rpn;
2628 rpn = ccl_find_str (bibset, query, &error, &pos);
2631 printf("CCL ERROR: %s\n", ccl_err_msg(error));
2635 yaz_oidval_to_z3950oid(out, CLASS_ATTSET, VAL_BIB1);
2636 if (!(req->termListAndStartPoint = ccl_scan_query (out, rpn)))
2638 printf("Couldn't convert CCL to Scan term\n");
2641 ccl_rpn_delete (rpn);
2645 YAZ_PQF_Parser pqf_parser = yaz_pqf_create ();
2647 if (!(req->termListAndStartPoint =
2648 yaz_pqf_scan(pqf_parser, out, &req->attributeSet, query)))
2650 const char *pqf_msg;
2652 int code = yaz_pqf_error (pqf_parser, &pqf_msg, &off);
2653 printf("%*s^\n", off+7, "");
2654 printf("Prefix query error: %s (code %d)\n", pqf_msg, code);
2655 yaz_pqf_destroy (pqf_parser);
2658 yaz_pqf_destroy (pqf_parser);
2662 if (req->termListAndStartPoint->term &&
2663 req->termListAndStartPoint->term->which == Z_Term_general &&
2664 req->termListAndStartPoint->term->u.general)
2666 req->termListAndStartPoint->term->u.general->buf =
2667 (unsigned char *) odr_strdup(out, term);
2668 req->termListAndStartPoint->term->u.general->len =
2669 req->termListAndStartPoint->term->u.general->size =
2673 req->referenceId = set_refid (out);
2674 req->num_databaseNames = num_databaseNames;
2675 req->databaseNames = databaseNames;
2676 req->numberOfTermsRequested = #
2677 req->preferredPositionInResponse = &pp;
2678 req->stepSize = odr_intdup(out, scan_stepSize);
2683 int send_sortrequest(const char *arg, int newset)
2685 Z_APDU *apdu = zget_APDU(out, Z_APDU_sortRequest);
2686 Z_SortRequest *req = apdu->u.sortRequest;
2687 Z_SortKeySpecList *sksl = (Z_SortKeySpecList *)
2688 odr_malloc (out, sizeof(*sksl));
2694 sprintf (setstring, "%d", setnumber);
2696 sprintf (setstring, "default");
2698 req->referenceId = set_refid (out);
2700 req->num_inputResultSetNames = 1;
2701 req->inputResultSetNames = (Z_InternationalString **)
2702 odr_malloc (out, sizeof(*req->inputResultSetNames));
2703 req->inputResultSetNames[0] = odr_strdup (out, setstring);
2705 if (newset && setnumber >= 0)
2706 sprintf (setstring, "%d", ++setnumber);
2708 req->sortedResultSetName = odr_strdup (out, setstring);
2710 req->sortSequence = yaz_sort_spec (out, arg);
2711 if (!req->sortSequence)
2713 printf ("Missing sort specifications\n");
2720 void display_term(Z_TermInfo *t)
2723 printf("%s", t->displayTerm);
2724 else if (t->term->which == Z_Term_general)
2726 printf("%.*s", t->term->u.general->len, t->term->u.general->buf);
2727 sprintf(last_scan_line, "%.*s", t->term->u.general->len,
2728 t->term->u.general->buf);
2731 printf("Term (not general)");
2732 if (t->globalOccurrences)
2733 printf (" (%d)\n", *t->globalOccurrences);
2738 void process_scanResponse(Z_ScanResponse *res)
2741 Z_Entry **entries = NULL;
2742 int num_entries = 0;
2744 printf("Received ScanResponse\n");
2745 print_refid (res->referenceId);
2746 printf("%d entries", *res->numberOfEntriesReturned);
2747 if (res->positionOfTerm)
2748 printf (", position=%d", *res->positionOfTerm);
2750 if (*res->scanStatus != Z_Scan_success)
2751 printf("Scan returned code %d\n", *res->scanStatus);
2754 if ((entries = res->entries->entries))
2755 num_entries = res->entries->num_entries;
2756 for (i = 0; i < num_entries; i++)
2758 int pos_term = res->positionOfTerm ? *res->positionOfTerm : -1;
2759 if (entries[i]->which == Z_Entry_termInfo)
2761 printf("%c ", i + 1 == pos_term ? '*' : ' ');
2762 display_term(entries[i]->u.termInfo);
2765 display_diagrecs(&entries[i]->u.surrogateDiagnostic, 1);
2767 if (res->entries->nonsurrogateDiagnostics)
2768 display_diagrecs (res->entries->nonsurrogateDiagnostics,
2769 res->entries->num_nonsurrogateDiagnostics);
2772 void process_sortResponse(Z_SortResponse *res)
2774 printf("Received SortResponse: status=");
2775 switch (*res->sortStatus)
2777 case Z_SortResponse_success:
2778 printf ("success"); break;
2779 case Z_SortResponse_partial_1:
2780 printf ("partial"); break;
2781 case Z_SortResponse_failure:
2782 printf ("failure"); break;
2784 printf ("unknown (%d)", *res->sortStatus);
2787 print_refid (res->referenceId);
2788 if (res->diagnostics)
2789 display_diagrecs(res->diagnostics,
2790 res->num_diagnostics);
2793 void process_deleteResultSetResponse (Z_DeleteResultSetResponse *res)
2795 printf("Got deleteResultSetResponse status=%d\n",
2796 *res->deleteOperationStatus);
2797 if (res->deleteListStatuses)
2800 for (i = 0; i < res->deleteListStatuses->num; i++)
2802 printf ("%s status=%d\n", res->deleteListStatuses->elements[i]->id,
2803 *res->deleteListStatuses->elements[i]->status);
2808 int cmd_sort_generic(const char *arg, int newset)
2812 printf("Session not initialized yet\n");
2817 if (!ODR_MASK_GET(session->options, Z_Options_sort))
2819 printf("Target doesn't support sort\n");
2824 if (send_sortrequest(arg, newset) < 0)
2831 int cmd_sort(const char *arg)
2833 return cmd_sort_generic (arg, 0);
2836 int cmd_sort_newset (const char *arg)
2838 return cmd_sort_generic (arg, 1);
2841 int cmd_scanstep(const char *arg)
2843 scan_stepSize = atoi(arg);
2847 int cmd_scanpos(const char *arg)
2849 int r = sscanf(arg, "%d", &scan_position);
2855 int cmd_scan(const char *arg)
2857 if (protocol == PROTO_HTTP)
2866 if (send_SRW_scanRequest(arg, scan_position, 20) < 0)
2871 if (send_SRW_scanRequest(last_scan_line, 1, 20) < 0)
2886 printf("Session not initialized yet\n");
2890 if (!ODR_MASK_GET(session->options, Z_Options_scan))
2892 printf("Target doesn't support scan\n");
2897 strcpy (last_scan_query, arg);
2898 if (send_scanrequest(arg, scan_position, 20, 0) < 0)
2903 if (send_scanrequest(last_scan_query, 1, 20, last_scan_line) < 0)
2910 int cmd_schema(const char *arg)
2912 xfree(record_schema);
2915 record_schema = xstrdup(arg);
2919 int cmd_format(const char *arg)
2924 printf("Usage: format <recordsyntax>\n");
2927 nsyntax = oid_getvalbyname (arg);
2928 if (strcmp(arg, "none") && nsyntax == VAL_NONE)
2930 printf ("unknown record syntax\n");
2933 recordsyntax = nsyntax;
2937 int cmd_elements(const char *arg)
2939 static Z_ElementSetNames esn;
2940 static char what[100];
2944 elementSetNames = 0;
2948 esn.which = Z_ElementSetNames_generic;
2949 esn.u.generic = what;
2950 elementSetNames = &esn;
2954 int cmd_attributeset(const char *arg)
2960 printf("Usage: attributeset <setname>\n");
2963 sscanf(arg, "%s", what);
2964 if (p_query_attset (what))
2966 printf("Unknown attribute set name\n");
2972 int cmd_querytype (const char *arg)
2974 if (!strcmp (arg, "ccl"))
2975 queryType = QueryType_CCL;
2976 else if (!strcmp (arg, "prefix") || !strcmp(arg, "rpn"))
2977 queryType = QueryType_Prefix;
2978 else if (!strcmp (arg, "ccl2rpn") || !strcmp (arg, "cclrpn"))
2979 queryType = QueryType_CCL2RPN;
2980 else if (!strcmp(arg, "cql"))
2981 queryType = QueryType_CQL;
2982 else if (!strcmp (arg, "cql2rpn") || !strcmp (arg, "cqlrpn"))
2983 queryType = QueryType_CQL2RPN;
2986 printf ("Querytype must be one of:\n");
2987 printf (" prefix - Prefix query\n");
2988 printf (" ccl - CCL query\n");
2989 printf (" ccl2rpn - CCL query converted to RPN\n");
2990 printf (" cql - CQL\n");
2991 printf (" cql2rpn - CQL query converted to RPN\n");
2997 int cmd_refid (const char *arg)
3002 refid = xstrdup (arg);
3006 int cmd_close(const char *arg)
3015 apdu = zget_APDU(out, Z_APDU_close);
3016 req = apdu->u.close;
3017 *req->closeReason = Z_Close_finished;
3019 printf("Sent close request.\n");
3024 int cmd_packagename(const char* arg)
3026 xfree (esPackageName);
3027 esPackageName = NULL;
3029 esPackageName = xstrdup(arg);
3033 int cmd_proxy(const char* arg)
3038 yazProxy = xstrdup (arg);
3042 int cmd_marccharset(const char *arg)
3047 if (sscanf(arg, "%29s", l1) < 1)
3049 printf("MARC character set is `%s'\n",
3050 marcCharset ? marcCharset: "none");
3053 xfree (marcCharset);
3055 if (strcmp(l1, "-"))
3056 marcCharset = xstrdup(l1);
3060 int cmd_displaycharset(const char *arg)
3065 if (sscanf(arg, "%29s", l1) < 1)
3067 printf("Display character set is `%s'\n",
3068 outputCharset ? outputCharset: "none");
3072 xfree (outputCharset);
3074 if (!strcmp(l1, "auto") && codeset)
3078 printf ("Display character set: %s\n", codeset);
3079 outputCharset = xstrdup(codeset);
3082 printf ("No codeset found on this system\n");
3084 else if (strcmp(l1, "-") && strcmp(l1, "none"))
3085 outputCharset = xstrdup(l1);
3090 int cmd_negcharset(const char *arg)
3095 if (sscanf(arg, "%29s %d %d", l1, &negotiationCharsetRecords,
3096 &negotiationCharsetVersion) < 1)
3098 printf("Current negotiation character set is `%s'\n",
3099 negotiationCharset ? negotiationCharset: "none");
3100 printf("Records in charset %s\n", negotiationCharsetRecords ?
3102 printf("Charneg version %d\n", negotiationCharsetVersion);
3106 xfree (negotiationCharset);
3107 negotiationCharset = NULL;
3108 if (*l1 && strcmp(l1, "-") && strcmp(l1, "none"))
3110 negotiationCharset = xstrdup(l1);
3111 printf ("Character set negotiation : %s\n", negotiationCharset);
3117 int cmd_charset(const char* arg)
3119 char l1[30], l2[30], l3[30];
3121 *l1 = *l2 = *l3 = 0;
3122 if (sscanf(arg, "%29s %29s %29s", l1, l2, l3) < 1)
3125 cmd_displaycharset("");
3126 cmd_marccharset("");
3132 cmd_displaycharset(l2);
3134 cmd_marccharset(l3);
3139 int cmd_lang(const char* arg)
3142 printf("Current language is `%s'\n", (yazLang)?yazLang:NULL);
3148 yazLang = xstrdup(arg);
3152 int cmd_source(const char* arg, int echo )
3154 /* first should open the file and read one line at a time.. */
3156 char line[102400], *cp;
3159 fprintf(stderr,"Error in source command use a filename\n");
3163 includeFile = fopen (arg, "r");
3166 fprintf(stderr,"Unable to open file %s for reading\n",arg);
3170 while(!feof(includeFile)) {
3171 memset(line,0,sizeof(line));
3172 fgets(line,sizeof(line),includeFile);
3174 if(strlen(line) < 2) continue;
3175 if(line[0] == '#') continue;
3177 if ((cp = strrchr (line, '\n')))
3181 printf( "processing line: %s\n",line );
3183 process_cmd_line(line);
3186 if(fclose(includeFile)<0) {
3187 perror("unable to close include file");
3193 int cmd_source_echo(const char* arg)
3199 int cmd_source_noecho(const char* arg)
3206 int cmd_subshell(const char* args)
3211 system(getenv("SHELL"));
3217 int cmd_set_berfile(const char *arg)
3219 if (ber_file && ber_file != stdout && ber_file != stderr)
3221 if (!strcmp(arg, ""))
3223 else if (!strcmp(arg, "-"))
3226 ber_file = fopen(arg, "a");
3230 int cmd_set_apdufile(const char *arg)
3232 if(apdu_file && apdu_file != stderr && apdu_file != stderr)
3234 if (!strcmp(arg, ""))
3236 else if (!strcmp(arg, "-"))
3240 apdu_file = fopen(arg, "a");
3242 perror("unable to open apdu log file");
3245 odr_setprint(print, apdu_file);
3249 int cmd_set_cclfile(const char* arg)
3253 bibset = ccl_qual_mk ();
3254 inf = fopen (arg, "r");
3256 perror("unable to open CCL file");
3259 ccl_qual_file (bibset, inf);
3262 strcpy(ccl_fields,arg);
3266 int cmd_set_cqlfile(const char* arg)
3268 cql_transform_t newcqltrans;
3270 if ((newcqltrans = cql_transform_open_fname(arg)) == 0) {
3271 perror("unable to open CQL file");
3275 cql_transform_close(cqltrans);
3277 cqltrans = newcqltrans;
3278 strcpy(cql_fields, arg);
3282 int cmd_set_auto_reconnect(const char* arg)
3284 if(strlen(arg)==0) {
3285 auto_reconnect = ! auto_reconnect;
3286 } else if(strcmp(arg,"on")==0) {
3288 } else if(strcmp(arg,"off")==0) {
3291 printf("Error use on or off\n");
3296 printf("Set auto reconnect enabled.\n");
3298 printf("Set auto reconnect disabled.\n");
3303 int cmd_set_marcdump(const char* arg)
3305 if(marc_file && marc_file != stderr) { /* don't close stdout*/
3309 if (!strcmp(arg, ""))
3311 else if (!strcmp(arg, "-"))
3315 marc_file = fopen(arg, "a");
3317 perror("unable to open marc log file");
3323 this command takes 3 arge {name class oid}
3325 int cmd_register_oid(const char* args) {
3330 {"appctx",CLASS_APPCTX},
3331 {"absyn",CLASS_ABSYN},
3332 {"attset",CLASS_ATTSET},
3333 {"transyn",CLASS_TRANSYN},
3334 {"diagset",CLASS_DIAGSET},
3335 {"recsyn",CLASS_RECSYN},
3336 {"resform",CLASS_RESFORM},
3337 {"accform",CLASS_ACCFORM},
3338 {"extserv",CLASS_EXTSERV},
3339 {"userinfo",CLASS_USERINFO},
3340 {"elemspec",CLASS_ELEMSPEC},
3341 {"varset",CLASS_VARSET},
3342 {"schema",CLASS_SCHEMA},
3343 {"tagset",CLASS_TAGSET},
3344 {"general",CLASS_GENERAL},
3345 {0,(enum oid_class) 0}
3347 char oname_str[101], oclass_str[101], oid_str[101];
3350 oid_class oidclass = CLASS_GENERAL;
3351 int val = 0, oid[OID_SIZE];
3352 struct oident * new_oident=NULL;
3354 if (sscanf (args, "%100[^ ] %100[^ ] %100s",
3355 oname_str,oclass_str, oid_str) < 1) {
3356 printf("Error in register command \n");
3360 for (i = 0; oid_classes[i].className; i++) {
3361 if (!strcmp(oid_classes[i].className, oclass_str))
3363 oidclass=oid_classes[i].oclass;
3368 if(!(oid_classes[i].className)) {
3369 printf("Unknown oid class %s\n",oclass_str);
3377 while (isdigit (*(unsigned char *) name))
3379 val = val*10 + (*name - '0');
3392 new_oident = oid_addent (oid, PROTO_GENERAL, oidclass, oname_str,
3394 if(strcmp(new_oident->desc,oname_str))
3396 fprintf(stderr,"oid is already named as %s, registration failed\n",
3402 int cmd_push_command(const char* arg)
3404 #if HAVE_READLINE_HISTORY_H
3408 fprintf(stderr,"Not compiled with the readline/history module\n");
3413 void source_rcfile()
3415 /* Look for a $HOME/.yazclientrc and source it if it exists */
3416 struct stat statbuf;
3418 char* homedir=getenv("HOME");
3422 sprintf(buffer,"%s/.yazclientrc",homedir);
3424 if(stat(buffer,&statbuf)==0) {
3425 cmd_source(buffer, 0 );
3430 if(stat(".yazclientrc",&statbuf)==0) {
3431 cmd_source(".yazclientrc", 0 );
3436 static void initialize(void)
3441 if (!(out = odr_createmem(ODR_ENCODE)) ||
3442 !(in = odr_createmem(ODR_DECODE)) ||
3443 !(print = odr_createmem(ODR_PRINT)))
3445 fprintf(stderr, "failed to allocate ODR streams\n");
3450 setvbuf(stdout, 0, _IONBF, 0);
3452 odr_setprint(print, apdu_file);
3454 bibset = ccl_qual_mk ();
3455 inf = fopen (ccl_fields, "r");
3458 ccl_qual_file (bibset, inf);
3462 cqltrans = cql_transform_open_fname(cql_fields);
3463 /* If this fails, no problem: we detect cqltrans == 0 later */
3465 #if HAVE_READLINE_READLINE_H
3466 rl_attempted_completion_function = (CPPFunction*)readline_completer;
3470 for(i=0; i<maxOtherInfosSupported; ++i) {
3471 extraOtherInfos[i].oidval = -1;
3478 #if HAVE_GETTIMEOFDAY
3479 struct timeval tv_start, tv_end;
3483 static void handle_srw_record(Z_SRW_record *rec)
3485 if (rec->recordPosition)
3487 printf ("pos=%d", *rec->recordPosition);
3488 setno = *rec->recordPosition + 1;
3490 if (rec->recordSchema)
3491 printf (" schema=%s", rec->recordSchema);
3493 if (rec->recordData_buf && rec->recordData_len)
3495 fwrite(rec->recordData_buf, 1, rec->recordData_len, stdout);
3497 fwrite (rec->recordData_buf, 1, rec->recordData_len, marc_file);
3500 printf ("No data!");
3504 static void handle_srw_explain_response(Z_SRW_explainResponse *res)
3506 handle_srw_record(&res->record);
3509 static void handle_srw_response(Z_SRW_searchRetrieveResponse *res)
3513 printf ("Received SRW SearchRetrieve Response\n");
3515 for (i = 0; i<res->num_diagnostics; i++)
3517 if (res->diagnostics[i].uri)
3518 printf ("SRW diagnostic %s\n",
3519 res->diagnostics[i].uri);
3521 printf ("SRW diagnostic missing or could not be decoded\n");
3522 if (res->diagnostics[i].message)
3523 printf ("Message: %s\n", res->diagnostics[i].message);
3524 if (res->diagnostics[i].details)
3525 printf ("Details: %s\n", res->diagnostics[i].details);
3527 if (res->numberOfRecords)
3528 printf ("Number of hits: %d\n", *res->numberOfRecords);
3529 for (i = 0; i<res->num_records; i++)
3530 handle_srw_record(res->records + i);
3533 static void handle_srw_scan_term(Z_SRW_scanTerm *term)
3535 if (term->displayTerm)
3536 printf("%s:", term->displayTerm);
3537 else if (term->value)
3538 printf("%s:", term->value);
3540 printf("No value:");
3541 if (term->numberOfRecords)
3542 printf(" %d", *term->numberOfRecords);
3543 if (term->whereInList)
3544 printf(" %s", term->whereInList);
3545 if (term->value && term->displayTerm)
3546 printf(" %s", term->value);
3548 strcpy(last_scan_line, term->value);
3552 static void handle_srw_scan_response(Z_SRW_scanResponse *res)
3556 printf ("Received SRW Scan Response\n");
3558 for (i = 0; i<res->num_diagnostics; i++)
3560 if (res->diagnostics[i].uri)
3561 printf ("SRW diagnostic %s\n",
3562 res->diagnostics[i].uri);
3564 printf ("SRW diagnostic missing or could not be decoded\n");
3565 if (res->diagnostics[i].message)
3566 printf ("Message: %s\n", res->diagnostics[i].message);
3567 if (res->diagnostics[i].details)
3568 printf ("Details: %s\n", res->diagnostics[i].details);
3571 for (i = 0; i<res->num_terms; i++)
3572 handle_srw_scan_term(res->terms + i);
3575 static void http_response(Z_HTTP_Response *hres)
3578 const char *content_type = z_HTTP_header_lookup(hres->headers,
3580 const char *connection_head = z_HTTP_header_lookup(hres->headers,
3582 if (content_type && !yaz_strcmp_del("text/xml", content_type, "; "))
3584 Z_SOAP *soap_package = 0;
3585 ODR o = odr_createmem(ODR_DECODE);
3586 Z_SOAP_Handler soap_handlers[2] = {
3587 {"http://www.loc.gov/zing/srw/", 0,
3588 (Z_SOAP_fun) yaz_srw_codec},
3591 ret = z_soap_codec(o, &soap_package,
3592 &hres->content_buf, &hres->content_len,
3594 if (!ret && soap_package->which == Z_SOAP_generic &&
3595 soap_package->u.generic->no == 0)
3597 Z_SRW_PDU *sr = soap_package->u.generic->p;
3598 if (sr->which == Z_SRW_searchRetrieve_response)
3599 handle_srw_response(sr->u.response);
3600 else if (sr->which == Z_SRW_explain_response)
3601 handle_srw_explain_response(sr->u.explain_response);
3602 else if (sr->which == Z_SRW_scan_response)
3603 handle_srw_scan_response(sr->u.scan_response);
3607 else if (soap_package && (soap_package->which == Z_SOAP_fault
3608 || soap_package->which == Z_SOAP_error))
3610 printf ("HTTP Error Status=%d\n", hres->code);
3611 printf ("SOAP Fault code %s\n",
3612 soap_package->u.fault->fault_code);
3613 printf ("SOAP Fault string %s\n",
3614 soap_package->u.fault->fault_string);
3615 if (soap_package->u.fault->details)
3616 printf ("SOAP Details %s\n",
3617 soap_package->u.fault->details);
3625 if (hres->code != 200)
3627 printf ("HTTP Error Status=%d\n", hres->code);
3631 printf ("Decoding of SRW package failed\n");
3637 if (!strcmp(hres->version, "1.0"))
3639 /* HTTP 1.0: only if Keep-Alive we stay alive.. */
3640 if (!connection_head || strcmp(connection_head, "Keep-Alive"))
3645 /* HTTP 1.1: only if no close we stay alive .. */
3646 if (connection_head && !strcmp(connection_head, "close"))
3653 void wait_and_handle_response()
3655 int reconnect_ok = 1;
3658 int netbufferlen = 0;
3663 res = cs_get(conn, &netbuffer, &netbufferlen);
3664 if (reconnect_ok && res <= 0 && protocol == PROTO_HTTP)
3675 buf_out = odr_getbuf(out, &len_out, 0);
3677 do_hex_dump(buf_out, len_out);
3679 cs_put(conn, buf_out, len_out);
3687 printf("Target closed connection\n");
3692 odr_reset(in); /* release APDU from last round */
3694 do_hex_dump(netbuffer, res);
3695 odr_setbuf(in, netbuffer, res, 0);
3697 if (!z_GDU(in, &gdu, 0, 0))
3699 FILE *f = ber_file ? ber_file : stdout;
3700 odr_perror(in, "Decoding incoming APDU");
3701 fprintf(f, "[Near %d]\n", odr_offset(in));
3702 fprintf(f, "Packet dump:\n---------\n");
3703 odr_dumpBER(f, netbuffer, res);
3704 fprintf(f, "---------\n");
3707 z_GDU(print, &gdu, 0, 0);
3710 if (conn && cs_more(conn))
3715 odr_dumpBER(ber_file, netbuffer, res);
3716 if (apdu_file && !z_GDU(print, &gdu, 0, 0))
3718 odr_perror(print, "Failed to print incoming APDU");
3722 if (gdu->which == Z_GDU_Z3950)
3724 Z_APDU *apdu = gdu->u.z3950;
3727 case Z_APDU_initResponse:
3728 process_initResponse(apdu->u.initResponse);
3730 case Z_APDU_searchResponse:
3731 process_searchResponse(apdu->u.searchResponse);
3733 case Z_APDU_scanResponse:
3734 process_scanResponse(apdu->u.scanResponse);
3736 case Z_APDU_presentResponse:
3737 print_refid (apdu->u.presentResponse->referenceId);
3739 *apdu->u.presentResponse->numberOfRecordsReturned;
3740 if (apdu->u.presentResponse->records)
3741 display_records(apdu->u.presentResponse->records);
3743 printf("No records.\n");
3744 printf ("nextResultSetPosition = %d\n",
3745 *apdu->u.presentResponse->nextResultSetPosition);
3747 case Z_APDU_sortResponse:
3748 process_sortResponse(apdu->u.sortResponse);
3750 case Z_APDU_extendedServicesResponse:
3751 printf("Got extended services response\n");
3752 process_ESResponse(apdu->u.extendedServicesResponse);
3755 printf("Target has closed the association.\n");
3756 process_close(apdu->u.close);
3758 case Z_APDU_resourceControlRequest:
3759 process_resourceControlRequest
3760 (apdu->u.resourceControlRequest);
3762 case Z_APDU_deleteResultSetResponse:
3763 process_deleteResultSetResponse(apdu->u.
3764 deleteResultSetResponse);
3767 printf("Received unknown APDU type (%d).\n",
3773 else if (gdu->which == Z_GDU_HTTP_Response)
3775 http_response(gdu->u.HTTP_Response);
3778 if (conn && !cs_more(conn))
3783 #if HAVE_GETTIMEOFDAY
3784 gettimeofday (&tv_end, 0);
3786 printf ("S/U S/U=%ld/%ld %ld/%ld",
3787 (long) tv_start.tv_sec,
3788 (long) tv_start.tv_usec,
3789 (long) tv_end.tv_sec,
3790 (long) tv_end.tv_usec);
3792 printf ("Elapsed: %.6f\n",
3793 (double) tv_end.tv_usec / 1e6 + tv_end.tv_sec -
3794 ((double) tv_start.tv_usec / 1e6 + tv_start.tv_sec));
3801 int cmd_cclparse(const char* arg)
3804 struct ccl_rpn_node *rpn=NULL;
3807 rpn = ccl_find_str (bibset, arg, &error, &pos);
3810 printf ("%*s^ - ", 3+strlen(last_cmd)+1+pos, " ");
3811 printf ("%s\n", ccl_err_msg (error));
3817 ccl_pr_tree(rpn, stdout);
3821 ccl_rpn_delete(rpn);
3829 int cmd_set_otherinfo(const char* args)
3831 char oidstr[101], otherinfoString[101];
3836 sscan_res = sscanf (args, "%d %100[^ ] %100s", &otherinfoNo, oidstr, otherinfoString);
3838 /* reset this otherinfo */
3839 if(otherinfoNo>=maxOtherInfosSupported) {
3840 printf("Error otherinfo index to large (%d>%d)\n",
3841 otherinfoNo,maxOtherInfosSupported);
3843 extraOtherInfos[otherinfoNo].oidval = -1;
3844 if (extraOtherInfos[otherinfoNo].value)
3845 free(extraOtherInfos[otherinfoNo].value);
3849 printf("Error in set_otherinfo command \n");
3853 if (otherinfoNo>=maxOtherInfosSupported) {
3854 printf("Error otherinfo index to large (%d>%d)\n",
3855 otherinfoNo,maxOtherInfosSupported);
3858 oidval = oid_getvalbyname (oidstr);
3859 if (oidval == -1 ) {
3860 printf("Error in set_otherinfo command unknown oid %s \n",oidstr);
3863 extraOtherInfos[otherinfoNo].oidval = oidval;
3864 if(extraOtherInfos[otherinfoNo].value) free(extraOtherInfos[otherinfoNo].value);
3865 extraOtherInfos[otherinfoNo].value = strdup(otherinfoString);
3870 int cmd_sleep(const char* args )
3879 printf("Done sleeping %d seconds\n", sec);
3884 int cmd_list_otherinfo(const char* args)
3888 if(strlen(args)>0) {
3890 if( i >= maxOtherInfosSupported ) {
3891 printf("Error otherinfo index to large (%d>%d)\n",i,maxOtherInfosSupported);
3895 if(extraOtherInfos[i].oidval != -1)
3896 printf(" otherinfo %d %s %s\n",
3898 yaz_z3950_oid_value_to_str(
3899 (enum oid_value) extraOtherInfos[i].oidval,
3901 extraOtherInfos[i].value);
3904 for(i=0; i<maxOtherInfosSupported; ++i) {
3905 if(extraOtherInfos[i].oidval != -1)
3906 printf(" otherinfo %d %s %s\n",
3908 yaz_z3950_oid_value_to_str(
3909 (enum oid_value) extraOtherInfos[i].oidval,
3911 extraOtherInfos[i].value);
3919 int cmd_list_all(const char* args) {
3922 /* connection options */
3924 printf("Connected to : %s\n",last_open_command);
3926 if(last_open_command)
3927 printf("Not connected to : %s\n",last_open_command);
3929 printf("Not connected : \n");
3932 if(yazProxy) printf("using proxy : %s\n",yazProxy);
3934 printf("auto_reconnect : %s\n",auto_reconnect?"on":"off");
3937 printf("Authentication : none\n");
3939 switch(auth->which) {
3940 case Z_IdAuthentication_idPass:
3941 printf("Authentication : IdPass\n");
3942 printf(" Login User : %s\n",auth->u.idPass->userId?auth->u.idPass->userId:"");
3943 printf(" Login Group : %s\n",auth->u.idPass->groupId?auth->u.idPass->groupId:"");
3944 printf(" Password : %s\n",auth->u.idPass->password?auth->u.idPass->password:"");
3946 case Z_IdAuthentication_open:
3947 printf("Authentication : psOpen\n");
3948 printf(" Open string : %s\n",auth->u.open);
3951 printf("Authentication : Unknown\n");
3954 if (negotiationCharset)
3955 printf("Neg. Character set : `%s'\n", negotiationCharset);
3959 for (i = 0; i<num_databaseNames; i++) printf("%s ",databaseNames[i]);
3963 printf("CCL file : %s\n",ccl_fields);
3964 printf("CQL file : %s\n",cql_fields);
3965 printf("Query type : %s\n",query_type_as_string(queryType));
3967 printf("Named Result Sets : %s\n",setnumber==-1?"off":"on");
3969 /* piggy back options */
3970 printf("ssub/lslb/mspn : %d/%d/%d\n",smallSetUpperBound,largeSetLowerBound,mediumSetPresentNumber);
3972 /* print present related options */
3973 printf("Format : %s\n",yaz_z3950_oid_value_to_str(recordsyntax,CLASS_RECSYN));
3974 printf("Schema : %s\n",record_schema ? record_schema : "not set");
3975 printf("Elements : %s\n",elementSetNames?elementSetNames->u.generic:"");
3977 /* loging options */
3978 printf("APDU log : %s\n",apdu_file?"on":"off");
3979 printf("Record log : %s\n",marc_file?"on":"off");
3982 printf("Other Info: \n");
3983 cmd_list_otherinfo("");
3988 int cmd_clear_otherinfo(const char* args)
3990 if(strlen(args)>0) {
3992 otherinfoNo = atoi(args);
3993 if( otherinfoNo >= maxOtherInfosSupported ) {
3994 printf("Error otherinfo index to large (%d>%d)\n",otherinfoNo,maxOtherInfosSupported);
3998 if(extraOtherInfos[otherinfoNo].oidval != -1) {
3999 /* only clear if set. */
4000 extraOtherInfos[otherinfoNo].oidval=-1;
4001 free(extraOtherInfos[otherinfoNo].value);
4006 for(i=0; i<maxOtherInfosSupported; ++i) {
4007 if (extraOtherInfos[i].oidval!=-1 ) {
4008 extraOtherInfos[i].oidval=-1;
4009 free(extraOtherInfos[i].value);
4016 static int cmd_help (const char *line);
4018 typedef char *(*completerFunctionType)(const char *text, int state);
4022 int (*fun)(const char *arg);
4024 completerFunctionType rl_completerfunction;
4025 int complete_filenames;
4026 char **local_tabcompletes;
4028 {"open", cmd_open, "('tcp'|'ssl')':<host>[':'<port>][/<db>]",NULL,0,NULL},
4029 {"quit", cmd_quit, "",NULL,0,NULL},
4030 {"find", cmd_find, "<query>",NULL,0,NULL},
4031 {"delete", cmd_delete, "<setname>",NULL,0,NULL},
4032 {"base", cmd_base, "<base-name>",NULL,0,NULL},
4033 {"show", cmd_show, "<rec#>['+'<#recs>['+'<setname>]]",NULL,0,NULL},
4034 {"scan", cmd_scan, "<term>",NULL,0,NULL},
4035 {"scanstep", cmd_scanstep, "<size>",NULL,0,NULL},
4036 {"scanpos", cmd_scanpos, "<size>",NULL,0,NULL},
4037 {"sort", cmd_sort, "<sortkey> <flag> <sortkey> <flag> ...",NULL,0,NULL},
4038 {"sort+", cmd_sort_newset, "<sortkey> <flag> <sortkey> <flag> ...",NULL,0,NULL},
4039 {"authentication", cmd_authentication, "<acctstring>",NULL,0,NULL},
4040 {"lslb", cmd_lslb, "<largeSetLowerBound>",NULL,0,NULL},
4041 {"ssub", cmd_ssub, "<smallSetUpperBound>",NULL,0,NULL},
4042 {"mspn", cmd_mspn, "<mediumSetPresentNumber>",NULL,0,NULL},
4043 {"status", cmd_status, "",NULL,0,NULL},
4044 {"setnames", cmd_setnames, "",NULL,0,NULL},
4045 {"cancel", cmd_cancel, "",NULL,0,NULL},
4046 {"cancel_find", cmd_cancel_find, "<query>",NULL,0,NULL},
4047 {"format", cmd_format, "<recordsyntax>",complete_format,0,NULL},
4048 {"schema", cmd_schema, "<schema>",complete_schema,0,NULL},
4049 {"elements", cmd_elements, "<elementSetName>",NULL,0,NULL},
4050 {"close", cmd_close, "",NULL,0,NULL},
4051 {"attributeset", cmd_attributeset, "<attrset>",complete_attributeset,0,NULL},
4052 {"querytype", cmd_querytype, "<type>",complete_querytype,0,NULL},
4053 {"refid", cmd_refid, "<id>",NULL,0,NULL},
4054 {"itemorder", cmd_itemorder, "ill|item <itemno>",NULL,0,NULL},
4055 {"update", cmd_update, "<action> <recid> [<file>]",NULL,0,NULL},
4056 {"update0", cmd_update0, "<action> <recid> [<file>]",NULL,0,NULL},
4057 {"packagename", cmd_packagename, "<packagename>",NULL,0,NULL},
4058 {"proxy", cmd_proxy, "[('tcp'|'ssl')]<host>[':'<port>]",NULL,0,NULL},
4059 {"charset", cmd_charset, "<nego_charset> <output_charset>",NULL,0,NULL},
4060 {"negcharset", cmd_negcharset, "<nego_charset>",NULL,0,NULL},
4061 {"displaycharset", cmd_displaycharset, "<output_charset>",NULL,0,NULL},
4062 {"marccharset", cmd_marccharset, "<charset_name>",NULL,0,NULL},
4063 {"lang", cmd_lang, "<language_code>",NULL,0,NULL},
4064 {".", cmd_source_echo, "<filename>",NULL,1,NULL},
4065 {"!", cmd_subshell, "Subshell command",NULL,1,NULL},
4066 {"set_apdufile", cmd_set_apdufile, "<filename>",NULL,1,NULL},
4067 {"set_berfile", cmd_set_berfile, "<filename>",NULL,1,NULL},
4068 {"set_marcdump", cmd_set_marcdump," <filename>",NULL,1,NULL},
4069 {"set_cclfile", cmd_set_cclfile," <filename>",NULL,1,NULL},
4070 {"set_cqlfile", cmd_set_cqlfile," <filename>",NULL,1,NULL},
4071 {"set_auto_reconnect", cmd_set_auto_reconnect," on|off",complete_auto_reconnect,1,NULL},
4072 {"set_otherinfo", cmd_set_otherinfo,"<otherinfoinddex> <oid> <string>",NULL,0,NULL},
4073 {"sleep", cmd_sleep,"<seconds>",NULL,0,NULL},
4074 {"register_oid", cmd_register_oid,"<name> <class> <oid>",NULL,0,NULL},
4075 {"push_command", cmd_push_command,"<command>",command_generator,0,NULL},
4076 {"register_tab", cmd_register_tab,"<commandname> <tab>",command_generator,0,NULL},
4077 {"cclparse", cmd_cclparse,"<ccl find command>",NULL,0,NULL},
4078 {"list_otherinfo",cmd_list_otherinfo,"[otherinfoinddex]",NULL,0,NULL},
4079 {"list_all",cmd_list_all,"",NULL,0,NULL},
4080 {"clear_otherinfo",cmd_clear_otherinfo,"",NULL,0,NULL},
4081 /* Server Admin Functions */
4082 {"adm-reindex", cmd_adm_reindex, "<database-name>",NULL,0,NULL},
4083 {"adm-truncate", cmd_adm_truncate, "('database'|'index')<object-name>",NULL,0,NULL},
4084 {"adm-create", cmd_adm_create, "",NULL,0,NULL},
4085 {"adm-drop", cmd_adm_drop, "('database'|'index')<object-name>",NULL,0,NULL},
4086 {"adm-import", cmd_adm_import, "<record-type> <dir> <pattern>",NULL,0,NULL},
4087 {"adm-refresh", cmd_adm_refresh, "",NULL,0,NULL},
4088 {"adm-commit", cmd_adm_commit, "",NULL,0,NULL},
4089 {"adm-shutdown", cmd_adm_shutdown, "",NULL,0,NULL},
4090 {"adm-startup", cmd_adm_startup, "",NULL,0,NULL},
4091 {"explain", cmd_explain, "", NULL, 0, NULL},
4092 {"options", cmd_options, "", NULL, 0, NULL},
4093 {"zversion", cmd_zversion, "", NULL, 0, NULL},
4094 {"help", cmd_help, "", NULL,0,NULL},
4095 {"init", cmd_init, "", NULL,0,NULL},
4099 static int cmd_help (const char *line)
4105 sscanf (line, "%20s", topic);
4108 printf("Commands:\n");
4109 for (i = 0; cmd_array[i].cmd; i++)
4110 if (*topic == 0 || strcmp (topic, cmd_array[i].cmd) == 0)
4111 printf(" %s %s\n", cmd_array[i].cmd, cmd_array[i].ad);
4112 if (strcmp (topic, "find") == 0)
4115 printf (" \"term\" Simple Term\n");
4116 printf (" @attr [attset] type=value op Attribute\n");
4117 printf (" @and opl opr And\n");
4118 printf (" @or opl opr Or\n");
4119 printf (" @not opl opr And-Not\n");
4120 printf (" @set set Result set\n");
4122 printf ("Bib-1 attribute types\n");
4124 printf ("4=Title 7=ISBN 8=ISSN 30=Date 62=Abstract 1003=Author 1016=Any\n");
4125 printf ("2=Relation: ");
4126 printf ("1< 2<= 3= 4>= 5> 6!= 102=Relevance\n");
4127 printf ("3=Position: ");
4128 printf ("1=First in Field 2=First in subfield 3=Any position\n");
4129 printf ("4=Structure: ");
4130 printf ("1=Phrase 2=Word 3=Key 4=Year 5=Date 6=WordList\n");
4131 printf ("5=Truncation: ");
4132 printf ("1=Right 2=Left 3=L&R 100=No 101=# 102=Re-1 103=Re-2\n");
4133 printf ("6=Completeness:");
4134 printf ("1=Incomplete subfield 2=Complete subfield 3=Complete field\n");
4139 int cmd_register_tab(const char* arg) {
4141 char command[101], tabargument[101];
4146 if (sscanf (arg, "%100s %100s", command, tabargument) < 1) {
4150 /* locate the amdn in the list */
4151 for (i = 0; cmd_array[i].cmd; i++) {
4152 if (!strncmp(cmd_array[i].cmd, command, strlen(command))) {
4157 if(!cmd_array[i].cmd) {
4158 fprintf(stderr,"Unknown command %s\n",command);
4163 if(!cmd_array[i].local_tabcompletes)
4164 cmd_array[i].local_tabcompletes = (char **) calloc(1,sizeof(char**));
4168 tabslist = cmd_array[i].local_tabcompletes;
4169 for(;tabslist && *tabslist;tabslist++) {
4173 cmd_array[i].local_tabcompletes = (char **)
4174 realloc(cmd_array[i].local_tabcompletes,(num_of_tabs+2)*sizeof(char**));
4175 tabslist=cmd_array[i].local_tabcompletes;
4176 tabslist[num_of_tabs]=strdup(tabargument);
4177 tabslist[num_of_tabs+1]=NULL;
4182 void process_cmd_line(char* line)
4185 char word[32], arg[10240];
4187 #if HAVE_GETTIMEOFDAY
4188 gettimeofday (&tv_start, 0);
4191 if ((res = sscanf(line, "%31s %10239[^;]", word, arg)) <= 0)
4193 strcpy(word, last_cmd);
4198 strcpy(last_cmd, word);
4200 /* removed tailing spaces from the arg command */
4203 char* lastnonspace=NULL;
4206 if(!isspace(*(unsigned char *) p)) {
4211 *(++lastnonspace) = 0;
4214 for (i = 0; cmd_array[i].cmd; i++)
4215 if (!strncmp(cmd_array[i].cmd, word, strlen(word)))
4217 res = (*cmd_array[i].fun)(arg);
4221 if (!cmd_array[i].cmd) /* dump our help-screen */
4223 printf("Unknown command: %s.\n", word);
4224 printf("use help for list of commands\n");
4225 /* cmd_help (""); */
4229 if(apdu_file) fflush(apdu_file);
4232 wait_and_handle_response();
4241 char *command_generator(const char *text, int state)
4247 for( ; cmd_array[idx].cmd; ++idx) {
4248 if (!strncmp(cmd_array[idx].cmd,text,strlen(text))) {
4249 ++idx; /* skip this entry on the next run */
4250 return strdup(cmd_array[idx-1].cmd);
4258 This function only known how to complete on the first word
4260 char ** readline_completer(char *text, int start, int end) {
4261 #if HAVE_READLINE_READLINE_H
4263 completerFunctionType completerToUse;
4266 #if HAVE_READLINE_RL_COMPLETION_MATCHES
4267 char** res=rl_completion_matches(text,
4270 char** res=completion_matches(text,
4271 (CPFunction*)command_generator);
4273 rl_attempted_completion_over = 1;
4276 char arg[10240],word[32];
4278 if ((res = sscanf(rl_line_buffer, "%31s %10239[^;]", word, arg)) <= 0) {
4279 rl_attempted_completion_over = 1;
4283 for (i = 0; cmd_array[i].cmd; i++) {
4284 if (!strncmp(cmd_array[i].cmd, word, strlen(word))) {
4289 if(!cmd_array[i].cmd) return NULL;
4291 curret_global_list = cmd_array[i].local_tabcompletes;
4293 completerToUse = cmd_array[i].rl_completerfunction;
4294 if(completerToUse==NULL) /* if no pr. command completer is defined use the default completer */
4295 completerToUse = default_completer;
4297 if(completerToUse) {
4298 #ifdef HAVE_READLINE_RL_COMPLETION_MATCHES
4300 rl_completion_matches(text,
4304 completion_matches(text,
4305 (CPFunction*)completerToUse);
4307 if(!cmd_array[i].complete_filenames)
4308 rl_attempted_completion_over = 1;
4311 if(!cmd_array[i].complete_filenames)
4312 rl_attempted_completion_over = 1;
4322 static void client(void)
4328 #if HAVE_GETTIMEOFDAY
4329 gettimeofday (&tv_start, 0);
4334 char *line_in = NULL;
4335 #if HAVE_READLINE_READLINE_H
4338 line_in=readline(C_PROMPT);
4341 #if HAVE_READLINE_HISTORY_H
4343 add_history(line_in);
4345 strncpy(line, line_in, 10239);
4354 if (!fgets(line, 10239, stdin))
4356 if ((end_p = strchr (line, '\n')))
4359 process_cmd_line(line);
4363 static void show_version(void)
4367 yaz_version(vstr, 0);
4368 printf ("YAZ version: %s\n", YAZ_VERSION);
4369 if (strcmp(vstr, YAZ_VERSION))
4370 printf ("YAZ DLL/SO: %s\n", vstr);
4374 int main(int argc, char **argv)
4377 char *open_command = 0;
4378 char *auth_command = 0;
4383 if (!setlocale(LC_CTYPE, ""))
4384 fprintf (stderr, "setlocale failed\n");
4388 codeset = nl_langinfo(CODESET);
4392 outputCharset = xstrdup(codeset);
4394 ODR_MASK_SET(&z3950_options, Z_Options_search);
4395 ODR_MASK_SET(&z3950_options, Z_Options_present);
4396 ODR_MASK_SET(&z3950_options, Z_Options_namedResultSets);
4397 ODR_MASK_SET(&z3950_options, Z_Options_triggerResourceCtrl);
4398 ODR_MASK_SET(&z3950_options, Z_Options_scan);
4399 ODR_MASK_SET(&z3950_options, Z_Options_sort);
4400 ODR_MASK_SET(&z3950_options, Z_Options_extendedServices);
4401 ODR_MASK_SET(&z3950_options, Z_Options_delSet);
4403 while ((ret = options("k:c:q:a:b:m:v:p:u:t:Vxd:", argv, argc, &arg)) != -2)
4410 open_command = (char *) xmalloc (strlen(arg)+6);
4411 strcpy (open_command, "open ");
4412 strcat (open_command, arg);
4416 dump_file_prefix = arg;
4419 kilobytes = atoi(arg);
4422 if (!(marc_file = fopen (arg, "a")))
4429 outputCharset = xstrdup(arg);
4432 strncpy (ccl_fields, arg, sizeof(ccl_fields)-1);
4433 ccl_fields[sizeof(ccl_fields)-1] = '\0';
4436 strncpy (cql_fields, arg, sizeof(cql_fields)-1);
4437 cql_fields[sizeof(cql_fields)-1] = '\0';
4440 if (!strcmp(arg, "-"))
4443 ber_file=fopen(arg, "a");
4446 if (!strcmp(arg, "-"))
4449 apdu_file=fopen(arg, "a");
4455 yazProxy=strdup(arg);
4460 auth_command = (char *) xmalloc (strlen(arg)+6);
4461 strcpy (auth_command, "auth ");
4462 strcat (auth_command, arg);
4466 yaz_log_init(yaz_log_mask_str(arg), "", 0);
4472 fprintf (stderr, "Usage: %s [-m <marclog>] [ -a <apdulog>] "
4473 "[-b berdump] [-c cclfields] \n"
4474 "[-q cqlfields] [-p <proxy-addr>] [-u <auth>] "
4475 "[-k size] [-d dump] [-V] [<server-addr>]\n",
4483 #ifdef HAVE_GETTIMEOFDAY
4484 gettimeofday (&tv_start, 0);
4486 process_cmd_line (auth_command);
4487 #if HAVE_READLINE_HISTORY_H
4488 add_history(auth_command);
4490 xfree(auth_command);
4494 #ifdef HAVE_GETTIMEOFDAY
4495 gettimeofday (&tv_start, 0);
4497 process_cmd_line (open_command);
4498 #if HAVE_READLINE_HISTORY_H
4499 add_history(open_command);
4501 xfree(open_command);
4512 * vim600: sw=4 ts=8 fdm=marker
4513 * vim<600: sw=4 ts=8