2 * Copyright (c) 1995-2004, Index Data
3 * See the file LICENSE for details.
5 * $Id: client.c,v 1.242 2004-05-03 09:00:29 adam Exp $
19 #if HAVE_OPENSSL_SSL_H
20 #include <openssl/bio.h>
21 #include <openssl/crypto.h>
22 #include <openssl/x509.h>
23 #include <openssl/pem.h>
24 #include <openssl/ssl.h>
25 #include <openssl/err.h>
33 #define S_ISREG(x) (x & _S_IFREG)
34 #define S_ISDIR(x) (x & _S_IFDIR)
37 #include <yaz/yaz-util.h>
39 #include <yaz/comstack.h>
41 #include <yaz/proto.h>
42 #include <yaz/marcdisp.h>
43 #include <yaz/diagbib1.h>
44 #include <yaz/otherinfo.h>
45 #include <yaz/charneg.h>
47 #include <yaz/pquery.h>
48 #include <yaz/sortspec.h>
52 #include <yaz/yaz-ccl.h>
55 #if HAVE_READLINE_READLINE_H
56 #include <readline/readline.h>
59 #if HAVE_READLINE_HISTORY_H
60 #include <readline/history.h>
66 #include "tabcomplete.h"
68 #define C_PROMPT "Z> "
70 static char *codeset = 0; /* character set for output */
71 static int hex_dump = 0;
72 static char *dump_file_prefix = 0;
73 static ODR out, in, print; /* encoding and decoding streams */
75 static ODR srw_sr_odr_out = 0;
76 static Z_SRW_PDU *srw_sr = 0;
78 static FILE *apdu_file = 0;
79 static FILE *ber_file = 0;
80 static COMSTACK conn = 0; /* our z-association */
81 static Z_IdAuthentication *auth = 0; /* our current auth definition */
82 char *databaseNames[128];
83 int num_databaseNames = 0;
84 static Z_External *record_last = 0;
85 static int setnumber = -1; /* current result set number */
86 static int smallSetUpperBound = 0;
87 static int largeSetLowerBound = 1;
88 static int mediumSetPresentNumber = 0;
89 static Z_ElementSetNames *elementSetNames = 0;
90 static int setno = 1; /* current set offset */
91 static enum oid_proto protocol = PROTO_Z3950; /* current app protocol */
92 static enum oid_value recordsyntax = VAL_USMARC;
93 static char *record_schema = 0;
94 static int sent_close = 0;
95 static NMEM session_mem = NULL; /* memory handle for init-response */
96 static Z_InitResponse *session = 0; /* session parameters */
97 static char last_scan_line[512] = "0";
98 static char last_scan_query[512] = "0";
99 static char ccl_fields[512] = "default.bib";
100 /* ### How can I set this path to use wherever YAZ is installed? */
101 static char cql_fields[512] = "/usr/local/share/yaz/etc/pqf.properties";
102 static char *esPackageName = 0;
103 static char *yazProxy = 0;
104 static int kilobytes = 1024;
105 static char *negotiationCharset = 0;
106 static char *outputCharset = 0;
107 static char *marcCharset = 0;
108 static char* yazLang = 0;
109 static char* http_version = "1.1";
111 static char last_cmd[32] = "?";
112 static FILE *marc_file = 0;
113 static char *refid = NULL;
114 static char *last_open_command = NULL;
115 static int auto_reconnect = 0;
116 static Odr_bitmask z3950_options;
117 static int z3950_version = 3;
119 static char cur_host[200];
129 static QueryType queryType = QueryType_Prefix;
131 static CCL_bibset bibset; /* CCL bibset handle */
132 static cql_transform_t cqltrans; /* CQL context-set handle */
134 #if HAVE_READLINE_COMPLETION_OVER
137 /* readline doesn't have this var. Define it ourselves. */
138 int rl_attempted_completion_over = 0;
141 /* set this one to 1, to avoid decode of unknown MARCs */
142 #define AVOID_MARC_DECODE 1
144 #define maxOtherInfosSupported 10
148 } extraOtherInfos[maxOtherInfosSupported];
151 void process_cmd_line(char* line);
152 char ** readline_completer(char *text, int start, int end);
153 char *command_generator(const char *text, int state);
154 char** curret_global_list=NULL;
155 int cmd_register_tab(const char* arg);
157 static void close_session (void);
159 ODR getODROutputStream()
164 const char* query_type_as_string(QueryType q)
167 case QueryType_Prefix: return "prefix (RPN sent to server)";
168 case QueryType_CCL: return "CCL (CCL sent to server) ";
169 case QueryType_CCL2RPN: return "CCL -> RPN (RPN sent to server)";
170 case QueryType_CQL: return "CQL (CQL sent to server)";
171 case QueryType_CQL2RPN: return "CQL -> RPN (RPN sent to server)";
173 return "unknown Query type internal yaz-client error";
177 static void do_hex_dump(const char* buf, int len)
182 for( i=0; i<len ; i=i+16 )
185 for(x=0 ; i+x<len && x<16; ++x)
187 printf("%2.2X ",(unsigned int)((unsigned char)buf[i+x]));
192 if (dump_file_prefix)
195 if (++no < 1000 && strlen(dump_file_prefix) < 500)
199 sprintf (fname, "%s.%03d.raw", dump_file_prefix, no);
200 of = fopen(fname, "wb");
202 fwrite (buf, 1, len, of);
209 void add_otherInfos(Z_APDU *a)
211 Z_OtherInformation **oi;
215 for(i=0; i<maxOtherInfosSupported; ++i)
217 if(extraOtherInfos[i].oidval != -1)
218 yaz_oi_set_string_oidval(oi, out, extraOtherInfos[i].oidval,
219 1, extraOtherInfos[i].value);
223 int send_apdu(Z_APDU *a)
232 z_APDU(print, &a, 0, 0);
235 if (!z_APDU(out, &a, 0, 0))
237 odr_perror(out, "Encoding APDU");
241 buf = odr_getbuf(out, &len, 0);
243 odr_dumpBER(ber_file, buf, len);
244 /* printf ("sending APDU of size %d\n", len); */
245 do_hex_dump(buf, len);
246 if (cs_put(conn, buf, len) < 0)
248 fprintf(stderr, "cs_put: %s", cs_errmsg(cs_errno(conn)));
252 odr_reset(out); /* release the APDU structure */
256 static void print_stringn(const unsigned char *buf, size_t len)
259 for (i = 0; i<len; i++)
260 if ((buf[i] <= 126 && buf[i] >= 32) || strchr ("\n\r\t\f", buf[i]))
261 printf ("%c", buf[i]);
263 printf ("\\X%02X", buf[i]);
266 static void print_refid (Z_ReferenceId *id)
270 printf ("Reference Id: ");
271 print_stringn (id->buf, id->len);
276 static Z_ReferenceId *set_refid (ODR out)
281 id = (Z_ReferenceId *) odr_malloc (out, sizeof(*id));
282 id->size = id->len = strlen(refid);
283 id->buf = (unsigned char *) odr_malloc (out, id->len);
284 memcpy (id->buf, refid, id->len);
288 /* INIT SERVICE ------------------------------- */
290 static void send_initRequest(const char* type_and_host)
292 Z_APDU *apdu = zget_APDU(out, Z_APDU_initRequest);
293 Z_InitRequest *req = apdu->u.initRequest;
296 req->options = &z3950_options;
298 ODR_MASK_ZERO(req->protocolVersion);
299 for (i = 0; i<z3950_version; i++)
300 ODR_MASK_SET(req->protocolVersion, i);
302 *req->maximumRecordSize = 1024*kilobytes;
303 *req->preferredMessageSize = 1024*kilobytes;
305 req->idAuthentication = auth;
307 req->referenceId = set_refid (out);
309 if (yazProxy && type_and_host)
310 yaz_oi_set_string_oidval(&req->otherInfo, out, VAL_PROXY,
313 if (negotiationCharset || yazLang) {
314 Z_OtherInformation **p;
315 Z_OtherInformationUnit *p0;
317 yaz_oi_APDU(apdu, &p);
319 if ((p0=yaz_oi_update(p, out, NULL, 0, 0))) {
320 ODR_MASK_SET(req->options, Z_Options_negotiationModel);
322 p0->which = Z_OtherInfo_externallyDefinedInfo;
323 p0->information.externallyDefinedInfo =
324 yaz_set_proposal_charneg(
326 (const char**)&negotiationCharset,
327 negotiationCharset ? 1 : 0,
328 (const char**)&yazLang, yazLang ? 1 : 0, 1);
333 printf("Sent initrequest.\n");
337 /* These two are used only from process_initResponse() */
338 static void render_initUserInfo(Z_OtherInformation *ui1);
339 static void render_diag(Z_DiagnosticFormat *diag);
341 static void pr_opt(const char *opt, void *clientData)
346 static int process_initResponse(Z_InitResponse *res)
349 /* save session parameters for later use */
350 session_mem = odr_extract_mem(in);
353 for (ver = 0; ver < 8; ver++)
354 if (!ODR_MASK_GET(res->protocolVersion, ver))
358 printf("Connection rejected by v%d target.\n", ver);
360 printf("Connection accepted by v%d target.\n", ver);
361 if (res->implementationId)
362 printf("ID : %s\n", res->implementationId);
363 if (res->implementationName)
364 printf("Name : %s\n", res->implementationName);
365 if (res->implementationVersion)
366 printf("Version: %s\n", res->implementationVersion);
367 if (res->userInformationField)
369 Z_External *uif = res->userInformationField;
370 if (uif->which == Z_External_userInfo1) {
371 render_initUserInfo(uif->u.userInfo1);
373 printf("UserInformationfield:\n");
374 if (!z_External(print, (Z_External**)&uif, 0, 0)) {
375 odr_perror(print, "Printing userinfo\n");
378 if (uif->which == Z_External_octet) {
379 printf("Guessing visiblestring:\n");
380 printf("'%s'\n", uif->u. octet_aligned->buf);
381 } else if (uif->which == Z_External_single) {
382 /* Peek at any private Init-diagnostic APDUs */
383 Odr_any *sat = uif->u.single_ASN1_type;
384 printf("### NAUGHTY: External is '%s'\n", sat->buf);
390 yaz_init_opt_decode(res->options, pr_opt, 0);
393 if (ODR_MASK_GET(res->options, Z_Options_namedResultSets))
396 if (ODR_MASK_GET(res->options, Z_Options_negotiationModel)) {
398 Z_CharSetandLanguageNegotiation *p =
399 yaz_get_charneg_record(res->otherInfo);
403 char *charset=NULL, *lang=NULL;
406 yaz_get_response_charneg(session_mem, p, &charset, &lang,
409 if (outputCharset && negotiationCharset) {
410 odr_set_charset (out, charset, outputCharset);
411 odr_set_charset (in, outputCharset, charset);
414 odr_set_charset (out, 0, 0);
415 odr_set_charset (in, 0, 0);
418 printf("Accepted character set : %s\n", charset);
419 printf("Accepted code language : %s\n", lang ? lang : "none");
420 printf("Accepted records in ...: %d\n", selected );
428 static void render_initUserInfo(Z_OtherInformation *ui1) {
430 printf("Init response contains %d otherInfo unit%s:\n",
431 ui1->num_elements, ui1->num_elements == 1 ? "" : "s");
433 for (i = 0; i < ui1->num_elements; i++) {
434 Z_OtherInformationUnit *unit = ui1->list[i];
435 printf(" %d: otherInfo unit contains ", i+1);
436 if (unit->which == Z_OtherInfo_externallyDefinedInfo &&
437 unit->information.externallyDefinedInfo->which ==
439 render_diag(unit->information.externallyDefinedInfo->u.diag1);
441 printf("unsupported otherInfo unit type %d\n", unit->which);
447 /* ### should this share code with display_diagrecs()? */
448 static void render_diag(Z_DiagnosticFormat *diag) {
451 printf("%d diagnostic%s:\n", diag->num, diag->num == 1 ? "" : "s");
452 for (i = 0; i < diag->num; i++) {
453 Z_DiagnosticFormat_s *ds = diag->elements[i];
454 printf(" %d: ", i+1);
456 case Z_DiagnosticFormat_s_defaultDiagRec: {
457 Z_DefaultDiagFormat *dd = ds->u.defaultDiagRec;
458 /* ### should check `dd->diagnosticSetId' */
459 printf("code=%d (%s)", *dd->condition,
460 diagbib1_str(*dd->condition));
461 /* Both types of addinfo are the same, so use type-pun */
462 if (dd->u.v2Addinfo != 0)
463 printf(",\n\taddinfo='%s'", dd->u.v2Addinfo);
466 case Z_DiagnosticFormat_s_explicitDiagnostic:
467 printf("Explicit diagnostic (not supported)");
470 printf("Unrecognised diagnostic type %d", ds->which);
474 if (ds->message != 0)
475 printf(", message='%s'", ds->message);
481 static int set_base(const char *arg)
486 for (i = 0; i<num_databaseNames; i++)
487 xfree (databaseNames[i]);
488 num_databaseNames = 0;
492 if (!(cp = strchr(arg, ' ')))
493 cp = arg + strlen(arg);
496 databaseNames[num_databaseNames] = (char *)xmalloc (1 + cp - arg);
497 memcpy (databaseNames[num_databaseNames], arg, cp - arg);
498 databaseNames[num_databaseNames][cp - arg] = '\0';
500 for (cp1 = databaseNames[num_databaseNames]; *cp1 ; cp1++)
509 if (num_databaseNames == 0)
511 num_databaseNames = 1;
512 databaseNames[0] = xstrdup("");
517 static int cmd_base(const char *arg)
521 printf("Usage: base <database> <database> ...\n");
524 return set_base(arg);
527 void cmd_open_remember_last_open_command(const char* arg, char* new_open_command)
529 if(last_open_command != arg)
531 if(last_open_command) xfree(last_open_command);
532 last_open_command = xstrdup(new_open_command);
536 int session_connect(const char *arg)
539 char type_and_host[101];
540 const char *basep = 0;
541 #if HAVE_OPENSSL_SSL_H
550 nmem_destroy (session_mem);
554 cs_get_host_args(arg, &basep);
556 strncpy(type_and_host, arg, sizeof(type_and_host)-1);
557 type_and_host[sizeof(type_and_host)-1] = '\0';
559 cmd_open_remember_last_open_command(arg,type_and_host);
562 conn = cs_create_host(yazProxy, 1, &add);
564 conn = cs_create_host(arg, 1, &add);
567 printf ("Couldn't create comstack\n");
572 if (conn->protocol == PROTO_HTTP)
574 printf ("SRW/HTTP not enabled in this YAZ\n");
580 protocol = conn->protocol;
581 if (conn->protocol == PROTO_HTTP)
585 printf("Connecting...");
587 if (cs_connect(conn, add) < 0)
589 printf ("error = %s\n", cs_strerror(conn));
590 if (conn->cerrno == CSYSERR)
593 yaz_strerror(msg, sizeof(msg));
594 printf ("%s\n", msg);
601 #if HAVE_OPENSSL_SSL_H
602 if ((ssl = (SSL *) cs_get_ssl(conn)))
604 X509 *server_cert = SSL_get_peer_certificate (ssl);
610 BIO *bio = BIO_new(BIO_s_mem());
612 /* get PEM buffer in memory */
613 PEM_write_bio_X509(bio, server_cert);
614 pem_len = BIO_get_mem_data(bio, &pem_buf);
615 fwrite(pem_buf, pem_len, 1, stdout);
617 /* print all info on screen .. */
618 X509_print_fp(stdout, server_cert);
621 X509_free (server_cert);
627 if (protocol == PROTO_Z3950)
629 send_initRequest(type_and_host);
635 int cmd_open(const char *arg)
639 strncpy (cur_host, arg, sizeof(cur_host)-1);
640 cur_host[sizeof(cur_host)-1] = 0;
642 return session_connect(cur_host);
649 if(!( auto_reconnect && last_open_command) ) return ;
651 open_command = (char *) xmalloc (strlen(last_open_command)+6);
652 strcpy (open_command, "open ");
654 strcat (open_command, last_open_command);
656 process_cmd_line(open_command);
661 int cmd_authentication(const char *arg)
663 static Z_IdAuthentication au;
664 static char user[40], group[40], pass[40];
665 static Z_IdPass idPass;
670 printf("Auth field set to null\n");
674 r = sscanf (arg, "%39s %39s %39s", user, group, pass);
677 printf("Authentication set to null\n");
683 if (!strcmp(user, "-")) {
684 au.which = Z_IdAuthentication_anonymous;
685 printf("Authentication set to Anonymous\n");
687 au.which = Z_IdAuthentication_open;
689 printf("Authentication set to Open (%s)\n", user);
695 au.which = Z_IdAuthentication_idPass;
696 au.u.idPass = &idPass;
697 idPass.groupId = NULL;
698 idPass.userId = user;
699 idPass.password = group;
700 printf("Authentication set to User (%s), Pass (%s)\n", user, group);
705 au.which = Z_IdAuthentication_idPass;
706 au.u.idPass = &idPass;
707 idPass.groupId = group;
708 idPass.userId = user;
709 idPass.password = pass;
710 printf("Authentication set to User (%s), Group (%s), Pass (%s)\n",
716 /* SEARCH SERVICE ------------------------------ */
717 static void display_record(Z_External *r);
719 static void print_record(const unsigned char *buf, size_t len)
722 print_stringn (buf, len);
723 /* add newline if not already added ... */
724 if (i <= 0 || buf[i-1] != '\n')
728 static void display_record(Z_External *r)
730 oident *ent = oid_getentbyoid(r->direct_reference);
734 * Tell the user what we got.
736 if (r->direct_reference)
738 printf("Record type: ");
740 printf("%s\n", ent->desc);
741 else if (!odr_oid(print, &r->direct_reference, 0, 0))
743 odr_perror(print, "print oid");
747 /* Check if this is a known, ASN.1 type tucked away in an octet string */
748 if (ent && r->which == Z_External_octet)
750 Z_ext_typeent *type = z_ext_getentbyref(ent->value);
756 * Call the given decoder to process the record.
758 odr_setbuf(in, (char*)r->u.octet_aligned->buf,
759 r->u.octet_aligned->len, 0);
760 if (!(*type->fun)(in, &rr, 0, 0))
762 odr_perror(in, "Decoding constructed record.");
763 fprintf(stdout, "[Near %d]\n", odr_offset(in));
764 fprintf(stdout, "Packet dump:\n---------\n");
765 odr_dumpBER(stdout, (char*)r->u.octet_aligned->buf,
766 r->u.octet_aligned->len);
767 fprintf(stdout, "---------\n");
769 /* note just ignores the error ant print the bytes form the octet_aligned later */
772 * Note: we throw away the original, BER-encoded record here.
773 * Do something else with it if you want to keep it.
775 r->u.sutrs = (Z_SUTRS *) rr; /* we don't actually check the type here. */
776 r->which = type->what;
780 if (ent && ent->value == VAL_SOIF)
781 print_record((const unsigned char *) r->u.octet_aligned->buf,
782 r->u.octet_aligned->len);
783 else if (r->which == Z_External_octet)
785 const char *octet_buf = (char*)r->u.octet_aligned->buf;
786 if (ent->oclass == CLASS_RECSYN &&
787 (ent->value == VAL_TEXT_XML ||
788 ent->value == VAL_APPLICATION_XML ||
789 ent->value == VAL_HTML))
791 print_record((const unsigned char *) octet_buf,
792 r->u.octet_aligned->len);
794 else if (ent->value == VAL_POSTSCRIPT)
796 int size = r->u.octet_aligned->len;
799 print_record((const unsigned char *) octet_buf, size);
804 #if AVOID_MARC_DECODE
805 /* primitive check for a marc OID 5.1-29 except 16 */
806 ent->oidsuffix[0] == 5 && ent->oidsuffix[1] < 30 &&
807 ent->oidsuffix[1] != 16
816 yaz_marc_t mt = yaz_marc_create();
818 if (yaz_marc_decode_buf(mt, octet_buf,r->u.octet_aligned->len,
822 if (marcCharset && !strcmp(marcCharset, "auto"))
824 if (ent->value == VAL_USMARC)
826 if (octet_buf[9] == 'a')
834 else if (marcCharset)
836 if (outputCharset && from)
838 cd = yaz_iconv_open(outputCharset, from);
839 printf ("convert from %s to %s", from,
842 printf (" unsupported\n");
847 fwrite (result, 1, rlen, stdout);
851 size_t inbytesleft = rlen;
852 const char *inp = result;
856 size_t outbytesleft = sizeof(outbuf);
860 r = yaz_iconv (cd, (char**) &inp,
862 &outp, &outbytesleft);
863 if (r == (size_t) (-1))
865 int e = yaz_iconv_error(cd);
866 if (e != YAZ_ICONV_E2BIG)
869 fwrite (outbuf, outp - outbuf, 1, stdout);
875 printf ("bad MARC. Dumping as it is:\n");
876 print_record((const unsigned char*) octet_buf,
877 r->u.octet_aligned->len);
879 yaz_marc_destroy(mt);
885 print_record((const unsigned char*) octet_buf,
886 r->u.octet_aligned->len);
890 fwrite (octet_buf, 1, r->u.octet_aligned->len, marc_file);
892 else if (ent && ent->value == VAL_SUTRS)
894 if (r->which != Z_External_sutrs)
896 printf("Expecting single SUTRS type for SUTRS.\n");
899 print_record(r->u.sutrs->buf, r->u.sutrs->len);
901 else if (ent && ent->value == VAL_GRS1)
904 if (r->which != Z_External_grs1)
906 printf("Expecting single GRS type for GRS.\n");
910 yaz_display_grs1(w, r->u.grs1, 0);
914 else if ( /* OPAC display not complete yet .. */
915 ent && ent->value == VAL_OPAC)
918 if (r->u.opac->bibliographicRecord)
919 display_record(r->u.opac->bibliographicRecord);
920 for (i = 0; i<r->u.opac->num_holdingsData; i++)
922 Z_HoldingsRecord *h = r->u.opac->holdingsData[i];
923 if (h->which == Z_HoldingsRecord_marcHoldingsRecord)
925 printf ("MARC holdings %d\n", i);
926 display_record(h->u.marcHoldingsRecord);
928 else if (h->which == Z_HoldingsRecord_holdingsAndCirc)
932 Z_HoldingsAndCircData *data = h->u.holdingsAndCirc;
934 printf ("Data holdings %d\n", i);
935 if (data->typeOfRecord)
936 printf ("typeOfRecord: %s\n", data->typeOfRecord);
937 if (data->encodingLevel)
938 printf ("encodingLevel: %s\n", data->encodingLevel);
939 if (data->receiptAcqStatus)
940 printf ("receiptAcqStatus: %s\n", data->receiptAcqStatus);
941 if (data->generalRetention)
942 printf ("generalRetention: %s\n", data->generalRetention);
943 if (data->completeness)
944 printf ("completeness: %s\n", data->completeness);
945 if (data->dateOfReport)
946 printf ("dateOfReport: %s\n", data->dateOfReport);
948 printf ("nucCode: %s\n", data->nucCode);
949 if (data->localLocation)
950 printf ("localLocation: %s\n", data->localLocation);
951 if (data->shelvingLocation)
952 printf ("shelvingLocation: %s\n", data->shelvingLocation);
953 if (data->callNumber)
954 printf ("callNumber: %s\n", data->callNumber);
955 if (data->shelvingData)
956 printf ("shelvingData: %s\n", data->shelvingData);
957 if (data->copyNumber)
958 printf ("copyNumber: %s\n", data->copyNumber);
959 if (data->publicNote)
960 printf ("publicNote: %s\n", data->publicNote);
961 if (data->reproductionNote)
962 printf ("reproductionNote: %s\n", data->reproductionNote);
963 if (data->termsUseRepro)
964 printf ("termsUseRepro: %s\n", data->termsUseRepro);
965 if (data->enumAndChron)
966 printf ("enumAndChron: %s\n", data->enumAndChron);
967 for (j = 0; j<data->num_volumes; j++)
969 printf ("volume %d\n", j);
970 if (data->volumes[j]->enumeration)
971 printf (" enumeration: %s\n",
972 data->volumes[j]->enumeration);
973 if (data->volumes[j]->chronology)
974 printf (" chronology: %s\n",
975 data->volumes[j]->chronology);
976 if (data->volumes[j]->enumAndChron)
977 printf (" enumAndChron: %s\n",
978 data->volumes[j]->enumAndChron);
980 for (j = 0; j<data->num_circulationData; j++)
982 printf ("circulation %d\n", j);
983 if (data->circulationData[j]->availableNow)
984 printf (" availableNow: %d\n",
985 *data->circulationData[j]->availableNow);
986 if (data->circulationData[j]->availablityDate)
987 printf (" availabiltyDate: %s\n",
988 data->circulationData[j]->availablityDate);
989 if (data->circulationData[j]->availableThru)
990 printf (" availableThru: %s\n",
991 data->circulationData[j]->availableThru);
992 if (data->circulationData[j]->restrictions)
993 printf (" restrictions: %s\n",
994 data->circulationData[j]->restrictions);
995 if (data->circulationData[j]->itemId)
996 printf (" itemId: %s\n",
997 data->circulationData[j]->itemId);
998 if (data->circulationData[j]->renewable)
999 printf (" renewable: %d\n",
1000 *data->circulationData[j]->renewable);
1001 if (data->circulationData[j]->onHold)
1002 printf (" onHold: %d\n",
1003 *data->circulationData[j]->onHold);
1004 if (data->circulationData[j]->enumAndChron)
1005 printf (" enumAndChron: %s\n",
1006 data->circulationData[j]->enumAndChron);
1007 if (data->circulationData[j]->midspine)
1008 printf (" midspine: %s\n",
1009 data->circulationData[j]->midspine);
1010 if (data->circulationData[j]->temporaryLocation)
1011 printf (" temporaryLocation: %s\n",
1012 data->circulationData[j]->temporaryLocation);
1019 printf("Unknown record representation.\n");
1020 if (!z_External(print, &r, 0, 0))
1022 odr_perror(print, "Printing external");
1028 static void display_diagrecs(Z_DiagRec **pp, int num)
1032 Z_DefaultDiagFormat *r;
1034 printf("Diagnostic message(s) from database:\n");
1035 for (i = 0; i<num; i++)
1037 Z_DiagRec *p = pp[i];
1038 if (p->which != Z_DiagRec_defaultFormat)
1040 printf("Diagnostic record not in default format.\n");
1044 r = p->u.defaultFormat;
1045 if (!(ent = oid_getentbyoid(r->diagnosticSetId)) ||
1046 ent->oclass != CLASS_DIAGSET || ent->value != VAL_BIB1)
1047 printf("Missing or unknown diagset\n");
1048 printf(" [%d] %s", *r->condition, diagbib1_str(*r->condition));
1051 case Z_DefaultDiagFormat_v2Addinfo:
1052 printf (" -- v2 addinfo '%s'\n", r->u.v2Addinfo);
1054 case Z_DefaultDiagFormat_v3Addinfo:
1055 printf (" -- v3 addinfo '%s'\n", r->u.v3Addinfo);
1062 static void display_nameplusrecord(Z_NamePlusRecord *p)
1064 if (p->databaseName)
1065 printf("[%s]", p->databaseName);
1066 if (p->which == Z_NamePlusRecord_surrogateDiagnostic)
1067 display_diagrecs(&p->u.surrogateDiagnostic, 1);
1068 else if (p->which == Z_NamePlusRecord_databaseRecord)
1069 display_record(p->u.databaseRecord);
1072 static void display_records(Z_Records *p)
1076 if (p->which == Z_Records_NSD)
1078 Z_DiagRec dr, *dr_p = &dr;
1079 dr.which = Z_DiagRec_defaultFormat;
1080 dr.u.defaultFormat = p->u.nonSurrogateDiagnostic;
1081 display_diagrecs (&dr_p, 1);
1083 else if (p->which == Z_Records_multipleNSD)
1084 display_diagrecs (p->u.multipleNonSurDiagnostics->diagRecs,
1085 p->u.multipleNonSurDiagnostics->num_diagRecs);
1088 printf("Records: %d\n", p->u.databaseOrSurDiagnostics->num_records);
1089 for (i = 0; i < p->u.databaseOrSurDiagnostics->num_records; i++)
1090 display_nameplusrecord(p->u.databaseOrSurDiagnostics->records[i]);
1094 static int send_deleteResultSetRequest(const char *arg)
1099 Z_APDU *apdu = zget_APDU(out, Z_APDU_deleteResultSetRequest);
1100 Z_DeleteResultSetRequest *req = apdu->u.deleteResultSetRequest;
1102 req->referenceId = set_refid (out);
1104 req->num_resultSetList =
1105 sscanf (arg, "%30s %30s %30s %30s %30s %30s %30s %30s",
1106 names[0], names[1], names[2], names[3],
1107 names[4], names[5], names[6], names[7]);
1109 req->deleteFunction = (int *)
1110 odr_malloc (out, sizeof(*req->deleteFunction));
1111 if (req->num_resultSetList > 0)
1113 *req->deleteFunction = Z_DeleteRequest_list;
1114 req->resultSetList = (char **)
1115 odr_malloc (out, sizeof(*req->resultSetList)*
1116 req->num_resultSetList);
1117 for (i = 0; i<req->num_resultSetList; i++)
1118 req->resultSetList[i] = names[i];
1122 *req->deleteFunction = Z_DeleteRequest_all;
1123 req->resultSetList = 0;
1127 printf("Sent deleteResultSetRequest.\n");
1132 static int send_srw(Z_SRW_PDU *sr)
1134 const char *charset = negotiationCharset;
1135 const char *host_port = cur_host;
1138 Z_SOAP_Handler h[2] = {
1139 {"http://www.loc.gov/zing/srw/", 0, (Z_SOAP_fun) yaz_srw_codec},
1142 ODR o = odr_createmem(ODR_ENCODE);
1144 Z_SOAP *p = odr_malloc(o, sizeof(*p));
1147 path = odr_malloc(out, strlen(databaseNames[0])+2);
1149 strcpy(path+1, databaseNames[0]);
1151 gdu = z_get_HTTP_Request(out);
1152 gdu->u.HTTP_Request->version = http_version;
1153 gdu->u.HTTP_Request->path = odr_strdup(out, path);
1157 const char *cp0 = strstr(host_port, "://");
1158 const char *cp1 = 0;
1164 cp1 = strchr(cp0, '/');
1166 cp1 = cp0+strlen(cp0);
1170 char *h = odr_malloc(out, cp1 - cp0 + 1);
1171 memcpy (h, cp0, cp1 - cp0);
1173 z_HTTP_header_add(out, &gdu->u.HTTP_Request->headers,
1178 strcpy(ctype, "text/xml");
1179 if (charset && strlen(charset) < 20)
1181 strcat(ctype, "; charset=");
1182 strcat(ctype, charset);
1184 z_HTTP_header_add(out, &gdu->u.HTTP_Request->headers,
1185 "Content-Type", ctype);
1186 z_HTTP_header_add(out, &gdu->u.HTTP_Request->headers,
1187 "SOAPAction", "\"\"");
1188 p->which = Z_SOAP_generic;
1189 p->u.generic = odr_malloc(o, sizeof(*p->u.generic));
1190 p->u.generic->no = 0;
1191 p->u.generic->ns = 0;
1192 p->u.generic->p = sr;
1193 p->ns = "http://schemas.xmlsoap.org/soap/envelope/";
1195 ret = z_soap_codec_enc(o, &p,
1196 &gdu->u.HTTP_Request->content_buf,
1197 &gdu->u.HTTP_Request->content_len, h,
1200 if (z_GDU(out, &gdu, 0, 0))
1208 if (!z_GDU(print, &gdu, 0, 0))
1209 printf ("Failed to print outgoing APDU\n");
1212 buf_out = odr_getbuf(out, &len_out, 0);
1214 /* we don't odr_reset(out), since we may need the buffer again */
1216 do_hex_dump(buf_out, len_out);
1218 r = cs_put(conn, buf_out, len_out);
1230 static int send_SRW_searchRequest(const char *arg)
1236 assert(srw_sr_odr_out == 0);
1237 srw_sr_odr_out = odr_createmem(ODR_ENCODE);
1239 odr_reset(srw_sr_odr_out);
1243 /* save this for later .. when fetching individual records */
1244 srw_sr = sr = yaz_srw_get(srw_sr_odr_out, Z_SRW_searchRetrieve_request);
1245 sr->u.request->query_type = Z_SRW_query_type_cql;
1246 sr->u.request->query.cql = odr_strdup(srw_sr_odr_out, arg);
1248 sr = yaz_srw_get(out, Z_SRW_searchRetrieve_request);
1249 sr->u.request->query_type = Z_SRW_query_type_cql;
1250 sr->u.request->query.cql = odr_strdup(out, arg);
1252 sr->u.request->maximumRecords = odr_intdup(out, 0);
1255 sr->u.request->recordSchema = record_schema;
1256 if (recordsyntax == VAL_TEXT_XML)
1257 sr->u.explain_request->recordPacking = "xml";
1258 return send_srw(sr);
1262 static int send_searchRequest(const char *arg)
1264 Z_APDU *apdu = zget_APDU(out, Z_APDU_searchRequest);
1265 Z_SearchRequest *req = apdu->u.searchRequest;
1267 struct ccl_rpn_node *rpn = NULL;
1269 char setstring[100];
1270 Z_RPNQuery *RPNquery;
1272 YAZ_PQF_Parser pqf_parser;
1274 QueryType myQueryType = queryType;
1277 if (myQueryType == QueryType_CCL2RPN)
1279 rpn = ccl_find_str(bibset, arg, &error, &pos);
1282 printf("CCL ERROR: %s\n", ccl_err_msg(error));
1285 } else if (myQueryType == QueryType_CQL2RPN) {
1286 /* ### All this code should be wrapped in a utility function */
1288 struct cql_node *node;
1289 const char *addinfo;
1290 if (cqltrans == 0) {
1291 printf("Can't use CQL: no translation file. Try set_cqlfile\n");
1294 parser = cql_parser_create();
1295 if ((error = cql_parser_string(parser, arg)) != 0) {
1296 printf("Can't parse CQL: must be a syntax error\n");
1299 node = cql_parser_result(parser);
1300 if ((error = cql_transform_buf(cqltrans, node, pqfbuf,
1301 sizeof pqfbuf)) != 0) {
1302 error = cql_transform_error(cqltrans, &addinfo);
1303 printf ("Can't convert CQL to PQF: %s (addinfo=%s)\n",
1304 cql_strerror(error), addinfo);
1308 myQueryType = QueryType_Prefix;
1311 req->referenceId = set_refid (out);
1312 if (!strcmp(arg, "@big")) /* strictly for troublemaking */
1314 static unsigned char big[2100];
1315 static Odr_oct bigo;
1317 /* send a very big referenceid to test transport stack etc. */
1318 memset(big, 'A', 2100);
1319 bigo.len = bigo.size = 2100;
1321 req->referenceId = &bigo;
1326 sprintf(setstring, "%d", ++setnumber);
1327 req->resultSetName = setstring;
1329 *req->smallSetUpperBound = smallSetUpperBound;
1330 *req->largeSetLowerBound = largeSetLowerBound;
1331 *req->mediumSetPresentNumber = mediumSetPresentNumber;
1332 if (smallSetUpperBound > 0 || (largeSetLowerBound > 1 &&
1333 mediumSetPresentNumber > 0))
1335 req->preferredRecordSyntax =
1336 yaz_oidval_to_z3950oid(out, CLASS_RECSYN, recordsyntax);
1338 req->smallSetElementSetNames =
1339 req->mediumSetElementSetNames = elementSetNames;
1341 req->num_databaseNames = num_databaseNames;
1342 req->databaseNames = databaseNames;
1344 req->query = &query;
1346 switch (myQueryType)
1348 case QueryType_Prefix:
1349 query.which = Z_Query_type_1;
1350 pqf_parser = yaz_pqf_create ();
1351 RPNquery = yaz_pqf_parse (pqf_parser, out, arg);
1354 const char *pqf_msg;
1356 int code = yaz_pqf_error (pqf_parser, &pqf_msg, &off);
1357 printf("%*s^\n", off+4, "");
1358 printf("Prefix query error: %s (code %d)\n", pqf_msg, code);
1360 yaz_pqf_destroy (pqf_parser);
1363 yaz_pqf_destroy (pqf_parser);
1364 query.u.type_1 = RPNquery;
1367 query.which = Z_Query_type_2;
1368 query.u.type_2 = &ccl_query;
1369 ccl_query.buf = (unsigned char*) arg;
1370 ccl_query.len = strlen(arg);
1372 case QueryType_CCL2RPN:
1373 query.which = Z_Query_type_1;
1374 RPNquery = ccl_rpn_query(out, rpn);
1377 printf ("Couldn't convert from CCL to RPN\n");
1380 query.u.type_1 = RPNquery;
1381 ccl_rpn_delete (rpn);
1384 query.which = Z_Query_type_104;
1385 ext = (Z_External *) odr_malloc(out, sizeof(*ext));
1386 ext->direct_reference = odr_getoidbystr(out, "1.2.840.10003.16.2");
1387 ext->indirect_reference = 0;
1388 ext->descriptor = 0;
1389 ext->which = Z_External_CQL;
1390 ext->u.cql = odr_strdup(out, arg);
1391 query.u.type_104 = ext;
1394 printf ("Unsupported query type\n");
1397 if (send_apdu(apdu))
1398 printf("Sent searchRequest.\n");
1403 /* display Query Expression as part of searchResult-1 */
1404 static void display_queryExpression (Z_QueryExpression *qe)
1408 if (qe->which == Z_QueryExpression_term)
1410 if (qe->u.term->queryTerm)
1412 Z_Term *term = qe->u.term->queryTerm;
1413 switch (term->which)
1415 case Z_Term_general:
1416 printf (" %.*s", term->u.general->len, term->u.general->buf);
1418 case Z_Term_characterString:
1419 printf (" %s", term->u.characterString);
1421 case Z_Term_numeric:
1422 printf (" %d", *term->u.numeric);
1432 /* see if we can find USR:SearchResult-1 */
1433 static void display_searchResult (Z_OtherInformation *o)
1438 for (i = 0; i < o->num_elements; i++)
1440 if (o->list[i]->which == Z_OtherInfo_externallyDefinedInfo)
1442 Z_External *ext = o->list[i]->information.externallyDefinedInfo;
1444 if (ext->which == Z_External_searchResult1)
1447 Z_SearchInfoReport *sr = ext->u.searchResult1;
1448 printf ("SearchResult-1:");
1449 for (j = 0; j < sr->num; j++)
1451 if (!sr->elements[j]->subqueryExpression)
1453 display_queryExpression (
1454 sr->elements[j]->subqueryExpression);
1455 display_queryExpression (
1456 sr->elements[j]->subqueryInterpretation);
1457 display_queryExpression (
1458 sr->elements[j]->subqueryRecommendation);
1459 if (sr->elements[j]->subqueryCount)
1460 printf ("(%d)", *sr->elements[j]->subqueryCount);
1468 static int process_searchResponse(Z_SearchResponse *res)
1470 printf ("Received SearchResponse.\n");
1471 print_refid (res->referenceId);
1472 if (*res->searchStatus)
1473 printf("Search was a success.\n");
1475 printf("Search was a bloomin' failure.\n");
1476 printf("Number of hits: %d", *res->resultCount);
1478 printf (", setno %d", setnumber);
1480 display_searchResult (res->additionalSearchInfo);
1481 printf("records returned: %d\n",
1482 *res->numberOfRecordsReturned);
1483 setno += *res->numberOfRecordsReturned;
1485 display_records(res->records);
1489 static void print_level(int iLevel)
1492 for (i = 0; i < iLevel * 4; i++)
1496 static void print_int(int iLevel, const char *pTag, int *pInt)
1500 print_level(iLevel);
1501 printf("%s: %d\n", pTag, *pInt);
1505 static void print_string(int iLevel, const char *pTag, const char *pString)
1507 if (pString != NULL)
1509 print_level(iLevel);
1510 printf("%s: %s\n", pTag, pString);
1514 static void print_oid(int iLevel, const char *pTag, Odr_oid *pOid)
1520 print_level(iLevel);
1521 printf("%s:", pTag);
1522 for (; *pInt != -1; pInt++)
1523 printf(" %d", *pInt);
1528 static void print_referenceId(int iLevel, Z_ReferenceId *referenceId)
1530 if (referenceId != NULL)
1534 print_level(iLevel);
1535 printf("Ref Id (%d, %d): ", referenceId->len, referenceId->size);
1536 for (i = 0; i < referenceId->len; i++)
1537 printf("%c", referenceId->buf[i]);
1542 static void print_string_or_numeric(int iLevel, const char *pTag, Z_StringOrNumeric *pStringNumeric)
1544 if (pStringNumeric != NULL)
1546 switch (pStringNumeric->which)
1548 case Z_StringOrNumeric_string:
1549 print_string(iLevel, pTag, pStringNumeric->u.string);
1552 case Z_StringOrNumeric_numeric:
1553 print_int(iLevel, pTag, pStringNumeric->u.numeric);
1557 print_level(iLevel);
1558 printf("%s: valid type for Z_StringOrNumeric\n", pTag);
1564 static void print_universe_report_duplicate(
1566 Z_UniverseReportDuplicate *pUniverseReportDuplicate)
1568 if (pUniverseReportDuplicate != NULL)
1570 print_level(iLevel);
1571 printf("Universe Report Duplicate: \n");
1573 print_string_or_numeric(iLevel, "Hit No",
1574 pUniverseReportDuplicate->hitno);
1578 static void print_universe_report_hits(
1580 Z_UniverseReportHits *pUniverseReportHits)
1582 if (pUniverseReportHits != NULL)
1584 print_level(iLevel);
1585 printf("Universe Report Hits: \n");
1587 print_string_or_numeric(iLevel, "Database",
1588 pUniverseReportHits->database);
1589 print_string_or_numeric(iLevel, "Hits", pUniverseReportHits->hits);
1593 static void print_universe_report(int iLevel, Z_UniverseReport *pUniverseReport)
1595 if (pUniverseReport != NULL)
1597 print_level(iLevel);
1598 printf("Universe Report: \n");
1600 print_int(iLevel, "Total Hits", pUniverseReport->totalHits);
1601 switch (pUniverseReport->which)
1603 case Z_UniverseReport_databaseHits:
1604 print_universe_report_hits(iLevel,
1605 pUniverseReport->u.databaseHits);
1608 case Z_UniverseReport_duplicate:
1609 print_universe_report_duplicate(iLevel,
1610 pUniverseReport->u.duplicate);
1614 print_level(iLevel);
1615 printf("Type: %d\n", pUniverseReport->which);
1621 static void print_external(int iLevel, Z_External *pExternal)
1623 if (pExternal != NULL)
1625 print_level(iLevel);
1626 printf("External: \n");
1628 print_oid(iLevel, "Direct Reference", pExternal->direct_reference);
1629 print_int(iLevel, "InDirect Reference", pExternal->indirect_reference);
1630 print_string(iLevel, "Descriptor", pExternal->descriptor);
1631 switch (pExternal->which)
1633 case Z_External_universeReport:
1634 print_universe_report(iLevel, pExternal->u.universeReport);
1638 print_level(iLevel);
1639 printf("Type: %d\n", pExternal->which);
1645 static int process_resourceControlRequest (Z_ResourceControlRequest *req)
1647 printf ("Received ResourceControlRequest.\n");
1648 print_referenceId(1, req->referenceId);
1649 print_int(1, "Suspended Flag", req->suspendedFlag);
1650 print_int(1, "Partial Results Available", req->partialResultsAvailable);
1651 print_int(1, "Response Required", req->responseRequired);
1652 print_int(1, "Triggered Request Flag", req->triggeredRequestFlag);
1653 print_external(1, req->resourceReport);
1657 void process_ESResponse(Z_ExtendedServicesResponse *res)
1660 switch (*res->operationStatus)
1662 case Z_ExtendedServicesResponse_done:
1665 case Z_ExtendedServicesResponse_accepted:
1666 printf ("accepted\n");
1668 case Z_ExtendedServicesResponse_failure:
1669 printf ("failure\n");
1670 display_diagrecs(res->diagnostics, res->num_diagnostics);
1673 printf ("unknown\n");
1675 if ( (*res->operationStatus != Z_ExtendedServicesResponse_failure) &&
1676 (res->num_diagnostics != 0) ) {
1677 display_diagrecs(res->diagnostics, res->num_diagnostics);
1679 print_refid (res->referenceId);
1680 if (res->taskPackage &&
1681 res->taskPackage->which == Z_External_extendedService)
1683 Z_TaskPackage *taskPackage = res->taskPackage->u.extendedService;
1684 Odr_oct *id = taskPackage->targetReference;
1685 Z_External *ext = taskPackage->taskSpecificParameters;
1689 printf ("Target Reference: ");
1690 print_stringn (id->buf, id->len);
1693 if (ext->which == Z_External_update)
1695 Z_IUUpdateTaskPackage *utp = ext->u.update->u.taskPackage;
1696 if (utp && utp->targetPart)
1698 Z_IUTargetPart *targetPart = utp->targetPart;
1701 for (i = 0; i<targetPart->num_taskPackageRecords; i++)
1704 Z_IUTaskPackageRecordStructure *tpr =
1705 targetPart->taskPackageRecords[i];
1706 printf ("task package record %d\n", i+1);
1707 if (tpr->which == Z_IUTaskPackageRecordStructure_record)
1709 display_record (tpr->u.record);
1713 printf ("other type\n");
1721 const char *get_ill_element (void *clientData, const char *element)
1726 static Z_External *create_external_itemRequest()
1728 struct ill_get_ctl ctl;
1729 ILL_ItemRequest *req;
1731 int item_request_size = 0;
1732 char *item_request_buf = 0;
1736 ctl.f = get_ill_element;
1738 req = ill_get_ItemRequest(&ctl, "ill", 0);
1740 printf ("ill_get_ItemRequest failed\n");
1742 if (!ill_ItemRequest (out, &req, 0, 0))
1746 ill_ItemRequest(print, &req, 0, 0);
1749 item_request_buf = odr_getbuf (out, &item_request_size, 0);
1750 if (item_request_buf)
1751 odr_setbuf (out, item_request_buf, item_request_size, 1);
1752 printf ("Couldn't encode ItemRequest, size %d\n", item_request_size);
1759 item_request_buf = odr_getbuf (out, &item_request_size, 0);
1760 oid.proto = PROTO_GENERAL;
1761 oid.oclass = CLASS_GENERAL;
1762 oid.value = VAL_ISO_ILL_1;
1764 r = (Z_External *) odr_malloc (out, sizeof(*r));
1765 r->direct_reference = odr_oiddup(out,oid_getoidbyent(&oid));
1766 r->indirect_reference = 0;
1768 r->which = Z_External_single;
1770 r->u.single_ASN1_type = (Odr_oct *)
1771 odr_malloc (out, sizeof(*r->u.single_ASN1_type));
1772 r->u.single_ASN1_type->buf = (unsigned char *)
1773 odr_malloc (out, item_request_size);
1774 r->u.single_ASN1_type->len = item_request_size;
1775 r->u.single_ASN1_type->size = item_request_size;
1776 memcpy (r->u.single_ASN1_type->buf, item_request_buf,
1779 do_hex_dump(item_request_buf,item_request_size);
1784 static Z_External *create_external_ILL_APDU(int which)
1786 struct ill_get_ctl ctl;
1789 int ill_request_size = 0;
1790 char *ill_request_buf = 0;
1794 ctl.f = get_ill_element;
1796 ill_apdu = ill_get_APDU(&ctl, "ill", 0);
1798 if (!ill_APDU (out, &ill_apdu, 0, 0))
1802 printf ("-------------------\n");
1803 ill_APDU(print, &ill_apdu, 0, 0);
1805 printf ("-------------------\n");
1807 ill_request_buf = odr_getbuf (out, &ill_request_size, 0);
1808 if (ill_request_buf)
1809 odr_setbuf (out, ill_request_buf, ill_request_size, 1);
1810 printf ("Couldn't encode ILL-Request, size %d\n", ill_request_size);
1816 ill_request_buf = odr_getbuf (out, &ill_request_size, 0);
1818 oid.proto = PROTO_GENERAL;
1819 oid.oclass = CLASS_GENERAL;
1820 oid.value = VAL_ISO_ILL_1;
1822 r = (Z_External *) odr_malloc (out, sizeof(*r));
1823 r->direct_reference = odr_oiddup(out,oid_getoidbyent(&oid));
1824 r->indirect_reference = 0;
1826 r->which = Z_External_single;
1828 r->u.single_ASN1_type = (Odr_oct *)
1829 odr_malloc (out, sizeof(*r->u.single_ASN1_type));
1830 r->u.single_ASN1_type->buf = (unsigned char *)
1831 odr_malloc (out, ill_request_size);
1832 r->u.single_ASN1_type->len = ill_request_size;
1833 r->u.single_ASN1_type->size = ill_request_size;
1834 memcpy (r->u.single_ASN1_type->buf, ill_request_buf, ill_request_size);
1835 /* printf ("len = %d\n", ill_request_size); */
1836 /* do_hex_dump(ill_request_buf,ill_request_size); */
1837 /* printf("--- end of extenal\n"); */
1844 static Z_External *create_ItemOrderExternal(const char *type, int itemno)
1846 Z_External *r = (Z_External *) odr_malloc(out, sizeof(Z_External));
1847 oident ItemOrderRequest;
1849 ItemOrderRequest.proto = PROTO_Z3950;
1850 ItemOrderRequest.oclass = CLASS_EXTSERV;
1851 ItemOrderRequest.value = VAL_ITEMORDER;
1853 r->direct_reference = odr_oiddup(out,oid_getoidbyent(&ItemOrderRequest));
1854 r->indirect_reference = 0;
1857 r->which = Z_External_itemOrder;
1859 r->u.itemOrder = (Z_ItemOrder *) odr_malloc(out,sizeof(Z_ItemOrder));
1860 memset(r->u.itemOrder, 0, sizeof(Z_ItemOrder));
1861 r->u.itemOrder->which=Z_IOItemOrder_esRequest;
1863 r->u.itemOrder->u.esRequest = (Z_IORequest *)
1864 odr_malloc(out,sizeof(Z_IORequest));
1865 memset(r->u.itemOrder->u.esRequest, 0, sizeof(Z_IORequest));
1867 r->u.itemOrder->u.esRequest->toKeep = (Z_IOOriginPartToKeep *)
1868 odr_malloc(out,sizeof(Z_IOOriginPartToKeep));
1869 memset(r->u.itemOrder->u.esRequest->toKeep, 0, sizeof(Z_IOOriginPartToKeep));
1870 r->u.itemOrder->u.esRequest->notToKeep = (Z_IOOriginPartNotToKeep *)
1871 odr_malloc(out,sizeof(Z_IOOriginPartNotToKeep));
1872 memset(r->u.itemOrder->u.esRequest->notToKeep, 0, sizeof(Z_IOOriginPartNotToKeep));
1874 r->u.itemOrder->u.esRequest->toKeep->supplDescription = NULL;
1875 r->u.itemOrder->u.esRequest->toKeep->contact = NULL;
1876 r->u.itemOrder->u.esRequest->toKeep->addlBilling = NULL;
1878 r->u.itemOrder->u.esRequest->notToKeep->resultSetItem =
1879 (Z_IOResultSetItem *) odr_malloc(out, sizeof(Z_IOResultSetItem));
1880 memset(r->u.itemOrder->u.esRequest->notToKeep->resultSetItem, 0, sizeof(Z_IOResultSetItem));
1881 r->u.itemOrder->u.esRequest->notToKeep->resultSetItem->resultSetId = "1";
1883 r->u.itemOrder->u.esRequest->notToKeep->resultSetItem->item =
1884 (int *) odr_malloc(out, sizeof(int));
1885 *r->u.itemOrder->u.esRequest->notToKeep->resultSetItem->item = itemno;
1887 if (!strcmp (type, "item") || !strcmp(type, "2"))
1889 printf ("using item-request\n");
1890 r->u.itemOrder->u.esRequest->notToKeep->itemRequest =
1891 create_external_itemRequest();
1893 else if (!strcmp(type, "ill") || !strcmp(type, "1"))
1895 printf ("using ILL-request\n");
1896 r->u.itemOrder->u.esRequest->notToKeep->itemRequest =
1897 create_external_ILL_APDU(ILL_APDU_ILL_Request);
1899 else if (!strcmp(type, "xml") || !strcmp(type, "3"))
1901 const char *xml_buf =
1903 " <type>request</type>\n"
1904 " <libraryNo>000200</libraryNo>\n"
1905 " <borrowerTicketNo> 1212 </borrowerTicketNo>\n"
1907 r->u.itemOrder->u.esRequest->notToKeep->itemRequest =
1908 z_ext_record (out, VAL_TEXT_XML, xml_buf, strlen(xml_buf));
1911 r->u.itemOrder->u.esRequest->notToKeep->itemRequest = 0;
1916 static int send_itemorder(const char *type, int itemno)
1918 Z_APDU *apdu = zget_APDU(out, Z_APDU_extendedServicesRequest);
1919 Z_ExtendedServicesRequest *req = apdu->u.extendedServicesRequest;
1920 oident ItemOrderRequest;
1922 ItemOrderRequest.proto = PROTO_Z3950;
1923 ItemOrderRequest.oclass = CLASS_EXTSERV;
1924 ItemOrderRequest.value = VAL_ITEMORDER;
1925 req->packageType = odr_oiddup(out,oid_getoidbyent(&ItemOrderRequest));
1926 req->packageName = esPackageName;
1928 req->taskSpecificParameters = create_ItemOrderExternal(type, itemno);
1934 static int only_z3950()
1936 if (protocol == PROTO_HTTP)
1938 printf ("Not supported by SRW\n");
1944 static int cmd_update_common(const char *arg, int version);
1946 static int cmd_update(const char *arg)
1948 return cmd_update_common(arg, 1);
1951 static int cmd_update0(const char *arg)
1953 return cmd_update_common(arg, 0);
1956 static int cmd_update_common(const char *arg, int version)
1958 Z_APDU *apdu = zget_APDU(out, Z_APDU_extendedServicesRequest );
1959 Z_ExtendedServicesRequest *req = apdu->u.extendedServicesRequest;
1961 char action[20], recid[20], fname[80];
1963 Z_External *record_this = 0;
1970 sscanf (arg, "%19s %19s %79s", action, recid, fname);
1972 if (!strcmp (action, "insert"))
1973 action_no = Z_IUOriginPartToKeep_recordInsert;
1974 else if (!strcmp (action, "replace"))
1975 action_no = Z_IUOriginPartToKeep_recordReplace;
1976 else if (!strcmp (action, "delete"))
1977 action_no = Z_IUOriginPartToKeep_recordDelete;
1978 else if (!strcmp (action, "update"))
1979 action_no = Z_IUOriginPartToKeep_specialUpdate;
1982 printf ("Bad action: %s\n", action);
1983 printf ("Possible values: insert, replace, delete, update\n");
1991 stat (fname, &status);
1992 if (S_ISREG(status.st_mode) && (inf = fopen(fname, "r")))
1994 size_t len = status.st_size;
1995 char *buf = (char *) xmalloc (len);
1997 fread (buf, 1, len, inf);
2001 record_this = z_ext_record (out, VAL_TEXT_XML, buf, len);
2007 printf ("File %s doesn't exist\n", fname);
2015 printf ("No last record (update ignored)\n");
2018 record_this = record_last;
2022 yaz_oidval_to_z3950oid(out, CLASS_EXTSERV,
2023 version == 0 ? VAL_DBUPDATE0 : VAL_DBUPDATE);
2025 req->packageName = esPackageName;
2027 req->referenceId = set_refid (out);
2029 r = req->taskSpecificParameters = (Z_External *)
2030 odr_malloc (out, sizeof(*r));
2031 r->direct_reference = req->packageType;
2032 r->indirect_reference = 0;
2036 Z_IU0OriginPartToKeep *toKeep;
2037 Z_IU0SuppliedRecords *notToKeep;
2039 r->which = Z_External_update0;
2040 r->u.update0 = (Z_IU0Update *) odr_malloc(out, sizeof(*r->u.update0));
2041 r->u.update0->which = Z_IUUpdate_esRequest;
2042 r->u.update0->u.esRequest = (Z_IU0UpdateEsRequest *)
2043 odr_malloc(out, sizeof(*r->u.update0->u.esRequest));
2044 toKeep = r->u.update0->u.esRequest->toKeep = (Z_IU0OriginPartToKeep *)
2045 odr_malloc(out, sizeof(*r->u.update0->u.esRequest->toKeep));
2047 toKeep->databaseName = databaseNames[0];
2049 toKeep->elementSetName = 0;
2051 toKeep->action = (int *) odr_malloc(out, sizeof(*toKeep->action));
2052 *toKeep->action = action_no;
2054 notToKeep = r->u.update0->u.esRequest->notToKeep = (Z_IU0SuppliedRecords *)
2055 odr_malloc(out, sizeof(*r->u.update0->u.esRequest->notToKeep));
2057 notToKeep->elements = (Z_IU0SuppliedRecords_elem **)
2058 odr_malloc(out, sizeof(*notToKeep->elements));
2059 notToKeep->elements[0] = (Z_IU0SuppliedRecords_elem *)
2060 odr_malloc(out, sizeof(**notToKeep->elements));
2061 notToKeep->elements[0]->which = Z_IUSuppliedRecords_elem_opaque;
2064 notToKeep->elements[0]->u.opaque = (Odr_oct *)
2065 odr_malloc (out, sizeof(Odr_oct));
2066 notToKeep->elements[0]->u.opaque->buf = (unsigned char *) recid;
2067 notToKeep->elements[0]->u.opaque->size = strlen(recid);
2068 notToKeep->elements[0]->u.opaque->len = strlen(recid);
2071 notToKeep->elements[0]->u.opaque = 0;
2072 notToKeep->elements[0]->supplementalId = 0;
2073 notToKeep->elements[0]->correlationInfo = 0;
2074 notToKeep->elements[0]->record = record_this;
2078 Z_IUOriginPartToKeep *toKeep;
2079 Z_IUSuppliedRecords *notToKeep;
2081 r->which = Z_External_update;
2082 r->u.update = (Z_IUUpdate *) odr_malloc(out, sizeof(*r->u.update));
2083 r->u.update->which = Z_IUUpdate_esRequest;
2084 r->u.update->u.esRequest = (Z_IUUpdateEsRequest *)
2085 odr_malloc(out, sizeof(*r->u.update->u.esRequest));
2086 toKeep = r->u.update->u.esRequest->toKeep = (Z_IUOriginPartToKeep *)
2087 odr_malloc(out, sizeof(*r->u.update->u.esRequest->toKeep));
2089 toKeep->databaseName = databaseNames[0];
2091 toKeep->elementSetName = 0;
2092 toKeep->actionQualifier = 0;
2093 toKeep->action = (int *) odr_malloc(out, sizeof(*toKeep->action));
2094 *toKeep->action = action_no;
2096 notToKeep = r->u.update->u.esRequest->notToKeep = (Z_IUSuppliedRecords *)
2097 odr_malloc(out, sizeof(*r->u.update->u.esRequest->notToKeep));
2099 notToKeep->elements = (Z_IUSuppliedRecords_elem **)
2100 odr_malloc(out, sizeof(*notToKeep->elements));
2101 notToKeep->elements[0] = (Z_IUSuppliedRecords_elem *)
2102 odr_malloc(out, sizeof(**notToKeep->elements));
2103 notToKeep->elements[0]->which = Z_IUSuppliedRecords_elem_opaque;
2106 notToKeep->elements[0]->u.opaque = (Odr_oct *)
2107 odr_malloc (out, sizeof(Odr_oct));
2108 notToKeep->elements[0]->u.opaque->buf = (unsigned char *) recid;
2109 notToKeep->elements[0]->u.opaque->size = strlen(recid);
2110 notToKeep->elements[0]->u.opaque->len = strlen(recid);
2113 notToKeep->elements[0]->u.opaque = 0;
2114 notToKeep->elements[0]->supplementalId = 0;
2115 notToKeep->elements[0]->correlationInfo = 0;
2116 notToKeep->elements[0]->record = record_this;
2124 static int cmd_itemorder(const char *arg)
2131 if (sscanf (arg, "%10s %d", type, &itemno) != 2)
2134 printf("Item order request\n");
2136 send_itemorder(type, itemno);
2140 static void show_opt(const char *arg, void *clientData)
2142 printf ("%s ", arg);
2145 static int cmd_zversion(const char *arg)
2148 z3950_version = atoi(arg);
2150 printf ("version is %d\n", z3950_version);
2154 static int cmd_options(const char *arg)
2160 r = yaz_init_opt_encode(&z3950_options, arg, &pos);
2164 yaz_init_opt_decode(&z3950_options, show_opt, 0);
2170 static int cmd_explain(const char *arg)
2172 if (protocol != PROTO_HTTP)
2183 /* save this for later .. when fetching individual records */
2184 sr = yaz_srw_get(out, Z_SRW_explain_request);
2185 if (recordsyntax == VAL_TEXT_XML)
2186 sr->u.explain_request->recordPacking = "xml";
2194 static int cmd_init(const char *arg)
2196 if (!conn || protocol != PROTO_Z3950)
2198 send_initRequest(0);
2202 static int cmd_find(const char *arg)
2206 printf("Find what?\n");
2209 if (protocol == PROTO_HTTP)
2216 if (!send_SRW_searchRequest(arg))
2229 printf("Not connected yet\n");
2233 if (!send_searchRequest(arg))
2239 static int cmd_delete(const char *arg)
2243 printf("Not connected yet\n");
2248 if (!send_deleteResultSetRequest(arg))
2253 static int cmd_ssub(const char *arg)
2255 if (!(smallSetUpperBound = atoi(arg)))
2260 static int cmd_lslb(const char *arg)
2264 if (!(largeSetLowerBound = atoi(arg)))
2269 static int cmd_mspn(const char *arg)
2273 if (!(mediumSetPresentNumber = atoi(arg)))
2278 static int cmd_status(const char *arg)
2280 printf("smallSetUpperBound: %d\n", smallSetUpperBound);
2281 printf("largeSetLowerBound: %d\n", largeSetLowerBound);
2282 printf("mediumSetPresentNumber: %d\n", mediumSetPresentNumber);
2286 static int cmd_setnames(const char *arg)
2288 if (*arg == '1') /* enable ? */
2290 else if (*arg == '0') /* disable ? */
2292 else if (setnumber < 0) /* no args, toggle .. */
2298 printf("Set numbering enabled.\n");
2300 printf("Set numbering disabled.\n");
2304 /* PRESENT SERVICE ----------------------------- */
2306 static void parse_show_args(const char *arg_c, char *setstring,
2307 int *start, int *number)
2312 strncpy(arg, arg_c, sizeof(arg)-1);
2313 arg[sizeof(arg)-1] = '\0';
2315 if ((p = strchr(arg, '+')))
2317 *number = atoi(p + 1);
2322 if (p && (p=strchr(p+1, '+')))
2323 strcpy (setstring, p+1);
2324 else if (setnumber >= 0)
2325 sprintf(setstring, "%d", setnumber);
2330 static int send_presentRequest(const char *arg)
2332 Z_APDU *apdu = zget_APDU(out, Z_APDU_presentRequest);
2333 Z_PresentRequest *req = apdu->u.presentRequest;
2334 Z_RecordComposition compo;
2336 char setstring[100];
2338 req->referenceId = set_refid (out);
2340 parse_show_args(arg, setstring, &setno, &nos);
2342 req->resultSetId = setstring;
2344 req->resultSetStartPoint = &setno;
2345 req->numberOfRecordsRequested = &nos;
2347 req->preferredRecordSyntax =
2348 yaz_oidval_to_z3950oid(out, CLASS_RECSYN, recordsyntax);
2352 req->recordComposition = &compo;
2353 compo.which = Z_RecordComp_complex;
2354 compo.u.complex = (Z_CompSpec *)
2355 odr_malloc(out, sizeof(*compo.u.complex));
2356 compo.u.complex->selectAlternativeSyntax = (bool_t *)
2357 odr_malloc(out, sizeof(bool_t));
2358 *compo.u.complex->selectAlternativeSyntax = 0;
2360 compo.u.complex->generic = (Z_Specification *)
2361 odr_malloc(out, sizeof(*compo.u.complex->generic));
2362 compo.u.complex->generic->which = Z_Schema_oid;
2364 compo.u.complex->generic->schema.oid =
2365 yaz_str_to_z3950oid(out, CLASS_SCHEMA, record_schema);
2367 if (!compo.u.complex->generic->schema.oid)
2369 /* OID wasn't a schema! Try record syntax instead. */
2370 compo.u.complex->generic->schema.oid = (Odr_oid *)
2371 yaz_str_to_z3950oid(out, CLASS_RECSYN, record_schema);
2373 if (!elementSetNames)
2374 compo.u.complex->generic->elementSpec = 0;
2377 compo.u.complex->generic->elementSpec = (Z_ElementSpec *)
2378 odr_malloc(out, sizeof(Z_ElementSpec));
2379 compo.u.complex->generic->elementSpec->which =
2380 Z_ElementSpec_elementSetName;
2381 compo.u.complex->generic->elementSpec->u.elementSetName =
2382 elementSetNames->u.generic;
2384 compo.u.complex->num_dbSpecific = 0;
2385 compo.u.complex->dbSpecific = 0;
2386 compo.u.complex->num_recordSyntax = 0;
2387 compo.u.complex->recordSyntax = 0;
2389 else if (elementSetNames)
2391 req->recordComposition = &compo;
2392 compo.which = Z_RecordComp_simple;
2393 compo.u.simple = elementSetNames;
2396 printf("Sent presentRequest (%d+%d).\n", setno, nos);
2401 static int send_SRW_presentRequest(const char *arg)
2403 char setstring[100];
2405 Z_SRW_PDU *sr = srw_sr;
2409 parse_show_args(arg, setstring, &setno, &nos);
2410 sr->u.request->startRecord = odr_intdup(out, setno);
2411 sr->u.request->maximumRecords = odr_intdup(out, nos);
2413 sr->u.request->recordSchema = record_schema;
2414 if (recordsyntax == VAL_TEXT_XML)
2415 sr->u.request->recordPacking = "xml";
2416 return send_srw(sr);
2420 static void close_session (void)
2427 nmem_destroy (session_mem);
2436 void process_close(Z_Close *req)
2438 Z_APDU *apdu = zget_APDU(out, Z_APDU_close);
2439 Z_Close *res = apdu->u.close;
2441 static char *reasons[] =
2446 "cost limit reached",
2448 "security violation",
2455 printf("Reason: %s, message: %s\n", reasons[*req->closeReason],
2456 req->diagnosticInformation ? req->diagnosticInformation : "NULL");
2461 *res->closeReason = Z_Close_finished;
2463 printf("Sent response.\n");
2468 static int cmd_show(const char *arg)
2470 if (protocol == PROTO_HTTP)
2477 if (!send_SRW_presentRequest(arg))
2487 printf("Not connected yet\n");
2490 if (!send_presentRequest(arg))
2496 int cmd_quit(const char *arg)
2498 printf("See you later, alligator.\n");
2504 int cmd_cancel(const char *arg)
2506 Z_APDU *apdu = zget_APDU(out, Z_APDU_triggerResourceControlRequest);
2507 Z_TriggerResourceControlRequest *req =
2508 apdu->u.triggerResourceControlRequest;
2513 printf("Session not initialized yet\n");
2518 if (!ODR_MASK_GET(session->options, Z_Options_triggerResourceCtrl))
2520 printf("Target doesn't support cancel (trigger resource ctrl)\n");
2523 *req->requestedAction = Z_TriggerResourceCtrl_cancel;
2524 req->resultSetWanted = &rfalse;
2527 printf("Sent cancel request\n");
2531 int send_scanrequest(const char *query, int pp, int num, const char *term)
2533 Z_APDU *apdu = zget_APDU(out, Z_APDU_scanRequest);
2534 Z_ScanRequest *req = apdu->u.scanRequest;
2538 if (queryType == QueryType_CCL2RPN)
2541 struct ccl_rpn_node *rpn;
2543 rpn = ccl_find_str (bibset, query, &error, &pos);
2546 printf("CCL ERROR: %s\n", ccl_err_msg(error));
2550 yaz_oidval_to_z3950oid(out, CLASS_ATTSET, VAL_BIB1);
2551 if (!(req->termListAndStartPoint = ccl_scan_query (out, rpn)))
2553 printf("Couldn't convert CCL to Scan term\n");
2556 ccl_rpn_delete (rpn);
2560 YAZ_PQF_Parser pqf_parser = yaz_pqf_create ();
2562 if (!(req->termListAndStartPoint =
2563 yaz_pqf_scan(pqf_parser, out, &req->attributeSet, query)))
2565 const char *pqf_msg;
2567 int code = yaz_pqf_error (pqf_parser, &pqf_msg, &off);
2568 printf("%*s^\n", off+7, "");
2569 printf("Prefix query error: %s (code %d)\n", pqf_msg, code);
2570 yaz_pqf_destroy (pqf_parser);
2573 yaz_pqf_destroy (pqf_parser);
2577 if (req->termListAndStartPoint->term &&
2578 req->termListAndStartPoint->term->which == Z_Term_general &&
2579 req->termListAndStartPoint->term->u.general)
2581 req->termListAndStartPoint->term->u.general->buf =
2582 (unsigned char *) odr_strdup(out, term);
2583 req->termListAndStartPoint->term->u.general->len =
2584 req->termListAndStartPoint->term->u.general->size =
2588 req->referenceId = set_refid (out);
2589 req->num_databaseNames = num_databaseNames;
2590 req->databaseNames = databaseNames;
2591 req->numberOfTermsRequested = #
2592 req->preferredPositionInResponse = &pp;
2597 int send_sortrequest(const char *arg, int newset)
2599 Z_APDU *apdu = zget_APDU(out, Z_APDU_sortRequest);
2600 Z_SortRequest *req = apdu->u.sortRequest;
2601 Z_SortKeySpecList *sksl = (Z_SortKeySpecList *)
2602 odr_malloc (out, sizeof(*sksl));
2608 sprintf (setstring, "%d", setnumber);
2610 sprintf (setstring, "default");
2612 req->referenceId = set_refid (out);
2614 req->num_inputResultSetNames = 1;
2615 req->inputResultSetNames = (Z_InternationalString **)
2616 odr_malloc (out, sizeof(*req->inputResultSetNames));
2617 req->inputResultSetNames[0] = odr_strdup (out, setstring);
2619 if (newset && setnumber >= 0)
2620 sprintf (setstring, "%d", ++setnumber);
2622 req->sortedResultSetName = odr_strdup (out, setstring);
2624 req->sortSequence = yaz_sort_spec (out, arg);
2625 if (!req->sortSequence)
2627 printf ("Missing sort specifications\n");
2634 void display_term(Z_TermInfo *t)
2637 printf("%s", t->displayTerm);
2638 else if (t->term->which == Z_Term_general)
2640 printf("%.*s", t->term->u.general->len, t->term->u.general->buf);
2641 sprintf(last_scan_line, "%.*s", t->term->u.general->len,
2642 t->term->u.general->buf);
2645 printf("Term (not general)");
2646 if (t->globalOccurrences)
2647 printf (" (%d)\n", *t->globalOccurrences);
2652 void process_scanResponse(Z_ScanResponse *res)
2655 Z_Entry **entries = NULL;
2656 int num_entries = 0;
2658 printf("Received ScanResponse\n");
2659 print_refid (res->referenceId);
2660 printf("%d entries", *res->numberOfEntriesReturned);
2661 if (res->positionOfTerm)
2662 printf (", position=%d", *res->positionOfTerm);
2664 if (*res->scanStatus != Z_Scan_success)
2665 printf("Scan returned code %d\n", *res->scanStatus);
2668 if ((entries = res->entries->entries))
2669 num_entries = res->entries->num_entries;
2670 for (i = 0; i < num_entries; i++)
2672 int pos_term = res->positionOfTerm ? *res->positionOfTerm : -1;
2673 if (entries[i]->which == Z_Entry_termInfo)
2675 printf("%c ", i + 1 == pos_term ? '*' : ' ');
2676 display_term(entries[i]->u.termInfo);
2679 display_diagrecs(&entries[i]->u.surrogateDiagnostic, 1);
2681 if (res->entries->nonsurrogateDiagnostics)
2682 display_diagrecs (res->entries->nonsurrogateDiagnostics,
2683 res->entries->num_nonsurrogateDiagnostics);
2686 void process_sortResponse(Z_SortResponse *res)
2688 printf("Received SortResponse: status=");
2689 switch (*res->sortStatus)
2691 case Z_SortStatus_success:
2692 printf ("success"); break;
2693 case Z_SortStatus_partial_1:
2694 printf ("partial"); break;
2695 case Z_SortStatus_failure:
2696 printf ("failure"); break;
2698 printf ("unknown (%d)", *res->sortStatus);
2701 print_refid (res->referenceId);
2702 if (res->diagnostics)
2703 display_diagrecs(res->diagnostics,
2704 res->num_diagnostics);
2707 void process_deleteResultSetResponse (Z_DeleteResultSetResponse *res)
2709 printf("Got deleteResultSetResponse status=%d\n",
2710 *res->deleteOperationStatus);
2711 if (res->deleteListStatuses)
2714 for (i = 0; i < res->deleteListStatuses->num; i++)
2716 printf ("%s status=%d\n", res->deleteListStatuses->elements[i]->id,
2717 *res->deleteListStatuses->elements[i]->status);
2722 int cmd_sort_generic(const char *arg, int newset)
2726 printf("Session not initialized yet\n");
2731 if (!ODR_MASK_GET(session->options, Z_Options_sort))
2733 printf("Target doesn't support sort\n");
2738 if (send_sortrequest(arg, newset) < 0)
2745 int cmd_sort(const char *arg)
2747 return cmd_sort_generic (arg, 0);
2750 int cmd_sort_newset (const char *arg)
2752 return cmd_sort_generic (arg, 1);
2755 int cmd_scan(const char *arg)
2764 printf("Session not initialized yet\n");
2768 if (!ODR_MASK_GET(session->options, Z_Options_scan))
2770 printf("Target doesn't support scan\n");
2775 strcpy (last_scan_query, arg);
2776 if (send_scanrequest(arg, 1, 20, 0) < 0)
2781 if (send_scanrequest(last_scan_query, 1, 20, last_scan_line) < 0)
2787 int cmd_schema(const char *arg)
2789 xfree(record_schema);
2792 record_schema = xstrdup(arg);
2796 int cmd_format(const char *arg)
2801 printf("Usage: format <recordsyntax>\n");
2804 nsyntax = oid_getvalbyname (arg);
2805 if (strcmp(arg, "none") && nsyntax == VAL_NONE)
2807 printf ("unknown record syntax\n");
2810 recordsyntax = nsyntax;
2814 int cmd_elements(const char *arg)
2816 static Z_ElementSetNames esn;
2817 static char what[100];
2821 elementSetNames = 0;
2825 esn.which = Z_ElementSetNames_generic;
2826 esn.u.generic = what;
2827 elementSetNames = &esn;
2831 int cmd_attributeset(const char *arg)
2837 printf("Usage: attributeset <setname>\n");
2840 sscanf(arg, "%s", what);
2841 if (p_query_attset (what))
2843 printf("Unknown attribute set name\n");
2849 int cmd_querytype (const char *arg)
2851 if (!strcmp (arg, "ccl"))
2852 queryType = QueryType_CCL;
2853 else if (!strcmp (arg, "prefix") || !strcmp(arg, "rpn"))
2854 queryType = QueryType_Prefix;
2855 else if (!strcmp (arg, "ccl2rpn") || !strcmp (arg, "cclrpn"))
2856 queryType = QueryType_CCL2RPN;
2857 else if (!strcmp(arg, "cql"))
2858 queryType = QueryType_CQL;
2859 else if (!strcmp (arg, "cql2rpn") || !strcmp (arg, "cqlrpn"))
2860 queryType = QueryType_CQL2RPN;
2863 printf ("Querytype must be one of:\n");
2864 printf (" prefix - Prefix query\n");
2865 printf (" ccl - CCL query\n");
2866 printf (" ccl2rpn - CCL query converted to RPN\n");
2867 printf (" cql - CQL\n");
2868 printf (" cql2rpn - CQL query converted to RPN\n");
2874 int cmd_refid (const char *arg)
2879 refid = xstrdup (arg);
2883 int cmd_close(const char *arg)
2892 apdu = zget_APDU(out, Z_APDU_close);
2893 req = apdu->u.close;
2894 *req->closeReason = Z_Close_finished;
2896 printf("Sent close request.\n");
2901 int cmd_packagename(const char* arg)
2903 xfree (esPackageName);
2904 esPackageName = NULL;
2906 esPackageName = xstrdup(arg);
2910 int cmd_proxy(const char* arg)
2915 yazProxy = xstrdup (arg);
2919 int cmd_marccharset(const char *arg)
2924 if (sscanf(arg, "%29s", l1) < 1)
2926 xfree (marcCharset);
2928 if (strcmp(l1, "-"))
2929 marcCharset = xstrdup(l1);
2933 int cmd_charset(const char* arg)
2935 char l1[30], l2[30];
2938 if (sscanf(arg, "%29s %29s", l1, l2) < 1)
2940 printf("Current negotiation character set is `%s'\n",
2941 negotiationCharset ? negotiationCharset: "none");
2942 printf("Current output character set is `%s'\n",
2943 outputCharset ? outputCharset: "none");
2946 xfree (negotiationCharset);
2947 negotiationCharset = NULL;
2948 if (*l1 && strcmp(l1, "-"))
2950 negotiationCharset = xstrdup(l1);
2951 printf ("Character set negotiation : %s\n", negotiationCharset);
2954 printf ("Character set negotiation disabled\n");
2957 xfree (outputCharset);
2959 if (!strcmp(l2, "auto") && codeset)
2963 printf ("output charset: %s\n", codeset);
2964 outputCharset = xstrdup(codeset);
2969 printf ("No codeset found on this system\n");
2971 else if (strcmp(l2, "-"))
2972 outputCharset = xstrdup(l2);
2974 printf ("Output charset conversion disabled\n");
2980 int cmd_lang(const char* arg)
2983 printf("Current language is `%s'\n", (yazLang)?yazLang:NULL);
2989 yazLang = xstrdup(arg);
2993 int cmd_source(const char* arg)
2995 /* first should open the file and read one line at a time.. */
2997 char line[1024], *cp;
3000 fprintf(stderr,"Error in source command use a filename\n");
3004 includeFile = fopen (arg, "r");
3007 fprintf(stderr,"Unable to open file %s for reading\n",arg);
3011 while(!feof(includeFile)) {
3012 memset(line,0,sizeof(line));
3013 fgets(line,sizeof(line),includeFile);
3015 if(strlen(line) < 2) continue;
3016 if(line[0] == '#') continue;
3018 if ((cp = strrchr (line, '\n')))
3021 process_cmd_line(line);
3024 if(fclose(includeFile)<0) {
3025 perror("unable to close include file");
3031 int cmd_subshell(const char* args)
3036 system(getenv("SHELL"));
3042 int cmd_set_berfile(const char *arg)
3044 if (ber_file && ber_file != stdout && ber_file != stderr)
3046 if (!strcmp(arg, ""))
3048 else if (!strcmp(arg, "-"))
3051 ber_file = fopen(arg, "a");
3055 int cmd_set_apdufile(const char *arg)
3057 if(apdu_file && apdu_file != stderr && apdu_file != stderr)
3059 if (!strcmp(arg, ""))
3061 else if (!strcmp(arg, "-"))
3065 apdu_file = fopen(arg, "a");
3067 perror("unable to open apdu log file");
3070 odr_setprint(print, apdu_file);
3074 int cmd_set_cclfile(const char* arg)
3078 bibset = ccl_qual_mk ();
3079 inf = fopen (arg, "r");
3081 perror("unable to open CCL file");
3084 ccl_qual_file (bibset, inf);
3087 strcpy(ccl_fields,arg);
3091 int cmd_set_cqlfile(const char* arg)
3093 cql_transform_t newcqltrans;
3095 if ((newcqltrans = cql_transform_open_fname(arg)) == 0) {
3096 perror("unable to open CQL file");
3100 cql_transform_close(cqltrans);
3102 cqltrans = newcqltrans;
3103 strcpy(cql_fields, arg);
3107 int cmd_set_auto_reconnect(const char* arg)
3109 if(strlen(arg)==0) {
3110 auto_reconnect = ! auto_reconnect;
3111 } else if(strcmp(arg,"on")==0) {
3113 } else if(strcmp(arg,"off")==0) {
3116 printf("Error use on or off\n");
3121 printf("Set auto reconnect enabled.\n");
3123 printf("Set auto reconnect disabled.\n");
3128 int cmd_set_marcdump(const char* arg)
3130 if(marc_file && marc_file != stderr) { /* don't close stdout*/
3134 if (!strcmp(arg, ""))
3136 else if (!strcmp(arg, "-"))
3140 marc_file = fopen(arg, "a");
3142 perror("unable to open marc log file");
3148 this command takes 3 arge {name class oid}
3150 int cmd_register_oid(const char* args) {
3155 {"appctx",CLASS_APPCTX},
3156 {"absyn",CLASS_ABSYN},
3157 {"attset",CLASS_ATTSET},
3158 {"transyn",CLASS_TRANSYN},
3159 {"diagset",CLASS_DIAGSET},
3160 {"recsyn",CLASS_RECSYN},
3161 {"resform",CLASS_RESFORM},
3162 {"accform",CLASS_ACCFORM},
3163 {"extserv",CLASS_EXTSERV},
3164 {"userinfo",CLASS_USERINFO},
3165 {"elemspec",CLASS_ELEMSPEC},
3166 {"varset",CLASS_VARSET},
3167 {"schema",CLASS_SCHEMA},
3168 {"tagset",CLASS_TAGSET},
3169 {"general",CLASS_GENERAL},
3170 {0,(enum oid_class) 0}
3172 char oname_str[101], oclass_str[101], oid_str[101];
3175 oid_class oidclass = CLASS_GENERAL;
3176 int val = 0, oid[OID_SIZE];
3177 struct oident * new_oident=NULL;
3179 if (sscanf (args, "%100[^ ] %100[^ ] %100s",
3180 oname_str,oclass_str, oid_str) < 1) {
3181 printf("Error in register command \n");
3185 for (i = 0; oid_classes[i].className; i++) {
3186 if (!strcmp(oid_classes[i].className, oclass_str))
3188 oidclass=oid_classes[i].oclass;
3193 if(!(oid_classes[i].className)) {
3194 printf("Unknown oid class %s\n",oclass_str);
3202 while (isdigit (*name))
3204 val = val*10 + (*name - '0');
3217 new_oident = oid_addent (oid, PROTO_GENERAL, oidclass, oname_str,
3219 if(strcmp(new_oident->desc,oname_str))
3221 fprintf(stderr,"oid is already named as %s, registration failed\n",
3227 int cmd_push_command(const char* arg)
3229 #if HAVE_READLINE_HISTORY_H
3233 fprintf(stderr,"Not compiled with the readline/history module\n");
3238 void source_rcfile()
3240 /* Look for a $HOME/.yazclientrc and source it if it exists */
3241 struct stat statbuf;
3243 char* homedir=getenv("HOME");
3245 if(!homedir) return;
3247 sprintf(buffer,"%s/.yazclientrc",homedir);
3249 if(stat(buffer,&statbuf)==0) {
3253 if(stat(".yazclientrc",&statbuf)==0) {
3254 cmd_source(".yazclientrc");
3259 static void initialize(void)
3264 if (!(out = odr_createmem(ODR_ENCODE)) ||
3265 !(in = odr_createmem(ODR_DECODE)) ||
3266 !(print = odr_createmem(ODR_PRINT)))
3268 fprintf(stderr, "failed to allocate ODR streams\n");
3273 setvbuf(stdout, 0, _IONBF, 0);
3275 odr_setprint(print, apdu_file);
3277 bibset = ccl_qual_mk ();
3278 inf = fopen (ccl_fields, "r");
3281 ccl_qual_file (bibset, inf);
3285 cqltrans = cql_transform_open_fname(cql_fields);
3286 /* If this fails, no problem: we detect cqltrans == 0 later */
3288 #if HAVE_READLINE_READLINE_H
3289 rl_attempted_completion_function = (CPPFunction*)readline_completer;
3293 for(i=0; i<maxOtherInfosSupported; ++i) {
3294 extraOtherInfos[i].oidval = -1;
3301 #if HAVE_GETTIMEOFDAY
3302 struct timeval tv_start, tv_end;
3306 static void handle_srw_record(Z_SRW_record *rec)
3308 if (rec->recordPosition)
3310 printf ("pos=%d", *rec->recordPosition);
3311 setno = *rec->recordPosition + 1;
3313 if (rec->recordSchema)
3314 printf (" schema=%s", rec->recordSchema);
3316 if (rec->recordData_buf && rec->recordData_len)
3317 fwrite(rec->recordData_buf, 1, rec->recordData_len, stdout);
3319 printf ("No data!");
3323 static void handle_srw_explain_response(Z_SRW_explainResponse *res)
3325 handle_srw_record(&res->record);
3328 static void handle_srw_response(Z_SRW_searchRetrieveResponse *res)
3332 printf ("Received SRW SearchRetrieve Response\n");
3334 for (i = 0; i<res->num_diagnostics; i++)
3336 if (res->diagnostics[i].uri)
3337 printf ("SRW diagnostic %s\n",
3338 res->diagnostics[i].uri);
3340 printf ("SRW diagnostic missing or could not be decoded\n");
3341 if (res->diagnostics[i].message)
3342 printf ("Message: %s\n", res->diagnostics[i].message);
3343 if (res->diagnostics[i].details)
3344 printf ("Details: %s\n", res->diagnostics[i].details);
3346 if (res->numberOfRecords)
3347 printf ("Number of hits: %d\n", *res->numberOfRecords);
3348 for (i = 0; i<res->num_records; i++)
3349 handle_srw_record(res->records + i);
3352 static void http_response(Z_HTTP_Response *hres)
3355 const char *content_type = z_HTTP_header_lookup(hres->headers,
3357 const char *connection_head = z_HTTP_header_lookup(hres->headers,
3359 if (content_type && !yaz_strcmp_del("text/xml", content_type, "; "))
3361 Z_SOAP *soap_package = 0;
3362 ODR o = odr_createmem(ODR_DECODE);
3363 Z_SOAP_Handler soap_handlers[2] = {
3364 {"http://www.loc.gov/zing/srw/", 0,
3365 (Z_SOAP_fun) yaz_srw_codec},
3368 ret = z_soap_codec(o, &soap_package,
3369 &hres->content_buf, &hres->content_len,
3371 if (!ret && soap_package->which == Z_SOAP_generic &&
3372 soap_package->u.generic->no == 0)
3374 Z_SRW_PDU *sr = soap_package->u.generic->p;
3375 if (sr->which == Z_SRW_searchRetrieve_response)
3376 handle_srw_response(sr->u.response);
3377 else if (sr->which == Z_SRW_explain_response)
3378 handle_srw_explain_response(sr->u.explain_response);
3382 else if (soap_package && (soap_package->which == Z_SOAP_fault
3383 || soap_package->which == Z_SOAP_error))
3385 printf ("HTTP Error Status=%d\n", hres->code);
3386 printf ("SOAP Fault code %s\n",
3387 soap_package->u.fault->fault_code);
3388 printf ("SOAP Fault string %s\n",
3389 soap_package->u.fault->fault_string);
3390 if (soap_package->u.fault->details)
3391 printf ("SOAP Details %s\n",
3392 soap_package->u.fault->details);
3400 if (hres->code != 200)
3402 printf ("HTTP Error Status=%d\n", hres->code);
3406 printf ("Decoding of SRW package failed\n");
3412 if (!strcmp(hres->version, "1.0"))
3414 /* HTTP 1.0: only if Keep-Alive we stay alive.. */
3415 if (!connection_head || strcmp(connection_head, "Keep-Alive"))
3420 /* HTTP 1.1: only if no close we stay alive .. */
3421 if (connection_head && !strcmp(connection_head, "close"))
3428 void wait_and_handle_response()
3430 int reconnect_ok = 1;
3433 int netbufferlen = 0;
3438 res = cs_get(conn, &netbuffer, &netbufferlen);
3439 if (reconnect_ok && res <= 0 && protocol == PROTO_HTTP)
3450 buf_out = odr_getbuf(out, &len_out, 0);
3452 do_hex_dump(buf_out, len_out);
3454 cs_put(conn, buf_out, len_out);
3462 printf("Target closed connection\n");
3467 odr_reset(in); /* release APDU from last round */
3469 do_hex_dump(netbuffer, res);
3470 odr_setbuf(in, netbuffer, res, 0);
3472 if (!z_GDU(in, &gdu, 0, 0))
3474 FILE *f = ber_file ? ber_file : stdout;
3475 odr_perror(in, "Decoding incoming APDU");
3476 fprintf(f, "[Near %d]\n", odr_offset(in));
3477 fprintf(f, "Packet dump:\n---------\n");
3478 odr_dumpBER(f, netbuffer, res);
3479 fprintf(f, "---------\n");
3482 z_GDU(print, &gdu, 0, 0);
3485 if (conn && cs_more(conn))
3490 odr_dumpBER(ber_file, netbuffer, res);
3491 if (apdu_file && !z_GDU(print, &gdu, 0, 0))
3493 odr_perror(print, "Failed to print incoming APDU");
3497 if (gdu->which == Z_GDU_Z3950)
3499 Z_APDU *apdu = gdu->u.z3950;
3502 case Z_APDU_initResponse:
3503 process_initResponse(apdu->u.initResponse);
3505 case Z_APDU_searchResponse:
3506 process_searchResponse(apdu->u.searchResponse);
3508 case Z_APDU_scanResponse:
3509 process_scanResponse(apdu->u.scanResponse);
3511 case Z_APDU_presentResponse:
3512 print_refid (apdu->u.presentResponse->referenceId);
3514 *apdu->u.presentResponse->numberOfRecordsReturned;
3515 if (apdu->u.presentResponse->records)
3516 display_records(apdu->u.presentResponse->records);
3518 printf("No records.\n");
3519 printf ("nextResultSetPosition = %d\n",
3520 *apdu->u.presentResponse->nextResultSetPosition);
3522 case Z_APDU_sortResponse:
3523 process_sortResponse(apdu->u.sortResponse);
3525 case Z_APDU_extendedServicesResponse:
3526 printf("Got extended services response\n");
3527 process_ESResponse(apdu->u.extendedServicesResponse);
3530 printf("Target has closed the association.\n");
3531 process_close(apdu->u.close);
3533 case Z_APDU_resourceControlRequest:
3534 process_resourceControlRequest
3535 (apdu->u.resourceControlRequest);
3537 case Z_APDU_deleteResultSetResponse:
3538 process_deleteResultSetResponse(apdu->u.
3539 deleteResultSetResponse);
3542 printf("Received unknown APDU type (%d).\n",
3548 else if (gdu->which == Z_GDU_HTTP_Response)
3550 http_response(gdu->u.HTTP_Response);
3553 if (conn && !cs_more(conn))
3558 #if HAVE_GETTIMEOFDAY
3559 gettimeofday (&tv_end, 0);
3561 printf ("S/U S/U=%ld/%ld %ld/%ld",
3562 (long) tv_start.tv_sec,
3563 (long) tv_start.tv_usec,
3564 (long) tv_end.tv_sec,
3565 (long) tv_end.tv_usec);
3567 printf ("Elapsed: %.6f\n",
3568 (double) tv_end.tv_usec / 1e6 + tv_end.tv_sec -
3569 ((double) tv_start.tv_usec / 1e6 + tv_start.tv_sec));
3576 int cmd_cclparse(const char* arg)
3579 struct ccl_rpn_node *rpn=NULL;
3582 rpn = ccl_find_str (bibset, arg, &error, &pos);
3585 printf ("%*s^ - ", 3+strlen(last_cmd)+1+pos, " ");
3586 printf ("%s\n", ccl_err_msg (error));
3592 ccl_pr_tree(rpn, stdout);
3596 ccl_rpn_delete(rpn);
3604 int cmd_set_otherinfo(const char* args)
3606 char oidstr[101], otherinfoString[101];
3611 sscan_res = sscanf (args, "%d %100[^ ] %100s", &otherinfoNo, oidstr, otherinfoString);
3613 /* reset this otherinfo */
3614 if(otherinfoNo>=maxOtherInfosSupported) {
3615 printf("Error otherinfo index to large (%d>%d)\n",
3616 otherinfoNo,maxOtherInfosSupported);
3618 extraOtherInfos[otherinfoNo].oidval = -1;
3619 if (extraOtherInfos[otherinfoNo].value)
3620 free(extraOtherInfos[otherinfoNo].value);
3624 printf("Error in set_otherinfo command \n");
3628 if (otherinfoNo>=maxOtherInfosSupported) {
3629 printf("Error otherinfo index to large (%d>%d)\n",
3630 otherinfoNo,maxOtherInfosSupported);
3633 oidval = oid_getvalbyname (oidstr);
3634 if (oidval == -1 ) {
3635 printf("Error in set_otherinfo command unknown oid %s \n",oidstr);
3638 extraOtherInfos[otherinfoNo].oidval = oidval;
3639 if(extraOtherInfos[otherinfoNo].value) free(extraOtherInfos[otherinfoNo].value);
3640 extraOtherInfos[otherinfoNo].value = strdup(otherinfoString);
3645 int cmd_list_otherinfo(const char* args)
3649 if(strlen(args)>0) {
3651 if( i >= maxOtherInfosSupported ) {
3652 printf("Error otherinfo index to large (%d>%d)\n",i,maxOtherInfosSupported);
3656 if(extraOtherInfos[i].oidval != -1)
3657 printf(" otherinfo %d %s %s\n",
3659 yaz_z3950_oid_value_to_str(
3660 (enum oid_value) extraOtherInfos[i].oidval,
3662 extraOtherInfos[i].value);
3665 for(i=0; i<maxOtherInfosSupported; ++i) {
3666 if(extraOtherInfos[i].oidval != -1)
3667 printf(" otherinfo %d %s %s\n",
3669 yaz_z3950_oid_value_to_str(
3670 (enum oid_value) extraOtherInfos[i].oidval,
3672 extraOtherInfos[i].value);
3680 int cmd_list_all(const char* args) {
3683 /* connection options */
3685 printf("Connected to : %s\n",last_open_command);
3687 if(last_open_command)
3688 printf("Not connected to : %s\n",last_open_command);
3690 printf("Not connected : \n");
3693 if(yazProxy) printf("using proxy : %s\n",yazProxy);
3695 printf("auto_reconnect : %s\n",auto_reconnect?"on":"off");
3698 printf("Authentication : none\n");
3700 switch(auth->which) {
3701 case Z_IdAuthentication_idPass:
3702 printf("Authentication : IdPass\n");
3703 printf(" Login User : %s\n",auth->u.idPass->userId?auth->u.idPass->userId:"");
3704 printf(" Login Group : %s\n",auth->u.idPass->groupId?auth->u.idPass->groupId:"");
3705 printf(" Password : %s\n",auth->u.idPass->password?auth->u.idPass->password:"");
3707 case Z_IdAuthentication_open:
3708 printf("Authentication : psOpen\n");
3709 printf(" Open string : %s\n",auth->u.open);
3712 printf("Authentication : Unknown\n");
3715 if (negotiationCharset)
3716 printf("Neg. Character set : `%s'\n", negotiationCharset);
3720 for (i = 0; i<num_databaseNames; i++) printf("%s ",databaseNames[i]);
3724 printf("CCL file : %s\n",ccl_fields);
3725 printf("CQL file : %s\n",cql_fields);
3726 printf("Query type : %s\n",query_type_as_string(queryType));
3728 printf("Named Result Sets : %s\n",setnumber==-1?"off":"on");
3730 /* piggy back options */
3731 printf("ssub/lslb/mspn : %d/%d/%d\n",smallSetUpperBound,largeSetLowerBound,mediumSetPresentNumber);
3733 /* print present related options */
3734 printf("Format : %s\n",yaz_z3950_oid_value_to_str(recordsyntax,CLASS_RECSYN));
3735 printf("Schema : %s\n",record_schema ? record_schema : "not set");
3736 printf("Elements : %s\n",elementSetNames?elementSetNames->u.generic:"");
3738 /* loging options */
3739 printf("APDU log : %s\n",apdu_file?"on":"off");
3740 printf("Record log : %s\n",marc_file?"on":"off");
3743 printf("Other Info: \n");
3744 cmd_list_otherinfo("");
3749 int cmd_clear_otherinfo(const char* args)
3751 if(strlen(args)>0) {
3753 otherinfoNo = atoi(args);
3754 if( otherinfoNo >= maxOtherInfosSupported ) {
3755 printf("Error otherinfo index to large (%d>%d)\n",otherinfoNo,maxOtherInfosSupported);
3759 if(extraOtherInfos[otherinfoNo].oidval != -1) {
3760 /* only clear if set. */
3761 extraOtherInfos[otherinfoNo].oidval=-1;
3762 free(extraOtherInfos[otherinfoNo].value);
3767 for(i=0; i<maxOtherInfosSupported; ++i) {
3768 if (extraOtherInfos[i].oidval!=-1 ) {
3769 extraOtherInfos[i].oidval=-1;
3770 free(extraOtherInfos[i].value);
3777 static int cmd_help (const char *line);
3779 typedef char *(*completerFunctionType)(const char *text, int state);
3783 int (*fun)(const char *arg);
3785 completerFunctionType rl_completerfunction;
3786 int complete_filenames;
3787 char **local_tabcompletes;
3789 {"open", cmd_open, "('tcp'|'ssl')':<host>[':'<port>][/<db>]",NULL,0,NULL},
3790 {"quit", cmd_quit, "",NULL,0,NULL},
3791 {"find", cmd_find, "<query>",NULL,0,NULL},
3792 {"delete", cmd_delete, "<setname>",NULL,0,NULL},
3793 {"base", cmd_base, "<base-name>",NULL,0,NULL},
3794 {"show", cmd_show, "<rec#>['+'<#recs>['+'<setname>]]",NULL,0,NULL},
3795 {"scan", cmd_scan, "<term>",NULL,0,NULL},
3796 {"sort", cmd_sort, "<sortkey> <flag> <sortkey> <flag> ...",NULL,0,NULL},
3797 {"sort+", cmd_sort_newset, "<sortkey> <flag> <sortkey> <flag> ...",NULL,0,NULL},
3798 {"authentication", cmd_authentication, "<acctstring>",NULL,0,NULL},
3799 {"lslb", cmd_lslb, "<largeSetLowerBound>",NULL,0,NULL},
3800 {"ssub", cmd_ssub, "<smallSetUpperBound>",NULL,0,NULL},
3801 {"mspn", cmd_mspn, "<mediumSetPresentNumber>",NULL,0,NULL},
3802 {"status", cmd_status, "",NULL,0,NULL},
3803 {"setnames", cmd_setnames, "",NULL,0,NULL},
3804 {"cancel", cmd_cancel, "",NULL,0,NULL},
3805 {"format", cmd_format, "<recordsyntax>",complete_format,0,NULL},
3806 {"schema", cmd_schema, "<schema>",complete_schema,0,NULL},
3807 {"elements", cmd_elements, "<elementSetName>",NULL,0,NULL},
3808 {"close", cmd_close, "",NULL,0,NULL},
3809 {"attributeset", cmd_attributeset, "<attrset>",complete_attributeset,0,NULL},
3810 {"querytype", cmd_querytype, "<type>",complete_querytype,0,NULL},
3811 {"refid", cmd_refid, "<id>",NULL,0,NULL},
3812 {"itemorder", cmd_itemorder, "ill|item <itemno>",NULL,0,NULL},
3813 {"update", cmd_update, "<action> <recid> [<file>]",NULL,0,NULL},
3814 {"update0", cmd_update0, "<action> <recid> [<file>]",NULL,0,NULL},
3815 {"packagename", cmd_packagename, "<packagename>",NULL,0,NULL},
3816 {"proxy", cmd_proxy, "[('tcp'|'ssl')]<host>[':'<port>]",NULL,0,NULL},
3817 {"charset", cmd_charset, "<nego_charset> <output_charset>",NULL,0,NULL},
3818 {"marccharset", cmd_marccharset, "<charset_name>",NULL,0,NULL},
3819 {"lang", cmd_lang, "<language_code>",NULL,0,NULL},
3820 {".", cmd_source, "<filename>",NULL,1,NULL},
3821 {"!", cmd_subshell, "Subshell command",NULL,1,NULL},
3822 {"set_apdufile", cmd_set_apdufile, "<filename>",NULL,1,NULL},
3823 {"set_berfile", cmd_set_berfile, "<filename>",NULL,1,NULL},
3824 {"set_marcdump", cmd_set_marcdump," <filename>",NULL,1,NULL},
3825 {"set_cclfile", cmd_set_cclfile," <filename>",NULL,1,NULL},
3826 {"set_cqlfile", cmd_set_cqlfile," <filename>",NULL,1,NULL},
3827 {"set_auto_reconnect", cmd_set_auto_reconnect," on|off",complete_auto_reconnect,1,NULL},
3828 {"set_otherinfo", cmd_set_otherinfo,"<otherinfoinddex> <oid> <string>",NULL,0,NULL},
3829 {"register_oid", cmd_register_oid,"<name> <class> <oid>",NULL,0,NULL},
3830 {"push_command", cmd_push_command,"<command>",command_generator,0,NULL},
3831 {"register_tab", cmd_register_tab,"<commandname> <tab>",command_generator,0,NULL},
3832 {"cclparse", cmd_cclparse,"<ccl find command>",NULL,0,NULL},
3833 {"list_otherinfo",cmd_list_otherinfo,"[otherinfoinddex]",NULL,0,NULL},
3834 {"list_all",cmd_list_all,"",NULL,0,NULL},
3835 {"clear_otherinfo",cmd_clear_otherinfo,"",NULL,0,NULL},
3836 /* Server Admin Functions */
3837 {"adm-reindex", cmd_adm_reindex, "<database-name>",NULL,0,NULL},
3838 {"adm-truncate", cmd_adm_truncate, "('database'|'index')<object-name>",NULL,0,NULL},
3839 {"adm-create", cmd_adm_create, "",NULL,0,NULL},
3840 {"adm-drop", cmd_adm_drop, "('database'|'index')<object-name>",NULL,0,NULL},
3841 {"adm-import", cmd_adm_import, "<record-type> <dir> <pattern>",NULL,0,NULL},
3842 {"adm-refresh", cmd_adm_refresh, "",NULL,0,NULL},
3843 {"adm-commit", cmd_adm_commit, "",NULL,0,NULL},
3844 {"adm-shutdown", cmd_adm_shutdown, "",NULL,0,NULL},
3845 {"adm-startup", cmd_adm_startup, "",NULL,0,NULL},
3846 {"explain", cmd_explain, "", NULL, 0, NULL},
3847 {"options", cmd_options, "", NULL, 0, NULL},
3848 {"zversion", cmd_zversion, "", NULL, 0, NULL},
3849 {"help", cmd_help, "", NULL,0,NULL},
3850 {"init", cmd_init, "", NULL,0,NULL},
3854 static int cmd_help (const char *line)
3860 sscanf (line, "%20s", topic);
3863 printf("Commands:\n");
3864 for (i = 0; cmd_array[i].cmd; i++)
3865 if (*topic == 0 || strcmp (topic, cmd_array[i].cmd) == 0)
3866 printf(" %s %s\n", cmd_array[i].cmd, cmd_array[i].ad);
3867 if (strcmp (topic, "find") == 0)
3870 printf (" \"term\" Simple Term\n");
3871 printf (" @attr [attset] type=value op Attribute\n");
3872 printf (" @and opl opr And\n");
3873 printf (" @or opl opr Or\n");
3874 printf (" @not opl opr And-Not\n");
3875 printf (" @set set Result set\n");
3877 printf ("Bib-1 attribute types\n");
3879 printf ("4=Title 7=ISBN 8=ISSN 30=Date 62=Abstract 1003=Author 1016=Any\n");
3880 printf ("2=Relation: ");
3881 printf ("1< 2<= 3= 4>= 5> 6!= 102=Relevance\n");
3882 printf ("3=Position: ");
3883 printf ("1=First in Field 2=First in subfield 3=Any position\n");
3884 printf ("4=Structure: ");
3885 printf ("1=Phrase 2=Word 3=Key 4=Year 5=Date 6=WordList\n");
3886 printf ("5=Truncation: ");
3887 printf ("1=Right 2=Left 3=L&R 100=No 101=# 102=Re-1 103=Re-2\n");
3888 printf ("6=Completeness:");
3889 printf ("1=Incomplete subfield 2=Complete subfield 3=Complete field\n");
3894 int cmd_register_tab(const char* arg) {
3896 char command[101], tabargument[101];
3901 if (sscanf (arg, "%100s %100s", command, tabargument) < 1) {
3905 /* locate the amdn in the list */
3906 for (i = 0; cmd_array[i].cmd; i++) {
3907 if (!strncmp(cmd_array[i].cmd, command, strlen(command))) {
3912 if(!cmd_array[i].cmd) {
3913 fprintf(stderr,"Unknown command %s\n",command);
3918 if(!cmd_array[i].local_tabcompletes)
3919 cmd_array[i].local_tabcompletes = (char **) calloc(1,sizeof(char**));
3923 tabslist = cmd_array[i].local_tabcompletes;
3924 for(;tabslist && *tabslist;tabslist++) {
3928 cmd_array[i].local_tabcompletes = (char **)
3929 realloc(cmd_array[i].local_tabcompletes,(num_of_tabs+2)*sizeof(char**));
3930 tabslist=cmd_array[i].local_tabcompletes;
3931 tabslist[num_of_tabs]=strdup(tabargument);
3932 tabslist[num_of_tabs+1]=NULL;
3937 void process_cmd_line(char* line)
3940 char word[32], arg[1024];
3942 #if HAVE_GETTIMEOFDAY
3943 gettimeofday (&tv_start, 0);
3946 if ((res = sscanf(line, "%31s %1023[^;]", word, arg)) <= 0)
3948 strcpy(word, last_cmd);
3953 strcpy(last_cmd, word);
3955 /* removed tailing spaces from the arg command */
3958 char* lastnonspace=NULL;
3966 *(++lastnonspace) = 0;
3969 for (i = 0; cmd_array[i].cmd; i++)
3970 if (!strncmp(cmd_array[i].cmd, word, strlen(word)))
3972 res = (*cmd_array[i].fun)(arg);
3976 if (!cmd_array[i].cmd) /* dump our help-screen */
3978 printf("Unknown command: %s.\n", word);
3979 printf("use help for list of commands\n");
3980 /* cmd_help (""); */
3984 if(apdu_file) fflush(apdu_file);
3987 wait_and_handle_response();
3996 char *command_generator(const char *text, int state)
4002 for( ; cmd_array[idx].cmd; ++idx) {
4003 if (!strncmp(cmd_array[idx].cmd,text,strlen(text))) {
4004 ++idx; /* skip this entry on the next run */
4005 return strdup(cmd_array[idx-1].cmd);
4013 This function only known how to complete on the first word
4015 char ** readline_completer(char *text, int start, int end) {
4016 #if HAVE_READLINE_READLINE_H
4018 completerFunctionType completerToUse;
4021 #if HAVE_READLINE_RL_COMPLETION_MATCHES
4022 char** res=rl_completion_matches(text,
4025 char** res=completion_matches(text,
4026 (CPFunction*)command_generator);
4028 rl_attempted_completion_over = 1;
4031 char arg[1024],word[32];
4033 if ((res = sscanf(rl_line_buffer, "%31s %1023[^;]", word, arg)) <= 0) {
4034 rl_attempted_completion_over = 1;
4038 for (i = 0; cmd_array[i].cmd; i++) {
4039 if (!strncmp(cmd_array[i].cmd, word, strlen(word))) {
4044 if(!cmd_array[i].cmd) return NULL;
4046 curret_global_list = cmd_array[i].local_tabcompletes;
4048 completerToUse = cmd_array[i].rl_completerfunction;
4049 if(completerToUse==NULL) /* if no pr. command completer is defined use the default completer */
4050 completerToUse = default_completer;
4052 if(completerToUse) {
4053 #ifdef HAVE_READLINE_RL_COMPLETION_MATCHES
4055 rl_completion_matches(text,
4059 completion_matches(text,
4060 (CPFunction*)completerToUse);
4062 if(!cmd_array[i].complete_filenames)
4063 rl_attempted_completion_over = 1;
4066 if(!cmd_array[i].complete_filenames)
4067 rl_attempted_completion_over = 1;
4077 static void client(void)
4083 #if HAVE_GETTIMEOFDAY
4084 gettimeofday (&tv_start, 0);
4089 char *line_in = NULL;
4090 #if HAVE_READLINE_READLINE_H
4093 line_in=readline(C_PROMPT);
4096 #if HAVE_READLINE_HISTORY_H
4098 add_history(line_in);
4100 strncpy(line, line_in, 1023);
4109 if (!fgets(line, 1023, stdin))
4111 if ((end_p = strchr (line, '\n')))
4114 process_cmd_line(line);
4118 static void show_version(void)
4122 yaz_version(vstr, 0);
4123 printf ("YAZ version: %s\n", YAZ_VERSION);
4124 if (strcmp(vstr, YAZ_VERSION))
4125 printf ("YAZ DLL/SO: %s\n", vstr);
4129 int main(int argc, char **argv)
4132 char *open_command = 0;
4133 char *auth_command = 0;
4138 if (!setlocale(LC_CTYPE, ""))
4139 fprintf (stderr, "setlocale failed\n");
4143 codeset = nl_langinfo(CODESET);
4147 outputCharset = xstrdup(codeset);
4149 ODR_MASK_SET(&z3950_options, Z_Options_search);
4150 ODR_MASK_SET(&z3950_options, Z_Options_present);
4151 ODR_MASK_SET(&z3950_options, Z_Options_namedResultSets);
4152 ODR_MASK_SET(&z3950_options, Z_Options_triggerResourceCtrl);
4153 ODR_MASK_SET(&z3950_options, Z_Options_scan);
4154 ODR_MASK_SET(&z3950_options, Z_Options_sort);
4155 ODR_MASK_SET(&z3950_options, Z_Options_extendedServices);
4156 ODR_MASK_SET(&z3950_options, Z_Options_delSet);
4158 while ((ret = options("k:c:q:a:b:m:v:p:u:t:Vxd:", argv, argc, &arg)) != -2)
4165 open_command = (char *) xmalloc (strlen(arg)+6);
4166 strcpy (open_command, "open ");
4167 strcat (open_command, arg);
4171 dump_file_prefix = arg;
4174 kilobytes = atoi(arg);
4177 if (!(marc_file = fopen (arg, "a")))
4184 outputCharset = xstrdup(arg);
4187 strncpy (ccl_fields, arg, sizeof(ccl_fields)-1);
4188 ccl_fields[sizeof(ccl_fields)-1] = '\0';
4191 strncpy (cql_fields, arg, sizeof(cql_fields)-1);
4192 cql_fields[sizeof(cql_fields)-1] = '\0';
4195 if (!strcmp(arg, "-"))
4198 ber_file=fopen(arg, "a");
4201 if (!strcmp(arg, "-"))
4204 apdu_file=fopen(arg, "a");
4210 yazProxy=strdup(arg);
4215 auth_command = (char *) xmalloc (strlen(arg)+6);
4216 strcpy (auth_command, "auth ");
4217 strcat (auth_command, arg);
4221 yaz_log_init(yaz_log_mask_str(arg), "", 0);
4227 fprintf (stderr, "Usage: %s [-m <marclog>] [ -a <apdulog>] "
4228 "[-b berdump] [-c cclfields] \n"
4229 "[-q cqlfields] [-p <proxy-addr>] [-u <auth>] "
4230 "[-k size] [-d dump] [-V] [<server-addr>]\n",
4238 #ifdef HAVE_GETTIMEOFDAY
4239 gettimeofday (&tv_start, 0);
4241 process_cmd_line (auth_command);
4242 #if HAVE_READLINE_HISTORY_H
4243 add_history(auth_command);
4245 xfree(auth_command);
4249 #ifdef HAVE_GETTIMEOFDAY
4250 gettimeofday (&tv_start, 0);
4252 process_cmd_line (open_command);
4253 #if HAVE_READLINE_HISTORY_H
4254 add_history(open_command);
4256 xfree(open_command);
4267 * vim600: sw=4 ts=8 fdm=marker
4268 * vim<600: sw=4 ts=8