2 * Copyright (c) 1995-2004, Index Data
3 * See the file LICENSE for details.
5 * $Id: client.c,v 1.241 2004-04-28 22:44:58 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;
1268 struct ccl_rpn_node *rpn = NULL;
1270 char setstring[100];
1271 Z_RPNQuery *RPNquery;
1273 YAZ_PQF_Parser pqf_parser;
1275 QueryType myQueryType = queryType;
1278 if (myQueryType == QueryType_CCL2RPN)
1280 rpn = ccl_find_str(bibset, arg, &error, &pos);
1283 printf("CCL ERROR: %s\n", ccl_err_msg(error));
1286 } else if (myQueryType == QueryType_CQL2RPN) {
1287 /* ### All this code should be wrapped in a utility function */
1289 struct cql_node *node;
1290 const char *addinfo;
1291 if (cqltrans == 0) {
1292 printf("Can't use CQL: no translation file. Try set_cqlfile\n");
1295 parser = cql_parser_create();
1296 if ((error = cql_parser_string(parser, arg)) != 0) {
1297 printf("Can't parse CQL: must be a syntax error\n");
1300 node = cql_parser_result(parser);
1301 if ((error = cql_transform_buf(cqltrans, node, pqfbuf,
1302 sizeof pqfbuf)) != 0) {
1303 error = cql_transform_error(cqltrans, &addinfo);
1304 printf ("Can't convert CQL to PQF: %s (addinfo=%s)\n",
1305 cql_strerror(error), addinfo);
1309 myQueryType = QueryType_Prefix;
1312 req->referenceId = set_refid (out);
1313 if (!strcmp(arg, "@big")) /* strictly for troublemaking */
1315 static unsigned char big[2100];
1316 static Odr_oct bigo;
1318 /* send a very big referenceid to test transport stack etc. */
1319 memset(big, 'A', 2100);
1320 bigo.len = bigo.size = 2100;
1322 req->referenceId = &bigo;
1327 sprintf(setstring, "%d", ++setnumber);
1328 req->resultSetName = setstring;
1330 *req->smallSetUpperBound = smallSetUpperBound;
1331 *req->largeSetLowerBound = largeSetLowerBound;
1332 *req->mediumSetPresentNumber = mediumSetPresentNumber;
1333 if (smallSetUpperBound > 0 || (largeSetLowerBound > 1 &&
1334 mediumSetPresentNumber > 0))
1338 prefsyn.proto = protocol;
1339 prefsyn.oclass = CLASS_RECSYN;
1340 prefsyn.value = recordsyntax;
1341 req->preferredRecordSyntax =
1342 odr_oiddup(out, oid_ent_to_oid(&prefsyn, oid));
1343 req->smallSetElementSetNames =
1344 req->mediumSetElementSetNames = elementSetNames;
1346 req->num_databaseNames = num_databaseNames;
1347 req->databaseNames = databaseNames;
1349 req->query = &query;
1351 switch (myQueryType)
1353 case QueryType_Prefix:
1354 query.which = Z_Query_type_1;
1355 pqf_parser = yaz_pqf_create ();
1356 RPNquery = yaz_pqf_parse (pqf_parser, out, arg);
1359 const char *pqf_msg;
1361 int code = yaz_pqf_error (pqf_parser, &pqf_msg, &off);
1362 printf("%*s^\n", off+4, "");
1363 printf("Prefix query error: %s (code %d)\n", pqf_msg, code);
1365 yaz_pqf_destroy (pqf_parser);
1368 yaz_pqf_destroy (pqf_parser);
1369 query.u.type_1 = RPNquery;
1372 query.which = Z_Query_type_2;
1373 query.u.type_2 = &ccl_query;
1374 ccl_query.buf = (unsigned char*) arg;
1375 ccl_query.len = strlen(arg);
1377 case QueryType_CCL2RPN:
1378 query.which = Z_Query_type_1;
1379 RPNquery = ccl_rpn_query(out, rpn);
1382 printf ("Couldn't convert from CCL to RPN\n");
1385 query.u.type_1 = RPNquery;
1386 ccl_rpn_delete (rpn);
1389 query.which = Z_Query_type_104;
1390 ext = (Z_External *) odr_malloc(out, sizeof(*ext));
1391 ext->direct_reference = odr_getoidbystr(out, "1.2.840.10003.16.2");
1392 ext->indirect_reference = 0;
1393 ext->descriptor = 0;
1394 ext->which = Z_External_CQL;
1395 ext->u.cql = odr_strdup(out, arg);
1396 query.u.type_104 = ext;
1399 printf ("Unsupported query type\n");
1402 if (send_apdu(apdu))
1403 printf("Sent searchRequest.\n");
1408 /* display Query Expression as part of searchResult-1 */
1409 static void display_queryExpression (Z_QueryExpression *qe)
1413 if (qe->which == Z_QueryExpression_term)
1415 if (qe->u.term->queryTerm)
1417 Z_Term *term = qe->u.term->queryTerm;
1418 switch (term->which)
1420 case Z_Term_general:
1421 printf (" %.*s", term->u.general->len, term->u.general->buf);
1423 case Z_Term_characterString:
1424 printf (" %s", term->u.characterString);
1426 case Z_Term_numeric:
1427 printf (" %d", *term->u.numeric);
1437 /* see if we can find USR:SearchResult-1 */
1438 static void display_searchResult (Z_OtherInformation *o)
1443 for (i = 0; i < o->num_elements; i++)
1445 if (o->list[i]->which == Z_OtherInfo_externallyDefinedInfo)
1447 Z_External *ext = o->list[i]->information.externallyDefinedInfo;
1449 if (ext->which == Z_External_searchResult1)
1452 Z_SearchInfoReport *sr = ext->u.searchResult1;
1453 printf ("SearchResult-1:");
1454 for (j = 0; j < sr->num; j++)
1456 if (!sr->elements[j]->subqueryExpression)
1458 display_queryExpression (
1459 sr->elements[j]->subqueryExpression);
1460 display_queryExpression (
1461 sr->elements[j]->subqueryInterpretation);
1462 display_queryExpression (
1463 sr->elements[j]->subqueryRecommendation);
1464 if (sr->elements[j]->subqueryCount)
1465 printf ("(%d)", *sr->elements[j]->subqueryCount);
1473 static int process_searchResponse(Z_SearchResponse *res)
1475 printf ("Received SearchResponse.\n");
1476 print_refid (res->referenceId);
1477 if (*res->searchStatus)
1478 printf("Search was a success.\n");
1480 printf("Search was a bloomin' failure.\n");
1481 printf("Number of hits: %d", *res->resultCount);
1483 printf (", setno %d", setnumber);
1485 display_searchResult (res->additionalSearchInfo);
1486 printf("records returned: %d\n",
1487 *res->numberOfRecordsReturned);
1488 setno += *res->numberOfRecordsReturned;
1490 display_records(res->records);
1494 static void print_level(int iLevel)
1497 for (i = 0; i < iLevel * 4; i++)
1501 static void print_int(int iLevel, const char *pTag, int *pInt)
1505 print_level(iLevel);
1506 printf("%s: %d\n", pTag, *pInt);
1510 static void print_string(int iLevel, const char *pTag, const char *pString)
1512 if (pString != NULL)
1514 print_level(iLevel);
1515 printf("%s: %s\n", pTag, pString);
1519 static void print_oid(int iLevel, const char *pTag, Odr_oid *pOid)
1525 print_level(iLevel);
1526 printf("%s:", pTag);
1527 for (; *pInt != -1; pInt++)
1528 printf(" %d", *pInt);
1533 static void print_referenceId(int iLevel, Z_ReferenceId *referenceId)
1535 if (referenceId != NULL)
1539 print_level(iLevel);
1540 printf("Ref Id (%d, %d): ", referenceId->len, referenceId->size);
1541 for (i = 0; i < referenceId->len; i++)
1542 printf("%c", referenceId->buf[i]);
1547 static void print_string_or_numeric(int iLevel, const char *pTag, Z_StringOrNumeric *pStringNumeric)
1549 if (pStringNumeric != NULL)
1551 switch (pStringNumeric->which)
1553 case Z_StringOrNumeric_string:
1554 print_string(iLevel, pTag, pStringNumeric->u.string);
1557 case Z_StringOrNumeric_numeric:
1558 print_int(iLevel, pTag, pStringNumeric->u.numeric);
1562 print_level(iLevel);
1563 printf("%s: valid type for Z_StringOrNumeric\n", pTag);
1569 static void print_universe_report_duplicate(
1571 Z_UniverseReportDuplicate *pUniverseReportDuplicate)
1573 if (pUniverseReportDuplicate != NULL)
1575 print_level(iLevel);
1576 printf("Universe Report Duplicate: \n");
1578 print_string_or_numeric(iLevel, "Hit No",
1579 pUniverseReportDuplicate->hitno);
1583 static void print_universe_report_hits(
1585 Z_UniverseReportHits *pUniverseReportHits)
1587 if (pUniverseReportHits != NULL)
1589 print_level(iLevel);
1590 printf("Universe Report Hits: \n");
1592 print_string_or_numeric(iLevel, "Database",
1593 pUniverseReportHits->database);
1594 print_string_or_numeric(iLevel, "Hits", pUniverseReportHits->hits);
1598 static void print_universe_report(int iLevel, Z_UniverseReport *pUniverseReport)
1600 if (pUniverseReport != NULL)
1602 print_level(iLevel);
1603 printf("Universe Report: \n");
1605 print_int(iLevel, "Total Hits", pUniverseReport->totalHits);
1606 switch (pUniverseReport->which)
1608 case Z_UniverseReport_databaseHits:
1609 print_universe_report_hits(iLevel,
1610 pUniverseReport->u.databaseHits);
1613 case Z_UniverseReport_duplicate:
1614 print_universe_report_duplicate(iLevel,
1615 pUniverseReport->u.duplicate);
1619 print_level(iLevel);
1620 printf("Type: %d\n", pUniverseReport->which);
1626 static void print_external(int iLevel, Z_External *pExternal)
1628 if (pExternal != NULL)
1630 print_level(iLevel);
1631 printf("External: \n");
1633 print_oid(iLevel, "Direct Reference", pExternal->direct_reference);
1634 print_int(iLevel, "InDirect Reference", pExternal->indirect_reference);
1635 print_string(iLevel, "Descriptor", pExternal->descriptor);
1636 switch (pExternal->which)
1638 case Z_External_universeReport:
1639 print_universe_report(iLevel, pExternal->u.universeReport);
1643 print_level(iLevel);
1644 printf("Type: %d\n", pExternal->which);
1650 static int process_resourceControlRequest (Z_ResourceControlRequest *req)
1652 printf ("Received ResourceControlRequest.\n");
1653 print_referenceId(1, req->referenceId);
1654 print_int(1, "Suspended Flag", req->suspendedFlag);
1655 print_int(1, "Partial Results Available", req->partialResultsAvailable);
1656 print_int(1, "Response Required", req->responseRequired);
1657 print_int(1, "Triggered Request Flag", req->triggeredRequestFlag);
1658 print_external(1, req->resourceReport);
1662 void process_ESResponse(Z_ExtendedServicesResponse *res)
1665 switch (*res->operationStatus)
1667 case Z_ExtendedServicesResponse_done:
1670 case Z_ExtendedServicesResponse_accepted:
1671 printf ("accepted\n");
1673 case Z_ExtendedServicesResponse_failure:
1674 printf ("failure\n");
1675 display_diagrecs(res->diagnostics, res->num_diagnostics);
1678 printf ("unknown\n");
1680 if ( (*res->operationStatus != Z_ExtendedServicesResponse_failure) &&
1681 (res->num_diagnostics != 0) ) {
1682 display_diagrecs(res->diagnostics, res->num_diagnostics);
1684 print_refid (res->referenceId);
1685 if (res->taskPackage &&
1686 res->taskPackage->which == Z_External_extendedService)
1688 Z_TaskPackage *taskPackage = res->taskPackage->u.extendedService;
1689 Odr_oct *id = taskPackage->targetReference;
1690 Z_External *ext = taskPackage->taskSpecificParameters;
1694 printf ("Target Reference: ");
1695 print_stringn (id->buf, id->len);
1698 if (ext->which == Z_External_update)
1700 Z_IUUpdateTaskPackage *utp = ext->u.update->u.taskPackage;
1701 if (utp && utp->targetPart)
1703 Z_IUTargetPart *targetPart = utp->targetPart;
1706 for (i = 0; i<targetPart->num_taskPackageRecords; i++)
1709 Z_IUTaskPackageRecordStructure *tpr =
1710 targetPart->taskPackageRecords[i];
1711 printf ("task package record %d\n", i+1);
1712 if (tpr->which == Z_IUTaskPackageRecordStructure_record)
1714 display_record (tpr->u.record);
1718 printf ("other type\n");
1726 const char *get_ill_element (void *clientData, const char *element)
1731 static Z_External *create_external_itemRequest()
1733 struct ill_get_ctl ctl;
1734 ILL_ItemRequest *req;
1736 int item_request_size = 0;
1737 char *item_request_buf = 0;
1741 ctl.f = get_ill_element;
1743 req = ill_get_ItemRequest(&ctl, "ill", 0);
1745 printf ("ill_get_ItemRequest failed\n");
1747 if (!ill_ItemRequest (out, &req, 0, 0))
1751 ill_ItemRequest(print, &req, 0, 0);
1754 item_request_buf = odr_getbuf (out, &item_request_size, 0);
1755 if (item_request_buf)
1756 odr_setbuf (out, item_request_buf, item_request_size, 1);
1757 printf ("Couldn't encode ItemRequest, size %d\n", item_request_size);
1764 item_request_buf = odr_getbuf (out, &item_request_size, 0);
1765 oid.proto = PROTO_GENERAL;
1766 oid.oclass = CLASS_GENERAL;
1767 oid.value = VAL_ISO_ILL_1;
1769 r = (Z_External *) odr_malloc (out, sizeof(*r));
1770 r->direct_reference = odr_oiddup(out,oid_getoidbyent(&oid));
1771 r->indirect_reference = 0;
1773 r->which = Z_External_single;
1775 r->u.single_ASN1_type = (Odr_oct *)
1776 odr_malloc (out, sizeof(*r->u.single_ASN1_type));
1777 r->u.single_ASN1_type->buf = (unsigned char *)
1778 odr_malloc (out, item_request_size);
1779 r->u.single_ASN1_type->len = item_request_size;
1780 r->u.single_ASN1_type->size = item_request_size;
1781 memcpy (r->u.single_ASN1_type->buf, item_request_buf,
1784 do_hex_dump(item_request_buf,item_request_size);
1789 static Z_External *create_external_ILL_APDU(int which)
1791 struct ill_get_ctl ctl;
1794 int ill_request_size = 0;
1795 char *ill_request_buf = 0;
1799 ctl.f = get_ill_element;
1801 ill_apdu = ill_get_APDU(&ctl, "ill", 0);
1803 if (!ill_APDU (out, &ill_apdu, 0, 0))
1807 printf ("-------------------\n");
1808 ill_APDU(print, &ill_apdu, 0, 0);
1810 printf ("-------------------\n");
1812 ill_request_buf = odr_getbuf (out, &ill_request_size, 0);
1813 if (ill_request_buf)
1814 odr_setbuf (out, ill_request_buf, ill_request_size, 1);
1815 printf ("Couldn't encode ILL-Request, size %d\n", ill_request_size);
1821 ill_request_buf = odr_getbuf (out, &ill_request_size, 0);
1823 oid.proto = PROTO_GENERAL;
1824 oid.oclass = CLASS_GENERAL;
1825 oid.value = VAL_ISO_ILL_1;
1827 r = (Z_External *) odr_malloc (out, sizeof(*r));
1828 r->direct_reference = odr_oiddup(out,oid_getoidbyent(&oid));
1829 r->indirect_reference = 0;
1831 r->which = Z_External_single;
1833 r->u.single_ASN1_type = (Odr_oct *)
1834 odr_malloc (out, sizeof(*r->u.single_ASN1_type));
1835 r->u.single_ASN1_type->buf = (unsigned char *)
1836 odr_malloc (out, ill_request_size);
1837 r->u.single_ASN1_type->len = ill_request_size;
1838 r->u.single_ASN1_type->size = ill_request_size;
1839 memcpy (r->u.single_ASN1_type->buf, ill_request_buf, ill_request_size);
1840 /* printf ("len = %d\n", ill_request_size); */
1841 /* do_hex_dump(ill_request_buf,ill_request_size); */
1842 /* printf("--- end of extenal\n"); */
1849 static Z_External *create_ItemOrderExternal(const char *type, int itemno)
1851 Z_External *r = (Z_External *) odr_malloc(out, sizeof(Z_External));
1852 oident ItemOrderRequest;
1854 ItemOrderRequest.proto = PROTO_Z3950;
1855 ItemOrderRequest.oclass = CLASS_EXTSERV;
1856 ItemOrderRequest.value = VAL_ITEMORDER;
1858 r->direct_reference = odr_oiddup(out,oid_getoidbyent(&ItemOrderRequest));
1859 r->indirect_reference = 0;
1862 r->which = Z_External_itemOrder;
1864 r->u.itemOrder = (Z_ItemOrder *) odr_malloc(out,sizeof(Z_ItemOrder));
1865 memset(r->u.itemOrder, 0, sizeof(Z_ItemOrder));
1866 r->u.itemOrder->which=Z_IOItemOrder_esRequest;
1868 r->u.itemOrder->u.esRequest = (Z_IORequest *)
1869 odr_malloc(out,sizeof(Z_IORequest));
1870 memset(r->u.itemOrder->u.esRequest, 0, sizeof(Z_IORequest));
1872 r->u.itemOrder->u.esRequest->toKeep = (Z_IOOriginPartToKeep *)
1873 odr_malloc(out,sizeof(Z_IOOriginPartToKeep));
1874 memset(r->u.itemOrder->u.esRequest->toKeep, 0, sizeof(Z_IOOriginPartToKeep));
1875 r->u.itemOrder->u.esRequest->notToKeep = (Z_IOOriginPartNotToKeep *)
1876 odr_malloc(out,sizeof(Z_IOOriginPartNotToKeep));
1877 memset(r->u.itemOrder->u.esRequest->notToKeep, 0, sizeof(Z_IOOriginPartNotToKeep));
1879 r->u.itemOrder->u.esRequest->toKeep->supplDescription = NULL;
1880 r->u.itemOrder->u.esRequest->toKeep->contact = NULL;
1881 r->u.itemOrder->u.esRequest->toKeep->addlBilling = NULL;
1883 r->u.itemOrder->u.esRequest->notToKeep->resultSetItem =
1884 (Z_IOResultSetItem *) odr_malloc(out, sizeof(Z_IOResultSetItem));
1885 memset(r->u.itemOrder->u.esRequest->notToKeep->resultSetItem, 0, sizeof(Z_IOResultSetItem));
1886 r->u.itemOrder->u.esRequest->notToKeep->resultSetItem->resultSetId = "1";
1888 r->u.itemOrder->u.esRequest->notToKeep->resultSetItem->item =
1889 (int *) odr_malloc(out, sizeof(int));
1890 *r->u.itemOrder->u.esRequest->notToKeep->resultSetItem->item = itemno;
1892 if (!strcmp (type, "item") || !strcmp(type, "2"))
1894 printf ("using item-request\n");
1895 r->u.itemOrder->u.esRequest->notToKeep->itemRequest =
1896 create_external_itemRequest();
1898 else if (!strcmp(type, "ill") || !strcmp(type, "1"))
1900 printf ("using ILL-request\n");
1901 r->u.itemOrder->u.esRequest->notToKeep->itemRequest =
1902 create_external_ILL_APDU(ILL_APDU_ILL_Request);
1904 else if (!strcmp(type, "xml") || !strcmp(type, "3"))
1906 const char *xml_buf =
1908 " <type>request</type>\n"
1909 " <libraryNo>000200</libraryNo>\n"
1910 " <borrowerTicketNo> 1212 </borrowerTicketNo>\n"
1912 r->u.itemOrder->u.esRequest->notToKeep->itemRequest =
1913 z_ext_record (out, VAL_TEXT_XML, xml_buf, strlen(xml_buf));
1916 r->u.itemOrder->u.esRequest->notToKeep->itemRequest = 0;
1921 static int send_itemorder(const char *type, int itemno)
1923 Z_APDU *apdu = zget_APDU(out, Z_APDU_extendedServicesRequest);
1924 Z_ExtendedServicesRequest *req = apdu->u.extendedServicesRequest;
1925 oident ItemOrderRequest;
1927 ItemOrderRequest.proto = PROTO_Z3950;
1928 ItemOrderRequest.oclass = CLASS_EXTSERV;
1929 ItemOrderRequest.value = VAL_ITEMORDER;
1930 req->packageType = odr_oiddup(out,oid_getoidbyent(&ItemOrderRequest));
1931 req->packageName = esPackageName;
1933 req->taskSpecificParameters = create_ItemOrderExternal(type, itemno);
1939 static int only_z3950()
1941 if (protocol == PROTO_HTTP)
1943 printf ("Not supported by SRW\n");
1949 static int cmd_update_common(const char *arg, int version);
1951 static int cmd_update(const char *arg)
1953 return cmd_update_common(arg, 1);
1956 static int cmd_update0(const char *arg)
1958 return cmd_update_common(arg, 0);
1961 static int cmd_update_common(const char *arg, int version)
1963 Z_APDU *apdu = zget_APDU(out, Z_APDU_extendedServicesRequest );
1964 Z_ExtendedServicesRequest *req = apdu->u.extendedServicesRequest;
1968 char action[20], recid[20], fname[80];
1970 Z_External *record_this = 0;
1977 sscanf (arg, "%19s %19s %79s", action, recid, fname);
1979 if (!strcmp (action, "insert"))
1980 action_no = Z_IUOriginPartToKeep_recordInsert;
1981 else if (!strcmp (action, "replace"))
1982 action_no = Z_IUOriginPartToKeep_recordReplace;
1983 else if (!strcmp (action, "delete"))
1984 action_no = Z_IUOriginPartToKeep_recordDelete;
1985 else if (!strcmp (action, "update"))
1986 action_no = Z_IUOriginPartToKeep_specialUpdate;
1989 printf ("Bad action: %s\n", action);
1990 printf ("Possible values: insert, replace, delete, update\n");
1998 stat (fname, &status);
1999 if (S_ISREG(status.st_mode) && (inf = fopen(fname, "r")))
2001 size_t len = status.st_size;
2002 char *buf = (char *) xmalloc (len);
2004 fread (buf, 1, len, inf);
2008 record_this = z_ext_record (out, VAL_TEXT_XML, buf, len);
2014 printf ("File %s doesn't exist\n", fname);
2022 printf ("No last record (update ignored)\n");
2025 record_this = record_last;
2028 update_oid.proto = PROTO_Z3950;
2029 update_oid.oclass = CLASS_EXTSERV;
2031 update_oid.value = VAL_DBUPDATE0;
2033 update_oid.value = VAL_DBUPDATE;
2034 oid_ent_to_oid (&update_oid, oid);
2035 req->packageType = odr_oiddup(out,oid);
2036 req->packageName = esPackageName;
2038 req->referenceId = set_refid (out);
2040 r = req->taskSpecificParameters = (Z_External *)
2041 odr_malloc (out, sizeof(*r));
2042 r->direct_reference = odr_oiddup(out,oid);
2043 r->indirect_reference = 0;
2047 Z_IU0OriginPartToKeep *toKeep;
2048 Z_IU0SuppliedRecords *notToKeep;
2050 r->which = Z_External_update0;
2051 r->u.update0 = (Z_IU0Update *) odr_malloc(out, sizeof(*r->u.update0));
2052 r->u.update0->which = Z_IUUpdate_esRequest;
2053 r->u.update0->u.esRequest = (Z_IU0UpdateEsRequest *)
2054 odr_malloc(out, sizeof(*r->u.update0->u.esRequest));
2055 toKeep = r->u.update0->u.esRequest->toKeep = (Z_IU0OriginPartToKeep *)
2056 odr_malloc(out, sizeof(*r->u.update0->u.esRequest->toKeep));
2058 toKeep->databaseName = databaseNames[0];
2060 toKeep->elementSetName = 0;
2062 toKeep->action = (int *) odr_malloc(out, sizeof(*toKeep->action));
2063 *toKeep->action = action_no;
2065 notToKeep = r->u.update0->u.esRequest->notToKeep = (Z_IU0SuppliedRecords *)
2066 odr_malloc(out, sizeof(*r->u.update0->u.esRequest->notToKeep));
2068 notToKeep->elements = (Z_IU0SuppliedRecords_elem **)
2069 odr_malloc(out, sizeof(*notToKeep->elements));
2070 notToKeep->elements[0] = (Z_IU0SuppliedRecords_elem *)
2071 odr_malloc(out, sizeof(**notToKeep->elements));
2072 notToKeep->elements[0]->which = Z_IUSuppliedRecords_elem_opaque;
2075 notToKeep->elements[0]->u.opaque = (Odr_oct *)
2076 odr_malloc (out, sizeof(Odr_oct));
2077 notToKeep->elements[0]->u.opaque->buf = (unsigned char *) recid;
2078 notToKeep->elements[0]->u.opaque->size = strlen(recid);
2079 notToKeep->elements[0]->u.opaque->len = strlen(recid);
2082 notToKeep->elements[0]->u.opaque = 0;
2083 notToKeep->elements[0]->supplementalId = 0;
2084 notToKeep->elements[0]->correlationInfo = 0;
2085 notToKeep->elements[0]->record = record_this;
2089 Z_IUOriginPartToKeep *toKeep;
2090 Z_IUSuppliedRecords *notToKeep;
2092 r->which = Z_External_update;
2093 r->u.update = (Z_IUUpdate *) odr_malloc(out, sizeof(*r->u.update));
2094 r->u.update->which = Z_IUUpdate_esRequest;
2095 r->u.update->u.esRequest = (Z_IUUpdateEsRequest *)
2096 odr_malloc(out, sizeof(*r->u.update->u.esRequest));
2097 toKeep = r->u.update->u.esRequest->toKeep = (Z_IUOriginPartToKeep *)
2098 odr_malloc(out, sizeof(*r->u.update->u.esRequest->toKeep));
2100 toKeep->databaseName = databaseNames[0];
2102 toKeep->elementSetName = 0;
2103 toKeep->actionQualifier = 0;
2104 toKeep->action = (int *) odr_malloc(out, sizeof(*toKeep->action));
2105 *toKeep->action = action_no;
2107 notToKeep = r->u.update->u.esRequest->notToKeep = (Z_IUSuppliedRecords *)
2108 odr_malloc(out, sizeof(*r->u.update->u.esRequest->notToKeep));
2110 notToKeep->elements = (Z_IUSuppliedRecords_elem **)
2111 odr_malloc(out, sizeof(*notToKeep->elements));
2112 notToKeep->elements[0] = (Z_IUSuppliedRecords_elem *)
2113 odr_malloc(out, sizeof(**notToKeep->elements));
2114 notToKeep->elements[0]->which = Z_IUSuppliedRecords_elem_opaque;
2117 notToKeep->elements[0]->u.opaque = (Odr_oct *)
2118 odr_malloc (out, sizeof(Odr_oct));
2119 notToKeep->elements[0]->u.opaque->buf = (unsigned char *) recid;
2120 notToKeep->elements[0]->u.opaque->size = strlen(recid);
2121 notToKeep->elements[0]->u.opaque->len = strlen(recid);
2124 notToKeep->elements[0]->u.opaque = 0;
2125 notToKeep->elements[0]->supplementalId = 0;
2126 notToKeep->elements[0]->correlationInfo = 0;
2127 notToKeep->elements[0]->record = record_this;
2135 static int cmd_itemorder(const char *arg)
2142 if (sscanf (arg, "%10s %d", type, &itemno) != 2)
2145 printf("Item order request\n");
2147 send_itemorder(type, itemno);
2151 static void show_opt(const char *arg, void *clientData)
2153 printf ("%s ", arg);
2156 static int cmd_zversion(const char *arg)
2159 z3950_version = atoi(arg);
2161 printf ("version is %d\n", z3950_version);
2165 static int cmd_options(const char *arg)
2171 r = yaz_init_opt_encode(&z3950_options, arg, &pos);
2175 yaz_init_opt_decode(&z3950_options, show_opt, 0);
2181 static int cmd_explain(const char *arg)
2183 if (protocol != PROTO_HTTP)
2194 /* save this for later .. when fetching individual records */
2195 sr = yaz_srw_get(out, Z_SRW_explain_request);
2196 if (recordsyntax == VAL_TEXT_XML)
2197 sr->u.explain_request->recordPacking = "xml";
2205 static int cmd_init(const char *arg)
2207 if (!conn || protocol != PROTO_Z3950)
2209 send_initRequest(0);
2213 static int cmd_find(const char *arg)
2217 printf("Find what?\n");
2220 if (protocol == PROTO_HTTP)
2227 if (!send_SRW_searchRequest(arg))
2240 printf("Not connected yet\n");
2244 if (!send_searchRequest(arg))
2250 static int cmd_delete(const char *arg)
2254 printf("Not connected yet\n");
2259 if (!send_deleteResultSetRequest(arg))
2264 static int cmd_ssub(const char *arg)
2266 if (!(smallSetUpperBound = atoi(arg)))
2271 static int cmd_lslb(const char *arg)
2275 if (!(largeSetLowerBound = atoi(arg)))
2280 static int cmd_mspn(const char *arg)
2284 if (!(mediumSetPresentNumber = atoi(arg)))
2289 static int cmd_status(const char *arg)
2291 printf("smallSetUpperBound: %d\n", smallSetUpperBound);
2292 printf("largeSetLowerBound: %d\n", largeSetLowerBound);
2293 printf("mediumSetPresentNumber: %d\n", mediumSetPresentNumber);
2297 static int cmd_setnames(const char *arg)
2299 if (*arg == '1') /* enable ? */
2301 else if (*arg == '0') /* disable ? */
2303 else if (setnumber < 0) /* no args, toggle .. */
2309 printf("Set numbering enabled.\n");
2311 printf("Set numbering disabled.\n");
2315 /* PRESENT SERVICE ----------------------------- */
2317 static void parse_show_args(const char *arg_c, char *setstring,
2318 int *start, int *number)
2323 strncpy(arg, arg_c, sizeof(arg)-1);
2324 arg[sizeof(arg)-1] = '\0';
2326 if ((p = strchr(arg, '+')))
2328 *number = atoi(p + 1);
2333 if (p && (p=strchr(p+1, '+')))
2334 strcpy (setstring, p+1);
2335 else if (setnumber >= 0)
2336 sprintf(setstring, "%d", setnumber);
2341 static int send_presentRequest(const char *arg)
2343 Z_APDU *apdu = zget_APDU(out, Z_APDU_presentRequest);
2344 Z_PresentRequest *req = apdu->u.presentRequest;
2345 Z_RecordComposition compo;
2349 char setstring[100];
2351 req->referenceId = set_refid (out);
2353 parse_show_args(arg, setstring, &setno, &nos);
2355 req->resultSetId = setstring;
2357 req->resultSetStartPoint = &setno;
2358 req->numberOfRecordsRequested = &nos;
2359 prefsyn.proto = protocol;
2360 prefsyn.oclass = CLASS_RECSYN;
2361 prefsyn.value = recordsyntax;
2362 req->preferredRecordSyntax =
2363 odr_oiddup (out, oid_ent_to_oid(&prefsyn, oid));
2369 prefschema.proto = protocol;
2370 prefschema.oclass = CLASS_SCHEMA;
2371 prefschema.value = oid_getvalbyname(record_schema);
2373 req->recordComposition = &compo;
2374 compo.which = Z_RecordComp_complex;
2375 compo.u.complex = (Z_CompSpec *)
2376 odr_malloc(out, sizeof(*compo.u.complex));
2377 compo.u.complex->selectAlternativeSyntax = (bool_t *)
2378 odr_malloc(out, sizeof(bool_t));
2379 *compo.u.complex->selectAlternativeSyntax = 0;
2381 compo.u.complex->generic = (Z_Specification *)
2382 odr_malloc(out, sizeof(*compo.u.complex->generic));
2383 compo.u.complex->generic->which = Z_Schema_oid;
2384 compo.u.complex->generic->schema.oid = (Odr_oid *)
2385 odr_oiddup(out, oid_ent_to_oid(&prefschema, oid));
2386 if (!compo.u.complex->generic->schema.oid)
2388 /* OID wasn't a schema! Try record syntax instead. */
2389 prefschema.oclass = CLASS_RECSYN;
2390 compo.u.complex->generic->schema.oid = (Odr_oid *)
2391 odr_oiddup(out, oid_ent_to_oid(&prefschema, oid));
2393 if (!elementSetNames)
2394 compo.u.complex->generic->elementSpec = 0;
2397 compo.u.complex->generic->elementSpec = (Z_ElementSpec *)
2398 odr_malloc(out, sizeof(Z_ElementSpec));
2399 compo.u.complex->generic->elementSpec->which =
2400 Z_ElementSpec_elementSetName;
2401 compo.u.complex->generic->elementSpec->u.elementSetName =
2402 elementSetNames->u.generic;
2404 compo.u.complex->num_dbSpecific = 0;
2405 compo.u.complex->dbSpecific = 0;
2406 compo.u.complex->num_recordSyntax = 0;
2407 compo.u.complex->recordSyntax = 0;
2409 else if (elementSetNames)
2411 req->recordComposition = &compo;
2412 compo.which = Z_RecordComp_simple;
2413 compo.u.simple = elementSetNames;
2416 printf("Sent presentRequest (%d+%d).\n", setno, nos);
2421 static int send_SRW_presentRequest(const char *arg)
2423 char setstring[100];
2425 Z_SRW_PDU *sr = srw_sr;
2429 parse_show_args(arg, setstring, &setno, &nos);
2430 sr->u.request->startRecord = odr_intdup(out, setno);
2431 sr->u.request->maximumRecords = odr_intdup(out, nos);
2433 sr->u.request->recordSchema = record_schema;
2434 if (recordsyntax == VAL_TEXT_XML)
2435 sr->u.request->recordPacking = "xml";
2436 return send_srw(sr);
2440 static void close_session (void)
2447 nmem_destroy (session_mem);
2456 void process_close(Z_Close *req)
2458 Z_APDU *apdu = zget_APDU(out, Z_APDU_close);
2459 Z_Close *res = apdu->u.close;
2461 static char *reasons[] =
2466 "cost limit reached",
2468 "security violation",
2475 printf("Reason: %s, message: %s\n", reasons[*req->closeReason],
2476 req->diagnosticInformation ? req->diagnosticInformation : "NULL");
2481 *res->closeReason = Z_Close_finished;
2483 printf("Sent response.\n");
2488 static int cmd_show(const char *arg)
2490 if (protocol == PROTO_HTTP)
2497 if (!send_SRW_presentRequest(arg))
2507 printf("Not connected yet\n");
2510 if (!send_presentRequest(arg))
2516 int cmd_quit(const char *arg)
2518 printf("See you later, alligator.\n");
2524 int cmd_cancel(const char *arg)
2526 Z_APDU *apdu = zget_APDU(out, Z_APDU_triggerResourceControlRequest);
2527 Z_TriggerResourceControlRequest *req =
2528 apdu->u.triggerResourceControlRequest;
2533 printf("Session not initialized yet\n");
2538 if (!ODR_MASK_GET(session->options, Z_Options_triggerResourceCtrl))
2540 printf("Target doesn't support cancel (trigger resource ctrl)\n");
2543 *req->requestedAction = Z_TriggerResourceCtrl_cancel;
2544 req->resultSetWanted = &rfalse;
2547 printf("Sent cancel request\n");
2551 int send_scanrequest(const char *query, int pp, int num, const char *term)
2553 Z_APDU *apdu = zget_APDU(out, Z_APDU_scanRequest);
2554 Z_ScanRequest *req = apdu->u.scanRequest;
2559 if (queryType == QueryType_CCL2RPN)
2563 struct ccl_rpn_node *rpn;
2565 rpn = ccl_find_str (bibset, query, &error, &pos);
2568 printf("CCL ERROR: %s\n", ccl_err_msg(error));
2571 bib1.proto = PROTO_Z3950;
2572 bib1.oclass = CLASS_ATTSET;
2573 bib1.value = VAL_BIB1;
2574 req->attributeSet = oid_ent_to_oid (&bib1, oid);
2575 if (!(req->termListAndStartPoint = ccl_scan_query (out, rpn)))
2577 printf("Couldn't convert CCL to Scan term\n");
2580 ccl_rpn_delete (rpn);
2584 YAZ_PQF_Parser pqf_parser = yaz_pqf_create ();
2586 if (!(req->termListAndStartPoint =
2587 yaz_pqf_scan(pqf_parser, out, &req->attributeSet, query)))
2589 const char *pqf_msg;
2591 int code = yaz_pqf_error (pqf_parser, &pqf_msg, &off);
2592 printf("%*s^\n", off+7, "");
2593 printf("Prefix query error: %s (code %d)\n", pqf_msg, code);
2594 yaz_pqf_destroy (pqf_parser);
2597 yaz_pqf_destroy (pqf_parser);
2601 if (req->termListAndStartPoint->term &&
2602 req->termListAndStartPoint->term->which == Z_Term_general &&
2603 req->termListAndStartPoint->term->u.general)
2605 req->termListAndStartPoint->term->u.general->buf =
2606 (unsigned char *) odr_strdup(out, term);
2607 req->termListAndStartPoint->term->u.general->len =
2608 req->termListAndStartPoint->term->u.general->size =
2612 req->referenceId = set_refid (out);
2613 req->num_databaseNames = num_databaseNames;
2614 req->databaseNames = databaseNames;
2615 req->numberOfTermsRequested = #
2616 req->preferredPositionInResponse = &pp;
2621 int send_sortrequest(const char *arg, int newset)
2623 Z_APDU *apdu = zget_APDU(out, Z_APDU_sortRequest);
2624 Z_SortRequest *req = apdu->u.sortRequest;
2625 Z_SortKeySpecList *sksl = (Z_SortKeySpecList *)
2626 odr_malloc (out, sizeof(*sksl));
2632 sprintf (setstring, "%d", setnumber);
2634 sprintf (setstring, "default");
2636 req->referenceId = set_refid (out);
2638 req->num_inputResultSetNames = 1;
2639 req->inputResultSetNames = (Z_InternationalString **)
2640 odr_malloc (out, sizeof(*req->inputResultSetNames));
2641 req->inputResultSetNames[0] = odr_strdup (out, setstring);
2643 if (newset && setnumber >= 0)
2644 sprintf (setstring, "%d", ++setnumber);
2646 req->sortedResultSetName = odr_strdup (out, setstring);
2648 req->sortSequence = yaz_sort_spec (out, arg);
2649 if (!req->sortSequence)
2651 printf ("Missing sort specifications\n");
2658 void display_term(Z_TermInfo *t)
2661 printf("%s", t->displayTerm);
2662 else if (t->term->which == Z_Term_general)
2664 printf("%.*s", t->term->u.general->len, t->term->u.general->buf);
2665 sprintf(last_scan_line, "%.*s", t->term->u.general->len,
2666 t->term->u.general->buf);
2669 printf("Term (not general)");
2670 if (t->globalOccurrences)
2671 printf (" (%d)\n", *t->globalOccurrences);
2676 void process_scanResponse(Z_ScanResponse *res)
2679 Z_Entry **entries = NULL;
2680 int num_entries = 0;
2682 printf("Received ScanResponse\n");
2683 print_refid (res->referenceId);
2684 printf("%d entries", *res->numberOfEntriesReturned);
2685 if (res->positionOfTerm)
2686 printf (", position=%d", *res->positionOfTerm);
2688 if (*res->scanStatus != Z_Scan_success)
2689 printf("Scan returned code %d\n", *res->scanStatus);
2692 if ((entries = res->entries->entries))
2693 num_entries = res->entries->num_entries;
2694 for (i = 0; i < num_entries; i++)
2696 int pos_term = res->positionOfTerm ? *res->positionOfTerm : -1;
2697 if (entries[i]->which == Z_Entry_termInfo)
2699 printf("%c ", i + 1 == pos_term ? '*' : ' ');
2700 display_term(entries[i]->u.termInfo);
2703 display_diagrecs(&entries[i]->u.surrogateDiagnostic, 1);
2705 if (res->entries->nonsurrogateDiagnostics)
2706 display_diagrecs (res->entries->nonsurrogateDiagnostics,
2707 res->entries->num_nonsurrogateDiagnostics);
2710 void process_sortResponse(Z_SortResponse *res)
2712 printf("Received SortResponse: status=");
2713 switch (*res->sortStatus)
2715 case Z_SortStatus_success:
2716 printf ("success"); break;
2717 case Z_SortStatus_partial_1:
2718 printf ("partial"); break;
2719 case Z_SortStatus_failure:
2720 printf ("failure"); break;
2722 printf ("unknown (%d)", *res->sortStatus);
2725 print_refid (res->referenceId);
2726 if (res->diagnostics)
2727 display_diagrecs(res->diagnostics,
2728 res->num_diagnostics);
2731 void process_deleteResultSetResponse (Z_DeleteResultSetResponse *res)
2733 printf("Got deleteResultSetResponse status=%d\n",
2734 *res->deleteOperationStatus);
2735 if (res->deleteListStatuses)
2738 for (i = 0; i < res->deleteListStatuses->num; i++)
2740 printf ("%s status=%d\n", res->deleteListStatuses->elements[i]->id,
2741 *res->deleteListStatuses->elements[i]->status);
2746 int cmd_sort_generic(const char *arg, int newset)
2750 printf("Session not initialized yet\n");
2755 if (!ODR_MASK_GET(session->options, Z_Options_sort))
2757 printf("Target doesn't support sort\n");
2762 if (send_sortrequest(arg, newset) < 0)
2769 int cmd_sort(const char *arg)
2771 return cmd_sort_generic (arg, 0);
2774 int cmd_sort_newset (const char *arg)
2776 return cmd_sort_generic (arg, 1);
2779 int cmd_scan(const char *arg)
2788 printf("Session not initialized yet\n");
2792 if (!ODR_MASK_GET(session->options, Z_Options_scan))
2794 printf("Target doesn't support scan\n");
2799 strcpy (last_scan_query, arg);
2800 if (send_scanrequest(arg, 1, 20, 0) < 0)
2805 if (send_scanrequest(last_scan_query, 1, 20, last_scan_line) < 0)
2811 int cmd_schema(const char *arg)
2813 xfree(record_schema);
2816 record_schema = xstrdup(arg);
2820 int cmd_format(const char *arg)
2825 printf("Usage: format <recordsyntax>\n");
2828 nsyntax = oid_getvalbyname (arg);
2829 if (strcmp(arg, "none") && nsyntax == VAL_NONE)
2831 printf ("unknown record syntax\n");
2834 recordsyntax = nsyntax;
2838 int cmd_elements(const char *arg)
2840 static Z_ElementSetNames esn;
2841 static char what[100];
2845 elementSetNames = 0;
2849 esn.which = Z_ElementSetNames_generic;
2850 esn.u.generic = what;
2851 elementSetNames = &esn;
2855 int cmd_attributeset(const char *arg)
2861 printf("Usage: attributeset <setname>\n");
2864 sscanf(arg, "%s", what);
2865 if (p_query_attset (what))
2867 printf("Unknown attribute set name\n");
2873 int cmd_querytype (const char *arg)
2875 if (!strcmp (arg, "ccl"))
2876 queryType = QueryType_CCL;
2877 else if (!strcmp (arg, "prefix") || !strcmp(arg, "rpn"))
2878 queryType = QueryType_Prefix;
2879 else if (!strcmp (arg, "ccl2rpn") || !strcmp (arg, "cclrpn"))
2880 queryType = QueryType_CCL2RPN;
2881 else if (!strcmp(arg, "cql"))
2882 queryType = QueryType_CQL;
2883 else if (!strcmp (arg, "cql2rpn") || !strcmp (arg, "cqlrpn"))
2884 queryType = QueryType_CQL2RPN;
2887 printf ("Querytype must be one of:\n");
2888 printf (" prefix - Prefix query\n");
2889 printf (" ccl - CCL query\n");
2890 printf (" ccl2rpn - CCL query converted to RPN\n");
2891 printf (" cql - CQL\n");
2892 printf (" cql2rpn - CQL query converted to RPN\n");
2898 int cmd_refid (const char *arg)
2904 refid = (char *) xmalloc (strlen(arg)+1);
2905 strcpy (refid, arg);
2910 int cmd_close(const char *arg)
2919 apdu = zget_APDU(out, Z_APDU_close);
2920 req = apdu->u.close;
2921 *req->closeReason = Z_Close_finished;
2923 printf("Sent close request.\n");
2928 int cmd_packagename(const char* arg)
2930 xfree (esPackageName);
2931 esPackageName = NULL;
2933 esPackageName = xstrdup(arg);
2937 int cmd_proxy(const char* arg)
2942 yazProxy = xstrdup (arg);
2946 int cmd_marccharset(const char *arg)
2951 if (sscanf(arg, "%29s", l1) < 1)
2953 xfree (marcCharset);
2955 if (strcmp(l1, "-"))
2956 marcCharset = xstrdup(l1);
2960 int cmd_charset(const char* arg)
2962 char l1[30], l2[30];
2965 if (sscanf(arg, "%29s %29s", l1, l2) < 1)
2967 printf("Current negotiation character set is `%s'\n",
2968 negotiationCharset ? negotiationCharset: "none");
2969 printf("Current output character set is `%s'\n",
2970 outputCharset ? outputCharset: "none");
2973 xfree (negotiationCharset);
2974 negotiationCharset = NULL;
2975 if (*l1 && strcmp(l1, "-"))
2977 negotiationCharset = xstrdup(l1);
2978 printf ("Character set negotiation : %s\n", negotiationCharset);
2981 printf ("Character set negotiation disabled\n");
2984 xfree (outputCharset);
2986 if (!strcmp(l2, "auto") && codeset)
2990 printf ("output charset: %s\n", codeset);
2991 outputCharset = xstrdup(codeset);
2996 printf ("No codeset found on this system\n");
2998 else if (strcmp(l2, "-"))
2999 outputCharset = xstrdup(l2);
3001 printf ("Output charset conversion disabled\n");
3007 int cmd_lang(const char* arg)
3010 printf("Current language is `%s'\n", (yazLang)?yazLang:NULL);
3017 yazLang = (char *) xmalloc (strlen(arg)+1);
3018 strcpy (yazLang, arg);
3023 int cmd_source(const char* arg)
3025 /* first should open the file and read one line at a time.. */
3027 char line[1024], *cp;
3030 fprintf(stderr,"Error in source command use a filename\n");
3034 includeFile = fopen (arg, "r");
3037 fprintf(stderr,"Unable to open file %s for reading\n",arg);
3041 while(!feof(includeFile)) {
3042 memset(line,0,sizeof(line));
3043 fgets(line,sizeof(line),includeFile);
3045 if(strlen(line) < 2) continue;
3046 if(line[0] == '#') continue;
3048 if ((cp = strrchr (line, '\n')))
3051 process_cmd_line(line);
3054 if(fclose(includeFile)<0) {
3055 perror("unable to close include file");
3061 int cmd_subshell(const char* args)
3066 system(getenv("SHELL"));
3072 int cmd_set_berfile(const char *arg)
3074 if (ber_file && ber_file != stdout && ber_file != stderr)
3076 if (!strcmp(arg, ""))
3078 else if (!strcmp(arg, "-"))
3081 ber_file = fopen(arg, "a");
3085 int cmd_set_apdufile(const char *arg)
3087 if(apdu_file && apdu_file != stderr && apdu_file != stderr)
3089 if (!strcmp(arg, ""))
3091 else if (!strcmp(arg, "-"))
3095 apdu_file = fopen(arg, "a");
3097 perror("unable to open apdu log file");
3100 odr_setprint(print, apdu_file);
3104 int cmd_set_cclfile(const char* arg)
3108 bibset = ccl_qual_mk ();
3109 inf = fopen (arg, "r");
3111 perror("unable to open CCL file");
3114 ccl_qual_file (bibset, inf);
3117 strcpy(ccl_fields,arg);
3121 int cmd_set_cqlfile(const char* arg)
3123 cql_transform_t newcqltrans;
3125 if ((newcqltrans = cql_transform_open_fname(arg)) == 0) {
3126 perror("unable to open CQL file");
3130 cql_transform_close(cqltrans);
3132 cqltrans = newcqltrans;
3133 strcpy(cql_fields, arg);
3137 int cmd_set_auto_reconnect(const char* arg)
3139 if(strlen(arg)==0) {
3140 auto_reconnect = ! auto_reconnect;
3141 } else if(strcmp(arg,"on")==0) {
3143 } else if(strcmp(arg,"off")==0) {
3146 printf("Error use on or off\n");
3151 printf("Set auto reconnect enabled.\n");
3153 printf("Set auto reconnect disabled.\n");
3158 int cmd_set_marcdump(const char* arg)
3160 if(marc_file && marc_file != stderr) { /* don't close stdout*/
3164 if (!strcmp(arg, ""))
3166 else if (!strcmp(arg, "-"))
3170 marc_file = fopen(arg, "a");
3172 perror("unable to open marc log file");
3178 this command takes 3 arge {name class oid}
3180 int cmd_register_oid(const char* args) {
3185 {"appctx",CLASS_APPCTX},
3186 {"absyn",CLASS_ABSYN},
3187 {"attset",CLASS_ATTSET},
3188 {"transyn",CLASS_TRANSYN},
3189 {"diagset",CLASS_DIAGSET},
3190 {"recsyn",CLASS_RECSYN},
3191 {"resform",CLASS_RESFORM},
3192 {"accform",CLASS_ACCFORM},
3193 {"extserv",CLASS_EXTSERV},
3194 {"userinfo",CLASS_USERINFO},
3195 {"elemspec",CLASS_ELEMSPEC},
3196 {"varset",CLASS_VARSET},
3197 {"schema",CLASS_SCHEMA},
3198 {"tagset",CLASS_TAGSET},
3199 {"general",CLASS_GENERAL},
3200 {0,(enum oid_class) 0}
3202 char oname_str[101], oclass_str[101], oid_str[101];
3205 oid_class oidclass = CLASS_GENERAL;
3206 int val = 0, oid[OID_SIZE];
3207 struct oident * new_oident=NULL;
3209 if (sscanf (args, "%100[^ ] %100[^ ] %100s",
3210 oname_str,oclass_str, oid_str) < 1) {
3211 printf("Error in regristrate command \n");
3215 for (i = 0; oid_classes[i].className; i++) {
3216 if (!strcmp(oid_classes[i].className, oclass_str))
3218 oidclass=oid_classes[i].oclass;
3223 if(!(oid_classes[i].className)) {
3224 printf("Unknonwn oid class %s\n",oclass_str);
3232 while (isdigit (*name))
3234 val = val*10 + (*name - '0');
3247 new_oident=oid_addent (oid,PROTO_GENERAL,oidclass,oname_str,VAL_DYNAMIC);
3248 if(strcmp(new_oident->desc,oname_str)) {
3249 fprintf(stderr,"oid is already named as %s, regristration faild\n",
3255 int cmd_push_command(const char* arg)
3257 #if HAVE_READLINE_HISTORY_H
3261 fprintf(stderr,"Not compiled with the readline/history module\n");
3266 void source_rcfile()
3268 /* Look for a $HOME/.yazclientrc and source it if it exists */
3269 struct stat statbuf;
3271 char* homedir=getenv("HOME");
3273 if(!homedir) return;
3275 sprintf(buffer,"%s/.yazclientrc",homedir);
3277 if(stat(buffer,&statbuf)==0) {
3281 if(stat(".yazclientrc",&statbuf)==0) {
3282 cmd_source(".yazclientrc");
3287 static void initialize(void)
3292 if (!(out = odr_createmem(ODR_ENCODE)) ||
3293 !(in = odr_createmem(ODR_DECODE)) ||
3294 !(print = odr_createmem(ODR_PRINT)))
3296 fprintf(stderr, "failed to allocate ODR streams\n");
3301 setvbuf(stdout, 0, _IONBF, 0);
3303 odr_setprint(print, apdu_file);
3305 bibset = ccl_qual_mk ();
3306 inf = fopen (ccl_fields, "r");
3309 ccl_qual_file (bibset, inf);
3313 cqltrans = cql_transform_open_fname(cql_fields);
3314 /* If this fails, no problem: we detect cqltrans == 0 later */
3316 #if HAVE_READLINE_READLINE_H
3317 rl_attempted_completion_function = (CPPFunction*)readline_completer;
3321 for(i=0; i<maxOtherInfosSupported; ++i) {
3322 extraOtherInfos[i].oidval = -1;
3329 #if HAVE_GETTIMEOFDAY
3330 struct timeval tv_start, tv_end;
3334 static void handle_srw_record(Z_SRW_record *rec)
3336 if (rec->recordPosition)
3338 printf ("pos=%d", *rec->recordPosition);
3339 setno = *rec->recordPosition + 1;
3341 if (rec->recordSchema)
3342 printf (" schema=%s", rec->recordSchema);
3344 if (rec->recordData_buf && rec->recordData_len)
3345 fwrite(rec->recordData_buf, 1, rec->recordData_len, stdout);
3347 printf ("No data!");
3351 static void handle_srw_explain_response(Z_SRW_explainResponse *res)
3353 handle_srw_record(&res->record);
3356 static void handle_srw_response(Z_SRW_searchRetrieveResponse *res)
3360 printf ("Received SRW SearchRetrieve Response\n");
3362 for (i = 0; i<res->num_diagnostics; i++)
3364 if (res->diagnostics[i].uri)
3365 printf ("SRW diagnostic %s\n",
3366 res->diagnostics[i].uri);
3368 printf ("SRW diagnostic missing or could not be decoded\n");
3369 if (res->diagnostics[i].message)
3370 printf ("Message: %s\n", res->diagnostics[i].message);
3371 if (res->diagnostics[i].details)
3372 printf ("Details: %s\n", res->diagnostics[i].details);
3374 if (res->numberOfRecords)
3375 printf ("Number of hits: %d\n", *res->numberOfRecords);
3376 for (i = 0; i<res->num_records; i++)
3377 handle_srw_record(res->records + i);
3380 static void http_response(Z_HTTP_Response *hres)
3383 const char *content_type = z_HTTP_header_lookup(hres->headers,
3385 const char *connection_head = z_HTTP_header_lookup(hres->headers,
3387 if (content_type && !yaz_strcmp_del("text/xml", content_type, "; "))
3389 Z_SOAP *soap_package = 0;
3390 ODR o = odr_createmem(ODR_DECODE);
3391 Z_SOAP_Handler soap_handlers[2] = {
3392 {"http://www.loc.gov/zing/srw/", 0,
3393 (Z_SOAP_fun) yaz_srw_codec},
3396 ret = z_soap_codec(o, &soap_package,
3397 &hres->content_buf, &hres->content_len,
3399 if (!ret && soap_package->which == Z_SOAP_generic &&
3400 soap_package->u.generic->no == 0)
3402 Z_SRW_PDU *sr = soap_package->u.generic->p;
3403 if (sr->which == Z_SRW_searchRetrieve_response)
3404 handle_srw_response(sr->u.response);
3405 else if (sr->which == Z_SRW_explain_response)
3406 handle_srw_explain_response(sr->u.explain_response);
3410 else if (soap_package && (soap_package->which == Z_SOAP_fault
3411 || soap_package->which == Z_SOAP_error))
3413 printf ("HTTP Error Status=%d\n", hres->code);
3414 printf ("SOAP Fault code %s\n",
3415 soap_package->u.fault->fault_code);
3416 printf ("SOAP Fault string %s\n",
3417 soap_package->u.fault->fault_string);
3418 if (soap_package->u.fault->details)
3419 printf ("SOAP Details %s\n",
3420 soap_package->u.fault->details);
3428 if (hres->code != 200)
3430 printf ("HTTP Error Status=%d\n", hres->code);
3434 printf ("Decoding of SRW package failed\n");
3440 if (!strcmp(hres->version, "1.0"))
3442 /* HTTP 1.0: only if Keep-Alive we stay alive.. */
3443 if (!connection_head || strcmp(connection_head, "Keep-Alive"))
3448 /* HTTP 1.1: only if no close we stay alive .. */
3449 if (connection_head && !strcmp(connection_head, "close"))
3456 void wait_and_handle_response()
3458 int reconnect_ok = 1;
3461 int netbufferlen = 0;
3466 res = cs_get(conn, &netbuffer, &netbufferlen);
3467 if (reconnect_ok && res <= 0 && protocol == PROTO_HTTP)
3478 buf_out = odr_getbuf(out, &len_out, 0);
3480 do_hex_dump(buf_out, len_out);
3482 cs_put(conn, buf_out, len_out);
3490 printf("Target closed connection\n");
3495 odr_reset(in); /* release APDU from last round */
3497 do_hex_dump(netbuffer, res);
3498 odr_setbuf(in, netbuffer, res, 0);
3500 if (!z_GDU(in, &gdu, 0, 0))
3502 FILE *f = ber_file ? ber_file : stdout;
3503 odr_perror(in, "Decoding incoming APDU");
3504 fprintf(f, "[Near %d]\n", odr_offset(in));
3505 fprintf(f, "Packet dump:\n---------\n");
3506 odr_dumpBER(f, netbuffer, res);
3507 fprintf(f, "---------\n");
3510 z_GDU(print, &gdu, 0, 0);
3513 if (conn && cs_more(conn))
3518 odr_dumpBER(ber_file, netbuffer, res);
3519 if (apdu_file && !z_GDU(print, &gdu, 0, 0))
3521 odr_perror(print, "Failed to print incoming APDU");
3525 if (gdu->which == Z_GDU_Z3950)
3527 Z_APDU *apdu = gdu->u.z3950;
3530 case Z_APDU_initResponse:
3531 process_initResponse(apdu->u.initResponse);
3533 case Z_APDU_searchResponse:
3534 process_searchResponse(apdu->u.searchResponse);
3536 case Z_APDU_scanResponse:
3537 process_scanResponse(apdu->u.scanResponse);
3539 case Z_APDU_presentResponse:
3540 print_refid (apdu->u.presentResponse->referenceId);
3542 *apdu->u.presentResponse->numberOfRecordsReturned;
3543 if (apdu->u.presentResponse->records)
3544 display_records(apdu->u.presentResponse->records);
3546 printf("No records.\n");
3547 printf ("nextResultSetPosition = %d\n",
3548 *apdu->u.presentResponse->nextResultSetPosition);
3550 case Z_APDU_sortResponse:
3551 process_sortResponse(apdu->u.sortResponse);
3553 case Z_APDU_extendedServicesResponse:
3554 printf("Got extended services response\n");
3555 process_ESResponse(apdu->u.extendedServicesResponse);
3558 printf("Target has closed the association.\n");
3559 process_close(apdu->u.close);
3561 case Z_APDU_resourceControlRequest:
3562 process_resourceControlRequest
3563 (apdu->u.resourceControlRequest);
3565 case Z_APDU_deleteResultSetResponse:
3566 process_deleteResultSetResponse(apdu->u.
3567 deleteResultSetResponse);
3570 printf("Received unknown APDU type (%d).\n",
3576 else if (gdu->which == Z_GDU_HTTP_Response)
3578 http_response(gdu->u.HTTP_Response);
3581 if (conn && !cs_more(conn))
3586 #if HAVE_GETTIMEOFDAY
3587 gettimeofday (&tv_end, 0);
3589 printf ("S/U S/U=%ld/%ld %ld/%ld",
3590 (long) tv_start.tv_sec,
3591 (long) tv_start.tv_usec,
3592 (long) tv_end.tv_sec,
3593 (long) tv_end.tv_usec);
3595 printf ("Elapsed: %.6f\n",
3596 (double) tv_end.tv_usec / 1e6 + tv_end.tv_sec -
3597 ((double) tv_start.tv_usec / 1e6 + tv_start.tv_sec));
3604 int cmd_cclparse(const char* arg)
3607 struct ccl_rpn_node *rpn=NULL;
3610 rpn = ccl_find_str (bibset, arg, &error, &pos);
3613 printf ("%*s^ - ", 3+strlen(last_cmd)+1+pos, " ");
3614 printf ("%s\n", ccl_err_msg (error));
3620 ccl_pr_tree(rpn, stdout);
3624 ccl_rpn_delete(rpn);
3632 int cmd_set_otherinfo(const char* args)
3634 char oid[101], otherinfoString[101];
3639 sscan_res = sscanf (args, "%d %100[^ ] %100s", &otherinfoNo, oid, otherinfoString);
3641 /* reset this otherinfo */
3642 if(otherinfoNo>=maxOtherInfosSupported) {
3643 printf("Error otherinfo index to large (%d>%d)\n",otherinfoNo,maxOtherInfosSupported);
3645 extraOtherInfos[otherinfoNo].oidval = -1;
3646 if(extraOtherInfos[otherinfoNo].value) free(extraOtherInfos[otherinfoNo].value);
3650 printf("Error in set_otherinfo command \n");
3654 if(otherinfoNo>=maxOtherInfosSupported) {
3655 printf("Error otherinfo index to large (%d>%d)\n",otherinfoNo,maxOtherInfosSupported);
3658 oidval = oid_getvalbyname (oid);
3660 printf("Error in set_otherinfo command unknown oid %s \n",oid);
3663 extraOtherInfos[otherinfoNo].oidval = oidval;
3664 if(extraOtherInfos[otherinfoNo].value) free(extraOtherInfos[otherinfoNo].value);
3665 extraOtherInfos[otherinfoNo].value = strdup(otherinfoString);
3670 int cmd_list_otherinfo(const char* args)
3674 if(strlen(args)>0) {
3676 if( i >= maxOtherInfosSupported ) {
3677 printf("Error otherinfo index to large (%d>%d)\n",i,maxOtherInfosSupported);
3681 if(extraOtherInfos[i].oidval != -1)
3682 printf(" otherinfo %d %s %s\n",
3684 yaz_z3950_oid_value_to_str(
3685 (enum oid_value) extraOtherInfos[i].oidval,
3687 extraOtherInfos[i].value);
3690 for(i=0; i<maxOtherInfosSupported; ++i) {
3691 if(extraOtherInfos[i].oidval != -1)
3692 printf(" otherinfo %d %s %s\n",
3694 yaz_z3950_oid_value_to_str(
3695 (enum oid_value) extraOtherInfos[i].oidval,
3697 extraOtherInfos[i].value);
3705 int cmd_list_all(const char* args) {
3708 /* connection options */
3710 printf("Connected to : %s\n",last_open_command);
3712 if(last_open_command)
3713 printf("Not connected to : %s\n",last_open_command);
3715 printf("Not connected : \n");
3718 if(yazProxy) printf("using proxy : %s\n",yazProxy);
3720 printf("auto_reconnect : %s\n",auto_reconnect?"on":"off");
3723 printf("Authentication : none\n");
3725 switch(auth->which) {
3726 case Z_IdAuthentication_idPass:
3727 printf("Authentication : IdPass\n");
3728 printf(" Login User : %s\n",auth->u.idPass->userId?auth->u.idPass->userId:"");
3729 printf(" Login Group : %s\n",auth->u.idPass->groupId?auth->u.idPass->groupId:"");
3730 printf(" Password : %s\n",auth->u.idPass->password?auth->u.idPass->password:"");
3732 case Z_IdAuthentication_open:
3733 printf("Authentication : psOpen\n");
3734 printf(" Open string : %s\n",auth->u.open);
3737 printf("Authentication : Unknown\n");
3740 if (negotiationCharset)
3741 printf("Neg. Character set : `%s'\n", negotiationCharset);
3745 for (i = 0; i<num_databaseNames; i++) printf("%s ",databaseNames[i]);
3749 printf("CCL file : %s\n",ccl_fields);
3750 printf("CQL file : %s\n",cql_fields);
3751 printf("Query type : %s\n",query_type_as_string(queryType));
3753 printf("Named Result Sets : %s\n",setnumber==-1?"off":"on");
3755 /* piggy back options */
3756 printf("ssub/lslb/mspn : %d/%d/%d\n",smallSetUpperBound,largeSetLowerBound,mediumSetPresentNumber);
3758 /* print present related options */
3759 printf("Format : %s\n",yaz_z3950_oid_value_to_str(recordsyntax,CLASS_RECSYN));
3760 printf("Schema : %s\n",record_schema ? record_schema : "not set");
3761 printf("Elements : %s\n",elementSetNames?elementSetNames->u.generic:"");
3763 /* loging options */
3764 printf("APDU log : %s\n",apdu_file?"on":"off");
3765 printf("Record log : %s\n",marc_file?"on":"off");
3768 printf("Other Info: \n");
3769 cmd_list_otherinfo("");
3774 int cmd_clear_otherinfo(const char* args)
3776 if(strlen(args)>0) {
3778 otherinfoNo = atoi(args);
3779 if( otherinfoNo >= maxOtherInfosSupported ) {
3780 printf("Error otherinfo index to large (%d>%d)\n",otherinfoNo,maxOtherInfosSupported);
3784 if(extraOtherInfos[otherinfoNo].oidval != -1) {
3785 /* only clear if set. */
3786 extraOtherInfos[otherinfoNo].oidval=-1;
3787 free(extraOtherInfos[otherinfoNo].value);
3792 for(i=0; i<maxOtherInfosSupported; ++i) {
3793 if (extraOtherInfos[i].oidval!=-1 ) {
3794 extraOtherInfos[i].oidval=-1;
3795 free(extraOtherInfos[i].value);
3802 static int cmd_help (const char *line);
3804 typedef char *(*completerFunctionType)(const char *text, int state);
3808 int (*fun)(const char *arg);
3810 completerFunctionType rl_completerfunction;
3811 int complete_filenames;
3812 char **local_tabcompletes;
3814 {"open", cmd_open, "('tcp'|'ssl')':<host>[':'<port>][/<db>]",NULL,0,NULL},
3815 {"quit", cmd_quit, "",NULL,0,NULL},
3816 {"find", cmd_find, "<query>",NULL,0,NULL},
3817 {"delete", cmd_delete, "<setname>",NULL,0,NULL},
3818 {"base", cmd_base, "<base-name>",NULL,0,NULL},
3819 {"show", cmd_show, "<rec#>['+'<#recs>['+'<setname>]]",NULL,0,NULL},
3820 {"scan", cmd_scan, "<term>",NULL,0,NULL},
3821 {"sort", cmd_sort, "<sortkey> <flag> <sortkey> <flag> ...",NULL,0,NULL},
3822 {"sort+", cmd_sort_newset, "<sortkey> <flag> <sortkey> <flag> ...",NULL,0,NULL},
3823 {"authentication", cmd_authentication, "<acctstring>",NULL,0,NULL},
3824 {"lslb", cmd_lslb, "<largeSetLowerBound>",NULL,0,NULL},
3825 {"ssub", cmd_ssub, "<smallSetUpperBound>",NULL,0,NULL},
3826 {"mspn", cmd_mspn, "<mediumSetPresentNumber>",NULL,0,NULL},
3827 {"status", cmd_status, "",NULL,0,NULL},
3828 {"setnames", cmd_setnames, "",NULL,0,NULL},
3829 {"cancel", cmd_cancel, "",NULL,0,NULL},
3830 {"format", cmd_format, "<recordsyntax>",complete_format,0,NULL},
3831 {"schema", cmd_schema, "<schema>",complete_schema,0,NULL},
3832 {"elements", cmd_elements, "<elementSetName>",NULL,0,NULL},
3833 {"close", cmd_close, "",NULL,0,NULL},
3834 {"attributeset", cmd_attributeset, "<attrset>",complete_attributeset,0,NULL},
3835 {"querytype", cmd_querytype, "<type>",complete_querytype,0,NULL},
3836 {"refid", cmd_refid, "<id>",NULL,0,NULL},
3837 {"itemorder", cmd_itemorder, "ill|item <itemno>",NULL,0,NULL},
3838 {"update", cmd_update, "<action> <recid> [<file>]",NULL,0,NULL},
3839 {"update0", cmd_update0, "<action> <recid> [<file>]",NULL,0,NULL},
3840 {"packagename", cmd_packagename, "<packagename>",NULL,0,NULL},
3841 {"proxy", cmd_proxy, "[('tcp'|'ssl')]<host>[':'<port>]",NULL,0,NULL},
3842 {"charset", cmd_charset, "<nego_charset> <output_charset>",NULL,0,NULL},
3843 {"marccharset", cmd_marccharset, "<charset_name>",NULL,0,NULL},
3844 {"lang", cmd_lang, "<language_code>",NULL,0,NULL},
3845 {".", cmd_source, "<filename>",NULL,1,NULL},
3846 {"!", cmd_subshell, "Subshell command",NULL,1,NULL},
3847 {"set_apdufile", cmd_set_apdufile, "<filename>",NULL,1,NULL},
3848 {"set_berfile", cmd_set_berfile, "<filename>",NULL,1,NULL},
3849 {"set_marcdump", cmd_set_marcdump," <filename>",NULL,1,NULL},
3850 {"set_cclfile", cmd_set_cclfile," <filename>",NULL,1,NULL},
3851 {"set_cqlfile", cmd_set_cqlfile," <filename>",NULL,1,NULL},
3852 {"set_auto_reconnect", cmd_set_auto_reconnect," on|off",complete_auto_reconnect,1,NULL},
3853 {"set_otherinfo", cmd_set_otherinfo,"<otherinfoinddex> <oid> <string>",NULL,0,NULL},
3854 {"register_oid", cmd_register_oid,"<name> <class> <oid>",NULL,0,NULL},
3855 {"push_command", cmd_push_command,"<command>",command_generator,0,NULL},
3856 {"register_tab", cmd_register_tab,"<commandname> <tab>",command_generator,0,NULL},
3857 {"cclparse", cmd_cclparse,"<ccl find command>",NULL,0,NULL},
3858 {"list_otherinfo",cmd_list_otherinfo,"[otherinfoinddex]",NULL,0,NULL},
3859 {"list_all",cmd_list_all,"",NULL,0,NULL},
3860 {"clear_otherinfo",cmd_clear_otherinfo,"",NULL,0,NULL},
3861 /* Server Admin Functions */
3862 {"adm-reindex", cmd_adm_reindex, "<database-name>",NULL,0,NULL},
3863 {"adm-truncate", cmd_adm_truncate, "('database'|'index')<object-name>",NULL,0,NULL},
3864 {"adm-create", cmd_adm_create, "",NULL,0,NULL},
3865 {"adm-drop", cmd_adm_drop, "('database'|'index')<object-name>",NULL,0,NULL},
3866 {"adm-import", cmd_adm_import, "<record-type> <dir> <pattern>",NULL,0,NULL},
3867 {"adm-refresh", cmd_adm_refresh, "",NULL,0,NULL},
3868 {"adm-commit", cmd_adm_commit, "",NULL,0,NULL},
3869 {"adm-shutdown", cmd_adm_shutdown, "",NULL,0,NULL},
3870 {"adm-startup", cmd_adm_startup, "",NULL,0,NULL},
3871 {"explain", cmd_explain, "", NULL, 0, NULL},
3872 {"options", cmd_options, "", NULL, 0, NULL},
3873 {"zversion", cmd_zversion, "", NULL, 0, NULL},
3874 {"help", cmd_help, "", NULL,0,NULL},
3875 {"init", cmd_init, "", NULL,0,NULL},
3879 static int cmd_help (const char *line)
3885 sscanf (line, "%20s", topic);
3888 printf("Commands:\n");
3889 for (i = 0; cmd_array[i].cmd; i++)
3890 if (*topic == 0 || strcmp (topic, cmd_array[i].cmd) == 0)
3891 printf(" %s %s\n", cmd_array[i].cmd, cmd_array[i].ad);
3892 if (strcmp (topic, "find") == 0)
3895 printf (" \"term\" Simple Term\n");
3896 printf (" @attr [attset] type=value op Attribute\n");
3897 printf (" @and opl opr And\n");
3898 printf (" @or opl opr Or\n");
3899 printf (" @not opl opr And-Not\n");
3900 printf (" @set set Result set\n");
3902 printf ("Bib-1 attribute types\n");
3904 printf ("4=Title 7=ISBN 8=ISSN 30=Date 62=Abstract 1003=Author 1016=Any\n");
3905 printf ("2=Relation: ");
3906 printf ("1< 2<= 3= 4>= 5> 6!= 102=Relevance\n");
3907 printf ("3=Position: ");
3908 printf ("1=First in Field 2=First in subfield 3=Any position\n");
3909 printf ("4=Structure: ");
3910 printf ("1=Phrase 2=Word 3=Key 4=Year 5=Date 6=WordList\n");
3911 printf ("5=Truncation: ");
3912 printf ("1=Right 2=Left 3=L&R 100=No 101=# 102=Re-1 103=Re-2\n");
3913 printf ("6=Completeness:");
3914 printf ("1=Incomplete subfield 2=Complete subfield 3=Complete field\n");
3919 int cmd_register_tab(const char* arg) {
3921 char command[101], tabargument[101];
3926 if (sscanf (arg, "%100s %100s", command, tabargument) < 1) {
3930 /* locate the amdn in the list */
3931 for (i = 0; cmd_array[i].cmd; i++) {
3932 if (!strncmp(cmd_array[i].cmd, command, strlen(command))) {
3937 if(!cmd_array[i].cmd) {
3938 fprintf(stderr,"Unknown command %s\n",command);
3943 if(!cmd_array[i].local_tabcompletes)
3944 cmd_array[i].local_tabcompletes = (char **) calloc(1,sizeof(char**));
3948 tabslist = cmd_array[i].local_tabcompletes;
3949 for(;tabslist && *tabslist;tabslist++) {
3953 cmd_array[i].local_tabcompletes = (char **)
3954 realloc(cmd_array[i].local_tabcompletes,(num_of_tabs+2)*sizeof(char**));
3955 tabslist=cmd_array[i].local_tabcompletes;
3956 tabslist[num_of_tabs]=strdup(tabargument);
3957 tabslist[num_of_tabs+1]=NULL;
3962 void process_cmd_line(char* line)
3965 char word[32], arg[1024];
3967 #if HAVE_GETTIMEOFDAY
3968 gettimeofday (&tv_start, 0);
3971 if ((res = sscanf(line, "%31s %1023[^;]", word, arg)) <= 0)
3973 strcpy(word, last_cmd);
3978 strcpy(last_cmd, word);
3980 /* removed tailing spaces from the arg command */
3983 char* lastnonspace=NULL;
3991 *(++lastnonspace) = 0;
3994 for (i = 0; cmd_array[i].cmd; i++)
3995 if (!strncmp(cmd_array[i].cmd, word, strlen(word)))
3997 res = (*cmd_array[i].fun)(arg);
4001 if (!cmd_array[i].cmd) /* dump our help-screen */
4003 printf("Unknown command: %s.\n", word);
4004 printf("use help for list of commands\n");
4005 /* cmd_help (""); */
4009 if(apdu_file) fflush(apdu_file);
4012 wait_and_handle_response();
4021 char *command_generator(const char *text, int state)
4027 for( ; cmd_array[idx].cmd; ++idx) {
4028 if (!strncmp(cmd_array[idx].cmd,text,strlen(text))) {
4029 ++idx; /* skip this entry on the next run */
4030 return strdup(cmd_array[idx-1].cmd);
4038 This function only known how to complete on the first word
4040 char ** readline_completer(char *text, int start, int end) {
4041 #if HAVE_READLINE_READLINE_H
4043 completerFunctionType completerToUse;
4046 #if HAVE_READLINE_RL_COMPLETION_MATCHES
4047 char** res=rl_completion_matches(text,
4050 char** res=completion_matches(text,
4051 (CPFunction*)command_generator);
4053 rl_attempted_completion_over = 1;
4056 char arg[1024],word[32];
4058 if ((res = sscanf(rl_line_buffer, "%31s %1023[^;]", word, arg)) <= 0) {
4059 rl_attempted_completion_over = 1;
4063 for (i = 0; cmd_array[i].cmd; i++) {
4064 if (!strncmp(cmd_array[i].cmd, word, strlen(word))) {
4069 if(!cmd_array[i].cmd) return NULL;
4071 curret_global_list = cmd_array[i].local_tabcompletes;
4073 completerToUse = cmd_array[i].rl_completerfunction;
4074 if(completerToUse==NULL) /* if no pr. command completer is defined use the default completer */
4075 completerToUse = default_completer;
4077 if(completerToUse) {
4078 #ifdef HAVE_READLINE_RL_COMPLETION_MATCHES
4080 rl_completion_matches(text,
4084 completion_matches(text,
4085 (CPFunction*)completerToUse);
4087 if(!cmd_array[i].complete_filenames)
4088 rl_attempted_completion_over = 1;
4091 if(!cmd_array[i].complete_filenames)
4092 rl_attempted_completion_over = 1;
4102 static void client(void)
4108 #if HAVE_GETTIMEOFDAY
4109 gettimeofday (&tv_start, 0);
4114 char *line_in = NULL;
4115 #if HAVE_READLINE_READLINE_H
4118 line_in=readline(C_PROMPT);
4121 #if HAVE_READLINE_HISTORY_H
4123 add_history(line_in);
4125 strncpy(line, line_in, 1023);
4134 if (!fgets(line, 1023, stdin))
4136 if ((end_p = strchr (line, '\n')))
4139 process_cmd_line(line);
4143 static void show_version(void)
4147 yaz_version(vstr, 0);
4148 printf ("YAZ version: %s\n", YAZ_VERSION);
4149 if (strcmp(vstr, YAZ_VERSION))
4150 printf ("YAZ DLL/SO: %s\n", vstr);
4154 int main(int argc, char **argv)
4157 char *open_command = 0;
4158 char *auth_command = 0;
4163 if (!setlocale(LC_CTYPE, ""))
4164 fprintf (stderr, "setlocale failed\n");
4168 codeset = nl_langinfo(CODESET);
4172 outputCharset = xstrdup(codeset);
4174 ODR_MASK_SET(&z3950_options, Z_Options_search);
4175 ODR_MASK_SET(&z3950_options, Z_Options_present);
4176 ODR_MASK_SET(&z3950_options, Z_Options_namedResultSets);
4177 ODR_MASK_SET(&z3950_options, Z_Options_triggerResourceCtrl);
4178 ODR_MASK_SET(&z3950_options, Z_Options_scan);
4179 ODR_MASK_SET(&z3950_options, Z_Options_sort);
4180 ODR_MASK_SET(&z3950_options, Z_Options_extendedServices);
4181 ODR_MASK_SET(&z3950_options, Z_Options_delSet);
4183 while ((ret = options("k:c:q:a:b:m:v:p:u:t:Vxd:", argv, argc, &arg)) != -2)
4190 open_command = (char *) xmalloc (strlen(arg)+6);
4191 strcpy (open_command, "open ");
4192 strcat (open_command, arg);
4196 dump_file_prefix = arg;
4199 kilobytes = atoi(arg);
4202 if (!(marc_file = fopen (arg, "a")))
4209 outputCharset = xstrdup(arg);
4212 strncpy (ccl_fields, arg, sizeof(ccl_fields)-1);
4213 ccl_fields[sizeof(ccl_fields)-1] = '\0';
4216 strncpy (cql_fields, arg, sizeof(cql_fields)-1);
4217 cql_fields[sizeof(cql_fields)-1] = '\0';
4220 if (!strcmp(arg, "-"))
4223 ber_file=fopen(arg, "a");
4226 if (!strcmp(arg, "-"))
4229 apdu_file=fopen(arg, "a");
4235 yazProxy=strdup(arg);
4240 auth_command = (char *) xmalloc (strlen(arg)+6);
4241 strcpy (auth_command, "auth ");
4242 strcat (auth_command, arg);
4246 yaz_log_init(yaz_log_mask_str(arg), "", 0);
4252 fprintf (stderr, "Usage: %s [-m <marclog>] [ -a <apdulog>] "
4253 "[-b berdump] [-c cclfields] \n"
4254 "[-q cqlfields] [-p <proxy-addr>] [-u <auth>] "
4255 "[-k size] [-d dump] [-V] [<server-addr>]\n",
4263 #ifdef HAVE_GETTIMEOFDAY
4264 gettimeofday (&tv_start, 0);
4266 process_cmd_line (auth_command);
4267 #if HAVE_READLINE_HISTORY_H
4268 add_history(auth_command);
4270 xfree(auth_command);
4274 #ifdef HAVE_GETTIMEOFDAY
4275 gettimeofday (&tv_start, 0);
4277 process_cmd_line (open_command);
4278 #if HAVE_READLINE_HISTORY_H
4279 add_history(open_command);
4281 xfree(open_command);
4292 * vim600: sw=4 ts=8 fdm=marker
4293 * vim<600: sw=4 ts=8