2 * Copyright (c) 1995-2004, Index Data
3 * See the file LICENSE for details.
5 * $Id: client.c,v 1.230 2004-02-14 15:58:42 adam Exp $
24 #define S_ISREG(x) (x & _S_IFREG)
25 #define S_ISDIR(x) (x & _S_IFDIR)
28 #include <yaz/yaz-util.h>
30 #include <yaz/comstack.h>
32 #include <yaz/proto.h>
33 #include <yaz/marcdisp.h>
34 #include <yaz/diagbib1.h>
35 #include <yaz/otherinfo.h>
36 #include <yaz/charneg.h>
38 #include <yaz/pquery.h>
39 #include <yaz/sortspec.h>
43 #include <yaz/yaz-ccl.h>
46 #if HAVE_READLINE_READLINE_H
47 #include <readline/readline.h>
50 #if HAVE_READLINE_HISTORY_H
51 #include <readline/history.h>
57 #include "tabcomplete.h"
59 #define C_PROMPT "Z> "
61 static char *codeset = 0; /* character set for output */
62 static int hex_dump = 0;
63 static char *dump_file_prefix = 0;
64 static ODR out, in, print; /* encoding and decoding streams */
66 static ODR srw_sr_odr_out = 0;
67 static Z_SRW_PDU *srw_sr = 0;
69 static FILE *apdu_file = 0;
70 static FILE *ber_file = 0;
71 static COMSTACK conn = 0; /* our z-association */
72 static Z_IdAuthentication *auth = 0; /* our current auth definition */
73 char *databaseNames[128];
74 int num_databaseNames = 0;
75 static Z_External *record_last = 0;
76 static int setnumber = -1; /* current result set number */
77 static int smallSetUpperBound = 0;
78 static int largeSetLowerBound = 1;
79 static int mediumSetPresentNumber = 0;
80 static Z_ElementSetNames *elementSetNames = 0;
81 static int setno = 1; /* current set offset */
82 static enum oid_proto protocol = PROTO_Z3950; /* current app protocol */
83 static enum oid_value recordsyntax = VAL_USMARC;
84 static char *record_schema = 0;
85 static int sent_close = 0;
86 static NMEM session_mem = NULL; /* memory handle for init-response */
87 static Z_InitResponse *session = 0; /* session parameters */
88 static char last_scan_line[512] = "0";
89 static char last_scan_query[512] = "0";
90 static char ccl_fields[512] = "default.bib";
91 /* ### How can I set this path to use wherever YAZ is installed? */
92 static char cql_fields[512] = "/usr/local/share/yaz/etc/pqf.properties";
93 static char *esPackageName = 0;
94 static char *yazProxy = 0;
95 static int kilobytes = 1024;
96 static char *negotiationCharset = 0;
97 static char *outputCharset = 0;
98 static char *marcCharset = 0;
99 static char* yazLang = 0;
101 static char last_cmd[32] = "?";
102 static FILE *marc_file = 0;
103 static char *refid = NULL;
104 static char *last_open_command = NULL;
105 static int auto_reconnect = 0;
106 static Odr_bitmask z3950_options;
107 static int z3950_version = 3;
109 static char cur_host[200];
119 static QueryType queryType = QueryType_Prefix;
121 static CCL_bibset bibset; /* CCL bibset handle */
122 static cql_transform_t cqltrans; /* CQL context-set handle */
124 #if HAVE_READLINE_COMPLETION_OVER
127 /* readline doesn't have this var. Define it ourselves. */
128 int rl_attempted_completion_over = 0;
131 /* set this one to 1, to avoid decode of unknown MARCs */
132 #define AVOID_MARC_DECODE 1
134 #define maxOtherInfosSupported 10
138 } extraOtherInfos[maxOtherInfosSupported];
141 void process_cmd_line(char* line);
142 char ** readline_completer(char *text, int start, int end);
143 char *command_generator(const char *text, int state);
144 char** curret_global_list=NULL;
145 int cmd_register_tab(const char* arg);
147 static void close_session (void);
149 ODR getODROutputStream()
154 const char* query_type_as_string(QueryType q)
157 case QueryType_Prefix: return "prefix (RPN sent to server)";
158 case QueryType_CCL: return "CCL (CCL sent to server) ";
159 case QueryType_CCL2RPN: return "CCL -> RPN (RPN sent to server)";
160 case QueryType_CQL: return "CQL (CQL sent to server)";
161 case QueryType_CQL2RPN: return "CQL -> RPN (RPN sent to server)";
163 return "unknown Query type internal yaz-client error";
167 static void do_hex_dump(const char* buf, int len)
172 for( i=0; i<len ; i=i+16 )
175 for(x=0 ; i+x<len && x<16; ++x)
177 printf("%2.2X ",(unsigned int)((unsigned char)buf[i+x]));
182 if (dump_file_prefix)
185 if (++no < 1000 && strlen(dump_file_prefix) < 500)
189 sprintf (fname, "%s.%03d.raw", dump_file_prefix, no);
190 of = fopen(fname, "wb");
192 fwrite (buf, 1, len, of);
199 void add_otherInfos(Z_APDU *a)
201 Z_OtherInformation **oi;
205 for(i=0; i<maxOtherInfosSupported; ++i)
207 if(extraOtherInfos[i].oidval != -1)
208 yaz_oi_set_string_oidval(oi, out, extraOtherInfos[i].oidval,
209 1, extraOtherInfos[i].value);
213 int send_apdu(Z_APDU *a)
222 z_APDU(print, &a, 0, 0);
225 if (!z_APDU(out, &a, 0, 0))
227 odr_perror(out, "Encoding APDU");
231 buf = odr_getbuf(out, &len, 0);
233 odr_dumpBER(ber_file, buf, len);
234 /* printf ("sending APDU of size %d\n", len); */
235 do_hex_dump(buf, len);
236 if (cs_put(conn, buf, len) < 0)
238 fprintf(stderr, "cs_put: %s", cs_errmsg(cs_errno(conn)));
242 odr_reset(out); /* release the APDU structure */
246 static void print_stringn(const unsigned char *buf, size_t len)
249 for (i = 0; i<len; i++)
250 if ((buf[i] <= 126 && buf[i] >= 32) || strchr ("\n\r\t\f", buf[i]))
251 printf ("%c", buf[i]);
253 printf ("\\X%02X", buf[i]);
256 static void print_refid (Z_ReferenceId *id)
260 printf ("Reference Id: ");
261 print_stringn (id->buf, id->len);
266 static Z_ReferenceId *set_refid (ODR out)
271 id = (Z_ReferenceId *) odr_malloc (out, sizeof(*id));
272 id->size = id->len = strlen(refid);
273 id->buf = (unsigned char *) odr_malloc (out, id->len);
274 memcpy (id->buf, refid, id->len);
278 /* INIT SERVICE ------------------------------- */
280 static void send_initRequest(const char* type_and_host)
282 Z_APDU *apdu = zget_APDU(out, Z_APDU_initRequest);
283 Z_InitRequest *req = apdu->u.initRequest;
286 req->options = &z3950_options;
288 ODR_MASK_ZERO(req->protocolVersion);
289 for (i = 0; i<z3950_version; i++)
290 ODR_MASK_SET(req->protocolVersion, i);
292 *req->maximumRecordSize = 1024*kilobytes;
293 *req->preferredMessageSize = 1024*kilobytes;
295 req->idAuthentication = auth;
297 req->referenceId = set_refid (out);
299 if (yazProxy && type_and_host)
300 yaz_oi_set_string_oidval(&req->otherInfo, out, VAL_PROXY,
303 if (negotiationCharset || yazLang) {
304 Z_OtherInformation **p;
305 Z_OtherInformationUnit *p0;
307 yaz_oi_APDU(apdu, &p);
309 if ((p0=yaz_oi_update(p, out, NULL, 0, 0))) {
310 ODR_MASK_SET(req->options, Z_Options_negotiationModel);
312 p0->which = Z_OtherInfo_externallyDefinedInfo;
313 p0->information.externallyDefinedInfo =
314 yaz_set_proposal_charneg(
316 (const char**)&negotiationCharset,
317 negotiationCharset ? 1 : 0,
318 (const char**)&yazLang, yazLang ? 1 : 0, 1);
323 printf("Sent initrequest.\n");
327 /* These two are used only from process_initResponse() */
328 static void render_initUserInfo(Z_OtherInformation *ui1);
329 static void render_diag(Z_DiagnosticFormat *diag);
331 static void pr_opt(const char *opt, void *clientData)
336 static int process_initResponse(Z_InitResponse *res)
339 /* save session parameters for later use */
340 session_mem = odr_extract_mem(in);
343 for (ver = 0; ver < 8; ver++)
344 if (!ODR_MASK_GET(res->protocolVersion, ver))
348 printf("Connection rejected by v%d target.\n", ver);
350 printf("Connection accepted by v%d target.\n", ver);
351 if (res->implementationId)
352 printf("ID : %s\n", res->implementationId);
353 if (res->implementationName)
354 printf("Name : %s\n", res->implementationName);
355 if (res->implementationVersion)
356 printf("Version: %s\n", res->implementationVersion);
357 if (res->userInformationField)
359 Z_External *uif = res->userInformationField;
360 if (uif->which == Z_External_userInfo1) {
361 render_initUserInfo(uif->u.userInfo1);
363 printf("UserInformationfield:\n");
364 if (!z_External(print, (Z_External**)&uif, 0, 0)) {
365 odr_perror(print, "Printing userinfo\n");
368 if (uif->which == Z_External_octet) {
369 printf("Guessing visiblestring:\n");
370 printf("'%s'\n", uif->u. octet_aligned->buf);
371 } else if (uif->which == Z_External_single) {
372 /* Peek at any private Init-diagnostic APDUs */
373 Odr_any *sat = uif->u.single_ASN1_type;
374 printf("### NAUGHTY: External is '%s'\n", sat->buf);
380 yaz_init_opt_decode(res->options, pr_opt, 0);
383 if (ODR_MASK_GET(res->options, Z_Options_namedResultSets))
386 if (ODR_MASK_GET(res->options, Z_Options_negotiationModel)) {
388 Z_CharSetandLanguageNegotiation *p =
389 yaz_get_charneg_record(res->otherInfo);
393 char *charset=NULL, *lang=NULL;
396 yaz_get_response_charneg(session_mem, p, &charset, &lang,
399 if (outputCharset && negotiationCharset) {
400 odr_set_charset (out, charset, outputCharset);
401 odr_set_charset (in, outputCharset, charset);
404 odr_set_charset (out, 0, 0);
405 odr_set_charset (in, 0, 0);
408 printf("Accepted character set : %s\n", charset);
409 printf("Accepted code language : %s\n", lang ? lang : "none");
410 printf("Accepted records in ...: %d\n", selected );
418 static void render_initUserInfo(Z_OtherInformation *ui1) {
420 printf("Init response contains %d otherInfo unit%s:\n",
421 ui1->num_elements, ui1->num_elements == 1 ? "" : "s");
423 for (i = 0; i < ui1->num_elements; i++) {
424 Z_OtherInformationUnit *unit = ui1->list[i];
425 printf(" %d: otherInfo unit contains ", i+1);
426 if (unit->which == Z_OtherInfo_externallyDefinedInfo &&
427 unit->information.externallyDefinedInfo->which ==
429 render_diag(unit->information.externallyDefinedInfo->u.diag1);
431 printf("unsupported otherInfo unit type %d\n", unit->which);
437 /* ### should this share code with display_diagrecs()? */
438 static void render_diag(Z_DiagnosticFormat *diag) {
441 printf("%d diagnostic%s:\n", diag->num, diag->num == 1 ? "" : "s");
442 for (i = 0; i < diag->num; i++) {
443 Z_DiagnosticFormat_s *ds = diag->elements[i];
444 printf(" %d: ", i+1);
446 case Z_DiagnosticFormat_s_defaultDiagRec: {
447 Z_DefaultDiagFormat *dd = ds->u.defaultDiagRec;
448 /* ### should check `dd->diagnosticSetId' */
449 printf("code=%d (%s)", *dd->condition,
450 diagbib1_str(*dd->condition));
451 /* Both types of addinfo are the same, so use type-pun */
452 if (dd->u.v2Addinfo != 0)
453 printf(",\n\taddinfo='%s'", dd->u.v2Addinfo);
456 case Z_DiagnosticFormat_s_explicitDiagnostic:
457 printf("Explicit diagnostic (not supported)");
460 printf("Unrecognised diagnostic type %d", ds->which);
464 if (ds->message != 0)
465 printf(", message='%s'", ds->message);
471 static int set_base(const char *arg)
476 for (i = 0; i<num_databaseNames; i++)
477 xfree (databaseNames[i]);
478 num_databaseNames = 0;
482 if (!(cp = strchr(arg, ' ')))
483 cp = arg + strlen(arg);
486 databaseNames[num_databaseNames] = (char *)xmalloc (1 + cp - arg);
487 memcpy (databaseNames[num_databaseNames], arg, cp - arg);
488 databaseNames[num_databaseNames][cp - arg] = '\0';
490 for (cp1 = databaseNames[num_databaseNames]; *cp1 ; cp1++)
499 if (num_databaseNames == 0)
501 num_databaseNames = 1;
502 databaseNames[0] = xstrdup("");
507 static int cmd_base(const char *arg)
511 printf("Usage: base <database> <database> ...\n");
514 return set_base(arg);
517 void cmd_open_remember_last_open_command(const char* arg, char* new_open_command)
519 if(last_open_command != arg)
521 if(last_open_command) xfree(last_open_command);
522 last_open_command = xstrdup(new_open_command);
526 int session_connect(const char *arg)
529 char type_and_host[101];
530 const char *basep = 0;
537 nmem_destroy (session_mem);
541 cs_get_host_args(arg, &basep);
543 strncpy(type_and_host, arg, sizeof(type_and_host)-1);
544 type_and_host[sizeof(type_and_host)-1] = '\0';
546 cmd_open_remember_last_open_command(arg,type_and_host);
549 conn = cs_create_host(yazProxy, 1, &add);
551 conn = cs_create_host(arg, 1, &add);
554 printf ("Couldn't create comstack\n");
559 if (conn->protocol == PROTO_HTTP)
561 printf ("SRW/HTTP not enabled in this YAZ\n");
567 protocol = conn->protocol;
568 if (conn->protocol == PROTO_HTTP)
572 printf("Connecting...");
574 if (cs_connect(conn, add) < 0)
576 printf ("error = %s\n", cs_strerror(conn));
577 if (conn->cerrno == CSYSERR)
580 yaz_strerror(msg, sizeof(msg));
581 printf ("%s\n", msg);
590 if (protocol == PROTO_Z3950)
592 send_initRequest(type_and_host);
598 int cmd_open(const char *arg)
602 strncpy (cur_host, arg, sizeof(cur_host)-1);
603 cur_host[sizeof(cur_host)-1] = 0;
605 return session_connect(cur_host);
612 if(!( auto_reconnect && last_open_command) ) return ;
614 open_command = (char *) xmalloc (strlen(last_open_command)+6);
615 strcpy (open_command, "open ");
617 strcat (open_command, last_open_command);
619 process_cmd_line(open_command);
624 int cmd_authentication(const char *arg)
626 static Z_IdAuthentication au;
627 static char user[40], group[40], pass[40];
628 static Z_IdPass idPass;
633 printf("Auth field set to null\n");
637 r = sscanf (arg, "%39s %39s %39s", user, group, pass);
640 printf("Authentication set to null\n");
646 if (!strcmp(user, "-")) {
647 au.which = Z_IdAuthentication_anonymous;
648 printf("Authentication set to Anonymous\n");
650 au.which = Z_IdAuthentication_open;
652 printf("Authentication set to Open (%s)\n", user);
658 au.which = Z_IdAuthentication_idPass;
659 au.u.idPass = &idPass;
660 idPass.groupId = NULL;
661 idPass.userId = user;
662 idPass.password = group;
663 printf("Authentication set to User (%s), Pass (%s)\n", user, group);
668 au.which = Z_IdAuthentication_idPass;
669 au.u.idPass = &idPass;
670 idPass.groupId = group;
671 idPass.userId = user;
672 idPass.password = pass;
673 printf("Authentication set to User (%s), Group (%s), Pass (%s)\n",
679 /* SEARCH SERVICE ------------------------------ */
680 static void display_record(Z_External *r);
682 static void print_record(const unsigned char *buf, size_t len)
685 print_stringn (buf, len);
686 /* add newline if not already added ... */
687 if (i <= 0 || buf[i-1] != '\n')
691 static void display_record(Z_External *r)
693 oident *ent = oid_getentbyoid(r->direct_reference);
697 * Tell the user what we got.
699 if (r->direct_reference)
701 printf("Record type: ");
703 printf("%s\n", ent->desc);
704 else if (!odr_oid(print, &r->direct_reference, 0, 0))
706 odr_perror(print, "print oid");
710 /* Check if this is a known, ASN.1 type tucked away in an octet string */
711 if (ent && r->which == Z_External_octet)
713 Z_ext_typeent *type = z_ext_getentbyref(ent->value);
719 * Call the given decoder to process the record.
721 odr_setbuf(in, (char*)r->u.octet_aligned->buf,
722 r->u.octet_aligned->len, 0);
723 if (!(*type->fun)(in, (char **)&rr, 0, 0))
725 odr_perror(in, "Decoding constructed record.");
726 fprintf(stdout, "[Near %d]\n", odr_offset(in));
727 fprintf(stdout, "Packet dump:\n---------\n");
728 odr_dumpBER(stdout, (char*)r->u.octet_aligned->buf,
729 r->u.octet_aligned->len);
730 fprintf(stdout, "---------\n");
732 /* note just ignores the error ant print the bytes form the octet_aligned later */
735 * Note: we throw away the original, BER-encoded record here.
736 * Do something else with it if you want to keep it.
738 r->u.sutrs = (Z_SUTRS *) rr; /* we don't actually check the type here. */
739 r->which = type->what;
743 if (ent && ent->oclass != CLASS_RECSYN)
745 if (ent && ent->value == VAL_SOIF)
746 print_record((const unsigned char *) r->u.octet_aligned->buf,
747 r->u.octet_aligned->len);
748 else if (r->which == Z_External_octet)
750 const char *octet_buf = (char*)r->u.octet_aligned->buf;
751 if (ent->value == VAL_TEXT_XML || ent->value == VAL_APPLICATION_XML ||
752 ent->value == VAL_HTML)
754 print_record((const unsigned char *) octet_buf,
755 r->u.octet_aligned->len);
757 else if (ent->value == VAL_POSTSCRIPT)
759 int size = r->u.octet_aligned->len;
762 print_record((const unsigned char *) octet_buf, size);
767 #if AVOID_MARC_DECODE
768 /* primitive check for a marc OID 5.1-29 except 16 */
769 ent->oidsuffix[0] == 5 && ent->oidsuffix[1] < 30 &&
770 ent->oidsuffix[1] != 16
779 yaz_marc_t mt = yaz_marc_create();
781 if (yaz_marc_decode_buf(mt, octet_buf,r->u.octet_aligned->len,
785 if (marcCharset && !strcmp(marcCharset, "auto"))
787 if (ent->value == VAL_USMARC)
789 if (octet_buf[9] == 'a')
797 else if (marcCharset)
799 if (outputCharset && from)
801 cd = yaz_iconv_open(outputCharset, from);
802 printf ("convert from %s to %s", from,
805 printf (" unsupported\n");
810 fwrite (result, 1, rlen, stdout);
814 size_t inbytesleft = rlen;
815 const char *inp = result;
819 size_t outbytesleft = sizeof(outbuf);
823 r = yaz_iconv (cd, (char**) &inp,
825 &outp, &outbytesleft);
826 if (r == (size_t) (-1))
828 int e = yaz_iconv_error(cd);
829 if (e != YAZ_ICONV_E2BIG)
832 fwrite (outbuf, outp - outbuf, 1, stdout);
838 printf ("bad MARC. Dumping as it is:\n");
839 print_record((const unsigned char*) octet_buf,
840 r->u.octet_aligned->len);
842 yaz_marc_destroy(mt);
848 print_record((const unsigned char*) octet_buf,
849 r->u.octet_aligned->len);
853 fwrite (octet_buf, 1, r->u.octet_aligned->len, marc_file);
855 else if (ent && ent->value == VAL_SUTRS)
857 if (r->which != Z_External_sutrs)
859 printf("Expecting single SUTRS type for SUTRS.\n");
862 print_record(r->u.sutrs->buf, r->u.sutrs->len);
864 else if (ent && ent->value == VAL_GRS1)
867 if (r->which != Z_External_grs1)
869 printf("Expecting single GRS type for GRS.\n");
873 yaz_display_grs1(w, r->u.grs1, 0);
877 else if ( /* OPAC display not complete yet .. */
878 ent && ent->value == VAL_OPAC)
881 if (r->u.opac->bibliographicRecord)
882 display_record(r->u.opac->bibliographicRecord);
883 for (i = 0; i<r->u.opac->num_holdingsData; i++)
885 Z_HoldingsRecord *h = r->u.opac->holdingsData[i];
886 if (h->which == Z_HoldingsRecord_marcHoldingsRecord)
888 printf ("MARC holdings %d\n", i);
889 display_record(h->u.marcHoldingsRecord);
891 else if (h->which == Z_HoldingsRecord_holdingsAndCirc)
895 Z_HoldingsAndCircData *data = h->u.holdingsAndCirc;
897 printf ("Data holdings %d\n", i);
898 if (data->typeOfRecord)
899 printf ("typeOfRecord: %s\n", data->typeOfRecord);
900 if (data->encodingLevel)
901 printf ("encodingLevel: %s\n", data->encodingLevel);
902 if (data->receiptAcqStatus)
903 printf ("receiptAcqStatus: %s\n", data->receiptAcqStatus);
904 if (data->generalRetention)
905 printf ("generalRetention: %s\n", data->generalRetention);
906 if (data->completeness)
907 printf ("completeness: %s\n", data->completeness);
908 if (data->dateOfReport)
909 printf ("dateOfReport: %s\n", data->dateOfReport);
911 printf ("nucCode: %s\n", data->nucCode);
912 if (data->localLocation)
913 printf ("localLocation: %s\n", data->localLocation);
914 if (data->shelvingLocation)
915 printf ("shelvingLocation: %s\n", data->shelvingLocation);
916 if (data->callNumber)
917 printf ("callNumber: %s\n", data->callNumber);
918 if (data->copyNumber)
919 printf ("copyNumber: %s\n", data->copyNumber);
920 if (data->publicNote)
921 printf ("publicNote: %s\n", data->publicNote);
922 if (data->reproductionNote)
923 printf ("reproductionNote: %s\n", data->reproductionNote);
924 if (data->termsUseRepro)
925 printf ("termsUseRepro: %s\n", data->termsUseRepro);
926 if (data->enumAndChron)
927 printf ("enumAndChron: %s\n", data->enumAndChron);
928 for (j = 0; j<data->num_volumes; j++)
930 printf ("volume %d\n", j);
931 if (data->volumes[j]->enumeration)
932 printf (" enumeration: %s\n",
933 data->volumes[j]->enumeration);
934 if (data->volumes[j]->chronology)
935 printf (" chronology: %s\n",
936 data->volumes[j]->chronology);
937 if (data->volumes[j]->enumAndChron)
938 printf (" enumAndChron: %s\n",
939 data->volumes[j]->enumAndChron);
941 for (j = 0; j<data->num_circulationData; j++)
943 printf ("circulation %d\n", j);
944 if (data->circulationData[j]->availableNow)
945 printf (" availableNow: %d\n",
946 *data->circulationData[j]->availableNow);
947 if (data->circulationData[j]->availablityDate)
948 printf (" availabiltyDate: %s\n",
949 data->circulationData[j]->availablityDate);
950 if (data->circulationData[j]->availableThru)
951 printf (" availableThru: %s\n",
952 data->circulationData[j]->availableThru);
953 if (data->circulationData[j]->restrictions)
954 printf (" restrictions: %s\n",
955 data->circulationData[j]->restrictions);
956 if (data->circulationData[j]->itemId)
957 printf (" itemId: %s\n",
958 data->circulationData[j]->itemId);
959 if (data->circulationData[j]->renewable)
960 printf (" renewable: %d\n",
961 *data->circulationData[j]->renewable);
962 if (data->circulationData[j]->onHold)
963 printf (" onHold: %d\n",
964 *data->circulationData[j]->onHold);
965 if (data->circulationData[j]->enumAndChron)
966 printf (" enumAndChron: %s\n",
967 data->circulationData[j]->enumAndChron);
968 if (data->circulationData[j]->midspine)
969 printf (" midspine: %s\n",
970 data->circulationData[j]->midspine);
971 if (data->circulationData[j]->temporaryLocation)
972 printf (" temporaryLocation: %s\n",
973 data->circulationData[j]->temporaryLocation);
980 printf("Unknown record representation.\n");
981 if (!z_External(print, &r, 0, 0))
983 odr_perror(print, "Printing external");
989 static void display_diagrecs(Z_DiagRec **pp, int num)
993 Z_DefaultDiagFormat *r;
995 printf("Diagnostic message(s) from database:\n");
996 for (i = 0; i<num; i++)
998 Z_DiagRec *p = pp[i];
999 if (p->which != Z_DiagRec_defaultFormat)
1001 printf("Diagnostic record not in default format.\n");
1005 r = p->u.defaultFormat;
1006 if (!(ent = oid_getentbyoid(r->diagnosticSetId)) ||
1007 ent->oclass != CLASS_DIAGSET || ent->value != VAL_BIB1)
1008 printf("Missing or unknown diagset\n");
1009 printf(" [%d] %s", *r->condition, diagbib1_str(*r->condition));
1012 case Z_DefaultDiagFormat_v2Addinfo:
1013 printf (" -- v2 addinfo '%s'\n", r->u.v2Addinfo);
1015 case Z_DefaultDiagFormat_v3Addinfo:
1016 printf (" -- v3 addinfo '%s'\n", r->u.v3Addinfo);
1023 static void display_nameplusrecord(Z_NamePlusRecord *p)
1025 if (p->databaseName)
1026 printf("[%s]", p->databaseName);
1027 if (p->which == Z_NamePlusRecord_surrogateDiagnostic)
1028 display_diagrecs(&p->u.surrogateDiagnostic, 1);
1029 else if (p->which == Z_NamePlusRecord_databaseRecord)
1030 display_record(p->u.databaseRecord);
1033 static void display_records(Z_Records *p)
1037 if (p->which == Z_Records_NSD)
1039 Z_DiagRec dr, *dr_p = &dr;
1040 dr.which = Z_DiagRec_defaultFormat;
1041 dr.u.defaultFormat = p->u.nonSurrogateDiagnostic;
1042 display_diagrecs (&dr_p, 1);
1044 else if (p->which == Z_Records_multipleNSD)
1045 display_diagrecs (p->u.multipleNonSurDiagnostics->diagRecs,
1046 p->u.multipleNonSurDiagnostics->num_diagRecs);
1049 printf("Records: %d\n", p->u.databaseOrSurDiagnostics->num_records);
1050 for (i = 0; i < p->u.databaseOrSurDiagnostics->num_records; i++)
1051 display_nameplusrecord(p->u.databaseOrSurDiagnostics->records[i]);
1055 static int send_deleteResultSetRequest(const char *arg)
1060 Z_APDU *apdu = zget_APDU(out, Z_APDU_deleteResultSetRequest);
1061 Z_DeleteResultSetRequest *req = apdu->u.deleteResultSetRequest;
1063 req->referenceId = set_refid (out);
1065 req->num_resultSetList =
1066 sscanf (arg, "%30s %30s %30s %30s %30s %30s %30s %30s",
1067 names[0], names[1], names[2], names[3],
1068 names[4], names[5], names[6], names[7]);
1070 req->deleteFunction = (int *)
1071 odr_malloc (out, sizeof(*req->deleteFunction));
1072 if (req->num_resultSetList > 0)
1074 *req->deleteFunction = Z_DeleteRequest_list;
1075 req->resultSetList = (char **)
1076 odr_malloc (out, sizeof(*req->resultSetList)*
1077 req->num_resultSetList);
1078 for (i = 0; i<req->num_resultSetList; i++)
1079 req->resultSetList[i] = names[i];
1083 *req->deleteFunction = Z_DeleteRequest_all;
1084 req->resultSetList = 0;
1088 printf("Sent deleteResultSetRequest.\n");
1093 static int send_srw(Z_SRW_PDU *sr)
1095 const char *charset = negotiationCharset;
1096 const char *host_port = cur_host;
1099 Z_SOAP_Handler h[2] = {
1100 {"http://www.loc.gov/zing/srw/", 0, (Z_SOAP_fun) yaz_srw_codec},
1103 ODR o = odr_createmem(ODR_ENCODE);
1105 Z_SOAP *p = odr_malloc(o, sizeof(*p));
1108 path = odr_malloc(out, strlen(databaseNames[0])+2);
1110 strcpy(path+1, databaseNames[0]);
1112 gdu = z_get_HTTP_Request(out);
1113 gdu->u.HTTP_Request->path = odr_strdup(out, path);
1117 const char *cp0 = strstr(host_port, "://");
1118 const char *cp1 = 0;
1124 cp1 = strchr(cp0, '/');
1126 cp1 = cp0+strlen(cp0);
1130 char *h = odr_malloc(out, cp1 - cp0 + 1);
1131 memcpy (h, cp0, cp1 - cp0);
1133 z_HTTP_header_add(out, &gdu->u.HTTP_Request->headers,
1138 strcpy(ctype, "text/xml");
1139 if (charset && strlen(charset) < 20)
1141 strcat(ctype, "; charset=");
1142 strcat(ctype, charset);
1144 z_HTTP_header_add(out, &gdu->u.HTTP_Request->headers,
1145 "Content-Type", ctype);
1146 z_HTTP_header_add(out, &gdu->u.HTTP_Request->headers,
1147 "SOAPAction", "\"\"");
1148 p->which = Z_SOAP_generic;
1149 p->u.generic = odr_malloc(o, sizeof(*p->u.generic));
1150 p->u.generic->no = 0;
1151 p->u.generic->ns = 0;
1152 p->u.generic->p = sr;
1153 p->ns = "http://schemas.xmlsoap.org/soap/envelope/";
1155 ret = z_soap_codec_enc(o, &p,
1156 &gdu->u.HTTP_Request->content_buf,
1157 &gdu->u.HTTP_Request->content_len, h,
1160 if (z_GDU(out, &gdu, 0, 0))
1168 if (!z_GDU(print, &gdu, 0, 0))
1169 printf ("Failed to print outgoing APDU\n");
1172 buf_out = odr_getbuf(out, &len_out, 0);
1174 /* we don't odr_reset(out), since we may need the buffer again */
1176 do_hex_dump(buf_out, len_out);
1178 r = cs_put(conn, buf_out, len_out);
1190 static int send_SRW_searchRequest(const char *arg)
1196 assert(srw_sr_odr_out == 0);
1197 srw_sr_odr_out = odr_createmem(ODR_ENCODE);
1199 odr_reset(srw_sr_odr_out);
1203 /* save this for later .. when fetching individual records */
1204 srw_sr = sr = yaz_srw_get(srw_sr_odr_out, Z_SRW_searchRetrieve_request);
1205 sr->u.request->query_type = Z_SRW_query_type_cql;
1206 sr->u.request->query.cql = odr_strdup(srw_sr_odr_out, arg);
1208 sr = yaz_srw_get(out, Z_SRW_searchRetrieve_request);
1209 sr->u.request->query_type = Z_SRW_query_type_cql;
1210 sr->u.request->query.cql = odr_strdup(out, arg);
1212 sr->u.request->maximumRecords = odr_intdup(out, 0);
1215 sr->u.request->recordSchema = record_schema;
1216 return send_srw(sr);
1220 static int send_searchRequest(const char *arg)
1222 Z_APDU *apdu = zget_APDU(out, Z_APDU_searchRequest);
1223 Z_SearchRequest *req = apdu->u.searchRequest;
1226 struct ccl_rpn_node *rpn = NULL;
1228 char setstring[100];
1229 Z_RPNQuery *RPNquery;
1231 YAZ_PQF_Parser pqf_parser;
1233 QueryType myQueryType = queryType;
1236 if (myQueryType == QueryType_CCL2RPN)
1238 rpn = ccl_find_str(bibset, arg, &error, &pos);
1241 printf("CCL ERROR: %s\n", ccl_err_msg(error));
1244 } else if (myQueryType == QueryType_CQL2RPN) {
1245 /* ### All this code should be wrapped in a utility function */
1247 struct cql_node *node;
1248 const char *addinfo;
1249 if (cqltrans == 0) {
1250 printf("Can't use CQL: no translation file. Try set_cqlfile\n");
1253 parser = cql_parser_create();
1254 if ((error = cql_parser_string(parser, arg)) != 0) {
1255 printf("Can't parse CQL: must be a syntax error\n");
1258 node = cql_parser_result(parser);
1259 if ((error = cql_transform_buf(cqltrans, node, pqfbuf,
1260 sizeof pqfbuf)) != 0) {
1261 error = cql_transform_error(cqltrans, &addinfo);
1262 printf ("Can't convert CQL to PQF: %s (addinfo=%s)\n",
1263 cql_strerror(error), addinfo);
1267 myQueryType = QueryType_Prefix;
1270 req->referenceId = set_refid (out);
1271 if (!strcmp(arg, "@big")) /* strictly for troublemaking */
1273 static unsigned char big[2100];
1274 static Odr_oct bigo;
1276 /* send a very big referenceid to test transport stack etc. */
1277 memset(big, 'A', 2100);
1278 bigo.len = bigo.size = 2100;
1280 req->referenceId = &bigo;
1285 sprintf(setstring, "%d", ++setnumber);
1286 req->resultSetName = setstring;
1288 *req->smallSetUpperBound = smallSetUpperBound;
1289 *req->largeSetLowerBound = largeSetLowerBound;
1290 *req->mediumSetPresentNumber = mediumSetPresentNumber;
1291 if (smallSetUpperBound > 0 || (largeSetLowerBound > 1 &&
1292 mediumSetPresentNumber > 0))
1296 prefsyn.proto = protocol;
1297 prefsyn.oclass = CLASS_RECSYN;
1298 prefsyn.value = recordsyntax;
1299 req->preferredRecordSyntax =
1300 odr_oiddup(out, oid_ent_to_oid(&prefsyn, oid));
1301 req->smallSetElementSetNames =
1302 req->mediumSetElementSetNames = elementSetNames;
1304 req->num_databaseNames = num_databaseNames;
1305 req->databaseNames = databaseNames;
1307 req->query = &query;
1309 switch (myQueryType)
1311 case QueryType_Prefix:
1312 query.which = Z_Query_type_1;
1313 pqf_parser = yaz_pqf_create ();
1314 RPNquery = yaz_pqf_parse (pqf_parser, out, arg);
1317 const char *pqf_msg;
1319 int code = yaz_pqf_error (pqf_parser, &pqf_msg, &off);
1320 printf("%*s^\n", off+4, "");
1321 printf("Prefix query error: %s (code %d)\n", pqf_msg, code);
1323 yaz_pqf_destroy (pqf_parser);
1326 yaz_pqf_destroy (pqf_parser);
1327 query.u.type_1 = RPNquery;
1330 query.which = Z_Query_type_2;
1331 query.u.type_2 = &ccl_query;
1332 ccl_query.buf = (unsigned char*) arg;
1333 ccl_query.len = strlen(arg);
1335 case QueryType_CCL2RPN:
1336 query.which = Z_Query_type_1;
1337 RPNquery = ccl_rpn_query(out, rpn);
1340 printf ("Couldn't convert from CCL to RPN\n");
1343 query.u.type_1 = RPNquery;
1344 ccl_rpn_delete (rpn);
1347 query.which = Z_Query_type_104;
1348 ext = (Z_External *) odr_malloc(out, sizeof(*ext));
1349 ext->direct_reference = odr_getoidbystr(out, "1.2.840.10003.16.2");
1350 ext->indirect_reference = 0;
1351 ext->descriptor = 0;
1352 ext->which = Z_External_CQL;
1353 ext->u.cql = odr_strdup(out, arg);
1354 query.u.type_104 = ext;
1357 printf ("Unsupported query type\n");
1360 if (send_apdu(apdu))
1361 printf("Sent searchRequest.\n");
1366 /* display Query Expression as part of searchResult-1 */
1367 static void display_queryExpression (Z_QueryExpression *qe)
1371 if (qe->which == Z_QueryExpression_term)
1373 if (qe->u.term->queryTerm)
1375 Z_Term *term = qe->u.term->queryTerm;
1376 switch (term->which)
1378 case Z_Term_general:
1379 printf (" %.*s", term->u.general->len, term->u.general->buf);
1381 case Z_Term_characterString:
1382 printf (" %s", term->u.characterString);
1384 case Z_Term_numeric:
1385 printf (" %d", *term->u.numeric);
1395 /* see if we can find USR:SearchResult-1 */
1396 static void display_searchResult (Z_OtherInformation *o)
1401 for (i = 0; i < o->num_elements; i++)
1403 if (o->list[i]->which == Z_OtherInfo_externallyDefinedInfo)
1405 Z_External *ext = o->list[i]->information.externallyDefinedInfo;
1407 if (ext->which == Z_External_searchResult1)
1410 Z_SearchInfoReport *sr = ext->u.searchResult1;
1411 printf ("SearchResult-1:");
1412 for (j = 0; j < sr->num; j++)
1414 if (!sr->elements[j]->subqueryExpression)
1416 display_queryExpression (
1417 sr->elements[j]->subqueryExpression);
1418 display_queryExpression (
1419 sr->elements[j]->subqueryInterpretation);
1420 display_queryExpression (
1421 sr->elements[j]->subqueryRecommendation);
1422 if (sr->elements[j]->subqueryCount)
1423 printf ("(%d)", *sr->elements[j]->subqueryCount);
1431 static int process_searchResponse(Z_SearchResponse *res)
1433 printf ("Received SearchResponse.\n");
1434 print_refid (res->referenceId);
1435 if (*res->searchStatus)
1436 printf("Search was a success.\n");
1438 printf("Search was a bloomin' failure.\n");
1439 printf("Number of hits: %d", *res->resultCount);
1441 printf (", setno %d", setnumber);
1443 display_searchResult (res->additionalSearchInfo);
1444 printf("records returned: %d\n",
1445 *res->numberOfRecordsReturned);
1446 setno += *res->numberOfRecordsReturned;
1448 display_records(res->records);
1452 static void print_level(int iLevel)
1455 for (i = 0; i < iLevel * 4; i++)
1459 static void print_int(int iLevel, const char *pTag, int *pInt)
1463 print_level(iLevel);
1464 printf("%s: %d\n", pTag, *pInt);
1468 static void print_string(int iLevel, const char *pTag, const char *pString)
1470 if (pString != NULL)
1472 print_level(iLevel);
1473 printf("%s: %s\n", pTag, pString);
1477 static void print_oid(int iLevel, const char *pTag, Odr_oid *pOid)
1483 print_level(iLevel);
1484 printf("%s:", pTag);
1485 for (; *pInt != -1; pInt++)
1486 printf(" %d", *pInt);
1491 static void print_referenceId(int iLevel, Z_ReferenceId *referenceId)
1493 if (referenceId != NULL)
1497 print_level(iLevel);
1498 printf("Ref Id (%d, %d): ", referenceId->len, referenceId->size);
1499 for (i = 0; i < referenceId->len; i++)
1500 printf("%c", referenceId->buf[i]);
1505 static void print_string_or_numeric(int iLevel, const char *pTag, Z_StringOrNumeric *pStringNumeric)
1507 if (pStringNumeric != NULL)
1509 switch (pStringNumeric->which)
1511 case Z_StringOrNumeric_string:
1512 print_string(iLevel, pTag, pStringNumeric->u.string);
1515 case Z_StringOrNumeric_numeric:
1516 print_int(iLevel, pTag, pStringNumeric->u.numeric);
1520 print_level(iLevel);
1521 printf("%s: valid type for Z_StringOrNumeric\n", pTag);
1527 static void print_universe_report_duplicate(
1529 Z_UniverseReportDuplicate *pUniverseReportDuplicate)
1531 if (pUniverseReportDuplicate != NULL)
1533 print_level(iLevel);
1534 printf("Universe Report Duplicate: \n");
1536 print_string_or_numeric(iLevel, "Hit No",
1537 pUniverseReportDuplicate->hitno);
1541 static void print_universe_report_hits(
1543 Z_UniverseReportHits *pUniverseReportHits)
1545 if (pUniverseReportHits != NULL)
1547 print_level(iLevel);
1548 printf("Universe Report Hits: \n");
1550 print_string_or_numeric(iLevel, "Database",
1551 pUniverseReportHits->database);
1552 print_string_or_numeric(iLevel, "Hits", pUniverseReportHits->hits);
1556 static void print_universe_report(int iLevel, Z_UniverseReport *pUniverseReport)
1558 if (pUniverseReport != NULL)
1560 print_level(iLevel);
1561 printf("Universe Report: \n");
1563 print_int(iLevel, "Total Hits", pUniverseReport->totalHits);
1564 switch (pUniverseReport->which)
1566 case Z_UniverseReport_databaseHits:
1567 print_universe_report_hits(iLevel,
1568 pUniverseReport->u.databaseHits);
1571 case Z_UniverseReport_duplicate:
1572 print_universe_report_duplicate(iLevel,
1573 pUniverseReport->u.duplicate);
1577 print_level(iLevel);
1578 printf("Type: %d\n", pUniverseReport->which);
1584 static void print_external(int iLevel, Z_External *pExternal)
1586 if (pExternal != NULL)
1588 print_level(iLevel);
1589 printf("External: \n");
1591 print_oid(iLevel, "Direct Reference", pExternal->direct_reference);
1592 print_int(iLevel, "InDirect Reference", pExternal->indirect_reference);
1593 print_string(iLevel, "Descriptor", pExternal->descriptor);
1594 switch (pExternal->which)
1596 case Z_External_universeReport:
1597 print_universe_report(iLevel, pExternal->u.universeReport);
1601 print_level(iLevel);
1602 printf("Type: %d\n", pExternal->which);
1608 static int process_resourceControlRequest (Z_ResourceControlRequest *req)
1610 printf ("Received ResourceControlRequest.\n");
1611 print_referenceId(1, req->referenceId);
1612 print_int(1, "Suspended Flag", req->suspendedFlag);
1613 print_int(1, "Partial Results Available", req->partialResultsAvailable);
1614 print_int(1, "Response Required", req->responseRequired);
1615 print_int(1, "Triggered Request Flag", req->triggeredRequestFlag);
1616 print_external(1, req->resourceReport);
1620 void process_ESResponse(Z_ExtendedServicesResponse *res)
1623 switch (*res->operationStatus)
1625 case Z_ExtendedServicesResponse_done:
1628 case Z_ExtendedServicesResponse_accepted:
1629 printf ("accepted\n");
1631 case Z_ExtendedServicesResponse_failure:
1632 printf ("failure\n");
1633 display_diagrecs(res->diagnostics, res->num_diagnostics);
1636 printf ("unknown\n");
1638 if ( (*res->operationStatus != Z_ExtendedServicesResponse_failure) &&
1639 (res->num_diagnostics != 0) ) {
1640 display_diagrecs(res->diagnostics, res->num_diagnostics);
1642 print_refid (res->referenceId);
1643 if (res->taskPackage &&
1644 res->taskPackage->which == Z_External_extendedService)
1646 Z_TaskPackage *taskPackage = res->taskPackage->u.extendedService;
1647 Odr_oct *id = taskPackage->targetReference;
1648 Z_External *ext = taskPackage->taskSpecificParameters;
1652 printf ("Target Reference: ");
1653 print_stringn (id->buf, id->len);
1656 if (ext->which == Z_External_update)
1658 Z_IUUpdateTaskPackage *utp = ext->u.update->u.taskPackage;
1659 if (utp && utp->targetPart)
1661 Z_IUTargetPart *targetPart = utp->targetPart;
1664 for (i = 0; i<targetPart->num_taskPackageRecords; i++)
1667 Z_IUTaskPackageRecordStructure *tpr =
1668 targetPart->taskPackageRecords[i];
1669 printf ("task package record %d\n", i+1);
1670 if (tpr->which == Z_IUTaskPackageRecordStructure_record)
1672 display_record (tpr->u.record);
1676 printf ("other type\n");
1684 const char *get_ill_element (void *clientData, const char *element)
1689 static Z_External *create_external_itemRequest()
1691 struct ill_get_ctl ctl;
1692 ILL_ItemRequest *req;
1694 int item_request_size = 0;
1695 char *item_request_buf = 0;
1699 ctl.f = get_ill_element;
1701 req = ill_get_ItemRequest(&ctl, "ill", 0);
1703 printf ("ill_get_ItemRequest failed\n");
1705 if (!ill_ItemRequest (out, &req, 0, 0))
1709 ill_ItemRequest(print, &req, 0, 0);
1712 item_request_buf = odr_getbuf (out, &item_request_size, 0);
1713 if (item_request_buf)
1714 odr_setbuf (out, item_request_buf, item_request_size, 1);
1715 printf ("Couldn't encode ItemRequest, size %d\n", item_request_size);
1722 item_request_buf = odr_getbuf (out, &item_request_size, 0);
1723 oid.proto = PROTO_GENERAL;
1724 oid.oclass = CLASS_GENERAL;
1725 oid.value = VAL_ISO_ILL_1;
1727 r = (Z_External *) odr_malloc (out, sizeof(*r));
1728 r->direct_reference = odr_oiddup(out,oid_getoidbyent(&oid));
1729 r->indirect_reference = 0;
1731 r->which = Z_External_single;
1733 r->u.single_ASN1_type = (Odr_oct *)
1734 odr_malloc (out, sizeof(*r->u.single_ASN1_type));
1735 r->u.single_ASN1_type->buf = (unsigned char *)
1736 odr_malloc (out, item_request_size);
1737 r->u.single_ASN1_type->len = item_request_size;
1738 r->u.single_ASN1_type->size = item_request_size;
1739 memcpy (r->u.single_ASN1_type->buf, item_request_buf,
1742 do_hex_dump(item_request_buf,item_request_size);
1747 static Z_External *create_external_ILL_APDU(int which)
1749 struct ill_get_ctl ctl;
1752 int ill_request_size = 0;
1753 char *ill_request_buf = 0;
1757 ctl.f = get_ill_element;
1759 ill_apdu = ill_get_APDU(&ctl, "ill", 0);
1761 if (!ill_APDU (out, &ill_apdu, 0, 0))
1765 printf ("-------------------\n");
1766 ill_APDU(print, &ill_apdu, 0, 0);
1768 printf ("-------------------\n");
1770 ill_request_buf = odr_getbuf (out, &ill_request_size, 0);
1771 if (ill_request_buf)
1772 odr_setbuf (out, ill_request_buf, ill_request_size, 1);
1773 printf ("Couldn't encode ILL-Request, size %d\n", ill_request_size);
1779 ill_request_buf = odr_getbuf (out, &ill_request_size, 0);
1781 oid.proto = PROTO_GENERAL;
1782 oid.oclass = CLASS_GENERAL;
1783 oid.value = VAL_ISO_ILL_1;
1785 r = (Z_External *) odr_malloc (out, sizeof(*r));
1786 r->direct_reference = odr_oiddup(out,oid_getoidbyent(&oid));
1787 r->indirect_reference = 0;
1789 r->which = Z_External_single;
1791 r->u.single_ASN1_type = (Odr_oct *)
1792 odr_malloc (out, sizeof(*r->u.single_ASN1_type));
1793 r->u.single_ASN1_type->buf = (unsigned char *)
1794 odr_malloc (out, ill_request_size);
1795 r->u.single_ASN1_type->len = ill_request_size;
1796 r->u.single_ASN1_type->size = ill_request_size;
1797 memcpy (r->u.single_ASN1_type->buf, ill_request_buf, ill_request_size);
1798 /* printf ("len = %d\n", ill_request_size); */
1799 /* do_hex_dump(ill_request_buf,ill_request_size); */
1800 /* printf("--- end of extenal\n"); */
1807 static Z_External *create_ItemOrderExternal(const char *type, int itemno)
1809 Z_External *r = (Z_External *) odr_malloc(out, sizeof(Z_External));
1810 oident ItemOrderRequest;
1812 ItemOrderRequest.proto = PROTO_Z3950;
1813 ItemOrderRequest.oclass = CLASS_EXTSERV;
1814 ItemOrderRequest.value = VAL_ITEMORDER;
1816 r->direct_reference = odr_oiddup(out,oid_getoidbyent(&ItemOrderRequest));
1817 r->indirect_reference = 0;
1820 r->which = Z_External_itemOrder;
1822 r->u.itemOrder = (Z_ItemOrder *) odr_malloc(out,sizeof(Z_ItemOrder));
1823 memset(r->u.itemOrder, 0, sizeof(Z_ItemOrder));
1824 r->u.itemOrder->which=Z_IOItemOrder_esRequest;
1826 r->u.itemOrder->u.esRequest = (Z_IORequest *)
1827 odr_malloc(out,sizeof(Z_IORequest));
1828 memset(r->u.itemOrder->u.esRequest, 0, sizeof(Z_IORequest));
1830 r->u.itemOrder->u.esRequest->toKeep = (Z_IOOriginPartToKeep *)
1831 odr_malloc(out,sizeof(Z_IOOriginPartToKeep));
1832 memset(r->u.itemOrder->u.esRequest->toKeep, 0, sizeof(Z_IOOriginPartToKeep));
1833 r->u.itemOrder->u.esRequest->notToKeep = (Z_IOOriginPartNotToKeep *)
1834 odr_malloc(out,sizeof(Z_IOOriginPartNotToKeep));
1835 memset(r->u.itemOrder->u.esRequest->notToKeep, 0, sizeof(Z_IOOriginPartNotToKeep));
1837 r->u.itemOrder->u.esRequest->toKeep->supplDescription = NULL;
1838 r->u.itemOrder->u.esRequest->toKeep->contact = NULL;
1839 r->u.itemOrder->u.esRequest->toKeep->addlBilling = NULL;
1841 r->u.itemOrder->u.esRequest->notToKeep->resultSetItem =
1842 (Z_IOResultSetItem *) odr_malloc(out, sizeof(Z_IOResultSetItem));
1843 memset(r->u.itemOrder->u.esRequest->notToKeep->resultSetItem, 0, sizeof(Z_IOResultSetItem));
1844 r->u.itemOrder->u.esRequest->notToKeep->resultSetItem->resultSetId = "1";
1846 r->u.itemOrder->u.esRequest->notToKeep->resultSetItem->item =
1847 (int *) odr_malloc(out, sizeof(int));
1848 *r->u.itemOrder->u.esRequest->notToKeep->resultSetItem->item = itemno;
1850 if (!strcmp (type, "item") || !strcmp(type, "2"))
1852 printf ("using item-request\n");
1853 r->u.itemOrder->u.esRequest->notToKeep->itemRequest =
1854 create_external_itemRequest();
1856 else if (!strcmp(type, "ill") || !strcmp(type, "1"))
1858 printf ("using ILL-request\n");
1859 r->u.itemOrder->u.esRequest->notToKeep->itemRequest =
1860 create_external_ILL_APDU(ILL_APDU_ILL_Request);
1862 else if (!strcmp(type, "xml") || !strcmp(type, "3"))
1864 const char *xml_buf =
1866 " <type>request</type>\n"
1867 " <libraryNo>000200</libraryNo>\n"
1868 " <borrowerTicketNo> 1212 </borrowerTicketNo>\n"
1870 r->u.itemOrder->u.esRequest->notToKeep->itemRequest =
1871 z_ext_record (out, VAL_TEXT_XML, xml_buf, strlen(xml_buf));
1874 r->u.itemOrder->u.esRequest->notToKeep->itemRequest = 0;
1879 static int send_itemorder(const char *type, int itemno)
1881 Z_APDU *apdu = zget_APDU(out, Z_APDU_extendedServicesRequest);
1882 Z_ExtendedServicesRequest *req = apdu->u.extendedServicesRequest;
1883 oident ItemOrderRequest;
1885 ItemOrderRequest.proto = PROTO_Z3950;
1886 ItemOrderRequest.oclass = CLASS_EXTSERV;
1887 ItemOrderRequest.value = VAL_ITEMORDER;
1888 req->packageType = odr_oiddup(out,oid_getoidbyent(&ItemOrderRequest));
1889 req->packageName = esPackageName;
1891 req->taskSpecificParameters = create_ItemOrderExternal(type, itemno);
1897 static int only_z3950()
1899 if (protocol == PROTO_HTTP)
1901 printf ("Not supported by SRW\n");
1907 static int cmd_update_common(const char *arg, int version);
1909 static int cmd_update(const char *arg)
1911 return cmd_update_common(arg, 1);
1914 static int cmd_update0(const char *arg)
1916 return cmd_update_common(arg, 0);
1919 static int cmd_update_common(const char *arg, int version)
1921 Z_APDU *apdu = zget_APDU(out, Z_APDU_extendedServicesRequest );
1922 Z_ExtendedServicesRequest *req = apdu->u.extendedServicesRequest;
1926 char action[20], recid[20], fname[80];
1928 Z_External *record_this = 0;
1935 sscanf (arg, "%19s %19s %79s", action, recid, fname);
1937 if (!strcmp (action, "insert"))
1938 action_no = Z_IUOriginPartToKeep_recordInsert;
1939 else if (!strcmp (action, "replace"))
1940 action_no = Z_IUOriginPartToKeep_recordReplace;
1941 else if (!strcmp (action, "delete"))
1942 action_no = Z_IUOriginPartToKeep_recordDelete;
1943 else if (!strcmp (action, "update"))
1944 action_no = Z_IUOriginPartToKeep_specialUpdate;
1947 printf ("Bad action: %s\n", action);
1948 printf ("Possible values: insert, replace, delete, update\n");
1956 stat (fname, &status);
1957 if (S_ISREG(status.st_mode) && (inf = fopen(fname, "r")))
1959 size_t len = status.st_size;
1960 char *buf = (char *) xmalloc (len);
1962 fread (buf, 1, len, inf);
1966 record_this = z_ext_record (out, VAL_TEXT_XML, buf, len);
1972 printf ("File %s doesn't exist\n", fname);
1980 printf ("No last record (update ignored)\n");
1983 record_this = record_last;
1986 update_oid.proto = PROTO_Z3950;
1987 update_oid.oclass = CLASS_EXTSERV;
1989 update_oid.value = VAL_DBUPDATE0;
1991 update_oid.value = VAL_DBUPDATE;
1992 oid_ent_to_oid (&update_oid, oid);
1993 req->packageType = odr_oiddup(out,oid);
1994 req->packageName = esPackageName;
1996 req->referenceId = set_refid (out);
1998 r = req->taskSpecificParameters = (Z_External *)
1999 odr_malloc (out, sizeof(*r));
2000 r->direct_reference = odr_oiddup(out,oid);
2001 r->indirect_reference = 0;
2005 Z_IU0OriginPartToKeep *toKeep;
2006 Z_IU0SuppliedRecords *notToKeep;
2008 r->which = Z_External_update0;
2009 r->u.update0 = (Z_IU0Update *) odr_malloc(out, sizeof(*r->u.update0));
2010 r->u.update0->which = Z_IUUpdate_esRequest;
2011 r->u.update0->u.esRequest = (Z_IU0UpdateEsRequest *)
2012 odr_malloc(out, sizeof(*r->u.update0->u.esRequest));
2013 toKeep = r->u.update0->u.esRequest->toKeep = (Z_IU0OriginPartToKeep *)
2014 odr_malloc(out, sizeof(*r->u.update0->u.esRequest->toKeep));
2016 toKeep->databaseName = databaseNames[0];
2018 toKeep->elementSetName = 0;
2020 toKeep->action = (int *) odr_malloc(out, sizeof(*toKeep->action));
2021 *toKeep->action = action_no;
2023 notToKeep = r->u.update0->u.esRequest->notToKeep = (Z_IU0SuppliedRecords *)
2024 odr_malloc(out, sizeof(*r->u.update0->u.esRequest->notToKeep));
2026 notToKeep->elements = (Z_IU0SuppliedRecords_elem **)
2027 odr_malloc(out, sizeof(*notToKeep->elements));
2028 notToKeep->elements[0] = (Z_IU0SuppliedRecords_elem *)
2029 odr_malloc(out, sizeof(**notToKeep->elements));
2030 notToKeep->elements[0]->which = Z_IUSuppliedRecords_elem_opaque;
2033 notToKeep->elements[0]->u.opaque = (Odr_oct *)
2034 odr_malloc (out, sizeof(Odr_oct));
2035 notToKeep->elements[0]->u.opaque->buf = (unsigned char *) recid;
2036 notToKeep->elements[0]->u.opaque->size = strlen(recid);
2037 notToKeep->elements[0]->u.opaque->len = strlen(recid);
2040 notToKeep->elements[0]->u.opaque = 0;
2041 notToKeep->elements[0]->supplementalId = 0;
2042 notToKeep->elements[0]->correlationInfo = 0;
2043 notToKeep->elements[0]->record = record_this;
2047 Z_IUOriginPartToKeep *toKeep;
2048 Z_IUSuppliedRecords *notToKeep;
2050 r->which = Z_External_update;
2051 r->u.update = (Z_IUUpdate *) odr_malloc(out, sizeof(*r->u.update));
2052 r->u.update->which = Z_IUUpdate_esRequest;
2053 r->u.update->u.esRequest = (Z_IUUpdateEsRequest *)
2054 odr_malloc(out, sizeof(*r->u.update->u.esRequest));
2055 toKeep = r->u.update->u.esRequest->toKeep = (Z_IUOriginPartToKeep *)
2056 odr_malloc(out, sizeof(*r->u.update->u.esRequest->toKeep));
2058 toKeep->databaseName = databaseNames[0];
2060 toKeep->elementSetName = 0;
2061 toKeep->actionQualifier = 0;
2062 toKeep->action = (int *) odr_malloc(out, sizeof(*toKeep->action));
2063 *toKeep->action = action_no;
2065 notToKeep = r->u.update->u.esRequest->notToKeep = (Z_IUSuppliedRecords *)
2066 odr_malloc(out, sizeof(*r->u.update->u.esRequest->notToKeep));
2068 notToKeep->elements = (Z_IUSuppliedRecords_elem **)
2069 odr_malloc(out, sizeof(*notToKeep->elements));
2070 notToKeep->elements[0] = (Z_IUSuppliedRecords_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;
2093 static int cmd_itemorder(const char *arg)
2100 if (sscanf (arg, "%10s %d", type, &itemno) != 2)
2103 printf("Item order request\n");
2105 send_itemorder(type, itemno);
2109 static void show_opt(const char *arg, void *clientData)
2111 printf ("%s ", arg);
2114 static int cmd_zversion(const char *arg)
2117 z3950_version = atoi(arg);
2119 printf ("version is %d\n", z3950_version);
2123 static int cmd_options(const char *arg)
2129 r = yaz_init_opt_encode(&z3950_options, arg, &pos);
2133 yaz_init_opt_decode(&z3950_options, show_opt, 0);
2139 static int cmd_explain(const char *arg)
2141 if (protocol != PROTO_HTTP)
2152 /* save this for later .. when fetching individual records */
2153 sr = yaz_srw_get(out, Z_SRW_explain_request);
2161 static int cmd_init(const char *arg)
2163 if (!conn || protocol != PROTO_Z3950)
2165 send_initRequest(0);
2169 static int cmd_find(const char *arg)
2173 printf("Find what?\n");
2176 if (protocol == PROTO_HTTP)
2183 if (!send_SRW_searchRequest(arg))
2196 printf("Not connected yet\n");
2200 if (!send_searchRequest(arg))
2206 static int cmd_delete(const char *arg)
2210 printf("Not connected yet\n");
2215 if (!send_deleteResultSetRequest(arg))
2220 static int cmd_ssub(const char *arg)
2222 if (!(smallSetUpperBound = atoi(arg)))
2227 static int cmd_lslb(const char *arg)
2231 if (!(largeSetLowerBound = atoi(arg)))
2236 static int cmd_mspn(const char *arg)
2240 if (!(mediumSetPresentNumber = atoi(arg)))
2245 static int cmd_status(const char *arg)
2247 printf("smallSetUpperBound: %d\n", smallSetUpperBound);
2248 printf("largeSetLowerBound: %d\n", largeSetLowerBound);
2249 printf("mediumSetPresentNumber: %d\n", mediumSetPresentNumber);
2253 static int cmd_setnames(const char *arg)
2255 if (*arg == '1') /* enable ? */
2257 else if (*arg == '0') /* disable ? */
2259 else if (setnumber < 0) /* no args, toggle .. */
2265 printf("Set numbering enabled.\n");
2267 printf("Set numbering disabled.\n");
2271 /* PRESENT SERVICE ----------------------------- */
2273 static void parse_show_args(const char *arg_c, char *setstring,
2274 int *start, int *number)
2279 strncpy(arg, arg_c, sizeof(arg)-1);
2280 arg[sizeof(arg)-1] = '\0';
2282 if ((p = strchr(arg, '+')))
2284 *number = atoi(p + 1);
2289 if (p && (p=strchr(p+1, '+')))
2290 strcpy (setstring, p+1);
2291 else if (setnumber >= 0)
2292 sprintf(setstring, "%d", setnumber);
2297 static int send_presentRequest(const char *arg)
2299 Z_APDU *apdu = zget_APDU(out, Z_APDU_presentRequest);
2300 Z_PresentRequest *req = apdu->u.presentRequest;
2301 Z_RecordComposition compo;
2305 char setstring[100];
2307 req->referenceId = set_refid (out);
2309 parse_show_args(arg, setstring, &setno, &nos);
2311 req->resultSetId = setstring;
2313 req->resultSetStartPoint = &setno;
2314 req->numberOfRecordsRequested = &nos;
2315 prefsyn.proto = protocol;
2316 prefsyn.oclass = CLASS_RECSYN;
2317 prefsyn.value = recordsyntax;
2318 req->preferredRecordSyntax =
2319 odr_oiddup (out, oid_ent_to_oid(&prefsyn, oid));
2325 prefschema.proto = protocol;
2326 prefschema.oclass = CLASS_SCHEMA;
2327 prefschema.value = oid_getvalbyname(record_schema);
2329 req->recordComposition = &compo;
2330 compo.which = Z_RecordComp_complex;
2331 compo.u.complex = (Z_CompSpec *)
2332 odr_malloc(out, sizeof(*compo.u.complex));
2333 compo.u.complex->selectAlternativeSyntax = (bool_t *)
2334 odr_malloc(out, sizeof(bool_t));
2335 *compo.u.complex->selectAlternativeSyntax = 0;
2337 compo.u.complex->generic = (Z_Specification *)
2338 odr_malloc(out, sizeof(*compo.u.complex->generic));
2339 compo.u.complex->generic->which = Z_Schema_oid;
2340 compo.u.complex->generic->schema.oid = (Odr_oid *)
2341 odr_oiddup(out, oid_ent_to_oid(&prefschema, oid));
2342 if (!compo.u.complex->generic->schema.oid)
2344 /* OID wasn't a schema! Try record syntax instead. */
2345 prefschema.oclass = CLASS_RECSYN;
2346 compo.u.complex->generic->schema.oid = (Odr_oid *)
2347 odr_oiddup(out, oid_ent_to_oid(&prefschema, oid));
2349 if (!elementSetNames)
2350 compo.u.complex->generic->elementSpec = 0;
2353 compo.u.complex->generic->elementSpec = (Z_ElementSpec *)
2354 odr_malloc(out, sizeof(Z_ElementSpec));
2355 compo.u.complex->generic->elementSpec->which =
2356 Z_ElementSpec_elementSetName;
2357 compo.u.complex->generic->elementSpec->u.elementSetName =
2358 elementSetNames->u.generic;
2360 compo.u.complex->num_dbSpecific = 0;
2361 compo.u.complex->dbSpecific = 0;
2362 compo.u.complex->num_recordSyntax = 0;
2363 compo.u.complex->recordSyntax = 0;
2365 else if (elementSetNames)
2367 req->recordComposition = &compo;
2368 compo.which = Z_RecordComp_simple;
2369 compo.u.simple = elementSetNames;
2372 printf("Sent presentRequest (%d+%d).\n", setno, nos);
2377 static int send_SRW_presentRequest(const char *arg)
2379 char setstring[100];
2381 Z_SRW_PDU *sr = srw_sr;
2385 parse_show_args(arg, setstring, &setno, &nos);
2386 sr->u.request->startRecord = odr_intdup(out, setno);
2387 sr->u.request->maximumRecords = odr_intdup(out, nos);
2389 sr->u.request->recordSchema = record_schema;
2390 return send_srw(sr);
2394 static void close_session (void)
2401 nmem_destroy (session_mem);
2410 void process_close(Z_Close *req)
2412 Z_APDU *apdu = zget_APDU(out, Z_APDU_close);
2413 Z_Close *res = apdu->u.close;
2415 static char *reasons[] =
2420 "cost limit reached",
2422 "security violation",
2429 printf("Reason: %s, message: %s\n", reasons[*req->closeReason],
2430 req->diagnosticInformation ? req->diagnosticInformation : "NULL");
2435 *res->closeReason = Z_Close_finished;
2437 printf("Sent response.\n");
2442 static int cmd_show(const char *arg)
2444 if (protocol == PROTO_HTTP)
2451 if (!send_SRW_presentRequest(arg))
2461 printf("Not connected yet\n");
2464 if (!send_presentRequest(arg))
2470 int cmd_quit(const char *arg)
2472 printf("See you later, alligator.\n");
2478 int cmd_cancel(const char *arg)
2480 Z_APDU *apdu = zget_APDU(out, Z_APDU_triggerResourceControlRequest);
2481 Z_TriggerResourceControlRequest *req =
2482 apdu->u.triggerResourceControlRequest;
2487 printf("Session not initialized yet\n");
2492 if (!ODR_MASK_GET(session->options, Z_Options_triggerResourceCtrl))
2494 printf("Target doesn't support cancel (trigger resource ctrl)\n");
2497 *req->requestedAction = Z_TriggerResourceCtrl_cancel;
2498 req->resultSetWanted = &rfalse;
2501 printf("Sent cancel request\n");
2505 int send_scanrequest(const char *query, int pp, int num, const char *term)
2507 Z_APDU *apdu = zget_APDU(out, Z_APDU_scanRequest);
2508 Z_ScanRequest *req = apdu->u.scanRequest;
2513 if (queryType == QueryType_CCL2RPN)
2517 struct ccl_rpn_node *rpn;
2519 rpn = ccl_find_str (bibset, query, &error, &pos);
2522 printf("CCL ERROR: %s\n", ccl_err_msg(error));
2525 bib1.proto = PROTO_Z3950;
2526 bib1.oclass = CLASS_ATTSET;
2527 bib1.value = VAL_BIB1;
2528 req->attributeSet = oid_ent_to_oid (&bib1, oid);
2529 if (!(req->termListAndStartPoint = ccl_scan_query (out, rpn)))
2531 printf("Couldn't convert CCL to Scan term\n");
2534 ccl_rpn_delete (rpn);
2538 YAZ_PQF_Parser pqf_parser = yaz_pqf_create ();
2540 if (!(req->termListAndStartPoint =
2541 yaz_pqf_scan(pqf_parser, out, &req->attributeSet, query)))
2543 const char *pqf_msg;
2545 int code = yaz_pqf_error (pqf_parser, &pqf_msg, &off);
2546 printf("%*s^\n", off+7, "");
2547 printf("Prefix query error: %s (code %d)\n", pqf_msg, code);
2548 yaz_pqf_destroy (pqf_parser);
2551 yaz_pqf_destroy (pqf_parser);
2555 if (req->termListAndStartPoint->term &&
2556 req->termListAndStartPoint->term->which == Z_Term_general &&
2557 req->termListAndStartPoint->term->u.general)
2559 req->termListAndStartPoint->term->u.general->buf =
2560 (unsigned char *) odr_strdup(out, term);
2561 req->termListAndStartPoint->term->u.general->len =
2562 req->termListAndStartPoint->term->u.general->size =
2566 req->referenceId = set_refid (out);
2567 req->num_databaseNames = num_databaseNames;
2568 req->databaseNames = databaseNames;
2569 req->numberOfTermsRequested = #
2570 req->preferredPositionInResponse = &pp;
2575 int send_sortrequest(const char *arg, int newset)
2577 Z_APDU *apdu = zget_APDU(out, Z_APDU_sortRequest);
2578 Z_SortRequest *req = apdu->u.sortRequest;
2579 Z_SortKeySpecList *sksl = (Z_SortKeySpecList *)
2580 odr_malloc (out, sizeof(*sksl));
2586 sprintf (setstring, "%d", setnumber);
2588 sprintf (setstring, "default");
2590 req->referenceId = set_refid (out);
2592 req->num_inputResultSetNames = 1;
2593 req->inputResultSetNames = (Z_InternationalString **)
2594 odr_malloc (out, sizeof(*req->inputResultSetNames));
2595 req->inputResultSetNames[0] = odr_strdup (out, setstring);
2597 if (newset && setnumber >= 0)
2598 sprintf (setstring, "%d", ++setnumber);
2600 req->sortedResultSetName = odr_strdup (out, setstring);
2602 req->sortSequence = yaz_sort_spec (out, arg);
2603 if (!req->sortSequence)
2605 printf ("Missing sort specifications\n");
2612 void display_term(Z_TermInfo *t)
2615 printf("%s", t->displayTerm);
2616 else if (t->term->which == Z_Term_general)
2618 printf("%.*s", t->term->u.general->len, t->term->u.general->buf);
2619 sprintf(last_scan_line, "%.*s", t->term->u.general->len,
2620 t->term->u.general->buf);
2623 printf("Term (not general)");
2624 if (t->globalOccurrences)
2625 printf (" (%d)\n", *t->globalOccurrences);
2630 void process_scanResponse(Z_ScanResponse *res)
2633 Z_Entry **entries = NULL;
2634 int num_entries = 0;
2636 printf("Received ScanResponse\n");
2637 print_refid (res->referenceId);
2638 printf("%d entries", *res->numberOfEntriesReturned);
2639 if (res->positionOfTerm)
2640 printf (", position=%d", *res->positionOfTerm);
2642 if (*res->scanStatus != Z_Scan_success)
2643 printf("Scan returned code %d\n", *res->scanStatus);
2646 if ((entries = res->entries->entries))
2647 num_entries = res->entries->num_entries;
2648 for (i = 0; i < num_entries; i++)
2650 int pos_term = res->positionOfTerm ? *res->positionOfTerm : -1;
2651 if (entries[i]->which == Z_Entry_termInfo)
2653 printf("%c ", i + 1 == pos_term ? '*' : ' ');
2654 display_term(entries[i]->u.termInfo);
2657 display_diagrecs(&entries[i]->u.surrogateDiagnostic, 1);
2659 if (res->entries->nonsurrogateDiagnostics)
2660 display_diagrecs (res->entries->nonsurrogateDiagnostics,
2661 res->entries->num_nonsurrogateDiagnostics);
2664 void process_sortResponse(Z_SortResponse *res)
2666 printf("Received SortResponse: status=");
2667 switch (*res->sortStatus)
2669 case Z_SortStatus_success:
2670 printf ("success"); break;
2671 case Z_SortStatus_partial_1:
2672 printf ("partial"); break;
2673 case Z_SortStatus_failure:
2674 printf ("failure"); break;
2676 printf ("unknown (%d)", *res->sortStatus);
2679 print_refid (res->referenceId);
2680 if (res->diagnostics)
2681 display_diagrecs(res->diagnostics,
2682 res->num_diagnostics);
2685 void process_deleteResultSetResponse (Z_DeleteResultSetResponse *res)
2687 printf("Got deleteResultSetResponse status=%d\n",
2688 *res->deleteOperationStatus);
2689 if (res->deleteListStatuses)
2692 for (i = 0; i < res->deleteListStatuses->num; i++)
2694 printf ("%s status=%d\n", res->deleteListStatuses->elements[i]->id,
2695 *res->deleteListStatuses->elements[i]->status);
2700 int cmd_sort_generic(const char *arg, int newset)
2704 printf("Session not initialized yet\n");
2709 if (!ODR_MASK_GET(session->options, Z_Options_sort))
2711 printf("Target doesn't support sort\n");
2716 if (send_sortrequest(arg, newset) < 0)
2723 int cmd_sort(const char *arg)
2725 return cmd_sort_generic (arg, 0);
2728 int cmd_sort_newset (const char *arg)
2730 return cmd_sort_generic (arg, 1);
2733 int cmd_scan(const char *arg)
2742 printf("Session not initialized yet\n");
2746 if (!ODR_MASK_GET(session->options, Z_Options_scan))
2748 printf("Target doesn't support scan\n");
2753 strcpy (last_scan_query, arg);
2754 if (send_scanrequest(arg, 1, 20, 0) < 0)
2759 if (send_scanrequest(last_scan_query, 1, 20, last_scan_line) < 0)
2765 int cmd_schema(const char *arg)
2767 xfree(record_schema);
2770 record_schema = xstrdup(arg);
2774 int cmd_format(const char *arg)
2779 printf("Usage: format <recordsyntax>\n");
2782 nsyntax = oid_getvalbyname (arg);
2783 if (strcmp(arg, "none") && nsyntax == VAL_NONE)
2785 printf ("unknown record syntax\n");
2788 recordsyntax = nsyntax;
2792 int cmd_elements(const char *arg)
2794 static Z_ElementSetNames esn;
2795 static char what[100];
2799 elementSetNames = 0;
2803 esn.which = Z_ElementSetNames_generic;
2804 esn.u.generic = what;
2805 elementSetNames = &esn;
2809 int cmd_attributeset(const char *arg)
2815 printf("Usage: attributeset <setname>\n");
2818 sscanf(arg, "%s", what);
2819 if (p_query_attset (what))
2821 printf("Unknown attribute set name\n");
2827 int cmd_querytype (const char *arg)
2829 if (!strcmp (arg, "ccl"))
2830 queryType = QueryType_CCL;
2831 else if (!strcmp (arg, "prefix") || !strcmp(arg, "rpn"))
2832 queryType = QueryType_Prefix;
2833 else if (!strcmp (arg, "ccl2rpn") || !strcmp (arg, "cclrpn"))
2834 queryType = QueryType_CCL2RPN;
2835 else if (!strcmp(arg, "cql"))
2836 queryType = QueryType_CQL;
2837 else if (!strcmp (arg, "cql2rpn") || !strcmp (arg, "cqlrpn"))
2838 queryType = QueryType_CQL2RPN;
2841 printf ("Querytype must be one of:\n");
2842 printf (" prefix - Prefix query\n");
2843 printf (" ccl - CCL query\n");
2844 printf (" ccl2rpn - CCL query converted to RPN\n");
2845 printf (" cql - CQL\n");
2846 printf (" cql2rpn - CQL query converted to RPN\n");
2852 int cmd_refid (const char *arg)
2858 refid = (char *) xmalloc (strlen(arg)+1);
2859 strcpy (refid, arg);
2864 int cmd_close(const char *arg)
2873 apdu = zget_APDU(out, Z_APDU_close);
2874 req = apdu->u.close;
2875 *req->closeReason = Z_Close_finished;
2877 printf("Sent close request.\n");
2882 int cmd_packagename(const char* arg)
2884 xfree (esPackageName);
2885 esPackageName = NULL;
2887 esPackageName = xstrdup(arg);
2891 int cmd_proxy(const char* arg)
2896 yazProxy = xstrdup (arg);
2900 int cmd_marccharset(const char *arg)
2905 if (sscanf(arg, "%29s", l1) < 1)
2907 xfree (marcCharset);
2909 if (strcmp(l1, "-"))
2910 marcCharset = xstrdup(l1);
2914 int cmd_charset(const char* arg)
2916 char l1[30], l2[30];
2919 if (sscanf(arg, "%29s %29s", l1, l2) < 1)
2921 printf("Current negotiation character set is `%s'\n",
2922 negotiationCharset ? negotiationCharset: "none");
2923 printf("Current output character set is `%s'\n",
2924 outputCharset ? outputCharset: "none");
2927 xfree (negotiationCharset);
2928 negotiationCharset = NULL;
2929 if (*l1 && strcmp(l1, "-"))
2931 negotiationCharset = xstrdup(l1);
2932 printf ("Character set negotiation : %s\n", negotiationCharset);
2935 printf ("Character set negotiation disabled\n");
2938 xfree (outputCharset);
2940 if (!strcmp(l2, "auto") && codeset)
2944 printf ("output charset: %s\n", codeset);
2945 outputCharset = xstrdup(codeset);
2950 printf ("No codeset found on this system\n");
2952 else if (strcmp(l2, "-"))
2953 outputCharset = xstrdup(l2);
2955 printf ("Output charset conversion disabled\n");
2961 int cmd_lang(const char* arg)
2964 printf("Current language is `%s'\n", (yazLang)?yazLang:NULL);
2971 yazLang = (char *) xmalloc (strlen(arg)+1);
2972 strcpy (yazLang, arg);
2977 int cmd_source(const char* arg)
2979 /* first should open the file and read one line at a time.. */
2981 char line[1024], *cp;
2984 fprintf(stderr,"Error in source command use a filename\n");
2988 includeFile = fopen (arg, "r");
2991 fprintf(stderr,"Unable to open file %s for reading\n",arg);
2995 while(!feof(includeFile)) {
2996 memset(line,0,sizeof(line));
2997 fgets(line,sizeof(line),includeFile);
2999 if(strlen(line) < 2) continue;
3000 if(line[0] == '#') continue;
3002 if ((cp = strrchr (line, '\n')))
3005 process_cmd_line(line);
3008 if(fclose(includeFile)<0) {
3009 perror("unable to close include file");
3015 int cmd_subshell(const char* args)
3020 system(getenv("SHELL"));
3026 int cmd_set_berfile(const char *arg)
3028 if (ber_file && ber_file != stdout && ber_file != stderr)
3030 if (!strcmp(arg, ""))
3032 else if (!strcmp(arg, "-"))
3035 ber_file = fopen(arg, "a");
3039 int cmd_set_apdufile(const char *arg)
3041 if(apdu_file && apdu_file != stderr && apdu_file != stderr)
3043 if (!strcmp(arg, ""))
3045 else if (!strcmp(arg, "-"))
3049 apdu_file = fopen(arg, "a");
3051 perror("unable to open apdu log file");
3054 odr_setprint(print, apdu_file);
3058 int cmd_set_cclfile(const char* arg)
3062 bibset = ccl_qual_mk ();
3063 inf = fopen (arg, "r");
3065 perror("unable to open CCL file");
3068 ccl_qual_file (bibset, inf);
3071 strcpy(ccl_fields,arg);
3075 int cmd_set_cqlfile(const char* arg)
3077 cql_transform_t newcqltrans;
3079 if ((newcqltrans = cql_transform_open_fname(arg)) == 0) {
3080 perror("unable to open CQL file");
3084 cql_transform_close(cqltrans);
3086 cqltrans = newcqltrans;
3087 strcpy(cql_fields, arg);
3091 int cmd_set_auto_reconnect(const char* arg)
3093 if(strlen(arg)==0) {
3094 auto_reconnect = ! auto_reconnect;
3095 } else if(strcmp(arg,"on")==0) {
3097 } else if(strcmp(arg,"off")==0) {
3100 printf("Error use on or off\n");
3105 printf("Set auto reconnect enabled.\n");
3107 printf("Set auto reconnect disabled.\n");
3112 int cmd_set_marcdump(const char* arg)
3114 if(marc_file && marc_file != stderr) { /* don't close stdout*/
3118 if (!strcmp(arg, ""))
3120 else if (!strcmp(arg, "-"))
3124 marc_file = fopen(arg, "a");
3126 perror("unable to open marc log file");
3132 this command takes 3 arge {name class oid}
3134 int cmd_register_oid(const char* args) {
3139 {"appctx",CLASS_APPCTX},
3140 {"absyn",CLASS_ABSYN},
3141 {"attset",CLASS_ATTSET},
3142 {"transyn",CLASS_TRANSYN},
3143 {"diagset",CLASS_DIAGSET},
3144 {"recsyn",CLASS_RECSYN},
3145 {"resform",CLASS_RESFORM},
3146 {"accform",CLASS_ACCFORM},
3147 {"extserv",CLASS_EXTSERV},
3148 {"userinfo",CLASS_USERINFO},
3149 {"elemspec",CLASS_ELEMSPEC},
3150 {"varset",CLASS_VARSET},
3151 {"schema",CLASS_SCHEMA},
3152 {"tagset",CLASS_TAGSET},
3153 {"general",CLASS_GENERAL},
3154 {0,(enum oid_class) 0}
3156 char oname_str[101], oclass_str[101], oid_str[101];
3159 oid_class oidclass = CLASS_GENERAL;
3160 int val = 0, oid[OID_SIZE];
3161 struct oident * new_oident=NULL;
3163 if (sscanf (args, "%100[^ ] %100[^ ] %100s",
3164 oname_str,oclass_str, oid_str) < 1) {
3165 printf("Error in regristrate command \n");
3169 for (i = 0; oid_classes[i].className; i++) {
3170 if (!strcmp(oid_classes[i].className, oclass_str))
3172 oidclass=oid_classes[i].oclass;
3177 if(!(oid_classes[i].className)) {
3178 printf("Unknonwn oid class %s\n",oclass_str);
3186 while (isdigit (*name))
3188 val = val*10 + (*name - '0');
3201 new_oident=oid_addent (oid,PROTO_GENERAL,oidclass,oname_str,VAL_DYNAMIC);
3202 if(strcmp(new_oident->desc,oname_str)) {
3203 fprintf(stderr,"oid is already named as %s, regristration faild\n",
3209 int cmd_push_command(const char* arg)
3211 #if HAVE_READLINE_HISTORY_H
3215 fprintf(stderr,"Not compiled with the readline/history module\n");
3220 void source_rcfile()
3222 /* Look for a $HOME/.yazclientrc and source it if it exists */
3223 struct stat statbuf;
3225 char* homedir=getenv("HOME");
3227 if(!homedir) return;
3229 sprintf(buffer,"%s/.yazclientrc",homedir);
3231 if(stat(buffer,&statbuf)==0) {
3235 if(stat(".yazclientrc",&statbuf)==0) {
3236 cmd_source(".yazclientrc");
3241 static void initialize(void)
3246 if (!(out = odr_createmem(ODR_ENCODE)) ||
3247 !(in = odr_createmem(ODR_DECODE)) ||
3248 !(print = odr_createmem(ODR_PRINT)))
3250 fprintf(stderr, "failed to allocate ODR streams\n");
3255 setvbuf(stdout, 0, _IONBF, 0);
3257 odr_setprint(print, apdu_file);
3259 bibset = ccl_qual_mk ();
3260 inf = fopen (ccl_fields, "r");
3263 ccl_qual_file (bibset, inf);
3267 cqltrans = cql_transform_open_fname(cql_fields);
3268 /* If this fails, no problem: we detect cqltrans == 0 later */
3270 #if HAVE_READLINE_READLINE_H
3271 rl_attempted_completion_function = (CPPFunction*)readline_completer;
3275 for(i=0; i<maxOtherInfosSupported; ++i) {
3276 extraOtherInfos[i].oidval = -1;
3283 #if HAVE_GETTIMEOFDAY
3284 struct timeval tv_start, tv_end;
3288 static void handle_srw_record(Z_SRW_record *rec)
3290 if (rec->recordPosition)
3292 printf ("pos=%d", *rec->recordPosition);
3293 setno = *rec->recordPosition + 1;
3295 if (rec->recordSchema)
3296 printf (" schema=%s", rec->recordSchema);
3298 if (rec->recordData_buf && rec->recordData_len)
3299 fwrite(rec->recordData_buf, 1, rec->recordData_len, stdout);
3301 printf ("No data!");
3305 static void handle_srw_explain_response(Z_SRW_explainResponse *res)
3307 handle_srw_record(&res->record);
3310 static void handle_srw_response(Z_SRW_searchRetrieveResponse *res)
3314 printf ("Received SRW SearchRetrieve Response\n");
3316 for (i = 0; i<res->num_diagnostics; i++)
3318 if (res->diagnostics[i].uri)
3319 printf ("SRW diagnostic %s\n",
3320 res->diagnostics[i].uri);
3322 printf ("SRW diagnostic missing or could not be decoded\n");
3323 if (res->diagnostics[i].message)
3324 printf ("Message: %s\n", res->diagnostics[i].message);
3325 if (res->diagnostics[i].details)
3326 printf ("Details: %s\n", res->diagnostics[i].details);
3328 if (res->numberOfRecords)
3329 printf ("Number of hits: %d\n", *res->numberOfRecords);
3330 for (i = 0; i<res->num_records; i++)
3331 handle_srw_record(res->records + i);
3334 static void http_response(Z_HTTP_Response *hres)
3337 const char *content_type = z_HTTP_header_lookup(hres->headers,
3339 const char *connection_head = z_HTTP_header_lookup(hres->headers,
3341 if (content_type && !yaz_strcmp_del("text/xml", content_type, "; "))
3343 Z_SOAP *soap_package = 0;
3344 ODR o = odr_createmem(ODR_DECODE);
3345 Z_SOAP_Handler soap_handlers[2] = {
3346 {"http://www.loc.gov/zing/srw/", 0,
3347 (Z_SOAP_fun) yaz_srw_codec},
3350 ret = z_soap_codec(o, &soap_package,
3351 &hres->content_buf, &hres->content_len,
3353 if (!ret && soap_package->which == Z_SOAP_generic &&
3354 soap_package->u.generic->no == 0)
3356 Z_SRW_PDU *sr = soap_package->u.generic->p;
3357 if (sr->which == Z_SRW_searchRetrieve_response)
3358 handle_srw_response(sr->u.response);
3359 else if (sr->which == Z_SRW_explain_response)
3360 handle_srw_explain_response(sr->u.explain_response);
3364 else if (soap_package && (soap_package->which == Z_SOAP_fault
3365 || soap_package->which == Z_SOAP_error))
3367 printf ("HTTP Error Status=%d\n", hres->code);
3368 printf ("SOAP Fault code %s\n",
3369 soap_package->u.fault->fault_code);
3370 printf ("SOAP Fault string %s\n",
3371 soap_package->u.fault->fault_string);
3372 if (soap_package->u.fault->details)
3373 printf ("SOAP Details %s\n",
3374 soap_package->u.fault->details);
3382 if (hres->code != 200)
3384 printf ("HTTP Error Status=%d\n", hres->code);
3388 printf ("Decoding of SRW package failed\n");
3394 if (!strcmp(hres->version, "1.0"))
3396 /* HTTP 1.0: only if Keep-Alive we stay alive.. */
3397 if (!connection_head || strcmp(connection_head, "Keep-Alive"))
3402 /* HTTP 1.1: only if no close we stay alive .. */
3403 if (connection_head && !strcmp(connection_head, "close"))
3410 void wait_and_handle_response()
3412 int reconnect_ok = 1;
3415 int netbufferlen = 0;
3420 res = cs_get(conn, &netbuffer, &netbufferlen);
3421 if (reconnect_ok && res <= 0 && protocol == PROTO_HTTP)
3432 buf_out = odr_getbuf(out, &len_out, 0);
3434 do_hex_dump(buf_out, len_out);
3436 cs_put(conn, buf_out, len_out);
3444 printf("Target closed connection\n");
3449 odr_reset(in); /* release APDU from last round */
3451 do_hex_dump(netbuffer, res);
3452 odr_setbuf(in, netbuffer, res, 0);
3454 if (!z_GDU(in, &gdu, 0, 0))
3456 FILE *f = ber_file ? ber_file : stdout;
3457 odr_perror(in, "Decoding incoming APDU");
3458 fprintf(f, "[Near %d]\n", odr_offset(in));
3459 fprintf(f, "Packet dump:\n---------\n");
3460 odr_dumpBER(f, netbuffer, res);
3461 fprintf(f, "---------\n");
3464 z_GDU(print, &gdu, 0, 0);
3467 if (conn && cs_more(conn))
3472 odr_dumpBER(ber_file, netbuffer, res);
3473 if (apdu_file && !z_GDU(print, &gdu, 0, 0))
3475 odr_perror(print, "Failed to print incoming APDU");
3479 if (gdu->which == Z_GDU_Z3950)
3481 Z_APDU *apdu = gdu->u.z3950;
3484 case Z_APDU_initResponse:
3485 process_initResponse(apdu->u.initResponse);
3487 case Z_APDU_searchResponse:
3488 process_searchResponse(apdu->u.searchResponse);
3490 case Z_APDU_scanResponse:
3491 process_scanResponse(apdu->u.scanResponse);
3493 case Z_APDU_presentResponse:
3494 print_refid (apdu->u.presentResponse->referenceId);
3496 *apdu->u.presentResponse->numberOfRecordsReturned;
3497 if (apdu->u.presentResponse->records)
3498 display_records(apdu->u.presentResponse->records);
3500 printf("No records.\n");
3501 printf ("nextResultSetPosition = %d\n",
3502 *apdu->u.presentResponse->nextResultSetPosition);
3504 case Z_APDU_sortResponse:
3505 process_sortResponse(apdu->u.sortResponse);
3507 case Z_APDU_extendedServicesResponse:
3508 printf("Got extended services response\n");
3509 process_ESResponse(apdu->u.extendedServicesResponse);
3512 printf("Target has closed the association.\n");
3513 process_close(apdu->u.close);
3515 case Z_APDU_resourceControlRequest:
3516 process_resourceControlRequest
3517 (apdu->u.resourceControlRequest);
3519 case Z_APDU_deleteResultSetResponse:
3520 process_deleteResultSetResponse(apdu->u.
3521 deleteResultSetResponse);
3524 printf("Received unknown APDU type (%d).\n",
3530 else if (gdu->which == Z_GDU_HTTP_Response)
3532 http_response(gdu->u.HTTP_Response);
3535 if (conn && !cs_more(conn))
3540 #if HAVE_GETTIMEOFDAY
3541 gettimeofday (&tv_end, 0);
3543 printf ("S/U S/U=%ld/%ld %ld/%ld",
3544 (long) tv_start.tv_sec,
3545 (long) tv_start.tv_usec,
3546 (long) tv_end.tv_sec,
3547 (long) tv_end.tv_usec);
3549 printf ("Elapsed: %.6f\n",
3550 (double) tv_end.tv_usec / 1e6 + tv_end.tv_sec -
3551 ((double) tv_start.tv_usec / 1e6 + tv_start.tv_sec));
3558 int cmd_cclparse(const char* arg)
3561 struct ccl_rpn_node *rpn=NULL;
3564 rpn = ccl_find_str (bibset, arg, &error, &pos);
3567 printf ("%*s^ - ", 3+strlen(last_cmd)+1+pos, " ");
3568 printf ("%s\n", ccl_err_msg (error));
3574 ccl_pr_tree(rpn, stdout);
3578 ccl_rpn_delete(rpn);
3586 int cmd_set_otherinfo(const char* args)
3588 char oid[101], otherinfoString[101];
3593 sscan_res = sscanf (args, "%d %100[^ ] %100s", &otherinfoNo, oid, otherinfoString);
3595 /* reset this otherinfo */
3596 if(otherinfoNo>=maxOtherInfosSupported) {
3597 printf("Error otherinfo index to large (%d>%d)\n",otherinfoNo,maxOtherInfosSupported);
3599 extraOtherInfos[otherinfoNo].oidval = -1;
3600 if(extraOtherInfos[otherinfoNo].value) free(extraOtherInfos[otherinfoNo].value);
3604 printf("Error in set_otherinfo command \n");
3608 if(otherinfoNo>=maxOtherInfosSupported) {
3609 printf("Error otherinfo index to large (%d>%d)\n",otherinfoNo,maxOtherInfosSupported);
3612 oidval = oid_getvalbyname (oid);
3614 printf("Error in set_otherinfo command unknown oid %s \n",oid);
3617 extraOtherInfos[otherinfoNo].oidval = oidval;
3618 if(extraOtherInfos[otherinfoNo].value) free(extraOtherInfos[otherinfoNo].value);
3619 extraOtherInfos[otherinfoNo].value = strdup(otherinfoString);
3624 int cmd_list_otherinfo(const char* args)
3628 if(strlen(args)>0) {
3630 if( i >= maxOtherInfosSupported ) {
3631 printf("Error otherinfo index to large (%d>%d)\n",i,maxOtherInfosSupported);
3635 if(extraOtherInfos[i].oidval != -1)
3636 printf(" otherinfo %d %s %s\n",
3638 yaz_z3950_oid_value_to_str(
3639 (enum oid_value) extraOtherInfos[i].oidval,
3641 extraOtherInfos[i].value);
3644 for(i=0; i<maxOtherInfosSupported; ++i) {
3645 if(extraOtherInfos[i].oidval != -1)
3646 printf(" otherinfo %d %s %s\n",
3648 yaz_z3950_oid_value_to_str(
3649 (enum oid_value) extraOtherInfos[i].oidval,
3651 extraOtherInfos[i].value);
3659 int cmd_list_all(const char* args) {
3662 /* connection options */
3664 printf("Connected to : %s\n",last_open_command);
3666 if(last_open_command)
3667 printf("Not connected to : %s\n",last_open_command);
3669 printf("Not connected : \n");
3672 if(yazProxy) printf("using proxy : %s\n",yazProxy);
3674 printf("auto_reconnect : %s\n",auto_reconnect?"on":"off");
3677 printf("Authentication : none\n");
3679 switch(auth->which) {
3680 case Z_IdAuthentication_idPass:
3681 printf("Authentication : IdPass\n");
3682 printf(" Login User : %s\n",auth->u.idPass->userId?auth->u.idPass->userId:"");
3683 printf(" Login Group : %s\n",auth->u.idPass->groupId?auth->u.idPass->groupId:"");
3684 printf(" Password : %s\n",auth->u.idPass->password?auth->u.idPass->password:"");
3686 case Z_IdAuthentication_open:
3687 printf("Authentication : psOpen\n");
3688 printf(" Open string : %s\n",auth->u.open);
3691 printf("Authentication : Unknown\n");
3694 if (negotiationCharset)
3695 printf("Neg. Character set : `%s'\n", negotiationCharset);
3699 for (i = 0; i<num_databaseNames; i++) printf("%s ",databaseNames[i]);
3703 printf("CCL file : %s\n",ccl_fields);
3704 printf("CQL file : %s\n",cql_fields);
3705 printf("Query type : %s\n",query_type_as_string(queryType));
3707 printf("Named Result Sets : %s\n",setnumber==-1?"off":"on");
3709 /* piggy back options */
3710 printf("ssub/lslb/mspn : %d/%d/%d\n",smallSetUpperBound,largeSetLowerBound,mediumSetPresentNumber);
3712 /* print present related options */
3713 printf("Format : %s\n",yaz_z3950_oid_value_to_str(recordsyntax,CLASS_RECSYN));
3714 printf("Schema : %s\n",record_schema ? record_schema : "not set");
3715 printf("Elements : %s\n",elementSetNames?elementSetNames->u.generic:"");
3717 /* loging options */
3718 printf("APDU log : %s\n",apdu_file?"on":"off");
3719 printf("Record log : %s\n",marc_file?"on":"off");
3722 printf("Other Info: \n");
3723 cmd_list_otherinfo("");
3728 int cmd_clear_otherinfo(const char* args)
3730 if(strlen(args)>0) {
3732 otherinfoNo = atoi(args);
3733 if( otherinfoNo >= maxOtherInfosSupported ) {
3734 printf("Error otherinfo index to large (%d>%d)\n",otherinfoNo,maxOtherInfosSupported);
3738 if(extraOtherInfos[otherinfoNo].oidval != -1) {
3739 /* only clear if set. */
3740 extraOtherInfos[otherinfoNo].oidval=-1;
3741 free(extraOtherInfos[otherinfoNo].value);
3746 for(i=0; i<maxOtherInfosSupported; ++i) {
3747 if (extraOtherInfos[i].oidval!=-1 ) {
3748 extraOtherInfos[i].oidval=-1;
3749 free(extraOtherInfos[i].value);
3756 static int cmd_help (const char *line);
3758 typedef char *(*completerFunctionType)(const char *text, int state);
3762 int (*fun)(const char *arg);
3764 completerFunctionType rl_completerfunction;
3765 int complete_filenames;
3766 char **local_tabcompletes;
3768 {"open", cmd_open, "('tcp'|'ssl')':<host>[':'<port>][/<db>]",NULL,0,NULL},
3769 {"quit", cmd_quit, "",NULL,0,NULL},
3770 {"find", cmd_find, "<query>",NULL,0,NULL},
3771 {"delete", cmd_delete, "<setname>",NULL,0,NULL},
3772 {"base", cmd_base, "<base-name>",NULL,0,NULL},
3773 {"show", cmd_show, "<rec#>['+'<#recs>['+'<setname>]]",NULL,0,NULL},
3774 {"scan", cmd_scan, "<term>",NULL,0,NULL},
3775 {"sort", cmd_sort, "<sortkey> <flag> <sortkey> <flag> ...",NULL,0,NULL},
3776 {"sort+", cmd_sort_newset, "<sortkey> <flag> <sortkey> <flag> ...",NULL,0,NULL},
3777 {"authentication", cmd_authentication, "<acctstring>",NULL,0,NULL},
3778 {"lslb", cmd_lslb, "<largeSetLowerBound>",NULL,0,NULL},
3779 {"ssub", cmd_ssub, "<smallSetUpperBound>",NULL,0,NULL},
3780 {"mspn", cmd_mspn, "<mediumSetPresentNumber>",NULL,0,NULL},
3781 {"status", cmd_status, "",NULL,0,NULL},
3782 {"setnames", cmd_setnames, "",NULL,0,NULL},
3783 {"cancel", cmd_cancel, "",NULL,0,NULL},
3784 {"format", cmd_format, "<recordsyntax>",complete_format,0,NULL},
3785 {"schema", cmd_schema, "<schema>",complete_schema,0,NULL},
3786 {"elements", cmd_elements, "<elementSetName>",NULL,0,NULL},
3787 {"close", cmd_close, "",NULL,0,NULL},
3788 {"attributeset", cmd_attributeset, "<attrset>",complete_attributeset,0,NULL},
3789 {"querytype", cmd_querytype, "<type>",complete_querytype,0,NULL},
3790 {"refid", cmd_refid, "<id>",NULL,0,NULL},
3791 {"itemorder", cmd_itemorder, "ill|item <itemno>",NULL,0,NULL},
3792 {"update", cmd_update, "<action> <recid> [<file>]",NULL,0,NULL},
3793 {"update0", cmd_update0, "<action> <recid> [<file>]",NULL,0,NULL},
3794 {"packagename", cmd_packagename, "<packagename>",NULL,0,NULL},
3795 {"proxy", cmd_proxy, "[('tcp'|'ssl')]<host>[':'<port>]",NULL,0,NULL},
3796 {"charset", cmd_charset, "<nego_charset> <output_charset>",NULL,0,NULL},
3797 {"marccharset", cmd_marccharset, "<charset_name>",NULL,0,NULL},
3798 {"lang", cmd_lang, "<language_code>",NULL,0,NULL},
3799 {".", cmd_source, "<filename>",NULL,1,NULL},
3800 {"!", cmd_subshell, "Subshell command",NULL,1,NULL},
3801 {"set_apdufile", cmd_set_apdufile, "<filename>",NULL,1,NULL},
3802 {"set_berfile", cmd_set_berfile, "<filename>",NULL,1,NULL},
3803 {"set_marcdump", cmd_set_marcdump," <filename>",NULL,1,NULL},
3804 {"set_cclfile", cmd_set_cclfile," <filename>",NULL,1,NULL},
3805 {"set_cqlfile", cmd_set_cqlfile," <filename>",NULL,1,NULL},
3806 {"set_auto_reconnect", cmd_set_auto_reconnect," on|off",complete_auto_reconnect,1,NULL},
3807 {"set_otherinfo", cmd_set_otherinfo,"<otherinfoinddex> <oid> <string>",NULL,0,NULL},
3808 {"register_oid", cmd_register_oid,"<name> <class> <oid>",NULL,0,NULL},
3809 {"push_command", cmd_push_command,"<command>",command_generator,0,NULL},
3810 {"register_tab", cmd_register_tab,"<commandname> <tab>",command_generator,0,NULL},
3811 {"cclparse", cmd_cclparse,"<ccl find command>",NULL,0,NULL},
3812 {"list_otherinfo",cmd_list_otherinfo,"[otherinfoinddex]",NULL,0,NULL},
3813 {"list_all",cmd_list_all,"",NULL,0,NULL},
3814 {"clear_otherinfo",cmd_clear_otherinfo,"",NULL,0,NULL},
3815 /* Server Admin Functions */
3816 {"adm-reindex", cmd_adm_reindex, "<database-name>",NULL,0,NULL},
3817 {"adm-truncate", cmd_adm_truncate, "('database'|'index')<object-name>",NULL,0,NULL},
3818 {"adm-create", cmd_adm_create, "",NULL,0,NULL},
3819 {"adm-drop", cmd_adm_drop, "('database'|'index')<object-name>",NULL,0,NULL},
3820 {"adm-import", cmd_adm_import, "<record-type> <dir> <pattern>",NULL,0,NULL},
3821 {"adm-refresh", cmd_adm_refresh, "",NULL,0,NULL},
3822 {"adm-commit", cmd_adm_commit, "",NULL,0,NULL},
3823 {"adm-shutdown", cmd_adm_shutdown, "",NULL,0,NULL},
3824 {"adm-startup", cmd_adm_startup, "",NULL,0,NULL},
3825 {"explain", cmd_explain, "", NULL, 0, NULL},
3826 {"options", cmd_options, "", NULL, 0, NULL},
3827 {"zversion", cmd_zversion, "", NULL, 0, NULL},
3828 {"help", cmd_help, "", NULL,0,NULL},
3829 {"init", cmd_init, "", NULL,0,NULL},
3833 static int cmd_help (const char *line)
3839 sscanf (line, "%20s", topic);
3842 printf("Commands:\n");
3843 for (i = 0; cmd_array[i].cmd; i++)
3844 if (*topic == 0 || strcmp (topic, cmd_array[i].cmd) == 0)
3845 printf(" %s %s\n", cmd_array[i].cmd, cmd_array[i].ad);
3846 if (strcmp (topic, "find") == 0)
3849 printf (" \"term\" Simple Term\n");
3850 printf (" @attr [attset] type=value op Attribute\n");
3851 printf (" @and opl opr And\n");
3852 printf (" @or opl opr Or\n");
3853 printf (" @not opl opr And-Not\n");
3854 printf (" @set set Result set\n");
3856 printf ("Bib-1 attribute types\n");
3858 printf ("4=Title 7=ISBN 8=ISSN 30=Date 62=Abstract 1003=Author 1016=Any\n");
3859 printf ("2=Relation: ");
3860 printf ("1< 2<= 3= 4>= 5> 6!= 102=Relevance\n");
3861 printf ("3=Position: ");
3862 printf ("1=First in Field 2=First in subfield 3=Any position\n");
3863 printf ("4=Structure: ");
3864 printf ("1=Phrase 2=Word 3=Key 4=Year 5=Date 6=WordList\n");
3865 printf ("5=Truncation: ");
3866 printf ("1=Right 2=Left 3=L&R 100=No 101=# 102=Re-1 103=Re-2\n");
3867 printf ("6=Completeness:");
3868 printf ("1=Incomplete subfield 2=Complete subfield 3=Complete field\n");
3873 int cmd_register_tab(const char* arg) {
3875 char command[101], tabargument[101];
3880 if (sscanf (arg, "%100s %100s", command, tabargument) < 1) {
3884 /* locate the amdn in the list */
3885 for (i = 0; cmd_array[i].cmd; i++) {
3886 if (!strncmp(cmd_array[i].cmd, command, strlen(command))) {
3891 if(!cmd_array[i].cmd) {
3892 fprintf(stderr,"Unknown command %s\n",command);
3897 if(!cmd_array[i].local_tabcompletes)
3898 cmd_array[i].local_tabcompletes = (char **) calloc(1,sizeof(char**));
3902 tabslist = cmd_array[i].local_tabcompletes;
3903 for(;tabslist && *tabslist;tabslist++) {
3907 cmd_array[i].local_tabcompletes = (char **)
3908 realloc(cmd_array[i].local_tabcompletes,(num_of_tabs+2)*sizeof(char**));
3909 tabslist=cmd_array[i].local_tabcompletes;
3910 tabslist[num_of_tabs]=strdup(tabargument);
3911 tabslist[num_of_tabs+1]=NULL;
3916 void process_cmd_line(char* line)
3919 char word[32], arg[1024];
3921 #if HAVE_GETTIMEOFDAY
3922 gettimeofday (&tv_start, 0);
3925 if ((res = sscanf(line, "%31s %1023[^;]", word, arg)) <= 0)
3927 strcpy(word, last_cmd);
3932 strcpy(last_cmd, word);
3934 /* removed tailing spaces from the arg command */
3937 char* lastnonspace=NULL;
3945 *(++lastnonspace) = 0;
3948 for (i = 0; cmd_array[i].cmd; i++)
3949 if (!strncmp(cmd_array[i].cmd, word, strlen(word)))
3951 res = (*cmd_array[i].fun)(arg);
3955 if (!cmd_array[i].cmd) /* dump our help-screen */
3957 printf("Unknown command: %s.\n", word);
3958 printf("use help for list of commands\n");
3959 /* cmd_help (""); */
3963 if(apdu_file) fflush(apdu_file);
3966 wait_and_handle_response();
3975 char *command_generator(const char *text, int state)
3981 for( ; cmd_array[idx].cmd; ++idx) {
3982 if (!strncmp(cmd_array[idx].cmd,text,strlen(text))) {
3983 ++idx; /* skip this entry on the next run */
3984 return strdup(cmd_array[idx-1].cmd);
3992 This function only known how to complete on the first word
3994 char ** readline_completer(char *text, int start, int end) {
3995 #if HAVE_READLINE_READLINE_H
3997 completerFunctionType completerToUse;
4000 #if HAVE_READLINE_RL_COMPLETION_MATCHES
4001 char** res=rl_completion_matches(text,
4004 char** res=completion_matches(text,
4005 (CPFunction*)command_generator);
4007 rl_attempted_completion_over = 1;
4010 char arg[1024],word[32];
4012 if ((res = sscanf(rl_line_buffer, "%31s %1023[^;]", word, arg)) <= 0) {
4013 rl_attempted_completion_over = 1;
4017 for (i = 0; cmd_array[i].cmd; i++) {
4018 if (!strncmp(cmd_array[i].cmd, word, strlen(word))) {
4023 if(!cmd_array[i].cmd) return NULL;
4025 curret_global_list = cmd_array[i].local_tabcompletes;
4027 completerToUse = cmd_array[i].rl_completerfunction;
4028 if(completerToUse==NULL) /* if no pr. command completer is defined use the default completer */
4029 completerToUse = default_completer;
4031 if(completerToUse) {
4032 #ifdef HAVE_READLINE_RL_COMPLETION_MATCHES
4034 rl_completion_matches(text,
4038 completion_matches(text,
4039 (CPFunction*)completerToUse);
4041 if(!cmd_array[i].complete_filenames)
4042 rl_attempted_completion_over = 1;
4045 if(!cmd_array[i].complete_filenames)
4046 rl_attempted_completion_over = 1;
4056 static void client(void)
4062 #if HAVE_GETTIMEOFDAY
4063 gettimeofday (&tv_start, 0);
4068 char *line_in = NULL;
4069 #if HAVE_READLINE_READLINE_H
4072 line_in=readline(C_PROMPT);
4075 #if HAVE_READLINE_HISTORY_H
4077 add_history(line_in);
4079 strncpy(line, line_in, 1023);
4088 if (!fgets(line, 1023, stdin))
4090 if ((end_p = strchr (line, '\n')))
4093 process_cmd_line(line);
4097 static void show_version(void)
4101 yaz_version(vstr, 0);
4102 printf ("YAZ version: %s\n", YAZ_VERSION);
4103 if (strcmp(vstr, YAZ_VERSION))
4104 printf ("YAZ DLL/SO: %s\n", vstr);
4108 int main(int argc, char **argv)
4111 char *open_command = 0;
4112 char *auth_command = 0;
4117 if (!setlocale(LC_CTYPE, ""))
4118 fprintf (stderr, "setlocale failed\n");
4122 codeset = nl_langinfo(CODESET);
4126 outputCharset = xstrdup(codeset);
4128 ODR_MASK_SET(&z3950_options, Z_Options_search);
4129 ODR_MASK_SET(&z3950_options, Z_Options_present);
4130 ODR_MASK_SET(&z3950_options, Z_Options_namedResultSets);
4131 ODR_MASK_SET(&z3950_options, Z_Options_triggerResourceCtrl);
4132 ODR_MASK_SET(&z3950_options, Z_Options_scan);
4133 ODR_MASK_SET(&z3950_options, Z_Options_sort);
4134 ODR_MASK_SET(&z3950_options, Z_Options_extendedServices);
4135 ODR_MASK_SET(&z3950_options, Z_Options_delSet);
4137 while ((ret = options("k:c:q:a:b:m:v:p:u:t:Vxd:", argv, argc, &arg)) != -2)
4144 open_command = (char *) xmalloc (strlen(arg)+6);
4145 strcpy (open_command, "open ");
4146 strcat (open_command, arg);
4150 dump_file_prefix = arg;
4153 kilobytes = atoi(arg);
4156 if (!(marc_file = fopen (arg, "a")))
4163 outputCharset = xstrdup(arg);
4166 strncpy (ccl_fields, arg, sizeof(ccl_fields)-1);
4167 ccl_fields[sizeof(ccl_fields)-1] = '\0';
4170 strncpy (cql_fields, arg, sizeof(cql_fields)-1);
4171 cql_fields[sizeof(cql_fields)-1] = '\0';
4174 if (!strcmp(arg, "-"))
4177 ber_file=fopen(arg, "a");
4180 if (!strcmp(arg, "-"))
4183 apdu_file=fopen(arg, "a");
4189 yazProxy=strdup(arg);
4194 auth_command = (char *) xmalloc (strlen(arg)+6);
4195 strcpy (auth_command, "auth ");
4196 strcat (auth_command, arg);
4200 yaz_log_init(yaz_log_mask_str(arg), "", 0);
4206 fprintf (stderr, "Usage: %s [-m <marclog>] [ -a <apdulog>] "
4207 "[-b berdump] [-c cclfields] \n"
4208 "[-q cqlfields] [-p <proxy-addr>] [-u <auth>] "
4209 "[-k size] [-d dump] [-V] [<server-addr>]\n",
4217 #ifdef HAVE_GETTIMEOFDAY
4218 gettimeofday (&tv_start, 0);
4220 process_cmd_line (auth_command);
4221 #if HAVE_READLINE_HISTORY_H
4222 add_history(auth_command);
4224 xfree(auth_command);
4228 #ifdef HAVE_GETTIMEOFDAY
4229 gettimeofday (&tv_start, 0);
4231 process_cmd_line (open_command);
4232 #if HAVE_READLINE_HISTORY_H
4233 add_history(open_command);
4235 xfree(open_command);
4246 * vim600: sw=4 ts=8 fdm=marker
4247 * vim<600: sw=4 ts=8