2 * Copyright (c) 1995-2004, Index Data
3 * See the file LICENSE for details.
5 * $Id: client.c,v 1.225 2004-01-13 11:19:24 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;
108 static char cur_host[200];
118 static QueryType queryType = QueryType_Prefix;
120 static CCL_bibset bibset; /* CCL bibset handle */
121 static cql_transform_t cqltrans; /* CQL context-set handle */
123 #if HAVE_READLINE_COMPLETION_OVER
126 /* readline doesn't have this var. Define it ourselves. */
127 int rl_attempted_completion_over = 0;
130 /* set this one to 1, to avoid decode of unknown MARCs */
131 #define AVOID_MARC_DECODE 1
133 #define maxOtherInfosSupported 10
137 } extraOtherInfos[maxOtherInfosSupported];
140 void process_cmd_line(char* line);
141 char ** readline_completer(char *text, int start, int end);
142 char *command_generator(const char *text, int state);
143 char** curret_global_list=NULL;
144 int cmd_register_tab(const char* arg);
146 static void close_session (void);
148 ODR getODROutputStream()
153 const char* query_type_as_string(QueryType q)
156 case QueryType_Prefix: return "prefix (RPN sent to server)";
157 case QueryType_CCL: return "CCL (CCL sent to server) ";
158 case QueryType_CCL2RPN: return "CCL -> RPN (RPN sent to server)";
159 case QueryType_CQL: return "CQL (CQL sent to server)";
160 case QueryType_CQL2RPN: return "CQL -> RPN (RPN sent to server)";
162 return "unknown Query type internal yaz-client error";
166 static void do_hex_dump(const char* buf, int len)
171 for( i=0; i<len ; i=i+16 )
174 for(x=0 ; i+x<len && x<16; ++x)
176 printf("%2.2X ",(unsigned int)((unsigned char)buf[i+x]));
181 if (dump_file_prefix)
184 if (++no < 1000 && strlen(dump_file_prefix) < 500)
188 sprintf (fname, "%s.%03d.raw", dump_file_prefix, no);
189 of = fopen(fname, "wb");
191 fwrite (buf, 1, len, of);
198 void add_otherInfos(Z_APDU *a)
200 Z_OtherInformation **oi;
204 for(i=0; i<maxOtherInfosSupported; ++i)
206 if(extraOtherInfos[i].oidval != -1)
207 yaz_oi_set_string_oidval(oi, out, extraOtherInfos[i].oidval,
208 1, extraOtherInfos[i].value);
212 int send_apdu(Z_APDU *a)
221 z_APDU(print, &a, 0, 0);
224 if (!z_APDU(out, &a, 0, 0))
226 odr_perror(out, "Encoding APDU");
230 buf = odr_getbuf(out, &len, 0);
232 odr_dumpBER(ber_file, buf, len);
233 /* printf ("sending APDU of size %d\n", len); */
234 do_hex_dump(buf, len);
235 if (cs_put(conn, buf, len) < 0)
237 fprintf(stderr, "cs_put: %s", cs_errmsg(cs_errno(conn)));
241 odr_reset(out); /* release the APDU structure */
245 static void print_stringn(const unsigned char *buf, size_t len)
248 for (i = 0; i<len; i++)
249 if ((buf[i] <= 126 && buf[i] >= 32) || strchr ("\n\r\t\f", buf[i]))
250 printf ("%c", buf[i]);
252 printf ("\\X%02X", buf[i]);
255 static void print_refid (Z_ReferenceId *id)
259 printf ("Reference Id: ");
260 print_stringn (id->buf, id->len);
265 static Z_ReferenceId *set_refid (ODR out)
270 id = (Z_ReferenceId *) odr_malloc (out, sizeof(*id));
271 id->size = id->len = strlen(refid);
272 id->buf = (unsigned char *) odr_malloc (out, id->len);
273 memcpy (id->buf, refid, id->len);
277 /* INIT SERVICE ------------------------------- */
279 static void send_initRequest(const char* type_and_host)
281 Z_APDU *apdu = zget_APDU(out, Z_APDU_initRequest);
282 Z_InitRequest *req = apdu->u.initRequest;
284 req->options = &z3950_options;
286 ODR_MASK_SET(req->protocolVersion, Z_ProtocolVersion_1);
287 ODR_MASK_SET(req->protocolVersion, Z_ProtocolVersion_2);
288 ODR_MASK_SET(req->protocolVersion, Z_ProtocolVersion_3);
290 *req->maximumRecordSize = 1024*kilobytes;
291 *req->preferredMessageSize = 1024*kilobytes;
293 req->idAuthentication = auth;
295 req->referenceId = set_refid (out);
298 yaz_oi_set_string_oidval(&req->otherInfo, out, VAL_PROXY,
301 if (negotiationCharset || yazLang) {
302 Z_OtherInformation **p;
303 Z_OtherInformationUnit *p0;
305 yaz_oi_APDU(apdu, &p);
307 if ((p0=yaz_oi_update(p, out, NULL, 0, 0))) {
308 ODR_MASK_SET(req->options, Z_Options_negotiationModel);
310 p0->which = Z_OtherInfo_externallyDefinedInfo;
311 p0->information.externallyDefinedInfo =
312 yaz_set_proposal_charneg(
314 (const char**)&negotiationCharset,
315 negotiationCharset ? 1 : 0,
316 (const char**)&yazLang, yazLang ? 1 : 0, 1);
321 printf("Sent initrequest.\n");
325 /* These two are used only from process_initResponse() */
326 static void render_initUserInfo(Z_OtherInformation *ui1);
327 static void render_diag(Z_DiagnosticFormat *diag);
329 static void pr_opt(const char *opt)
334 static int process_initResponse(Z_InitResponse *res)
337 /* save session parameters for later use */
338 session_mem = odr_extract_mem(in);
341 for (ver = 0; ver<5; ver++)
342 if (!ODR_MASK_GET(res->protocolVersion, ver))
346 printf("Connection rejected by v%d target.\n", ver);
348 printf("Connection accepted by v%d target.\n", ver);
349 if (res->implementationId)
350 printf("ID : %s\n", res->implementationId);
351 if (res->implementationName)
352 printf("Name : %s\n", res->implementationName);
353 if (res->implementationVersion)
354 printf("Version: %s\n", res->implementationVersion);
355 if (res->userInformationField)
357 Z_External *uif = res->userInformationField;
358 if (uif->which == Z_External_userInfo1) {
359 render_initUserInfo(uif->u.userInfo1);
361 printf("UserInformationfield:\n");
362 if (!z_External(print, (Z_External**)&uif, 0, 0)) {
363 odr_perror(print, "Printing userinfo\n");
366 if (uif->which == Z_External_octet) {
367 printf("Guessing visiblestring:\n");
368 printf("'%s'\n", uif->u. octet_aligned->buf);
369 } else if (uif->which == Z_External_single) {
370 /* Peek at any private Init-diagnostic APDUs */
371 Odr_any *sat = uif->u.single_ASN1_type;
372 printf("### NAUGHTY: External is '%s'\n", sat->buf);
378 yaz_init_opt_decode(res->options, pr_opt);
381 if (ODR_MASK_GET(res->options, Z_Options_namedResultSets))
384 if (ODR_MASK_GET(res->options, Z_Options_negotiationModel)) {
386 Z_CharSetandLanguageNegotiation *p =
387 yaz_get_charneg_record(res->otherInfo);
391 char *charset=NULL, *lang=NULL;
394 yaz_get_response_charneg(session_mem, p, &charset, &lang,
397 if (outputCharset && negotiationCharset) {
398 odr_set_charset (out, charset, outputCharset);
399 odr_set_charset (in, outputCharset, charset);
402 odr_set_charset (out, 0, 0);
403 odr_set_charset (in, 0, 0);
406 printf("Accepted character set : %s\n", charset);
407 printf("Accepted code language : %s\n", lang ? lang : "none");
408 printf("Accepted records in ...: %d\n", selected );
416 static void render_initUserInfo(Z_OtherInformation *ui1) {
418 printf("Init response contains %d otherInfo unit%s:\n",
419 ui1->num_elements, ui1->num_elements == 1 ? "" : "s");
421 for (i = 0; i < ui1->num_elements; i++) {
422 Z_OtherInformationUnit *unit = ui1->list[i];
423 printf(" %d: otherInfo unit contains ", i+1);
424 if (unit->which == Z_OtherInfo_externallyDefinedInfo &&
425 unit->information.externallyDefinedInfo->which ==
427 render_diag(unit->information.externallyDefinedInfo->u.diag1);
429 printf("unsupported otherInfo unit type %d\n", unit->which);
435 /* ### should this share code with display_diagrecs()? */
436 static void render_diag(Z_DiagnosticFormat *diag) {
439 printf("%d diagnostic%s:\n", diag->num, diag->num == 1 ? "" : "s");
440 for (i = 0; i < diag->num; i++) {
441 Z_DiagnosticFormat_s *ds = diag->elements[i];
442 printf(" %d: ", i+1);
444 case Z_DiagnosticFormat_s_defaultDiagRec: {
445 Z_DefaultDiagFormat *dd = ds->u.defaultDiagRec;
446 /* ### should check `dd->diagnosticSetId' */
447 printf("code=%d (%s)", *dd->condition,
448 diagbib1_str(*dd->condition));
449 /* Both types of addinfo are the same, so use type-pun */
450 if (dd->u.v2Addinfo != 0)
451 printf(",\n\taddinfo='%s'", dd->u.v2Addinfo);
454 case Z_DiagnosticFormat_s_explicitDiagnostic:
455 printf("Explicit diagnostic (not supported)");
458 printf("Unrecognised diagnostic type %d", ds->which);
462 if (ds->message != 0)
463 printf(", message='%s'", ds->message);
469 static int set_base(const char *arg)
474 for (i = 0; i<num_databaseNames; i++)
475 xfree (databaseNames[i]);
476 num_databaseNames = 0;
480 if (!(cp = strchr(arg, ' ')))
481 cp = arg + strlen(arg);
484 databaseNames[num_databaseNames] = (char *)xmalloc (1 + cp - arg);
485 memcpy (databaseNames[num_databaseNames], arg, cp - arg);
486 databaseNames[num_databaseNames][cp - arg] = '\0';
488 for (cp1 = databaseNames[num_databaseNames]; *cp1 ; cp1++)
497 if (num_databaseNames == 0)
499 num_databaseNames = 1;
500 databaseNames[0] = xstrdup("");
505 static int cmd_base(const char *arg)
509 printf("Usage: base <database> <database> ...\n");
512 return set_base(arg);
515 void cmd_open_remember_last_open_command(const char* arg, char* new_open_command)
517 if(last_open_command != arg)
519 if(last_open_command) xfree(last_open_command);
520 last_open_command = xstrdup(new_open_command);
524 int session_connect(const char *arg)
527 char type_and_host[101];
528 const char *basep = 0;
535 nmem_destroy (session_mem);
539 cs_get_host_args(arg, &basep);
541 strncpy(type_and_host, arg, sizeof(type_and_host)-1);
542 type_and_host[sizeof(type_and_host)-1] = '\0';
544 cmd_open_remember_last_open_command(arg,type_and_host);
547 conn = cs_create_host(yazProxy, 1, &add);
549 conn = cs_create_host(arg, 1, &add);
552 printf ("Couldn't create comstack\n");
557 if (conn->protocol == PROTO_HTTP)
559 printf ("SRW/HTTP not enabled in this YAZ\n");
565 protocol = conn->protocol;
566 if (conn->protocol == PROTO_HTTP)
570 printf("Connecting...");
572 if (cs_connect(conn, add) < 0)
574 printf ("error = %s\n", cs_strerror(conn));
575 if (conn->cerrno == CSYSERR)
578 yaz_strerror(msg, sizeof(msg));
579 printf ("%s\n", msg);
588 if (protocol == PROTO_Z3950)
590 send_initRequest(type_and_host);
596 int cmd_open(const char *arg)
600 strncpy (cur_host, arg, sizeof(cur_host)-1);
601 cur_host[sizeof(cur_host)-1] = 0;
603 return session_connect(cur_host);
610 if(!( auto_reconnect && last_open_command) ) return ;
612 open_command = (char *) xmalloc (strlen(last_open_command)+6);
613 strcpy (open_command, "open ");
615 strcat (open_command, last_open_command);
617 process_cmd_line(open_command);
622 int cmd_authentication(const char *arg)
624 static Z_IdAuthentication au;
625 static char user[40], group[40], pass[40];
626 static Z_IdPass idPass;
631 printf("Auth field set to null\n");
635 r = sscanf (arg, "%39s %39s %39s", user, group, pass);
638 printf("Authentication set to null\n");
644 if (!strcmp(user, "-")) {
645 au.which = Z_IdAuthentication_anonymous;
646 printf("Authentication set to Anonymous\n");
648 au.which = Z_IdAuthentication_open;
650 printf("Authentication set to Open (%s)\n", user);
656 au.which = Z_IdAuthentication_idPass;
657 au.u.idPass = &idPass;
658 idPass.groupId = NULL;
659 idPass.userId = user;
660 idPass.password = group;
661 printf("Authentication set to User (%s), Pass (%s)\n", user, group);
666 au.which = Z_IdAuthentication_idPass;
667 au.u.idPass = &idPass;
668 idPass.groupId = group;
669 idPass.userId = user;
670 idPass.password = pass;
671 printf("Authentication set to User (%s), Group (%s), Pass (%s)\n",
677 /* SEARCH SERVICE ------------------------------ */
678 static void display_record(Z_External *r);
680 static void print_record(const unsigned char *buf, size_t len)
683 print_stringn (buf, len);
684 /* add newline if not already added ... */
685 if (i <= 0 || buf[i-1] != '\n')
689 static void display_record(Z_External *r)
691 oident *ent = oid_getentbyoid(r->direct_reference);
695 * Tell the user what we got.
697 if (r->direct_reference)
699 printf("Record type: ");
701 printf("%s\n", ent->desc);
702 else if (!odr_oid(print, &r->direct_reference, 0, 0))
704 odr_perror(print, "print oid");
708 /* Check if this is a known, ASN.1 type tucked away in an octet string */
709 if (ent && r->which == Z_External_octet)
711 Z_ext_typeent *type = z_ext_getentbyref(ent->value);
717 * Call the given decoder to process the record.
719 odr_setbuf(in, (char*)r->u.octet_aligned->buf,
720 r->u.octet_aligned->len, 0);
721 if (!(*type->fun)(in, (char **)&rr, 0, 0))
723 odr_perror(in, "Decoding constructed record.");
724 fprintf(stdout, "[Near %d]\n", odr_offset(in));
725 fprintf(stdout, "Packet dump:\n---------\n");
726 odr_dumpBER(stdout, (char*)r->u.octet_aligned->buf,
727 r->u.octet_aligned->len);
728 fprintf(stdout, "---------\n");
730 /* note just ignores the error ant print the bytes form the octet_aligned later */
733 * Note: we throw away the original, BER-encoded record here.
734 * Do something else with it if you want to keep it.
736 r->u.sutrs = (Z_SUTRS *) rr; /* we don't actually check the type here. */
737 r->which = type->what;
741 if (ent && ent->oclass != CLASS_RECSYN)
743 if (ent && ent->value == VAL_SOIF)
744 print_record((const unsigned char *) r->u.octet_aligned->buf,
745 r->u.octet_aligned->len);
746 else if (r->which == Z_External_octet)
748 const char *octet_buf = (char*)r->u.octet_aligned->buf;
749 if (ent->value == VAL_TEXT_XML || ent->value == VAL_APPLICATION_XML ||
750 ent->value == VAL_HTML)
752 print_record((const unsigned char *) octet_buf,
753 r->u.octet_aligned->len);
755 else if (ent->value == VAL_POSTSCRIPT)
757 int size = r->u.octet_aligned->len;
760 print_record((const unsigned char *) octet_buf, size);
765 #if AVOID_MARC_DECODE
766 /* primitive check for a marc OID 5.1-29 except 16 */
767 ent->oidsuffix[0] == 5 && ent->oidsuffix[1] < 30 &&
768 ent->oidsuffix[1] != 16
777 yaz_marc_t mt = yaz_marc_create();
779 if (yaz_marc_decode_buf(mt, octet_buf,r->u.octet_aligned->len,
783 if (marcCharset && !strcmp(marcCharset, "auto"))
785 if (ent->value == VAL_USMARC)
787 if (octet_buf[9] == 'a')
795 else if (marcCharset)
797 if (outputCharset && from)
799 cd = yaz_iconv_open(outputCharset, from);
800 printf ("convert from %s to %s", from,
803 printf (" unsupported\n");
808 fwrite (result, 1, rlen, stdout);
812 size_t inbytesleft = rlen;
813 const char *inp = result;
817 size_t outbytesleft = sizeof(outbuf);
821 r = yaz_iconv (cd, (char**) &inp,
823 &outp, &outbytesleft);
824 if (r == (size_t) (-1))
826 int e = yaz_iconv_error(cd);
827 if (e != YAZ_ICONV_E2BIG)
830 fwrite (outbuf, outp - outbuf, 1, stdout);
836 printf ("bad MARC. Dumping as it is:\n");
837 print_record((const unsigned char*) octet_buf,
838 r->u.octet_aligned->len);
840 yaz_marc_destroy(mt);
846 print_record((const unsigned char*) octet_buf,
847 r->u.octet_aligned->len);
851 fwrite (octet_buf, 1, r->u.octet_aligned->len, marc_file);
853 else if (ent && ent->value == VAL_SUTRS)
855 if (r->which != Z_External_sutrs)
857 printf("Expecting single SUTRS type for SUTRS.\n");
860 print_record(r->u.sutrs->buf, r->u.sutrs->len);
862 else if (ent && ent->value == VAL_GRS1)
865 if (r->which != Z_External_grs1)
867 printf("Expecting single GRS type for GRS.\n");
871 yaz_display_grs1(w, r->u.grs1, 0);
875 else if ( /* OPAC display not complete yet .. */
876 ent && ent->value == VAL_OPAC)
879 if (r->u.opac->bibliographicRecord)
880 display_record(r->u.opac->bibliographicRecord);
881 for (i = 0; i<r->u.opac->num_holdingsData; i++)
883 Z_HoldingsRecord *h = r->u.opac->holdingsData[i];
884 if (h->which == Z_HoldingsRecord_marcHoldingsRecord)
886 printf ("MARC holdings %d\n", i);
887 display_record(h->u.marcHoldingsRecord);
889 else if (h->which == Z_HoldingsRecord_holdingsAndCirc)
893 Z_HoldingsAndCircData *data = h->u.holdingsAndCirc;
895 printf ("Data holdings %d\n", i);
896 if (data->typeOfRecord)
897 printf ("typeOfRecord: %s\n", data->typeOfRecord);
898 if (data->encodingLevel)
899 printf ("encodingLevel: %s\n", data->encodingLevel);
900 if (data->receiptAcqStatus)
901 printf ("receiptAcqStatus: %s\n", data->receiptAcqStatus);
902 if (data->generalRetention)
903 printf ("generalRetention: %s\n", data->generalRetention);
904 if (data->completeness)
905 printf ("completeness: %s\n", data->completeness);
906 if (data->dateOfReport)
907 printf ("dateOfReport: %s\n", data->dateOfReport);
909 printf ("nucCode: %s\n", data->nucCode);
910 if (data->localLocation)
911 printf ("localLocation: %s\n", data->localLocation);
912 if (data->shelvingLocation)
913 printf ("shelvingLocation: %s\n", data->shelvingLocation);
914 if (data->callNumber)
915 printf ("callNumber: %s\n", data->callNumber);
916 if (data->copyNumber)
917 printf ("copyNumber: %s\n", data->copyNumber);
918 if (data->publicNote)
919 printf ("publicNote: %s\n", data->publicNote);
920 if (data->reproductionNote)
921 printf ("reproductionNote: %s\n", data->reproductionNote);
922 if (data->termsUseRepro)
923 printf ("termsUseRepro: %s\n", data->termsUseRepro);
924 if (data->enumAndChron)
925 printf ("enumAndChron: %s\n", data->enumAndChron);
926 for (j = 0; j<data->num_volumes; j++)
928 printf ("volume %d\n", j);
929 if (data->volumes[j]->enumeration)
930 printf (" enumeration: %s\n",
931 data->volumes[j]->enumeration);
932 if (data->volumes[j]->chronology)
933 printf (" chronology: %s\n",
934 data->volumes[j]->chronology);
935 if (data->volumes[j]->enumAndChron)
936 printf (" enumAndChron: %s\n",
937 data->volumes[j]->enumAndChron);
939 for (j = 0; j<data->num_circulationData; j++)
941 printf ("circulation %d\n", j);
942 if (data->circulationData[j]->availableNow)
943 printf (" availableNow: %d\n",
944 *data->circulationData[j]->availableNow);
945 if (data->circulationData[j]->availablityDate)
946 printf (" availabiltyDate: %s\n",
947 data->circulationData[j]->availablityDate);
948 if (data->circulationData[j]->availableThru)
949 printf (" availableThru: %s\n",
950 data->circulationData[j]->availableThru);
951 if (data->circulationData[j]->restrictions)
952 printf (" restrictions: %s\n",
953 data->circulationData[j]->restrictions);
954 if (data->circulationData[j]->itemId)
955 printf (" itemId: %s\n",
956 data->circulationData[j]->itemId);
957 if (data->circulationData[j]->renewable)
958 printf (" renewable: %d\n",
959 *data->circulationData[j]->renewable);
960 if (data->circulationData[j]->onHold)
961 printf (" onHold: %d\n",
962 *data->circulationData[j]->onHold);
963 if (data->circulationData[j]->enumAndChron)
964 printf (" enumAndChron: %s\n",
965 data->circulationData[j]->enumAndChron);
966 if (data->circulationData[j]->midspine)
967 printf (" midspine: %s\n",
968 data->circulationData[j]->midspine);
969 if (data->circulationData[j]->temporaryLocation)
970 printf (" temporaryLocation: %s\n",
971 data->circulationData[j]->temporaryLocation);
978 printf("Unknown record representation.\n");
979 if (!z_External(print, &r, 0, 0))
981 odr_perror(print, "Printing external");
987 static void display_diagrecs(Z_DiagRec **pp, int num)
991 Z_DefaultDiagFormat *r;
993 printf("Diagnostic message(s) from database:\n");
994 for (i = 0; i<num; i++)
996 Z_DiagRec *p = pp[i];
997 if (p->which != Z_DiagRec_defaultFormat)
999 printf("Diagnostic record not in default format.\n");
1003 r = p->u.defaultFormat;
1004 if (!(ent = oid_getentbyoid(r->diagnosticSetId)) ||
1005 ent->oclass != CLASS_DIAGSET || ent->value != VAL_BIB1)
1006 printf("Missing or unknown diagset\n");
1007 printf(" [%d] %s", *r->condition, diagbib1_str(*r->condition));
1010 case Z_DefaultDiagFormat_v2Addinfo:
1011 printf (" -- v2 addinfo '%s'\n", r->u.v2Addinfo);
1013 case Z_DefaultDiagFormat_v3Addinfo:
1014 printf (" -- v3 addinfo '%s'\n", r->u.v3Addinfo);
1021 static void display_nameplusrecord(Z_NamePlusRecord *p)
1023 if (p->databaseName)
1024 printf("[%s]", p->databaseName);
1025 if (p->which == Z_NamePlusRecord_surrogateDiagnostic)
1026 display_diagrecs(&p->u.surrogateDiagnostic, 1);
1027 else if (p->which == Z_NamePlusRecord_databaseRecord)
1028 display_record(p->u.databaseRecord);
1031 static void display_records(Z_Records *p)
1035 if (p->which == Z_Records_NSD)
1037 Z_DiagRec dr, *dr_p = &dr;
1038 dr.which = Z_DiagRec_defaultFormat;
1039 dr.u.defaultFormat = p->u.nonSurrogateDiagnostic;
1040 display_diagrecs (&dr_p, 1);
1042 else if (p->which == Z_Records_multipleNSD)
1043 display_diagrecs (p->u.multipleNonSurDiagnostics->diagRecs,
1044 p->u.multipleNonSurDiagnostics->num_diagRecs);
1047 printf("Records: %d\n", p->u.databaseOrSurDiagnostics->num_records);
1048 for (i = 0; i < p->u.databaseOrSurDiagnostics->num_records; i++)
1049 display_nameplusrecord(p->u.databaseOrSurDiagnostics->records[i]);
1053 static int send_deleteResultSetRequest(const char *arg)
1058 Z_APDU *apdu = zget_APDU(out, Z_APDU_deleteResultSetRequest);
1059 Z_DeleteResultSetRequest *req = apdu->u.deleteResultSetRequest;
1061 req->referenceId = set_refid (out);
1063 req->num_resultSetList =
1064 sscanf (arg, "%30s %30s %30s %30s %30s %30s %30s %30s",
1065 names[0], names[1], names[2], names[3],
1066 names[4], names[5], names[6], names[7]);
1068 req->deleteFunction = (int *)
1069 odr_malloc (out, sizeof(*req->deleteFunction));
1070 if (req->num_resultSetList > 0)
1072 *req->deleteFunction = Z_DeleteRequest_list;
1073 req->resultSetList = (char **)
1074 odr_malloc (out, sizeof(*req->resultSetList)*
1075 req->num_resultSetList);
1076 for (i = 0; i<req->num_resultSetList; i++)
1077 req->resultSetList[i] = names[i];
1081 *req->deleteFunction = Z_DeleteRequest_all;
1082 req->resultSetList = 0;
1086 printf("Sent deleteResultSetRequest.\n");
1091 static int send_srw(Z_SRW_PDU *sr)
1093 const char *charset = negotiationCharset;
1094 const char *host_port = cur_host;
1097 Z_SOAP_Handler h[2] = {
1098 {"http://www.loc.gov/zing/srw/", 0, (Z_SOAP_fun) yaz_srw_codec},
1101 ODR o = odr_createmem(ODR_ENCODE);
1103 Z_SOAP *p = odr_malloc(o, sizeof(*p));
1106 path = odr_malloc(out, strlen(databaseNames[0])+2);
1108 strcpy(path+1, databaseNames[0]);
1110 gdu = z_get_HTTP_Request(out);
1111 gdu->u.HTTP_Request->path = odr_strdup(out, path);
1115 const char *cp0 = strstr(host_port, "://");
1116 const char *cp1 = 0;
1122 cp1 = strchr(cp0, '/');
1124 cp1 = cp0+strlen(cp0);
1128 char *h = odr_malloc(out, cp1 - cp0 + 1);
1129 memcpy (h, cp0, cp1 - cp0);
1131 z_HTTP_header_add(out, &gdu->u.HTTP_Request->headers,
1136 strcpy(ctype, "text/xml");
1137 if (charset && strlen(charset) < 20)
1139 strcat(ctype, "; charset=");
1140 strcat(ctype, charset);
1142 z_HTTP_header_add(out, &gdu->u.HTTP_Request->headers,
1143 "Content-Type", ctype);
1144 z_HTTP_header_add(out, &gdu->u.HTTP_Request->headers,
1145 "SOAPAction", "\"\"");
1146 p->which = Z_SOAP_generic;
1147 p->u.generic = odr_malloc(o, sizeof(*p->u.generic));
1148 p->u.generic->no = 0;
1149 p->u.generic->ns = 0;
1150 p->u.generic->p = sr;
1151 p->ns = "http://schemas.xmlsoap.org/soap/envelope/";
1153 ret = z_soap_codec_enc(o, &p,
1154 &gdu->u.HTTP_Request->content_buf,
1155 &gdu->u.HTTP_Request->content_len, h,
1158 if (z_GDU(out, &gdu, 0, 0))
1166 if (!z_GDU(print, &gdu, 0, 0))
1167 printf ("Failed to print outgoing APDU\n");
1170 buf_out = odr_getbuf(out, &len_out, 0);
1172 /* we don't odr_reset(out), since we may need the buffer again */
1174 do_hex_dump(buf_out, len_out);
1176 r = cs_put(conn, buf_out, len_out);
1188 static int send_SRW_searchRequest(const char *arg)
1194 assert(srw_sr_odr_out == 0);
1195 srw_sr_odr_out = odr_createmem(ODR_ENCODE);
1197 odr_reset(srw_sr_odr_out);
1201 /* save this for later .. when fetching individual records */
1202 srw_sr = sr = yaz_srw_get(srw_sr_odr_out, Z_SRW_searchRetrieve_request);
1203 sr->u.request->query_type = Z_SRW_query_type_cql;
1204 sr->u.request->query.cql = odr_strdup(srw_sr_odr_out, arg);
1206 sr = yaz_srw_get(out, Z_SRW_searchRetrieve_request);
1207 sr->u.request->query_type = Z_SRW_query_type_cql;
1208 sr->u.request->query.cql = odr_strdup(out, arg);
1210 sr->u.request->recordSchema = record_schema;
1211 return send_srw(sr);
1215 static int send_searchRequest(const char *arg)
1217 Z_APDU *apdu = zget_APDU(out, Z_APDU_searchRequest);
1218 Z_SearchRequest *req = apdu->u.searchRequest;
1221 struct ccl_rpn_node *rpn = NULL;
1223 char setstring[100];
1224 Z_RPNQuery *RPNquery;
1226 YAZ_PQF_Parser pqf_parser;
1228 QueryType myQueryType = queryType;
1231 if (myQueryType == QueryType_CCL2RPN)
1233 rpn = ccl_find_str(bibset, arg, &error, &pos);
1236 printf("CCL ERROR: %s\n", ccl_err_msg(error));
1239 } else if (myQueryType == QueryType_CQL2RPN) {
1240 /* ### All this code should be wrapped in a utility function */
1242 struct cql_node *node;
1243 const char *addinfo;
1244 if (cqltrans == 0) {
1245 printf("Can't use CQL: no translation file. Try set_cqlfile\n");
1248 parser = cql_parser_create();
1249 if ((error = cql_parser_string(parser, arg)) != 0) {
1250 printf("Can't parse CQL: must be a syntax error\n");
1253 node = cql_parser_result(parser);
1254 if ((error = cql_transform_buf(cqltrans, node, pqfbuf,
1255 sizeof pqfbuf)) != 0) {
1256 error = cql_transform_error(cqltrans, &addinfo);
1257 printf ("Can't convert CQL to PQF: %s (addinfo=%s)\n",
1258 cql_strerror(error), addinfo);
1262 myQueryType = QueryType_Prefix;
1265 req->referenceId = set_refid (out);
1266 if (!strcmp(arg, "@big")) /* strictly for troublemaking */
1268 static unsigned char big[2100];
1269 static Odr_oct bigo;
1271 /* send a very big referenceid to test transport stack etc. */
1272 memset(big, 'A', 2100);
1273 bigo.len = bigo.size = 2100;
1275 req->referenceId = &bigo;
1280 sprintf(setstring, "%d", ++setnumber);
1281 req->resultSetName = setstring;
1283 *req->smallSetUpperBound = smallSetUpperBound;
1284 *req->largeSetLowerBound = largeSetLowerBound;
1285 *req->mediumSetPresentNumber = mediumSetPresentNumber;
1286 if (smallSetUpperBound > 0 || (largeSetLowerBound > 1 &&
1287 mediumSetPresentNumber > 0))
1291 prefsyn.proto = protocol;
1292 prefsyn.oclass = CLASS_RECSYN;
1293 prefsyn.value = recordsyntax;
1294 req->preferredRecordSyntax =
1295 odr_oiddup(out, oid_ent_to_oid(&prefsyn, oid));
1296 req->smallSetElementSetNames =
1297 req->mediumSetElementSetNames = elementSetNames;
1299 req->num_databaseNames = num_databaseNames;
1300 req->databaseNames = databaseNames;
1302 req->query = &query;
1304 switch (myQueryType)
1306 case QueryType_Prefix:
1307 query.which = Z_Query_type_1;
1308 pqf_parser = yaz_pqf_create ();
1309 RPNquery = yaz_pqf_parse (pqf_parser, out, arg);
1312 const char *pqf_msg;
1314 int code = yaz_pqf_error (pqf_parser, &pqf_msg, &off);
1315 printf("%*s^\n", off+4, "");
1316 printf("Prefix query error: %s (code %d)\n", pqf_msg, code);
1318 yaz_pqf_destroy (pqf_parser);
1321 yaz_pqf_destroy (pqf_parser);
1322 query.u.type_1 = RPNquery;
1325 query.which = Z_Query_type_2;
1326 query.u.type_2 = &ccl_query;
1327 ccl_query.buf = (unsigned char*) arg;
1328 ccl_query.len = strlen(arg);
1330 case QueryType_CCL2RPN:
1331 query.which = Z_Query_type_1;
1332 RPNquery = ccl_rpn_query(out, rpn);
1335 printf ("Couldn't convert from CCL to RPN\n");
1338 query.u.type_1 = RPNquery;
1339 ccl_rpn_delete (rpn);
1342 query.which = Z_Query_type_104;
1343 ext = (Z_External *) odr_malloc(out, sizeof(*ext));
1344 ext->direct_reference = odr_getoidbystr(out, "1.2.840.10003.16.2");
1345 ext->indirect_reference = 0;
1346 ext->descriptor = 0;
1347 ext->which = Z_External_CQL;
1348 ext->u.cql = odr_strdup(out, arg);
1349 query.u.type_104 = ext;
1352 printf ("Unsupported query type\n");
1355 if (send_apdu(apdu))
1356 printf("Sent searchRequest.\n");
1361 /* display Query Expression as part of searchResult-1 */
1362 static void display_queryExpression (Z_QueryExpression *qe)
1366 if (qe->which == Z_QueryExpression_term)
1368 if (qe->u.term->queryTerm)
1370 Z_Term *term = qe->u.term->queryTerm;
1371 switch (term->which)
1373 case Z_Term_general:
1374 printf (" %.*s", term->u.general->len, term->u.general->buf);
1376 case Z_Term_characterString:
1377 printf (" %s", term->u.characterString);
1379 case Z_Term_numeric:
1380 printf (" %d", *term->u.numeric);
1390 /* see if we can find USR:SearchResult-1 */
1391 static void display_searchResult (Z_OtherInformation *o)
1396 for (i = 0; i < o->num_elements; i++)
1398 if (o->list[i]->which == Z_OtherInfo_externallyDefinedInfo)
1400 Z_External *ext = o->list[i]->information.externallyDefinedInfo;
1402 if (ext->which == Z_External_searchResult1)
1405 Z_SearchInfoReport *sr = ext->u.searchResult1;
1406 printf ("SearchResult-1:");
1407 for (j = 0; j < sr->num; j++)
1409 if (!sr->elements[j]->subqueryExpression)
1411 display_queryExpression (
1412 sr->elements[j]->subqueryExpression);
1413 display_queryExpression (
1414 sr->elements[j]->subqueryInterpretation);
1415 display_queryExpression (
1416 sr->elements[j]->subqueryRecommendation);
1417 if (sr->elements[j]->subqueryCount)
1418 printf ("(%d)", *sr->elements[j]->subqueryCount);
1426 static int process_searchResponse(Z_SearchResponse *res)
1428 printf ("Received SearchResponse.\n");
1429 print_refid (res->referenceId);
1430 if (*res->searchStatus)
1431 printf("Search was a success.\n");
1433 printf("Search was a bloomin' failure.\n");
1434 printf("Number of hits: %d", *res->resultCount);
1436 printf (", setno %d", setnumber);
1438 display_searchResult (res->additionalSearchInfo);
1439 printf("records returned: %d\n",
1440 *res->numberOfRecordsReturned);
1441 setno += *res->numberOfRecordsReturned;
1443 display_records(res->records);
1447 static void print_level(int iLevel)
1450 for (i = 0; i < iLevel * 4; i++)
1454 static void print_int(int iLevel, const char *pTag, int *pInt)
1458 print_level(iLevel);
1459 printf("%s: %d\n", pTag, *pInt);
1463 static void print_string(int iLevel, const char *pTag, const char *pString)
1465 if (pString != NULL)
1467 print_level(iLevel);
1468 printf("%s: %s\n", pTag, pString);
1472 static void print_oid(int iLevel, const char *pTag, Odr_oid *pOid)
1478 print_level(iLevel);
1479 printf("%s:", pTag);
1480 for (; *pInt != -1; pInt++)
1481 printf(" %d", *pInt);
1486 static void print_referenceId(int iLevel, Z_ReferenceId *referenceId)
1488 if (referenceId != NULL)
1492 print_level(iLevel);
1493 printf("Ref Id (%d, %d): ", referenceId->len, referenceId->size);
1494 for (i = 0; i < referenceId->len; i++)
1495 printf("%c", referenceId->buf[i]);
1500 static void print_string_or_numeric(int iLevel, const char *pTag, Z_StringOrNumeric *pStringNumeric)
1502 if (pStringNumeric != NULL)
1504 switch (pStringNumeric->which)
1506 case Z_StringOrNumeric_string:
1507 print_string(iLevel, pTag, pStringNumeric->u.string);
1510 case Z_StringOrNumeric_numeric:
1511 print_int(iLevel, pTag, pStringNumeric->u.numeric);
1515 print_level(iLevel);
1516 printf("%s: valid type for Z_StringOrNumeric\n", pTag);
1522 static void print_universe_report_duplicate(
1524 Z_UniverseReportDuplicate *pUniverseReportDuplicate)
1526 if (pUniverseReportDuplicate != NULL)
1528 print_level(iLevel);
1529 printf("Universe Report Duplicate: \n");
1531 print_string_or_numeric(iLevel, "Hit No",
1532 pUniverseReportDuplicate->hitno);
1536 static void print_universe_report_hits(
1538 Z_UniverseReportHits *pUniverseReportHits)
1540 if (pUniverseReportHits != NULL)
1542 print_level(iLevel);
1543 printf("Universe Report Hits: \n");
1545 print_string_or_numeric(iLevel, "Database",
1546 pUniverseReportHits->database);
1547 print_string_or_numeric(iLevel, "Hits", pUniverseReportHits->hits);
1551 static void print_universe_report(int iLevel, Z_UniverseReport *pUniverseReport)
1553 if (pUniverseReport != NULL)
1555 print_level(iLevel);
1556 printf("Universe Report: \n");
1558 print_int(iLevel, "Total Hits", pUniverseReport->totalHits);
1559 switch (pUniverseReport->which)
1561 case Z_UniverseReport_databaseHits:
1562 print_universe_report_hits(iLevel,
1563 pUniverseReport->u.databaseHits);
1566 case Z_UniverseReport_duplicate:
1567 print_universe_report_duplicate(iLevel,
1568 pUniverseReport->u.duplicate);
1572 print_level(iLevel);
1573 printf("Type: %d\n", pUniverseReport->which);
1579 static void print_external(int iLevel, Z_External *pExternal)
1581 if (pExternal != NULL)
1583 print_level(iLevel);
1584 printf("External: \n");
1586 print_oid(iLevel, "Direct Reference", pExternal->direct_reference);
1587 print_int(iLevel, "InDirect Reference", pExternal->indirect_reference);
1588 print_string(iLevel, "Descriptor", pExternal->descriptor);
1589 switch (pExternal->which)
1591 case Z_External_universeReport:
1592 print_universe_report(iLevel, pExternal->u.universeReport);
1596 print_level(iLevel);
1597 printf("Type: %d\n", pExternal->which);
1603 static int process_resourceControlRequest (Z_ResourceControlRequest *req)
1605 printf ("Received ResourceControlRequest.\n");
1606 print_referenceId(1, req->referenceId);
1607 print_int(1, "Suspended Flag", req->suspendedFlag);
1608 print_int(1, "Partial Results Available", req->partialResultsAvailable);
1609 print_int(1, "Response Required", req->responseRequired);
1610 print_int(1, "Triggered Request Flag", req->triggeredRequestFlag);
1611 print_external(1, req->resourceReport);
1615 void process_ESResponse(Z_ExtendedServicesResponse *res)
1618 switch (*res->operationStatus)
1620 case Z_ExtendedServicesResponse_done:
1623 case Z_ExtendedServicesResponse_accepted:
1624 printf ("accepted\n");
1626 case Z_ExtendedServicesResponse_failure:
1627 printf ("failure\n");
1628 display_diagrecs(res->diagnostics, res->num_diagnostics);
1631 printf ("unknown\n");
1633 if ( (*res->operationStatus != Z_ExtendedServicesResponse_failure) &&
1634 (res->num_diagnostics != 0) ) {
1635 display_diagrecs(res->diagnostics, res->num_diagnostics);
1637 print_refid (res->referenceId);
1638 if (res->taskPackage &&
1639 res->taskPackage->which == Z_External_extendedService)
1641 Z_TaskPackage *taskPackage = res->taskPackage->u.extendedService;
1642 Odr_oct *id = taskPackage->targetReference;
1643 Z_External *ext = taskPackage->taskSpecificParameters;
1647 printf ("Target Reference: ");
1648 print_stringn (id->buf, id->len);
1651 if (ext->which == Z_External_update)
1653 Z_IUUpdateTaskPackage *utp = ext->u.update->u.taskPackage;
1654 if (utp && utp->targetPart)
1656 Z_IUTargetPart *targetPart = utp->targetPart;
1659 for (i = 0; i<targetPart->num_taskPackageRecords; i++)
1662 Z_IUTaskPackageRecordStructure *tpr =
1663 targetPart->taskPackageRecords[i];
1664 printf ("task package record %d\n", i+1);
1665 if (tpr->which == Z_IUTaskPackageRecordStructure_record)
1667 display_record (tpr->u.record);
1671 printf ("other type\n");
1679 const char *get_ill_element (void *clientData, const char *element)
1684 static Z_External *create_external_itemRequest()
1686 struct ill_get_ctl ctl;
1687 ILL_ItemRequest *req;
1689 int item_request_size = 0;
1690 char *item_request_buf = 0;
1694 ctl.f = get_ill_element;
1696 req = ill_get_ItemRequest(&ctl, "ill", 0);
1698 printf ("ill_get_ItemRequest failed\n");
1700 if (!ill_ItemRequest (out, &req, 0, 0))
1704 ill_ItemRequest(print, &req, 0, 0);
1707 item_request_buf = odr_getbuf (out, &item_request_size, 0);
1708 if (item_request_buf)
1709 odr_setbuf (out, item_request_buf, item_request_size, 1);
1710 printf ("Couldn't encode ItemRequest, size %d\n", item_request_size);
1717 item_request_buf = odr_getbuf (out, &item_request_size, 0);
1718 oid.proto = PROTO_GENERAL;
1719 oid.oclass = CLASS_GENERAL;
1720 oid.value = VAL_ISO_ILL_1;
1722 r = (Z_External *) odr_malloc (out, sizeof(*r));
1723 r->direct_reference = odr_oiddup(out,oid_getoidbyent(&oid));
1724 r->indirect_reference = 0;
1726 r->which = Z_External_single;
1728 r->u.single_ASN1_type = (Odr_oct *)
1729 odr_malloc (out, sizeof(*r->u.single_ASN1_type));
1730 r->u.single_ASN1_type->buf = (unsigned char *)
1731 odr_malloc (out, item_request_size);
1732 r->u.single_ASN1_type->len = item_request_size;
1733 r->u.single_ASN1_type->size = item_request_size;
1734 memcpy (r->u.single_ASN1_type->buf, item_request_buf,
1737 do_hex_dump(item_request_buf,item_request_size);
1742 static Z_External *create_external_ILL_APDU(int which)
1744 struct ill_get_ctl ctl;
1747 int ill_request_size = 0;
1748 char *ill_request_buf = 0;
1752 ctl.f = get_ill_element;
1754 ill_apdu = ill_get_APDU(&ctl, "ill", 0);
1756 if (!ill_APDU (out, &ill_apdu, 0, 0))
1760 printf ("-------------------\n");
1761 ill_APDU(print, &ill_apdu, 0, 0);
1763 printf ("-------------------\n");
1765 ill_request_buf = odr_getbuf (out, &ill_request_size, 0);
1766 if (ill_request_buf)
1767 odr_setbuf (out, ill_request_buf, ill_request_size, 1);
1768 printf ("Couldn't encode ILL-Request, size %d\n", ill_request_size);
1774 ill_request_buf = odr_getbuf (out, &ill_request_size, 0);
1776 oid.proto = PROTO_GENERAL;
1777 oid.oclass = CLASS_GENERAL;
1778 oid.value = VAL_ISO_ILL_1;
1780 r = (Z_External *) odr_malloc (out, sizeof(*r));
1781 r->direct_reference = odr_oiddup(out,oid_getoidbyent(&oid));
1782 r->indirect_reference = 0;
1784 r->which = Z_External_single;
1786 r->u.single_ASN1_type = (Odr_oct *)
1787 odr_malloc (out, sizeof(*r->u.single_ASN1_type));
1788 r->u.single_ASN1_type->buf = (unsigned char *)
1789 odr_malloc (out, ill_request_size);
1790 r->u.single_ASN1_type->len = ill_request_size;
1791 r->u.single_ASN1_type->size = ill_request_size;
1792 memcpy (r->u.single_ASN1_type->buf, ill_request_buf, ill_request_size);
1793 /* printf ("len = %d\n", ill_request_size); */
1794 /* do_hex_dump(ill_request_buf,ill_request_size); */
1795 /* printf("--- end of extenal\n"); */
1802 static Z_External *create_ItemOrderExternal(const char *type, int itemno)
1804 Z_External *r = (Z_External *) odr_malloc(out, sizeof(Z_External));
1805 oident ItemOrderRequest;
1807 ItemOrderRequest.proto = PROTO_Z3950;
1808 ItemOrderRequest.oclass = CLASS_EXTSERV;
1809 ItemOrderRequest.value = VAL_ITEMORDER;
1811 r->direct_reference = odr_oiddup(out,oid_getoidbyent(&ItemOrderRequest));
1812 r->indirect_reference = 0;
1815 r->which = Z_External_itemOrder;
1817 r->u.itemOrder = (Z_ItemOrder *) odr_malloc(out,sizeof(Z_ItemOrder));
1818 memset(r->u.itemOrder, 0, sizeof(Z_ItemOrder));
1819 r->u.itemOrder->which=Z_IOItemOrder_esRequest;
1821 r->u.itemOrder->u.esRequest = (Z_IORequest *)
1822 odr_malloc(out,sizeof(Z_IORequest));
1823 memset(r->u.itemOrder->u.esRequest, 0, sizeof(Z_IORequest));
1825 r->u.itemOrder->u.esRequest->toKeep = (Z_IOOriginPartToKeep *)
1826 odr_malloc(out,sizeof(Z_IOOriginPartToKeep));
1827 memset(r->u.itemOrder->u.esRequest->toKeep, 0, sizeof(Z_IOOriginPartToKeep));
1828 r->u.itemOrder->u.esRequest->notToKeep = (Z_IOOriginPartNotToKeep *)
1829 odr_malloc(out,sizeof(Z_IOOriginPartNotToKeep));
1830 memset(r->u.itemOrder->u.esRequest->notToKeep, 0, sizeof(Z_IOOriginPartNotToKeep));
1832 r->u.itemOrder->u.esRequest->toKeep->supplDescription = NULL;
1833 r->u.itemOrder->u.esRequest->toKeep->contact = NULL;
1834 r->u.itemOrder->u.esRequest->toKeep->addlBilling = NULL;
1836 r->u.itemOrder->u.esRequest->notToKeep->resultSetItem =
1837 (Z_IOResultSetItem *) odr_malloc(out, sizeof(Z_IOResultSetItem));
1838 memset(r->u.itemOrder->u.esRequest->notToKeep->resultSetItem, 0, sizeof(Z_IOResultSetItem));
1839 r->u.itemOrder->u.esRequest->notToKeep->resultSetItem->resultSetId = "1";
1841 r->u.itemOrder->u.esRequest->notToKeep->resultSetItem->item =
1842 (int *) odr_malloc(out, sizeof(int));
1843 *r->u.itemOrder->u.esRequest->notToKeep->resultSetItem->item = itemno;
1845 if (!strcmp (type, "item") || !strcmp(type, "2"))
1847 printf ("using item-request\n");
1848 r->u.itemOrder->u.esRequest->notToKeep->itemRequest =
1849 create_external_itemRequest();
1851 else if (!strcmp(type, "ill") || !strcmp(type, "1"))
1853 printf ("using ILL-request\n");
1854 r->u.itemOrder->u.esRequest->notToKeep->itemRequest =
1855 create_external_ILL_APDU(ILL_APDU_ILL_Request);
1857 else if (!strcmp(type, "xml") || !strcmp(type, "3"))
1859 const char *xml_buf =
1861 " <type>request</type>\n"
1862 " <libraryNo>000200</libraryNo>\n"
1863 " <borrowerTicketNo> 1212 </borrowerTicketNo>\n"
1865 r->u.itemOrder->u.esRequest->notToKeep->itemRequest =
1866 z_ext_record (out, VAL_TEXT_XML, xml_buf, strlen(xml_buf));
1869 r->u.itemOrder->u.esRequest->notToKeep->itemRequest = 0;
1874 static int send_itemorder(const char *type, int itemno)
1876 Z_APDU *apdu = zget_APDU(out, Z_APDU_extendedServicesRequest);
1877 Z_ExtendedServicesRequest *req = apdu->u.extendedServicesRequest;
1878 oident ItemOrderRequest;
1880 ItemOrderRequest.proto = PROTO_Z3950;
1881 ItemOrderRequest.oclass = CLASS_EXTSERV;
1882 ItemOrderRequest.value = VAL_ITEMORDER;
1883 req->packageType = odr_oiddup(out,oid_getoidbyent(&ItemOrderRequest));
1884 req->packageName = esPackageName;
1886 req->taskSpecificParameters = create_ItemOrderExternal(type, itemno);
1892 static int only_z3950()
1894 if (protocol == PROTO_HTTP)
1896 printf ("Not supported by SRW\n");
1902 static int cmd_update_common(const char *arg, int version);
1904 static int cmd_update(const char *arg)
1906 return cmd_update_common(arg, 1);
1909 static int cmd_update0(const char *arg)
1911 return cmd_update_common(arg, 0);
1914 static int cmd_update_common(const char *arg, int version)
1916 Z_APDU *apdu = zget_APDU(out, Z_APDU_extendedServicesRequest );
1917 Z_ExtendedServicesRequest *req = apdu->u.extendedServicesRequest;
1921 char action[20], recid[20], fname[80];
1923 Z_External *record_this = 0;
1930 sscanf (arg, "%19s %19s %79s", action, recid, fname);
1932 if (!strcmp (action, "insert"))
1933 action_no = Z_IUOriginPartToKeep_recordInsert;
1934 else if (!strcmp (action, "replace"))
1935 action_no = Z_IUOriginPartToKeep_recordReplace;
1936 else if (!strcmp (action, "delete"))
1937 action_no = Z_IUOriginPartToKeep_recordDelete;
1938 else if (!strcmp (action, "update"))
1939 action_no = Z_IUOriginPartToKeep_specialUpdate;
1942 printf ("Bad action: %s\n", action);
1943 printf ("Possible values: insert, replace, delete, update\n");
1951 stat (fname, &status);
1952 if (S_ISREG(status.st_mode) && (inf = fopen(fname, "r")))
1954 size_t len = status.st_size;
1955 char *buf = (char *) xmalloc (len);
1957 fread (buf, 1, len, inf);
1961 record_this = z_ext_record (out, VAL_TEXT_XML, buf, len);
1967 printf ("File %s doesn't exist\n", fname);
1975 printf ("No last record (update ignored)\n");
1978 record_this = record_last;
1981 update_oid.proto = PROTO_Z3950;
1982 update_oid.oclass = CLASS_EXTSERV;
1984 update_oid.value = VAL_DBUPDATE0;
1986 update_oid.value = VAL_DBUPDATE;
1987 oid_ent_to_oid (&update_oid, oid);
1988 req->packageType = odr_oiddup(out,oid);
1989 req->packageName = esPackageName;
1991 req->referenceId = set_refid (out);
1993 r = req->taskSpecificParameters = (Z_External *)
1994 odr_malloc (out, sizeof(*r));
1995 r->direct_reference = odr_oiddup(out,oid);
1996 r->indirect_reference = 0;
2000 Z_IU0OriginPartToKeep *toKeep;
2001 Z_IU0SuppliedRecords *notToKeep;
2003 r->which = Z_External_update0;
2004 r->u.update0 = (Z_IU0Update *) odr_malloc(out, sizeof(*r->u.update0));
2005 r->u.update0->which = Z_IUUpdate_esRequest;
2006 r->u.update0->u.esRequest = (Z_IU0UpdateEsRequest *)
2007 odr_malloc(out, sizeof(*r->u.update0->u.esRequest));
2008 toKeep = r->u.update0->u.esRequest->toKeep = (Z_IU0OriginPartToKeep *)
2009 odr_malloc(out, sizeof(*r->u.update0->u.esRequest->toKeep));
2011 toKeep->databaseName = databaseNames[0];
2013 toKeep->elementSetName = 0;
2015 toKeep->action = (int *) odr_malloc(out, sizeof(*toKeep->action));
2016 *toKeep->action = action_no;
2018 notToKeep = r->u.update0->u.esRequest->notToKeep = (Z_IU0SuppliedRecords *)
2019 odr_malloc(out, sizeof(*r->u.update0->u.esRequest->notToKeep));
2021 notToKeep->elements = (Z_IU0SuppliedRecords_elem **)
2022 odr_malloc(out, sizeof(*notToKeep->elements));
2023 notToKeep->elements[0] = (Z_IU0SuppliedRecords_elem *)
2024 odr_malloc(out, sizeof(**notToKeep->elements));
2025 notToKeep->elements[0]->which = Z_IUSuppliedRecords_elem_opaque;
2028 notToKeep->elements[0]->u.opaque = (Odr_oct *)
2029 odr_malloc (out, sizeof(Odr_oct));
2030 notToKeep->elements[0]->u.opaque->buf = (unsigned char *) recid;
2031 notToKeep->elements[0]->u.opaque->size = strlen(recid);
2032 notToKeep->elements[0]->u.opaque->len = strlen(recid);
2035 notToKeep->elements[0]->u.opaque = 0;
2036 notToKeep->elements[0]->supplementalId = 0;
2037 notToKeep->elements[0]->correlationInfo = 0;
2038 notToKeep->elements[0]->record = record_this;
2042 Z_IUOriginPartToKeep *toKeep;
2043 Z_IUSuppliedRecords *notToKeep;
2045 r->which = Z_External_update;
2046 r->u.update = (Z_IUUpdate *) odr_malloc(out, sizeof(*r->u.update));
2047 r->u.update->which = Z_IUUpdate_esRequest;
2048 r->u.update->u.esRequest = (Z_IUUpdateEsRequest *)
2049 odr_malloc(out, sizeof(*r->u.update->u.esRequest));
2050 toKeep = r->u.update->u.esRequest->toKeep = (Z_IUOriginPartToKeep *)
2051 odr_malloc(out, sizeof(*r->u.update->u.esRequest->toKeep));
2053 toKeep->databaseName = databaseNames[0];
2055 toKeep->elementSetName = 0;
2056 toKeep->actionQualifier = 0;
2057 toKeep->action = (int *) odr_malloc(out, sizeof(*toKeep->action));
2058 *toKeep->action = action_no;
2060 notToKeep = r->u.update->u.esRequest->notToKeep = (Z_IUSuppliedRecords *)
2061 odr_malloc(out, sizeof(*r->u.update->u.esRequest->notToKeep));
2063 notToKeep->elements = (Z_IUSuppliedRecords_elem **)
2064 odr_malloc(out, sizeof(*notToKeep->elements));
2065 notToKeep->elements[0] = (Z_IUSuppliedRecords_elem *)
2066 odr_malloc(out, sizeof(**notToKeep->elements));
2067 notToKeep->elements[0]->which = Z_IUSuppliedRecords_elem_opaque;
2070 notToKeep->elements[0]->u.opaque = (Odr_oct *)
2071 odr_malloc (out, sizeof(Odr_oct));
2072 notToKeep->elements[0]->u.opaque->buf = (unsigned char *) recid;
2073 notToKeep->elements[0]->u.opaque->size = strlen(recid);
2074 notToKeep->elements[0]->u.opaque->len = strlen(recid);
2077 notToKeep->elements[0]->u.opaque = 0;
2078 notToKeep->elements[0]->supplementalId = 0;
2079 notToKeep->elements[0]->correlationInfo = 0;
2080 notToKeep->elements[0]->record = record_this;
2088 static int cmd_itemorder(const char *arg)
2095 if (sscanf (arg, "%10s %d", type, &itemno) != 2)
2098 printf("Item order request\n");
2100 send_itemorder(type, itemno);
2104 static void show_opt(const char *arg)
2106 printf ("%s ", arg);
2109 static int cmd_options(const char *arg)
2115 r = yaz_init_opt_encode(&z3950_options, arg, &pos);
2119 yaz_init_opt_decode(&z3950_options, show_opt);
2125 static int cmd_explain(const char *arg)
2127 if (protocol != PROTO_HTTP)
2138 /* save this for later .. when fetching individual records */
2139 sr = yaz_srw_get(out, Z_SRW_explain_request);
2147 static int cmd_find(const char *arg)
2151 printf("Find what?\n");
2154 if (protocol == PROTO_HTTP)
2161 if (!send_SRW_searchRequest(arg))
2174 printf("Not connected yet\n");
2178 if (!send_searchRequest(arg))
2184 static int cmd_delete(const char *arg)
2188 printf("Not connected yet\n");
2193 if (!send_deleteResultSetRequest(arg))
2198 static int cmd_ssub(const char *arg)
2200 if (!(smallSetUpperBound = atoi(arg)))
2205 static int cmd_lslb(const char *arg)
2209 if (!(largeSetLowerBound = atoi(arg)))
2214 static int cmd_mspn(const char *arg)
2218 if (!(mediumSetPresentNumber = atoi(arg)))
2223 static int cmd_status(const char *arg)
2225 printf("smallSetUpperBound: %d\n", smallSetUpperBound);
2226 printf("largeSetLowerBound: %d\n", largeSetLowerBound);
2227 printf("mediumSetPresentNumber: %d\n", mediumSetPresentNumber);
2231 static int cmd_setnames(const char *arg)
2233 if (*arg == '1') /* enable ? */
2235 else if (*arg == '0') /* disable ? */
2237 else if (setnumber < 0) /* no args, toggle .. */
2243 printf("Set numbering enabled.\n");
2245 printf("Set numbering disabled.\n");
2249 /* PRESENT SERVICE ----------------------------- */
2251 static void parse_show_args(const char *arg_c, char *setstring,
2252 int *start, int *number)
2257 strncpy(arg, arg_c, sizeof(arg)-1);
2258 arg[sizeof(arg)-1] = '\0';
2260 if ((p = strchr(arg, '+')))
2262 *number = atoi(p + 1);
2267 if (p && (p=strchr(p+1, '+')))
2268 strcpy (setstring, p+1);
2269 else if (setnumber >= 0)
2270 sprintf(setstring, "%d", setnumber);
2275 static int send_presentRequest(const char *arg)
2277 Z_APDU *apdu = zget_APDU(out, Z_APDU_presentRequest);
2278 Z_PresentRequest *req = apdu->u.presentRequest;
2279 Z_RecordComposition compo;
2283 char setstring[100];
2285 req->referenceId = set_refid (out);
2287 parse_show_args(arg, setstring, &setno, &nos);
2289 req->resultSetId = setstring;
2291 req->resultSetStartPoint = &setno;
2292 req->numberOfRecordsRequested = &nos;
2293 prefsyn.proto = protocol;
2294 prefsyn.oclass = CLASS_RECSYN;
2295 prefsyn.value = recordsyntax;
2296 req->preferredRecordSyntax =
2297 odr_oiddup (out, oid_ent_to_oid(&prefsyn, oid));
2303 prefschema.proto = protocol;
2304 prefschema.oclass = CLASS_SCHEMA;
2305 prefschema.value = oid_getvalbyname(record_schema);
2307 req->recordComposition = &compo;
2308 compo.which = Z_RecordComp_complex;
2309 compo.u.complex = (Z_CompSpec *)
2310 odr_malloc(out, sizeof(*compo.u.complex));
2311 compo.u.complex->selectAlternativeSyntax = (bool_t *)
2312 odr_malloc(out, sizeof(bool_t));
2313 *compo.u.complex->selectAlternativeSyntax = 0;
2315 compo.u.complex->generic = (Z_Specification *)
2316 odr_malloc(out, sizeof(*compo.u.complex->generic));
2317 compo.u.complex->generic->which = Z_Schema_oid;
2318 compo.u.complex->generic->schema.oid = (Odr_oid *)
2319 odr_oiddup(out, oid_ent_to_oid(&prefschema, oid));
2320 if (!compo.u.complex->generic->schema.oid)
2322 /* OID wasn't a schema! Try record syntax instead. */
2323 prefschema.oclass = CLASS_RECSYN;
2324 compo.u.complex->generic->schema.oid = (Odr_oid *)
2325 odr_oiddup(out, oid_ent_to_oid(&prefschema, oid));
2327 if (!elementSetNames)
2328 compo.u.complex->generic->elementSpec = 0;
2331 compo.u.complex->generic->elementSpec = (Z_ElementSpec *)
2332 odr_malloc(out, sizeof(Z_ElementSpec));
2333 compo.u.complex->generic->elementSpec->which =
2334 Z_ElementSpec_elementSetName;
2335 compo.u.complex->generic->elementSpec->u.elementSetName =
2336 elementSetNames->u.generic;
2338 compo.u.complex->num_dbSpecific = 0;
2339 compo.u.complex->dbSpecific = 0;
2340 compo.u.complex->num_recordSyntax = 0;
2341 compo.u.complex->recordSyntax = 0;
2343 else if (elementSetNames)
2345 req->recordComposition = &compo;
2346 compo.which = Z_RecordComp_simple;
2347 compo.u.simple = elementSetNames;
2350 printf("Sent presentRequest (%d+%d).\n", setno, nos);
2355 static int send_SRW_presentRequest(const char *arg)
2357 char setstring[100];
2359 Z_SRW_PDU *sr = srw_sr;
2363 parse_show_args(arg, setstring, &setno, &nos);
2364 sr->u.request->startRecord = odr_intdup(out, setno);
2365 sr->u.request->maximumRecords = odr_intdup(out, nos);
2367 sr->u.request->recordSchema = record_schema;
2368 return send_srw(sr);
2372 static void close_session (void)
2379 nmem_destroy (session_mem);
2388 void process_close(Z_Close *req)
2390 Z_APDU *apdu = zget_APDU(out, Z_APDU_close);
2391 Z_Close *res = apdu->u.close;
2393 static char *reasons[] =
2398 "cost limit reached",
2400 "security violation",
2407 printf("Reason: %s, message: %s\n", reasons[*req->closeReason],
2408 req->diagnosticInformation ? req->diagnosticInformation : "NULL");
2413 *res->closeReason = Z_Close_finished;
2415 printf("Sent response.\n");
2420 static int cmd_show(const char *arg)
2422 if (protocol == PROTO_HTTP)
2429 if (!send_SRW_presentRequest(arg))
2439 printf("Not connected yet\n");
2442 if (!send_presentRequest(arg))
2448 int cmd_quit(const char *arg)
2450 printf("See you later, alligator.\n");
2456 int cmd_cancel(const char *arg)
2458 Z_APDU *apdu = zget_APDU(out, Z_APDU_triggerResourceControlRequest);
2459 Z_TriggerResourceControlRequest *req =
2460 apdu->u.triggerResourceControlRequest;
2465 printf("Session not initialized yet\n");
2470 if (!ODR_MASK_GET(session->options, Z_Options_triggerResourceCtrl))
2472 printf("Target doesn't support cancel (trigger resource ctrl)\n");
2475 *req->requestedAction = Z_TriggerResourceCtrl_cancel;
2476 req->resultSetWanted = &rfalse;
2479 printf("Sent cancel request\n");
2483 int send_scanrequest(const char *query, int pp, int num, const char *term)
2485 Z_APDU *apdu = zget_APDU(out, Z_APDU_scanRequest);
2486 Z_ScanRequest *req = apdu->u.scanRequest;
2491 if (queryType == QueryType_CCL2RPN)
2495 struct ccl_rpn_node *rpn;
2497 rpn = ccl_find_str (bibset, query, &error, &pos);
2500 printf("CCL ERROR: %s\n", ccl_err_msg(error));
2503 bib1.proto = PROTO_Z3950;
2504 bib1.oclass = CLASS_ATTSET;
2505 bib1.value = VAL_BIB1;
2506 req->attributeSet = oid_ent_to_oid (&bib1, oid);
2507 if (!(req->termListAndStartPoint = ccl_scan_query (out, rpn)))
2509 printf("Couldn't convert CCL to Scan term\n");
2512 ccl_rpn_delete (rpn);
2516 YAZ_PQF_Parser pqf_parser = yaz_pqf_create ();
2518 if (!(req->termListAndStartPoint =
2519 yaz_pqf_scan(pqf_parser, out, &req->attributeSet, query)))
2521 const char *pqf_msg;
2523 int code = yaz_pqf_error (pqf_parser, &pqf_msg, &off);
2524 printf("%*s^\n", off+7, "");
2525 printf("Prefix query error: %s (code %d)\n", pqf_msg, code);
2526 yaz_pqf_destroy (pqf_parser);
2529 yaz_pqf_destroy (pqf_parser);
2533 if (req->termListAndStartPoint->term &&
2534 req->termListAndStartPoint->term->which == Z_Term_general &&
2535 req->termListAndStartPoint->term->u.general)
2537 req->termListAndStartPoint->term->u.general->buf =
2538 (unsigned char *) odr_strdup(out, term);
2539 req->termListAndStartPoint->term->u.general->len =
2540 req->termListAndStartPoint->term->u.general->size =
2544 req->referenceId = set_refid (out);
2545 req->num_databaseNames = num_databaseNames;
2546 req->databaseNames = databaseNames;
2547 req->numberOfTermsRequested = #
2548 req->preferredPositionInResponse = &pp;
2553 int send_sortrequest(const char *arg, int newset)
2555 Z_APDU *apdu = zget_APDU(out, Z_APDU_sortRequest);
2556 Z_SortRequest *req = apdu->u.sortRequest;
2557 Z_SortKeySpecList *sksl = (Z_SortKeySpecList *)
2558 odr_malloc (out, sizeof(*sksl));
2564 sprintf (setstring, "%d", setnumber);
2566 sprintf (setstring, "default");
2568 req->referenceId = set_refid (out);
2570 req->num_inputResultSetNames = 1;
2571 req->inputResultSetNames = (Z_InternationalString **)
2572 odr_malloc (out, sizeof(*req->inputResultSetNames));
2573 req->inputResultSetNames[0] = odr_strdup (out, setstring);
2575 if (newset && setnumber >= 0)
2576 sprintf (setstring, "%d", ++setnumber);
2578 req->sortedResultSetName = odr_strdup (out, setstring);
2580 req->sortSequence = yaz_sort_spec (out, arg);
2581 if (!req->sortSequence)
2583 printf ("Missing sort specifications\n");
2590 void display_term(Z_TermInfo *t)
2593 printf("%s", t->displayTerm);
2594 else if (t->term->which == Z_Term_general)
2596 printf("%.*s", t->term->u.general->len, t->term->u.general->buf);
2597 sprintf(last_scan_line, "%.*s", t->term->u.general->len,
2598 t->term->u.general->buf);
2601 printf("Term (not general)");
2602 if (t->globalOccurrences)
2603 printf (" (%d)\n", *t->globalOccurrences);
2608 void process_scanResponse(Z_ScanResponse *res)
2611 Z_Entry **entries = NULL;
2612 int num_entries = 0;
2614 printf("Received ScanResponse\n");
2615 print_refid (res->referenceId);
2616 printf("%d entries", *res->numberOfEntriesReturned);
2617 if (res->positionOfTerm)
2618 printf (", position=%d", *res->positionOfTerm);
2620 if (*res->scanStatus != Z_Scan_success)
2621 printf("Scan returned code %d\n", *res->scanStatus);
2624 if ((entries = res->entries->entries))
2625 num_entries = res->entries->num_entries;
2626 for (i = 0; i < num_entries; i++)
2628 int pos_term = res->positionOfTerm ? *res->positionOfTerm : -1;
2629 if (entries[i]->which == Z_Entry_termInfo)
2631 printf("%c ", i + 1 == pos_term ? '*' : ' ');
2632 display_term(entries[i]->u.termInfo);
2635 display_diagrecs(&entries[i]->u.surrogateDiagnostic, 1);
2637 if (res->entries->nonsurrogateDiagnostics)
2638 display_diagrecs (res->entries->nonsurrogateDiagnostics,
2639 res->entries->num_nonsurrogateDiagnostics);
2642 void process_sortResponse(Z_SortResponse *res)
2644 printf("Received SortResponse: status=");
2645 switch (*res->sortStatus)
2647 case Z_SortStatus_success:
2648 printf ("success"); break;
2649 case Z_SortStatus_partial_1:
2650 printf ("partial"); break;
2651 case Z_SortStatus_failure:
2652 printf ("failure"); break;
2654 printf ("unknown (%d)", *res->sortStatus);
2657 print_refid (res->referenceId);
2658 if (res->diagnostics)
2659 display_diagrecs(res->diagnostics,
2660 res->num_diagnostics);
2663 void process_deleteResultSetResponse (Z_DeleteResultSetResponse *res)
2665 printf("Got deleteResultSetResponse status=%d\n",
2666 *res->deleteOperationStatus);
2667 if (res->deleteListStatuses)
2670 for (i = 0; i < res->deleteListStatuses->num; i++)
2672 printf ("%s status=%d\n", res->deleteListStatuses->elements[i]->id,
2673 *res->deleteListStatuses->elements[i]->status);
2678 int cmd_sort_generic(const char *arg, int newset)
2682 printf("Session not initialized yet\n");
2687 if (!ODR_MASK_GET(session->options, Z_Options_sort))
2689 printf("Target doesn't support sort\n");
2694 if (send_sortrequest(arg, newset) < 0)
2701 int cmd_sort(const char *arg)
2703 return cmd_sort_generic (arg, 0);
2706 int cmd_sort_newset (const char *arg)
2708 return cmd_sort_generic (arg, 1);
2711 int cmd_scan(const char *arg)
2720 printf("Session not initialized yet\n");
2724 if (!ODR_MASK_GET(session->options, Z_Options_scan))
2726 printf("Target doesn't support scan\n");
2731 strcpy (last_scan_query, arg);
2732 if (send_scanrequest(arg, 1, 20, 0) < 0)
2737 if (send_scanrequest(last_scan_query, 1, 20, last_scan_line) < 0)
2743 int cmd_schema(const char *arg)
2745 xfree(record_schema);
2748 record_schema = xstrdup(arg);
2752 int cmd_format(const char *arg)
2757 printf("Usage: format <recordsyntax>\n");
2760 nsyntax = oid_getvalbyname (arg);
2761 if (strcmp(arg, "none") && nsyntax == VAL_NONE)
2763 printf ("unknown record syntax\n");
2766 recordsyntax = nsyntax;
2770 int cmd_elements(const char *arg)
2772 static Z_ElementSetNames esn;
2773 static char what[100];
2777 elementSetNames = 0;
2781 esn.which = Z_ElementSetNames_generic;
2782 esn.u.generic = what;
2783 elementSetNames = &esn;
2787 int cmd_attributeset(const char *arg)
2793 printf("Usage: attributeset <setname>\n");
2796 sscanf(arg, "%s", what);
2797 if (p_query_attset (what))
2799 printf("Unknown attribute set name\n");
2805 int cmd_querytype (const char *arg)
2807 if (!strcmp (arg, "ccl"))
2808 queryType = QueryType_CCL;
2809 else if (!strcmp (arg, "prefix") || !strcmp(arg, "rpn"))
2810 queryType = QueryType_Prefix;
2811 else if (!strcmp (arg, "ccl2rpn") || !strcmp (arg, "cclrpn"))
2812 queryType = QueryType_CCL2RPN;
2813 else if (!strcmp(arg, "cql"))
2814 queryType = QueryType_CQL;
2815 else if (!strcmp (arg, "cql2rpn") || !strcmp (arg, "cqlrpn"))
2816 queryType = QueryType_CQL2RPN;
2819 printf ("Querytype must be one of:\n");
2820 printf (" prefix - Prefix query\n");
2821 printf (" ccl - CCL query\n");
2822 printf (" ccl2rpn - CCL query converted to RPN\n");
2823 printf (" cql - CQL\n");
2824 printf (" cql2rpn - CQL query converted to RPN\n");
2830 int cmd_refid (const char *arg)
2836 refid = (char *) xmalloc (strlen(arg)+1);
2837 strcpy (refid, arg);
2842 int cmd_close(const char *arg)
2851 apdu = zget_APDU(out, Z_APDU_close);
2852 req = apdu->u.close;
2853 *req->closeReason = Z_Close_finished;
2855 printf("Sent close request.\n");
2860 int cmd_packagename(const char* arg)
2862 xfree (esPackageName);
2863 esPackageName = NULL;
2865 esPackageName = xstrdup(arg);
2869 int cmd_proxy(const char* arg)
2874 yazProxy = xstrdup (arg);
2878 int cmd_marccharset(const char *arg)
2883 if (sscanf(arg, "%29s", l1) < 1)
2885 xfree (marcCharset);
2887 if (strcmp(l1, "-"))
2888 marcCharset = xstrdup(l1);
2892 int cmd_charset(const char* arg)
2894 char l1[30], l2[30];
2897 if (sscanf(arg, "%29s %29s", l1, l2) < 1)
2899 printf("Current negotiation character set is `%s'\n",
2900 negotiationCharset ? negotiationCharset: "none");
2901 printf("Current output character set is `%s'\n",
2902 outputCharset ? outputCharset: "none");
2905 xfree (negotiationCharset);
2906 negotiationCharset = NULL;
2907 if (*l1 && strcmp(l1, "-"))
2909 negotiationCharset = xstrdup(l1);
2910 printf ("Character set negotiation : %s\n", negotiationCharset);
2913 printf ("Character set negotiation disabled\n");
2916 xfree (outputCharset);
2918 if (!strcmp(l2, "auto") && codeset)
2922 printf ("output charset: %s\n", codeset);
2923 outputCharset = xstrdup(codeset);
2928 printf ("No codeset found on this system\n");
2930 else if (strcmp(l2, "-"))
2931 outputCharset = xstrdup(l2);
2933 printf ("Output charset conversion disabled\n");
2939 int cmd_lang(const char* arg)
2942 printf("Current language is `%s'\n", (yazLang)?yazLang:NULL);
2949 yazLang = (char *) xmalloc (strlen(arg)+1);
2950 strcpy (yazLang, arg);
2955 int cmd_source(const char* arg)
2957 /* first should open the file and read one line at a time.. */
2959 char line[1024], *cp;
2962 fprintf(stderr,"Error in source command use a filename\n");
2966 includeFile = fopen (arg, "r");
2969 fprintf(stderr,"Unable to open file %s for reading\n",arg);
2973 while(!feof(includeFile)) {
2974 memset(line,0,sizeof(line));
2975 fgets(line,sizeof(line),includeFile);
2977 if(strlen(line) < 2) continue;
2978 if(line[0] == '#') continue;
2980 if ((cp = strrchr (line, '\n')))
2983 process_cmd_line(line);
2986 if(fclose(includeFile)<0) {
2987 perror("unable to close include file");
2993 int cmd_subshell(const char* args)
2998 system(getenv("SHELL"));
3004 int cmd_set_berfile(const char *arg)
3006 if (ber_file && ber_file != stdout && ber_file != stderr)
3008 if (!strcmp(arg, ""))
3010 else if (!strcmp(arg, "-"))
3013 ber_file = fopen(arg, "a");
3017 int cmd_set_apdufile(const char *arg)
3019 if(apdu_file && apdu_file != stderr && apdu_file != stderr)
3021 if (!strcmp(arg, ""))
3023 else if (!strcmp(arg, "-"))
3027 apdu_file = fopen(arg, "a");
3029 perror("unable to open apdu log file");
3032 odr_setprint(print, apdu_file);
3036 int cmd_set_cclfile(const char* arg)
3040 bibset = ccl_qual_mk ();
3041 inf = fopen (arg, "r");
3043 perror("unable to open CCL file");
3046 ccl_qual_file (bibset, inf);
3049 strcpy(ccl_fields,arg);
3053 int cmd_set_cqlfile(const char* arg)
3055 cql_transform_t newcqltrans;
3057 if ((newcqltrans = cql_transform_open_fname(arg)) == 0) {
3058 perror("unable to open CQL file");
3062 cql_transform_close(cqltrans);
3064 cqltrans = newcqltrans;
3065 strcpy(cql_fields, arg);
3069 int cmd_set_auto_reconnect(const char* arg)
3071 if(strlen(arg)==0) {
3072 auto_reconnect = ! auto_reconnect;
3073 } else if(strcmp(arg,"on")==0) {
3075 } else if(strcmp(arg,"off")==0) {
3078 printf("Error use on or off\n");
3083 printf("Set auto reconnect enabled.\n");
3085 printf("Set auto reconnect disabled.\n");
3090 int cmd_set_marcdump(const char* arg)
3092 if(marc_file && marc_file != stderr) { /* don't close stdout*/
3096 if (!strcmp(arg, ""))
3098 else if (!strcmp(arg, "-"))
3102 marc_file = fopen(arg, "a");
3104 perror("unable to open marc log file");
3110 this command takes 3 arge {name class oid}
3112 int cmd_register_oid(const char* args) {
3117 {"appctx",CLASS_APPCTX},
3118 {"absyn",CLASS_ABSYN},
3119 {"attset",CLASS_ATTSET},
3120 {"transyn",CLASS_TRANSYN},
3121 {"diagset",CLASS_DIAGSET},
3122 {"recsyn",CLASS_RECSYN},
3123 {"resform",CLASS_RESFORM},
3124 {"accform",CLASS_ACCFORM},
3125 {"extserv",CLASS_EXTSERV},
3126 {"userinfo",CLASS_USERINFO},
3127 {"elemspec",CLASS_ELEMSPEC},
3128 {"varset",CLASS_VARSET},
3129 {"schema",CLASS_SCHEMA},
3130 {"tagset",CLASS_TAGSET},
3131 {"general",CLASS_GENERAL},
3132 {0,(enum oid_class) 0}
3134 char oname_str[101], oclass_str[101], oid_str[101];
3137 oid_class oidclass = CLASS_GENERAL;
3138 int val = 0, oid[OID_SIZE];
3139 struct oident * new_oident=NULL;
3141 if (sscanf (args, "%100[^ ] %100[^ ] %100s",
3142 oname_str,oclass_str, oid_str) < 1) {
3143 printf("Error in regristrate command \n");
3147 for (i = 0; oid_classes[i].className; i++) {
3148 if (!strcmp(oid_classes[i].className, oclass_str))
3150 oidclass=oid_classes[i].oclass;
3155 if(!(oid_classes[i].className)) {
3156 printf("Unknonwn oid class %s\n",oclass_str);
3164 while (isdigit (*name))
3166 val = val*10 + (*name - '0');
3179 new_oident=oid_addent (oid,PROTO_GENERAL,oidclass,oname_str,VAL_DYNAMIC);
3180 if(strcmp(new_oident->desc,oname_str)) {
3181 fprintf(stderr,"oid is already named as %s, regristration faild\n",
3187 int cmd_push_command(const char* arg)
3189 #if HAVE_READLINE_HISTORY_H
3193 fprintf(stderr,"Not compiled with the readline/history module\n");
3198 void source_rcfile()
3200 /* Look for a $HOME/.yazclientrc and source it if it exists */
3201 struct stat statbuf;
3203 char* homedir=getenv("HOME");
3205 if(!homedir) return;
3207 sprintf(buffer,"%s/.yazclientrc",homedir);
3209 if(stat(buffer,&statbuf)==0) {
3213 if(stat(".yazclientrc",&statbuf)==0) {
3214 cmd_source(".yazclientrc");
3219 static void initialize(void)
3224 if (!(out = odr_createmem(ODR_ENCODE)) ||
3225 !(in = odr_createmem(ODR_DECODE)) ||
3226 !(print = odr_createmem(ODR_PRINT)))
3228 fprintf(stderr, "failed to allocate ODR streams\n");
3233 setvbuf(stdout, 0, _IONBF, 0);
3235 odr_setprint(print, apdu_file);
3237 bibset = ccl_qual_mk ();
3238 inf = fopen (ccl_fields, "r");
3241 ccl_qual_file (bibset, inf);
3245 cqltrans = cql_transform_open_fname(cql_fields);
3246 /* If this fails, no problem: we detect cqltrans == 0 later */
3248 #if HAVE_READLINE_READLINE_H
3249 rl_attempted_completion_function = (CPPFunction*)readline_completer;
3253 for(i=0; i<maxOtherInfosSupported; ++i) {
3254 extraOtherInfos[i].oidval = -1;
3261 #if HAVE_GETTIMEOFDAY
3262 struct timeval tv_start, tv_end;
3266 static void handle_srw_record(Z_SRW_record *rec)
3268 if (rec->recordPosition)
3270 printf ("pos=%d", *rec->recordPosition);
3271 setno = *rec->recordPosition + 1;
3273 if (rec->recordSchema)
3274 printf (" schema=%s", rec->recordSchema);
3276 if (rec->recordData_buf && rec->recordData_len)
3277 fwrite(rec->recordData_buf, 1, rec->recordData_len, stdout);
3279 printf ("No data!");
3283 static void handle_srw_explain_response(Z_SRW_explainResponse *res)
3285 handle_srw_record(&res->record);
3288 static void handle_srw_response(Z_SRW_searchRetrieveResponse *res)
3292 printf ("Received SRW SearchRetrieve Response\n");
3294 for (i = 0; i<res->num_diagnostics; i++)
3296 printf ("SRW diagnostic %d %s\n",
3297 *res->diagnostics[i].code,
3298 yaz_diag_srw_str(*res->diagnostics[i].code));
3300 if (res->diagnostics[i].details)
3301 printf ("Details: %s\n", res->diagnostics[i].details);
3303 if (res->numberOfRecords)
3304 printf ("Number of hits: %d\n", *res->numberOfRecords);
3305 for (i = 0; i<res->num_records; i++)
3306 handle_srw_record(res->records + i);
3309 static void http_response(Z_HTTP_Response *hres)
3312 const char *content_type = z_HTTP_header_lookup(hres->headers,
3314 const char *connection_head = z_HTTP_header_lookup(hres->headers,
3316 if (content_type && !yaz_strcmp_del("text/xml", content_type, "; "))
3318 Z_SOAP *soap_package = 0;
3319 ODR o = odr_createmem(ODR_DECODE);
3320 Z_SOAP_Handler soap_handlers[2] = {
3321 {"http://www.loc.gov/zing/srw/", 0,
3322 (Z_SOAP_fun) yaz_srw_codec},
3325 ret = z_soap_codec(o, &soap_package,
3326 &hres->content_buf, &hres->content_len,
3328 if (!ret && soap_package->which == Z_SOAP_generic &&
3329 soap_package->u.generic->no == 0)
3331 Z_SRW_PDU *sr = soap_package->u.generic->p;
3332 if (sr->which == Z_SRW_searchRetrieve_response)
3333 handle_srw_response(sr->u.response);
3334 else if (sr->which == Z_SRW_explain_response)
3335 handle_srw_explain_response(sr->u.explain_response);
3339 else if (soap_package && (soap_package->which == Z_SOAP_fault
3340 || soap_package->which == Z_SOAP_error))
3342 printf ("HTTP Error Status=%d\n", hres->code);
3343 printf ("SOAP Fault code %s\n",
3344 soap_package->u.fault->fault_code);
3345 printf ("SOAP Fault string %s\n",
3346 soap_package->u.fault->fault_string);
3347 if (soap_package->u.fault->details)
3348 printf ("SOAP Details %s\n",
3349 soap_package->u.fault->details);
3357 if (hres->code != 200)
3359 printf ("HTTP Error Status=%d\n", hres->code);
3363 printf ("Decoding of SRW package failed\n");
3369 if (!strcmp(hres->version, "1.0"))
3371 /* HTTP 1.0: only if Keep-Alive we stay alive.. */
3372 if (!connection_head || strcmp(connection_head, "Keep-Alive"))
3377 /* HTTP 1.1: only if no close we stay alive .. */
3378 if (connection_head && !strcmp(connection_head, "close"))
3385 void wait_and_handle_response()
3387 int reconnect_ok = 1;
3390 int netbufferlen = 0;
3395 res = cs_get(conn, &netbuffer, &netbufferlen);
3396 if (reconnect_ok && res <= 0 && protocol == PROTO_HTTP)
3407 buf_out = odr_getbuf(out, &len_out, 0);
3409 do_hex_dump(buf_out, len_out);
3411 cs_put(conn, buf_out, len_out);
3419 printf("Target closed connection\n");
3424 odr_reset(in); /* release APDU from last round */
3426 do_hex_dump(netbuffer, res);
3427 odr_setbuf(in, netbuffer, res, 0);
3429 if (!z_GDU(in, &gdu, 0, 0))
3431 FILE *f = ber_file ? ber_file : stdout;
3432 odr_perror(in, "Decoding incoming APDU");
3433 fprintf(f, "[Near %d]\n", odr_offset(in));
3434 fprintf(f, "Packet dump:\n---------\n");
3435 odr_dumpBER(f, netbuffer, res);
3436 fprintf(f, "---------\n");
3439 z_GDU(print, &gdu, 0, 0);
3442 if (conn && cs_more(conn))
3447 odr_dumpBER(ber_file, netbuffer, res);
3448 if (apdu_file && !z_GDU(print, &gdu, 0, 0))
3450 odr_perror(print, "Failed to print incoming APDU");
3454 if (gdu->which == Z_GDU_Z3950)
3456 Z_APDU *apdu = gdu->u.z3950;
3459 case Z_APDU_initResponse:
3460 process_initResponse(apdu->u.initResponse);
3462 case Z_APDU_searchResponse:
3463 process_searchResponse(apdu->u.searchResponse);
3465 case Z_APDU_scanResponse:
3466 process_scanResponse(apdu->u.scanResponse);
3468 case Z_APDU_presentResponse:
3469 print_refid (apdu->u.presentResponse->referenceId);
3471 *apdu->u.presentResponse->numberOfRecordsReturned;
3472 if (apdu->u.presentResponse->records)
3473 display_records(apdu->u.presentResponse->records);
3475 printf("No records.\n");
3476 printf ("nextResultSetPosition = %d\n",
3477 *apdu->u.presentResponse->nextResultSetPosition);
3479 case Z_APDU_sortResponse:
3480 process_sortResponse(apdu->u.sortResponse);
3482 case Z_APDU_extendedServicesResponse:
3483 printf("Got extended services response\n");
3484 process_ESResponse(apdu->u.extendedServicesResponse);
3487 printf("Target has closed the association.\n");
3488 process_close(apdu->u.close);
3490 case Z_APDU_resourceControlRequest:
3491 process_resourceControlRequest
3492 (apdu->u.resourceControlRequest);
3494 case Z_APDU_deleteResultSetResponse:
3495 process_deleteResultSetResponse(apdu->u.
3496 deleteResultSetResponse);
3499 printf("Received unknown APDU type (%d).\n",
3505 else if (gdu->which == Z_GDU_HTTP_Response)
3507 http_response(gdu->u.HTTP_Response);
3510 if (conn && !cs_more(conn))
3515 #if HAVE_GETTIMEOFDAY
3516 gettimeofday (&tv_end, 0);
3518 printf ("S/U S/U=%ld/%ld %ld/%ld",
3519 (long) tv_start.tv_sec,
3520 (long) tv_start.tv_usec,
3521 (long) tv_end.tv_sec,
3522 (long) tv_end.tv_usec);
3524 printf ("Elapsed: %.6f\n",
3525 (double) tv_end.tv_usec / 1e6 + tv_end.tv_sec -
3526 ((double) tv_start.tv_usec / 1e6 + tv_start.tv_sec));
3533 int cmd_cclparse(const char* arg)
3536 struct ccl_rpn_node *rpn=NULL;
3539 rpn = ccl_find_str (bibset, arg, &error, &pos);
3542 printf ("%*s^ - ", 3+strlen(last_cmd)+1+pos, " ");
3543 printf ("%s\n", ccl_err_msg (error));
3549 ccl_pr_tree(rpn, stdout);
3553 ccl_rpn_delete(rpn);
3561 int cmd_set_otherinfo(const char* args)
3563 char oid[101], otherinfoString[101];
3568 sscan_res = sscanf (args, "%d %100[^ ] %100s", &otherinfoNo, oid, otherinfoString);
3570 /* reset this otherinfo */
3571 if(otherinfoNo>=maxOtherInfosSupported) {
3572 printf("Error otherinfo index to large (%d>%d)\n",otherinfoNo,maxOtherInfosSupported);
3574 extraOtherInfos[otherinfoNo].oidval = -1;
3575 if(extraOtherInfos[otherinfoNo].value) free(extraOtherInfos[otherinfoNo].value);
3579 printf("Error in set_otherinfo command \n");
3583 if(otherinfoNo>=maxOtherInfosSupported) {
3584 printf("Error otherinfo index to large (%d>%d)\n",otherinfoNo,maxOtherInfosSupported);
3587 oidval = oid_getvalbyname (oid);
3589 printf("Error in set_otherinfo command unknown oid %s \n",oid);
3592 extraOtherInfos[otherinfoNo].oidval = oidval;
3593 if(extraOtherInfos[otherinfoNo].value) free(extraOtherInfos[otherinfoNo].value);
3594 extraOtherInfos[otherinfoNo].value = strdup(otherinfoString);
3599 int cmd_list_otherinfo(const char* args)
3603 if(strlen(args)>0) {
3605 if( i >= maxOtherInfosSupported ) {
3606 printf("Error otherinfo index to large (%d>%d)\n",i,maxOtherInfosSupported);
3610 if(extraOtherInfos[i].oidval != -1)
3611 printf(" otherinfo %d %s %s\n",
3613 yaz_z3950_oid_value_to_str(
3614 (enum oid_value) extraOtherInfos[i].oidval,
3616 extraOtherInfos[i].value);
3619 for(i=0; i<maxOtherInfosSupported; ++i) {
3620 if(extraOtherInfos[i].oidval != -1)
3621 printf(" otherinfo %d %s %s\n",
3623 yaz_z3950_oid_value_to_str(
3624 (enum oid_value) extraOtherInfos[i].oidval,
3626 extraOtherInfos[i].value);
3634 int cmd_list_all(const char* args) {
3637 /* connection options */
3639 printf("Connected to : %s\n",last_open_command);
3641 if(last_open_command)
3642 printf("Not connected to : %s\n",last_open_command);
3644 printf("Not connected : \n");
3647 if(yazProxy) printf("using proxy : %s\n",yazProxy);
3649 printf("auto_reconnect : %s\n",auto_reconnect?"on":"off");
3652 printf("Authentication : none\n");
3654 switch(auth->which) {
3655 case Z_IdAuthentication_idPass:
3656 printf("Authentication : IdPass\n");
3657 printf(" Login User : %s\n",auth->u.idPass->userId?auth->u.idPass->userId:"");
3658 printf(" Login Group : %s\n",auth->u.idPass->groupId?auth->u.idPass->groupId:"");
3659 printf(" Password : %s\n",auth->u.idPass->password?auth->u.idPass->password:"");
3661 case Z_IdAuthentication_open:
3662 printf("Authentication : psOpen\n");
3663 printf(" Open string : %s\n",auth->u.open);
3666 printf("Authentication : Unknown\n");
3669 if (negotiationCharset)
3670 printf("Neg. Character set : `%s'\n", negotiationCharset);
3674 for (i = 0; i<num_databaseNames; i++) printf("%s ",databaseNames[i]);
3678 printf("CCL file : %s\n",ccl_fields);
3679 printf("CQL file : %s\n",cql_fields);
3680 printf("Query type : %s\n",query_type_as_string(queryType));
3682 printf("Named Result Sets : %s\n",setnumber==-1?"off":"on");
3684 /* piggy back options */
3685 printf("ssub/lslb/mspn : %d/%d/%d\n",smallSetUpperBound,largeSetLowerBound,mediumSetPresentNumber);
3687 /* print present related options */
3688 printf("Format : %s\n",yaz_z3950_oid_value_to_str(recordsyntax,CLASS_RECSYN));
3689 printf("Schema : %s\n",record_schema ? record_schema : "not set");
3690 printf("Elements : %s\n",elementSetNames?elementSetNames->u.generic:"");
3692 /* loging options */
3693 printf("APDU log : %s\n",apdu_file?"on":"off");
3694 printf("Record log : %s\n",marc_file?"on":"off");
3697 printf("Other Info: \n");
3698 cmd_list_otherinfo("");
3703 int cmd_clear_otherinfo(const char* args)
3705 if(strlen(args)>0) {
3707 otherinfoNo = atoi(args);
3708 if( otherinfoNo >= maxOtherInfosSupported ) {
3709 printf("Error otherinfo index to large (%d>%d)\n",otherinfoNo,maxOtherInfosSupported);
3713 if(extraOtherInfos[otherinfoNo].oidval != -1) {
3714 /* only clear if set. */
3715 extraOtherInfos[otherinfoNo].oidval=-1;
3716 free(extraOtherInfos[otherinfoNo].value);
3721 for(i=0; i<maxOtherInfosSupported; ++i) {
3722 if (extraOtherInfos[i].oidval!=-1 ) {
3723 extraOtherInfos[i].oidval=-1;
3724 free(extraOtherInfos[i].value);
3731 static int cmd_help (const char *line);
3733 typedef char *(*completerFunctionType)(const char *text, int state);
3737 int (*fun)(const char *arg);
3739 completerFunctionType rl_completerfunction;
3740 int complete_filenames;
3741 char **local_tabcompletes;
3743 {"open", cmd_open, "('tcp'|'ssl')':<host>[':'<port>][/<db>]",NULL,0,NULL},
3744 {"quit", cmd_quit, "",NULL,0,NULL},
3745 {"find", cmd_find, "<query>",NULL,0,NULL},
3746 {"delete", cmd_delete, "<setname>",NULL,0,NULL},
3747 {"base", cmd_base, "<base-name>",NULL,0,NULL},
3748 {"show", cmd_show, "<rec#>['+'<#recs>['+'<setname>]]",NULL,0,NULL},
3749 {"scan", cmd_scan, "<term>",NULL,0,NULL},
3750 {"sort", cmd_sort, "<sortkey> <flag> <sortkey> <flag> ...",NULL,0,NULL},
3751 {"sort+", cmd_sort_newset, "<sortkey> <flag> <sortkey> <flag> ...",NULL,0,NULL},
3752 {"authentication", cmd_authentication, "<acctstring>",NULL,0,NULL},
3753 {"lslb", cmd_lslb, "<largeSetLowerBound>",NULL,0,NULL},
3754 {"ssub", cmd_ssub, "<smallSetUpperBound>",NULL,0,NULL},
3755 {"mspn", cmd_mspn, "<mediumSetPresentNumber>",NULL,0,NULL},
3756 {"status", cmd_status, "",NULL,0,NULL},
3757 {"setnames", cmd_setnames, "",NULL,0,NULL},
3758 {"cancel", cmd_cancel, "",NULL,0,NULL},
3759 {"format", cmd_format, "<recordsyntax>",complete_format,0,NULL},
3760 {"schema", cmd_schema, "<schema>",complete_schema,0,NULL},
3761 {"elements", cmd_elements, "<elementSetName>",NULL,0,NULL},
3762 {"close", cmd_close, "",NULL,0,NULL},
3763 {"attributeset", cmd_attributeset, "<attrset>",complete_attributeset,0,NULL},
3764 {"querytype", cmd_querytype, "<type>",complete_querytype,0,NULL},
3765 {"refid", cmd_refid, "<id>",NULL,0,NULL},
3766 {"itemorder", cmd_itemorder, "ill|item <itemno>",NULL,0,NULL},
3767 {"update", cmd_update, "<action> <recid> [<file>]",NULL,0,NULL},
3768 {"update0", cmd_update0, "<action> <recid> [<file>]",NULL,0,NULL},
3769 {"packagename", cmd_packagename, "<packagename>",NULL,0,NULL},
3770 {"proxy", cmd_proxy, "[('tcp'|'ssl')]<host>[':'<port>]",NULL,0,NULL},
3771 {"charset", cmd_charset, "<nego_charset> <output_charset>",NULL,0,NULL},
3772 {"marccharset", cmd_marccharset, "<charset_name>",NULL,0,NULL},
3773 {"lang", cmd_lang, "<language_code>",NULL,0,NULL},
3774 {".", cmd_source, "<filename>",NULL,1,NULL},
3775 {"!", cmd_subshell, "Subshell command",NULL,1,NULL},
3776 {"set_apdufile", cmd_set_apdufile, "<filename>",NULL,1,NULL},
3777 {"set_berfile", cmd_set_berfile, "<filename>",NULL,1,NULL},
3778 {"set_marcdump", cmd_set_marcdump," <filename>",NULL,1,NULL},
3779 {"set_cclfile", cmd_set_cclfile," <filename>",NULL,1,NULL},
3780 {"set_cqlfile", cmd_set_cqlfile," <filename>",NULL,1,NULL},
3781 {"set_auto_reconnect", cmd_set_auto_reconnect," on|off",complete_auto_reconnect,1,NULL},
3782 {"set_otherinfo", cmd_set_otherinfo,"<otherinfoinddex> <oid> <string>",NULL,0,NULL},
3783 {"register_oid", cmd_register_oid,"<name> <class> <oid>",NULL,0,NULL},
3784 {"push_command", cmd_push_command,"<command>",command_generator,0,NULL},
3785 {"register_tab", cmd_register_tab,"<commandname> <tab>",command_generator,0,NULL},
3786 {"cclparse", cmd_cclparse,"<ccl find command>",NULL,0,NULL},
3787 {"list_otherinfo",cmd_list_otherinfo,"[otherinfoinddex]",NULL,0,NULL},
3788 {"list_all",cmd_list_all,"",NULL,0,NULL},
3789 {"clear_otherinfo",cmd_clear_otherinfo,"",NULL,0,NULL},
3790 /* Server Admin Functions */
3791 {"adm-reindex", cmd_adm_reindex, "<database-name>",NULL,0,NULL},
3792 {"adm-truncate", cmd_adm_truncate, "('database'|'index')<object-name>",NULL,0,NULL},
3793 {"adm-create", cmd_adm_create, "",NULL,0,NULL},
3794 {"adm-drop", cmd_adm_drop, "('database'|'index')<object-name>",NULL,0,NULL},
3795 {"adm-import", cmd_adm_import, "<record-type> <dir> <pattern>",NULL,0,NULL},
3796 {"adm-refresh", cmd_adm_refresh, "",NULL,0,NULL},
3797 {"adm-commit", cmd_adm_commit, "",NULL,0,NULL},
3798 {"adm-shutdown", cmd_adm_shutdown, "",NULL,0,NULL},
3799 {"adm-startup", cmd_adm_startup, "",NULL,0,NULL},
3800 {"explain", cmd_explain, "", NULL, 0, NULL},
3801 {"options", cmd_options, "", NULL, 0, NULL},
3802 {"help", cmd_help, "", NULL,0,NULL},
3806 static int cmd_help (const char *line)
3812 sscanf (line, "%20s", topic);
3815 printf("Commands:\n");
3816 for (i = 0; cmd_array[i].cmd; i++)
3817 if (*topic == 0 || strcmp (topic, cmd_array[i].cmd) == 0)
3818 printf(" %s %s\n", cmd_array[i].cmd, cmd_array[i].ad);
3819 if (strcmp (topic, "find") == 0)
3822 printf (" \"term\" Simple Term\n");
3823 printf (" @attr [attset] type=value op Attribute\n");
3824 printf (" @and opl opr And\n");
3825 printf (" @or opl opr Or\n");
3826 printf (" @not opl opr And-Not\n");
3827 printf (" @set set Result set\n");
3829 printf ("Bib-1 attribute types\n");
3831 printf ("4=Title 7=ISBN 8=ISSN 30=Date 62=Abstract 1003=Author 1016=Any\n");
3832 printf ("2=Relation: ");
3833 printf ("1< 2<= 3= 4>= 5> 6!= 102=Relevance\n");
3834 printf ("3=Position: ");
3835 printf ("1=First in Field 2=First in subfield 3=Any position\n");
3836 printf ("4=Structure: ");
3837 printf ("1=Phrase 2=Word 3=Key 4=Year 5=Date 6=WordList\n");
3838 printf ("5=Truncation: ");
3839 printf ("1=Right 2=Left 3=L&R 100=No 101=# 102=Re-1 103=Re-2\n");
3840 printf ("6=Completeness:");
3841 printf ("1=Incomplete subfield 2=Complete subfield 3=Complete field\n");
3846 int cmd_register_tab(const char* arg) {
3848 char command[101], tabargument[101];
3853 if (sscanf (arg, "%100s %100s", command, tabargument) < 1) {
3857 /* locate the amdn in the list */
3858 for (i = 0; cmd_array[i].cmd; i++) {
3859 if (!strncmp(cmd_array[i].cmd, command, strlen(command))) {
3864 if(!cmd_array[i].cmd) {
3865 fprintf(stderr,"Unknown command %s\n",command);
3870 if(!cmd_array[i].local_tabcompletes)
3871 cmd_array[i].local_tabcompletes = (char **) calloc(1,sizeof(char**));
3875 tabslist = cmd_array[i].local_tabcompletes;
3876 for(;tabslist && *tabslist;tabslist++) {
3880 cmd_array[i].local_tabcompletes = (char **)
3881 realloc(cmd_array[i].local_tabcompletes,(num_of_tabs+2)*sizeof(char**));
3882 tabslist=cmd_array[i].local_tabcompletes;
3883 tabslist[num_of_tabs]=strdup(tabargument);
3884 tabslist[num_of_tabs+1]=NULL;
3889 void process_cmd_line(char* line)
3892 char word[32], arg[1024];
3894 #if HAVE_GETTIMEOFDAY
3895 gettimeofday (&tv_start, 0);
3898 if ((res = sscanf(line, "%31s %1023[^;]", word, arg)) <= 0)
3900 strcpy(word, last_cmd);
3905 strcpy(last_cmd, word);
3907 /* removed tailing spaces from the arg command */
3910 char* lastnonspace=NULL;
3918 *(++lastnonspace) = 0;
3921 for (i = 0; cmd_array[i].cmd; i++)
3922 if (!strncmp(cmd_array[i].cmd, word, strlen(word)))
3924 res = (*cmd_array[i].fun)(arg);
3928 if (!cmd_array[i].cmd) /* dump our help-screen */
3930 printf("Unknown command: %s.\n", word);
3931 printf("use help for list of commands\n");
3932 /* cmd_help (""); */
3936 if(apdu_file) fflush(apdu_file);
3939 wait_and_handle_response();
3948 char *command_generator(const char *text, int state)
3954 for( ; cmd_array[idx].cmd; ++idx) {
3955 if (!strncmp(cmd_array[idx].cmd,text,strlen(text))) {
3956 ++idx; /* skip this entry on the next run */
3957 return strdup(cmd_array[idx-1].cmd);
3965 This function only known how to complete on the first word
3967 char ** readline_completer(char *text, int start, int end) {
3968 #if HAVE_READLINE_READLINE_H
3970 completerFunctionType completerToUse;
3973 #if HAVE_READLINE_RL_COMPLETION_MATCHES
3974 char** res=rl_completion_matches(text,
3977 char** res=completion_matches(text,
3978 (CPFunction*)command_generator);
3980 rl_attempted_completion_over = 1;
3983 char arg[1024],word[32];
3985 if ((res = sscanf(rl_line_buffer, "%31s %1023[^;]", word, arg)) <= 0) {
3986 rl_attempted_completion_over = 1;
3990 for (i = 0; cmd_array[i].cmd; i++) {
3991 if (!strncmp(cmd_array[i].cmd, word, strlen(word))) {
3996 if(!cmd_array[i].cmd) return NULL;
3998 curret_global_list = cmd_array[i].local_tabcompletes;
4000 completerToUse = cmd_array[i].rl_completerfunction;
4001 if(completerToUse==NULL) /* if no pr. command completer is defined use the default completer */
4002 completerToUse = default_completer;
4004 if(completerToUse) {
4005 #ifdef HAVE_READLINE_RL_COMPLETION_MATCHES
4007 rl_completion_matches(text,
4011 completion_matches(text,
4012 (CPFunction*)completerToUse);
4014 if(!cmd_array[i].complete_filenames)
4015 rl_attempted_completion_over = 1;
4018 if(!cmd_array[i].complete_filenames)
4019 rl_attempted_completion_over = 1;
4029 static void client(void)
4035 #if HAVE_GETTIMEOFDAY
4036 gettimeofday (&tv_start, 0);
4041 char *line_in = NULL;
4042 #if HAVE_READLINE_READLINE_H
4045 line_in=readline(C_PROMPT);
4048 #if HAVE_READLINE_HISTORY_H
4050 add_history(line_in);
4052 strncpy(line, line_in, 1023);
4061 if (!fgets(line, 1023, stdin))
4063 if ((end_p = strchr (line, '\n')))
4066 process_cmd_line(line);
4070 static void show_version(void)
4074 yaz_version(vstr, 0);
4075 printf ("YAZ version: %s\n", YAZ_VERSION);
4076 if (strcmp(vstr, YAZ_VERSION))
4077 printf ("YAZ DLL/SO: %s\n", vstr);
4081 int main(int argc, char **argv)
4084 char *open_command = 0;
4085 char *auth_command = 0;
4090 if (!setlocale(LC_CTYPE, ""))
4091 fprintf (stderr, "setlocale failed\n");
4095 codeset = nl_langinfo(CODESET);
4099 outputCharset = xstrdup(codeset);
4101 ODR_MASK_SET(&z3950_options, Z_Options_search);
4102 ODR_MASK_SET(&z3950_options, Z_Options_present);
4103 ODR_MASK_SET(&z3950_options, Z_Options_namedResultSets);
4104 ODR_MASK_SET(&z3950_options, Z_Options_triggerResourceCtrl);
4105 ODR_MASK_SET(&z3950_options, Z_Options_scan);
4106 ODR_MASK_SET(&z3950_options, Z_Options_sort);
4107 ODR_MASK_SET(&z3950_options, Z_Options_extendedServices);
4108 ODR_MASK_SET(&z3950_options, Z_Options_delSet);
4110 while ((ret = options("k:c:q:a:b:m:v:p:u:t:Vxd:", argv, argc, &arg)) != -2)
4117 open_command = (char *) xmalloc (strlen(arg)+6);
4118 strcpy (open_command, "open ");
4119 strcat (open_command, arg);
4123 dump_file_prefix = arg;
4126 kilobytes = atoi(arg);
4129 if (!(marc_file = fopen (arg, "a")))
4136 outputCharset = xstrdup(arg);
4139 strncpy (ccl_fields, arg, sizeof(ccl_fields)-1);
4140 ccl_fields[sizeof(ccl_fields)-1] = '\0';
4143 strncpy (cql_fields, arg, sizeof(cql_fields)-1);
4144 cql_fields[sizeof(cql_fields)-1] = '\0';
4147 if (!strcmp(arg, "-"))
4150 ber_file=fopen(arg, "a");
4153 if (!strcmp(arg, "-"))
4156 apdu_file=fopen(arg, "a");
4162 yazProxy=strdup(arg);
4167 auth_command = (char *) xmalloc (strlen(arg)+6);
4168 strcpy (auth_command, "auth ");
4169 strcat (auth_command, arg);
4173 yaz_log_init(yaz_log_mask_str(arg), "", 0);
4179 fprintf (stderr, "Usage: %s [-m <marclog>] [ -a <apdulog>] "
4180 "[-b berdump] [-c cclfields] \n"
4181 "[-q cqlfields] [-p <proxy-addr>] [-u <auth>] "
4182 "[-k size] [-d dump] [-V] [<server-addr>]\n",
4190 #ifdef HAVE_GETTIMEOFDAY
4191 gettimeofday (&tv_start, 0);
4193 process_cmd_line (auth_command);
4194 #if HAVE_READLINE_HISTORY_H
4195 add_history(auth_command);
4197 xfree(auth_command);
4201 #ifdef HAVE_GETTIMEOFDAY
4202 gettimeofday (&tv_start, 0);
4204 process_cmd_line (open_command);
4205 #if HAVE_READLINE_HISTORY_H
4206 add_history(open_command);
4208 xfree(open_command);
4219 * vim600: sw=4 ts=8 fdm=marker
4220 * vim<600: sw=4 ts=8