2 * Copyright (c) 1995-2004, Index Data
3 * See the file LICENSE for details.
5 * $Id: client.c,v 1.224 2004-01-12 12:11:57 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 int process_initResponse(Z_InitResponse *res)
332 /* save session parameters for later use */
333 session_mem = odr_extract_mem(in);
336 for (ver = 0; ver<5; ver++)
337 if (!ODR_MASK_GET(res->protocolVersion, ver))
341 printf("Connection rejected by v%d target.\n", ver);
343 printf("Connection accepted by v%d target.\n", ver);
344 if (res->implementationId)
345 printf("ID : %s\n", res->implementationId);
346 if (res->implementationName)
347 printf("Name : %s\n", res->implementationName);
348 if (res->implementationVersion)
349 printf("Version: %s\n", res->implementationVersion);
350 if (res->userInformationField)
352 Z_External *uif = res->userInformationField;
353 if (uif->which == Z_External_userInfo1) {
354 render_initUserInfo(uif->u.userInfo1);
356 printf("UserInformationfield:\n");
357 if (!z_External(print, (Z_External**)&uif, 0, 0)) {
358 odr_perror(print, "Printing userinfo\n");
361 if (uif->which == Z_External_octet) {
362 printf("Guessing visiblestring:\n");
363 printf("'%s'\n", uif->u. octet_aligned->buf);
364 } else if (uif->which == Z_External_single) {
365 /* Peek at any private Init-diagnostic APDUs */
366 Odr_any *sat = uif->u.single_ASN1_type;
367 printf("### NAUGHTY: External is '%s'\n", sat->buf);
373 if (ODR_MASK_GET(res->options, Z_Options_search))
375 if (ODR_MASK_GET(res->options, Z_Options_present))
377 if (ODR_MASK_GET(res->options, Z_Options_delSet))
379 if (ODR_MASK_GET(res->options, Z_Options_resourceReport))
380 printf (" resourceReport");
381 if (ODR_MASK_GET(res->options, Z_Options_resourceCtrl))
382 printf (" resourceCtrl");
383 if (ODR_MASK_GET(res->options, Z_Options_accessCtrl))
384 printf (" accessCtrl");
385 if (ODR_MASK_GET(res->options, Z_Options_scan))
387 if (ODR_MASK_GET(res->options, Z_Options_sort))
389 if (ODR_MASK_GET(res->options, Z_Options_extendedServices))
390 printf (" extendedServices");
391 if (ODR_MASK_GET(res->options, Z_Options_level_1Segmentation))
392 printf (" level1Segmentation");
393 if (ODR_MASK_GET(res->options, Z_Options_level_2Segmentation))
394 printf (" level2Segmentation");
395 if (ODR_MASK_GET(res->options, Z_Options_concurrentOperations))
396 printf (" concurrentOperations");
397 if (ODR_MASK_GET(res->options, Z_Options_namedResultSets))
399 printf (" namedResultSets");
402 if (ODR_MASK_GET(res->options, Z_Options_encapsulation))
403 printf (" encapsulation");
404 if (ODR_MASK_GET(res->options, Z_Options_resultCount))
405 printf (" resultCount");
406 if (ODR_MASK_GET(res->options, Z_Options_negotiationModel))
407 printf (" negotiationModel");
408 if (ODR_MASK_GET(res->options, Z_Options_duplicateDetection))
409 printf (" duplicateDetection");
410 if (ODR_MASK_GET(res->options, Z_Options_queryType104))
411 printf (" queryType104");
414 if (ODR_MASK_GET(res->options, Z_Options_negotiationModel)) {
416 Z_CharSetandLanguageNegotiation *p =
417 yaz_get_charneg_record(res->otherInfo);
421 char *charset=NULL, *lang=NULL;
424 yaz_get_response_charneg(session_mem, p, &charset, &lang,
427 if (outputCharset && negotiationCharset) {
428 odr_set_charset (out, charset, outputCharset);
429 odr_set_charset (in, outputCharset, charset);
432 odr_set_charset (out, 0, 0);
433 odr_set_charset (in, 0, 0);
436 printf("Accepted character set : %s\n", charset);
437 printf("Accepted code language : %s\n", lang ? lang : "none");
438 printf("Accepted records in ...: %d\n", selected );
446 static void render_initUserInfo(Z_OtherInformation *ui1) {
448 printf("Init response contains %d otherInfo unit%s:\n",
449 ui1->num_elements, ui1->num_elements == 1 ? "" : "s");
451 for (i = 0; i < ui1->num_elements; i++) {
452 Z_OtherInformationUnit *unit = ui1->list[i];
453 printf(" %d: otherInfo unit contains ", i+1);
454 if (unit->which == Z_OtherInfo_externallyDefinedInfo &&
455 unit->information.externallyDefinedInfo->which ==
457 render_diag(unit->information.externallyDefinedInfo->u.diag1);
459 printf("unsupported otherInfo unit type %d\n", unit->which);
465 /* ### should this share code with display_diagrecs()? */
466 static void render_diag(Z_DiagnosticFormat *diag) {
469 printf("%d diagnostic%s:\n", diag->num, diag->num == 1 ? "" : "s");
470 for (i = 0; i < diag->num; i++) {
471 Z_DiagnosticFormat_s *ds = diag->elements[i];
472 printf(" %d: ", i+1);
474 case Z_DiagnosticFormat_s_defaultDiagRec: {
475 Z_DefaultDiagFormat *dd = ds->u.defaultDiagRec;
476 /* ### should check `dd->diagnosticSetId' */
477 printf("code=%d (%s)", *dd->condition,
478 diagbib1_str(*dd->condition));
479 /* Both types of addinfo are the same, so use type-pun */
480 if (dd->u.v2Addinfo != 0)
481 printf(",\n\taddinfo='%s'", dd->u.v2Addinfo);
484 case Z_DiagnosticFormat_s_explicitDiagnostic:
485 printf("Explicit diagnostic (not supported)");
488 printf("Unrecognised diagnostic type %d", ds->which);
492 if (ds->message != 0)
493 printf(", message='%s'", ds->message);
499 static int set_base(const char *arg)
504 for (i = 0; i<num_databaseNames; i++)
505 xfree (databaseNames[i]);
506 num_databaseNames = 0;
510 if (!(cp = strchr(arg, ' ')))
511 cp = arg + strlen(arg);
514 databaseNames[num_databaseNames] = (char *)xmalloc (1 + cp - arg);
515 memcpy (databaseNames[num_databaseNames], arg, cp - arg);
516 databaseNames[num_databaseNames][cp - arg] = '\0';
518 for (cp1 = databaseNames[num_databaseNames]; *cp1 ; cp1++)
527 if (num_databaseNames == 0)
529 num_databaseNames = 1;
530 databaseNames[0] = xstrdup("");
535 static int cmd_base(const char *arg)
539 printf("Usage: base <database> <database> ...\n");
542 return set_base(arg);
545 void cmd_open_remember_last_open_command(const char* arg, char* new_open_command)
547 if(last_open_command != arg)
549 if(last_open_command) xfree(last_open_command);
550 last_open_command = xstrdup(new_open_command);
554 int session_connect(const char *arg)
557 char type_and_host[101];
558 const char *basep = 0;
565 nmem_destroy (session_mem);
569 cs_get_host_args(arg, &basep);
571 strncpy(type_and_host, arg, sizeof(type_and_host)-1);
572 type_and_host[sizeof(type_and_host)-1] = '\0';
574 cmd_open_remember_last_open_command(arg,type_and_host);
577 conn = cs_create_host(yazProxy, 1, &add);
579 conn = cs_create_host(arg, 1, &add);
582 printf ("Couldn't create comstack\n");
587 if (conn->protocol == PROTO_HTTP)
589 printf ("SRW/HTTP not enabled in this YAZ\n");
595 protocol = conn->protocol;
596 if (conn->protocol == PROTO_HTTP)
600 printf("Connecting...");
602 if (cs_connect(conn, add) < 0)
604 printf ("error = %s\n", cs_strerror(conn));
605 if (conn->cerrno == CSYSERR)
608 yaz_strerror(msg, sizeof(msg));
609 printf ("%s\n", msg);
618 if (protocol == PROTO_Z3950)
620 send_initRequest(type_and_host);
626 int cmd_open(const char *arg)
630 strncpy (cur_host, arg, sizeof(cur_host)-1);
631 cur_host[sizeof(cur_host)-1] = 0;
633 return session_connect(cur_host);
640 if(!( auto_reconnect && last_open_command) ) return ;
642 open_command = (char *) xmalloc (strlen(last_open_command)+6);
643 strcpy (open_command, "open ");
645 strcat (open_command, last_open_command);
647 process_cmd_line(open_command);
652 int cmd_authentication(const char *arg)
654 static Z_IdAuthentication au;
655 static char user[40], group[40], pass[40];
656 static Z_IdPass idPass;
661 printf("Auth field set to null\n");
665 r = sscanf (arg, "%39s %39s %39s", user, group, pass);
668 printf("Authentication set to null\n");
674 if (!strcmp(user, "-")) {
675 au.which = Z_IdAuthentication_anonymous;
676 printf("Authentication set to Anonymous\n");
678 au.which = Z_IdAuthentication_open;
680 printf("Authentication set to Open (%s)\n", user);
686 au.which = Z_IdAuthentication_idPass;
687 au.u.idPass = &idPass;
688 idPass.groupId = NULL;
689 idPass.userId = user;
690 idPass.password = group;
691 printf("Authentication set to User (%s), Pass (%s)\n", user, group);
696 au.which = Z_IdAuthentication_idPass;
697 au.u.idPass = &idPass;
698 idPass.groupId = group;
699 idPass.userId = user;
700 idPass.password = pass;
701 printf("Authentication set to User (%s), Group (%s), Pass (%s)\n",
707 /* SEARCH SERVICE ------------------------------ */
708 static void display_record(Z_External *r);
710 static void print_record(const unsigned char *buf, size_t len)
713 print_stringn (buf, len);
714 /* add newline if not already added ... */
715 if (i <= 0 || buf[i-1] != '\n')
719 static void display_record(Z_External *r)
721 oident *ent = oid_getentbyoid(r->direct_reference);
725 * Tell the user what we got.
727 if (r->direct_reference)
729 printf("Record type: ");
731 printf("%s\n", ent->desc);
732 else if (!odr_oid(print, &r->direct_reference, 0, 0))
734 odr_perror(print, "print oid");
738 /* Check if this is a known, ASN.1 type tucked away in an octet string */
739 if (ent && r->which == Z_External_octet)
741 Z_ext_typeent *type = z_ext_getentbyref(ent->value);
747 * Call the given decoder to process the record.
749 odr_setbuf(in, (char*)r->u.octet_aligned->buf,
750 r->u.octet_aligned->len, 0);
751 if (!(*type->fun)(in, (char **)&rr, 0, 0))
753 odr_perror(in, "Decoding constructed record.");
754 fprintf(stdout, "[Near %d]\n", odr_offset(in));
755 fprintf(stdout, "Packet dump:\n---------\n");
756 odr_dumpBER(stdout, (char*)r->u.octet_aligned->buf,
757 r->u.octet_aligned->len);
758 fprintf(stdout, "---------\n");
760 /* note just ignores the error ant print the bytes form the octet_aligned later */
763 * Note: we throw away the original, BER-encoded record here.
764 * Do something else with it if you want to keep it.
766 r->u.sutrs = (Z_SUTRS *) rr; /* we don't actually check the type here. */
767 r->which = type->what;
771 if (ent && ent->oclass != CLASS_RECSYN)
773 if (ent && ent->value == VAL_SOIF)
774 print_record((const unsigned char *) r->u.octet_aligned->buf,
775 r->u.octet_aligned->len);
776 else if (r->which == Z_External_octet)
778 const char *octet_buf = (char*)r->u.octet_aligned->buf;
779 if (ent->value == VAL_TEXT_XML || ent->value == VAL_APPLICATION_XML ||
780 ent->value == VAL_HTML)
782 print_record((const unsigned char *) octet_buf,
783 r->u.octet_aligned->len);
785 else if (ent->value == VAL_POSTSCRIPT)
787 int size = r->u.octet_aligned->len;
790 print_record((const unsigned char *) octet_buf, size);
795 #if AVOID_MARC_DECODE
796 /* primitive check for a marc OID 5.1-29 except 16 */
797 ent->oidsuffix[0] == 5 && ent->oidsuffix[1] < 30 &&
798 ent->oidsuffix[1] != 16
807 yaz_marc_t mt = yaz_marc_create();
809 if (yaz_marc_decode_buf(mt, octet_buf,r->u.octet_aligned->len,
813 if (marcCharset && !strcmp(marcCharset, "auto"))
815 if (ent->value == VAL_USMARC)
817 if (octet_buf[9] == 'a')
825 else if (marcCharset)
827 if (outputCharset && from)
829 cd = yaz_iconv_open(outputCharset, from);
830 printf ("convert from %s to %s", from,
833 printf (" unsupported\n");
838 fwrite (result, 1, rlen, stdout);
842 size_t inbytesleft = rlen;
843 const char *inp = result;
847 size_t outbytesleft = sizeof(outbuf);
851 r = yaz_iconv (cd, (char**) &inp,
853 &outp, &outbytesleft);
854 if (r == (size_t) (-1))
856 int e = yaz_iconv_error(cd);
857 if (e != YAZ_ICONV_E2BIG)
860 fwrite (outbuf, outp - outbuf, 1, stdout);
866 printf ("bad MARC. Dumping as it is:\n");
867 print_record((const unsigned char*) octet_buf,
868 r->u.octet_aligned->len);
870 yaz_marc_destroy(mt);
876 print_record((const unsigned char*) octet_buf,
877 r->u.octet_aligned->len);
881 fwrite (octet_buf, 1, r->u.octet_aligned->len, marc_file);
883 else if (ent && ent->value == VAL_SUTRS)
885 if (r->which != Z_External_sutrs)
887 printf("Expecting single SUTRS type for SUTRS.\n");
890 print_record(r->u.sutrs->buf, r->u.sutrs->len);
892 else if (ent && ent->value == VAL_GRS1)
895 if (r->which != Z_External_grs1)
897 printf("Expecting single GRS type for GRS.\n");
901 yaz_display_grs1(w, r->u.grs1, 0);
905 else if ( /* OPAC display not complete yet .. */
906 ent && ent->value == VAL_OPAC)
909 if (r->u.opac->bibliographicRecord)
910 display_record(r->u.opac->bibliographicRecord);
911 for (i = 0; i<r->u.opac->num_holdingsData; i++)
913 Z_HoldingsRecord *h = r->u.opac->holdingsData[i];
914 if (h->which == Z_HoldingsRecord_marcHoldingsRecord)
916 printf ("MARC holdings %d\n", i);
917 display_record(h->u.marcHoldingsRecord);
919 else if (h->which == Z_HoldingsRecord_holdingsAndCirc)
923 Z_HoldingsAndCircData *data = h->u.holdingsAndCirc;
925 printf ("Data holdings %d\n", i);
926 if (data->typeOfRecord)
927 printf ("typeOfRecord: %s\n", data->typeOfRecord);
928 if (data->encodingLevel)
929 printf ("encodingLevel: %s\n", data->encodingLevel);
930 if (data->receiptAcqStatus)
931 printf ("receiptAcqStatus: %s\n", data->receiptAcqStatus);
932 if (data->generalRetention)
933 printf ("generalRetention: %s\n", data->generalRetention);
934 if (data->completeness)
935 printf ("completeness: %s\n", data->completeness);
936 if (data->dateOfReport)
937 printf ("dateOfReport: %s\n", data->dateOfReport);
939 printf ("nucCode: %s\n", data->nucCode);
940 if (data->localLocation)
941 printf ("localLocation: %s\n", data->localLocation);
942 if (data->shelvingLocation)
943 printf ("shelvingLocation: %s\n", data->shelvingLocation);
944 if (data->callNumber)
945 printf ("callNumber: %s\n", data->callNumber);
946 if (data->copyNumber)
947 printf ("copyNumber: %s\n", data->copyNumber);
948 if (data->publicNote)
949 printf ("publicNote: %s\n", data->publicNote);
950 if (data->reproductionNote)
951 printf ("reproductionNote: %s\n", data->reproductionNote);
952 if (data->termsUseRepro)
953 printf ("termsUseRepro: %s\n", data->termsUseRepro);
954 if (data->enumAndChron)
955 printf ("enumAndChron: %s\n", data->enumAndChron);
956 for (j = 0; j<data->num_volumes; j++)
958 printf ("volume %d\n", j);
959 if (data->volumes[j]->enumeration)
960 printf (" enumeration: %s\n",
961 data->volumes[j]->enumeration);
962 if (data->volumes[j]->chronology)
963 printf (" chronology: %s\n",
964 data->volumes[j]->chronology);
965 if (data->volumes[j]->enumAndChron)
966 printf (" enumAndChron: %s\n",
967 data->volumes[j]->enumAndChron);
969 for (j = 0; j<data->num_circulationData; j++)
971 printf ("circulation %d\n", j);
972 if (data->circulationData[j]->availableNow)
973 printf (" availableNow: %d\n",
974 *data->circulationData[j]->availableNow);
975 if (data->circulationData[j]->availablityDate)
976 printf (" availabiltyDate: %s\n",
977 data->circulationData[j]->availablityDate);
978 if (data->circulationData[j]->availableThru)
979 printf (" availableThru: %s\n",
980 data->circulationData[j]->availableThru);
981 if (data->circulationData[j]->restrictions)
982 printf (" restrictions: %s\n",
983 data->circulationData[j]->restrictions);
984 if (data->circulationData[j]->itemId)
985 printf (" itemId: %s\n",
986 data->circulationData[j]->itemId);
987 if (data->circulationData[j]->renewable)
988 printf (" renewable: %d\n",
989 *data->circulationData[j]->renewable);
990 if (data->circulationData[j]->onHold)
991 printf (" onHold: %d\n",
992 *data->circulationData[j]->onHold);
993 if (data->circulationData[j]->enumAndChron)
994 printf (" enumAndChron: %s\n",
995 data->circulationData[j]->enumAndChron);
996 if (data->circulationData[j]->midspine)
997 printf (" midspine: %s\n",
998 data->circulationData[j]->midspine);
999 if (data->circulationData[j]->temporaryLocation)
1000 printf (" temporaryLocation: %s\n",
1001 data->circulationData[j]->temporaryLocation);
1008 printf("Unknown record representation.\n");
1009 if (!z_External(print, &r, 0, 0))
1011 odr_perror(print, "Printing external");
1017 static void display_diagrecs(Z_DiagRec **pp, int num)
1021 Z_DefaultDiagFormat *r;
1023 printf("Diagnostic message(s) from database:\n");
1024 for (i = 0; i<num; i++)
1026 Z_DiagRec *p = pp[i];
1027 if (p->which != Z_DiagRec_defaultFormat)
1029 printf("Diagnostic record not in default format.\n");
1033 r = p->u.defaultFormat;
1034 if (!(ent = oid_getentbyoid(r->diagnosticSetId)) ||
1035 ent->oclass != CLASS_DIAGSET || ent->value != VAL_BIB1)
1036 printf("Missing or unknown diagset\n");
1037 printf(" [%d] %s", *r->condition, diagbib1_str(*r->condition));
1040 case Z_DefaultDiagFormat_v2Addinfo:
1041 printf (" -- v2 addinfo '%s'\n", r->u.v2Addinfo);
1043 case Z_DefaultDiagFormat_v3Addinfo:
1044 printf (" -- v3 addinfo '%s'\n", r->u.v3Addinfo);
1051 static void display_nameplusrecord(Z_NamePlusRecord *p)
1053 if (p->databaseName)
1054 printf("[%s]", p->databaseName);
1055 if (p->which == Z_NamePlusRecord_surrogateDiagnostic)
1056 display_diagrecs(&p->u.surrogateDiagnostic, 1);
1057 else if (p->which == Z_NamePlusRecord_databaseRecord)
1058 display_record(p->u.databaseRecord);
1061 static void display_records(Z_Records *p)
1065 if (p->which == Z_Records_NSD)
1067 Z_DiagRec dr, *dr_p = &dr;
1068 dr.which = Z_DiagRec_defaultFormat;
1069 dr.u.defaultFormat = p->u.nonSurrogateDiagnostic;
1070 display_diagrecs (&dr_p, 1);
1072 else if (p->which == Z_Records_multipleNSD)
1073 display_diagrecs (p->u.multipleNonSurDiagnostics->diagRecs,
1074 p->u.multipleNonSurDiagnostics->num_diagRecs);
1077 printf("Records: %d\n", p->u.databaseOrSurDiagnostics->num_records);
1078 for (i = 0; i < p->u.databaseOrSurDiagnostics->num_records; i++)
1079 display_nameplusrecord(p->u.databaseOrSurDiagnostics->records[i]);
1083 static int send_deleteResultSetRequest(const char *arg)
1088 Z_APDU *apdu = zget_APDU(out, Z_APDU_deleteResultSetRequest);
1089 Z_DeleteResultSetRequest *req = apdu->u.deleteResultSetRequest;
1091 req->referenceId = set_refid (out);
1093 req->num_resultSetList =
1094 sscanf (arg, "%30s %30s %30s %30s %30s %30s %30s %30s",
1095 names[0], names[1], names[2], names[3],
1096 names[4], names[5], names[6], names[7]);
1098 req->deleteFunction = (int *)
1099 odr_malloc (out, sizeof(*req->deleteFunction));
1100 if (req->num_resultSetList > 0)
1102 *req->deleteFunction = Z_DeleteRequest_list;
1103 req->resultSetList = (char **)
1104 odr_malloc (out, sizeof(*req->resultSetList)*
1105 req->num_resultSetList);
1106 for (i = 0; i<req->num_resultSetList; i++)
1107 req->resultSetList[i] = names[i];
1111 *req->deleteFunction = Z_DeleteRequest_all;
1112 req->resultSetList = 0;
1116 printf("Sent deleteResultSetRequest.\n");
1121 static int send_srw(Z_SRW_PDU *sr)
1123 const char *charset = negotiationCharset;
1124 const char *host_port = cur_host;
1127 Z_SOAP_Handler h[2] = {
1128 {"http://www.loc.gov/zing/srw/", 0, (Z_SOAP_fun) yaz_srw_codec},
1131 ODR o = odr_createmem(ODR_ENCODE);
1133 Z_SOAP *p = odr_malloc(o, sizeof(*p));
1136 path = odr_malloc(out, strlen(databaseNames[0])+2);
1138 strcpy(path+1, databaseNames[0]);
1140 gdu = z_get_HTTP_Request(out);
1141 gdu->u.HTTP_Request->path = odr_strdup(out, path);
1145 const char *cp0 = strstr(host_port, "://");
1146 const char *cp1 = 0;
1152 cp1 = strchr(cp0, '/');
1154 cp1 = cp0+strlen(cp0);
1158 char *h = odr_malloc(out, cp1 - cp0 + 1);
1159 memcpy (h, cp0, cp1 - cp0);
1161 z_HTTP_header_add(out, &gdu->u.HTTP_Request->headers,
1166 strcpy(ctype, "text/xml");
1167 if (charset && strlen(charset) < 20)
1169 strcat(ctype, "; charset=");
1170 strcat(ctype, charset);
1172 z_HTTP_header_add(out, &gdu->u.HTTP_Request->headers,
1173 "Content-Type", ctype);
1174 z_HTTP_header_add(out, &gdu->u.HTTP_Request->headers,
1175 "SOAPAction", "\"\"");
1176 p->which = Z_SOAP_generic;
1177 p->u.generic = odr_malloc(o, sizeof(*p->u.generic));
1178 p->u.generic->no = 0;
1179 p->u.generic->ns = 0;
1180 p->u.generic->p = sr;
1181 p->ns = "http://schemas.xmlsoap.org/soap/envelope/";
1183 ret = z_soap_codec_enc(o, &p,
1184 &gdu->u.HTTP_Request->content_buf,
1185 &gdu->u.HTTP_Request->content_len, h,
1188 if (z_GDU(out, &gdu, 0, 0))
1196 if (!z_GDU(print, &gdu, 0, 0))
1197 printf ("Failed to print outgoing APDU\n");
1200 buf_out = odr_getbuf(out, &len_out, 0);
1202 /* we don't odr_reset(out), since we may need the buffer again */
1204 do_hex_dump(buf_out, len_out);
1206 r = cs_put(conn, buf_out, len_out);
1218 static int send_SRW_searchRequest(const char *arg)
1224 assert(srw_sr_odr_out == 0);
1225 srw_sr_odr_out = odr_createmem(ODR_ENCODE);
1227 odr_reset(srw_sr_odr_out);
1231 /* save this for later .. when fetching individual records */
1232 srw_sr = sr = yaz_srw_get(srw_sr_odr_out, Z_SRW_searchRetrieve_request);
1233 sr->u.request->query_type = Z_SRW_query_type_cql;
1234 sr->u.request->query.cql = odr_strdup(srw_sr_odr_out, arg);
1236 sr = yaz_srw_get(out, Z_SRW_searchRetrieve_request);
1237 sr->u.request->query_type = Z_SRW_query_type_cql;
1238 sr->u.request->query.cql = odr_strdup(out, arg);
1240 sr->u.request->recordSchema = record_schema;
1241 return send_srw(sr);
1245 static int send_searchRequest(const char *arg)
1247 Z_APDU *apdu = zget_APDU(out, Z_APDU_searchRequest);
1248 Z_SearchRequest *req = apdu->u.searchRequest;
1251 struct ccl_rpn_node *rpn = NULL;
1253 char setstring[100];
1254 Z_RPNQuery *RPNquery;
1256 YAZ_PQF_Parser pqf_parser;
1258 QueryType myQueryType = queryType;
1261 if (myQueryType == QueryType_CCL2RPN)
1263 rpn = ccl_find_str(bibset, arg, &error, &pos);
1266 printf("CCL ERROR: %s\n", ccl_err_msg(error));
1269 } else if (myQueryType == QueryType_CQL2RPN) {
1270 /* ### All this code should be wrapped in a utility function */
1272 struct cql_node *node;
1273 const char *addinfo;
1274 if (cqltrans == 0) {
1275 printf("Can't use CQL: no translation file. Try set_cqlfile\n");
1278 parser = cql_parser_create();
1279 if ((error = cql_parser_string(parser, arg)) != 0) {
1280 printf("Can't parse CQL: must be a syntax error\n");
1283 node = cql_parser_result(parser);
1284 if ((error = cql_transform_buf(cqltrans, node, pqfbuf,
1285 sizeof pqfbuf)) != 0) {
1286 error = cql_transform_error(cqltrans, &addinfo);
1287 printf ("Can't convert CQL to PQF: %s (addinfo=%s)\n",
1288 cql_strerror(error), addinfo);
1292 myQueryType = QueryType_Prefix;
1295 req->referenceId = set_refid (out);
1296 if (!strcmp(arg, "@big")) /* strictly for troublemaking */
1298 static unsigned char big[2100];
1299 static Odr_oct bigo;
1301 /* send a very big referenceid to test transport stack etc. */
1302 memset(big, 'A', 2100);
1303 bigo.len = bigo.size = 2100;
1305 req->referenceId = &bigo;
1310 sprintf(setstring, "%d", ++setnumber);
1311 req->resultSetName = setstring;
1313 *req->smallSetUpperBound = smallSetUpperBound;
1314 *req->largeSetLowerBound = largeSetLowerBound;
1315 *req->mediumSetPresentNumber = mediumSetPresentNumber;
1316 if (smallSetUpperBound > 0 || (largeSetLowerBound > 1 &&
1317 mediumSetPresentNumber > 0))
1321 prefsyn.proto = protocol;
1322 prefsyn.oclass = CLASS_RECSYN;
1323 prefsyn.value = recordsyntax;
1324 req->preferredRecordSyntax =
1325 odr_oiddup(out, oid_ent_to_oid(&prefsyn, oid));
1326 req->smallSetElementSetNames =
1327 req->mediumSetElementSetNames = elementSetNames;
1329 req->num_databaseNames = num_databaseNames;
1330 req->databaseNames = databaseNames;
1332 req->query = &query;
1334 switch (myQueryType)
1336 case QueryType_Prefix:
1337 query.which = Z_Query_type_1;
1338 pqf_parser = yaz_pqf_create ();
1339 RPNquery = yaz_pqf_parse (pqf_parser, out, arg);
1342 const char *pqf_msg;
1344 int code = yaz_pqf_error (pqf_parser, &pqf_msg, &off);
1345 printf("%*s^\n", off+4, "");
1346 printf("Prefix query error: %s (code %d)\n", pqf_msg, code);
1348 yaz_pqf_destroy (pqf_parser);
1351 yaz_pqf_destroy (pqf_parser);
1352 query.u.type_1 = RPNquery;
1355 query.which = Z_Query_type_2;
1356 query.u.type_2 = &ccl_query;
1357 ccl_query.buf = (unsigned char*) arg;
1358 ccl_query.len = strlen(arg);
1360 case QueryType_CCL2RPN:
1361 query.which = Z_Query_type_1;
1362 RPNquery = ccl_rpn_query(out, rpn);
1365 printf ("Couldn't convert from CCL to RPN\n");
1368 query.u.type_1 = RPNquery;
1369 ccl_rpn_delete (rpn);
1372 query.which = Z_Query_type_104;
1373 ext = (Z_External *) odr_malloc(out, sizeof(*ext));
1374 ext->direct_reference = odr_getoidbystr(out, "1.2.840.10003.16.2");
1375 ext->indirect_reference = 0;
1376 ext->descriptor = 0;
1377 ext->which = Z_External_CQL;
1378 ext->u.cql = odr_strdup(out, arg);
1379 query.u.type_104 = ext;
1382 printf ("Unsupported query type\n");
1385 if (send_apdu(apdu))
1386 printf("Sent searchRequest.\n");
1391 /* display Query Expression as part of searchResult-1 */
1392 static void display_queryExpression (Z_QueryExpression *qe)
1396 if (qe->which == Z_QueryExpression_term)
1398 if (qe->u.term->queryTerm)
1400 Z_Term *term = qe->u.term->queryTerm;
1401 switch (term->which)
1403 case Z_Term_general:
1404 printf (" %.*s", term->u.general->len, term->u.general->buf);
1406 case Z_Term_characterString:
1407 printf (" %s", term->u.characterString);
1409 case Z_Term_numeric:
1410 printf (" %d", *term->u.numeric);
1420 /* see if we can find USR:SearchResult-1 */
1421 static void display_searchResult (Z_OtherInformation *o)
1426 for (i = 0; i < o->num_elements; i++)
1428 if (o->list[i]->which == Z_OtherInfo_externallyDefinedInfo)
1430 Z_External *ext = o->list[i]->information.externallyDefinedInfo;
1432 if (ext->which == Z_External_searchResult1)
1435 Z_SearchInfoReport *sr = ext->u.searchResult1;
1436 printf ("SearchResult-1:");
1437 for (j = 0; j < sr->num; j++)
1439 if (!sr->elements[j]->subqueryExpression)
1441 display_queryExpression (
1442 sr->elements[j]->subqueryExpression);
1443 display_queryExpression (
1444 sr->elements[j]->subqueryInterpretation);
1445 display_queryExpression (
1446 sr->elements[j]->subqueryRecommendation);
1447 if (sr->elements[j]->subqueryCount)
1448 printf ("(%d)", *sr->elements[j]->subqueryCount);
1456 static int process_searchResponse(Z_SearchResponse *res)
1458 printf ("Received SearchResponse.\n");
1459 print_refid (res->referenceId);
1460 if (*res->searchStatus)
1461 printf("Search was a success.\n");
1463 printf("Search was a bloomin' failure.\n");
1464 printf("Number of hits: %d", *res->resultCount);
1466 printf (", setno %d", setnumber);
1468 display_searchResult (res->additionalSearchInfo);
1469 printf("records returned: %d\n",
1470 *res->numberOfRecordsReturned);
1471 setno += *res->numberOfRecordsReturned;
1473 display_records(res->records);
1477 static void print_level(int iLevel)
1480 for (i = 0; i < iLevel * 4; i++)
1484 static void print_int(int iLevel, const char *pTag, int *pInt)
1488 print_level(iLevel);
1489 printf("%s: %d\n", pTag, *pInt);
1493 static void print_string(int iLevel, const char *pTag, const char *pString)
1495 if (pString != NULL)
1497 print_level(iLevel);
1498 printf("%s: %s\n", pTag, pString);
1502 static void print_oid(int iLevel, const char *pTag, Odr_oid *pOid)
1508 print_level(iLevel);
1509 printf("%s:", pTag);
1510 for (; *pInt != -1; pInt++)
1511 printf(" %d", *pInt);
1516 static void print_referenceId(int iLevel, Z_ReferenceId *referenceId)
1518 if (referenceId != NULL)
1522 print_level(iLevel);
1523 printf("Ref Id (%d, %d): ", referenceId->len, referenceId->size);
1524 for (i = 0; i < referenceId->len; i++)
1525 printf("%c", referenceId->buf[i]);
1530 static void print_string_or_numeric(int iLevel, const char *pTag, Z_StringOrNumeric *pStringNumeric)
1532 if (pStringNumeric != NULL)
1534 switch (pStringNumeric->which)
1536 case Z_StringOrNumeric_string:
1537 print_string(iLevel, pTag, pStringNumeric->u.string);
1540 case Z_StringOrNumeric_numeric:
1541 print_int(iLevel, pTag, pStringNumeric->u.numeric);
1545 print_level(iLevel);
1546 printf("%s: valid type for Z_StringOrNumeric\n", pTag);
1552 static void print_universe_report_duplicate(
1554 Z_UniverseReportDuplicate *pUniverseReportDuplicate)
1556 if (pUniverseReportDuplicate != NULL)
1558 print_level(iLevel);
1559 printf("Universe Report Duplicate: \n");
1561 print_string_or_numeric(iLevel, "Hit No",
1562 pUniverseReportDuplicate->hitno);
1566 static void print_universe_report_hits(
1568 Z_UniverseReportHits *pUniverseReportHits)
1570 if (pUniverseReportHits != NULL)
1572 print_level(iLevel);
1573 printf("Universe Report Hits: \n");
1575 print_string_or_numeric(iLevel, "Database",
1576 pUniverseReportHits->database);
1577 print_string_or_numeric(iLevel, "Hits", pUniverseReportHits->hits);
1581 static void print_universe_report(int iLevel, Z_UniverseReport *pUniverseReport)
1583 if (pUniverseReport != NULL)
1585 print_level(iLevel);
1586 printf("Universe Report: \n");
1588 print_int(iLevel, "Total Hits", pUniverseReport->totalHits);
1589 switch (pUniverseReport->which)
1591 case Z_UniverseReport_databaseHits:
1592 print_universe_report_hits(iLevel,
1593 pUniverseReport->u.databaseHits);
1596 case Z_UniverseReport_duplicate:
1597 print_universe_report_duplicate(iLevel,
1598 pUniverseReport->u.duplicate);
1602 print_level(iLevel);
1603 printf("Type: %d\n", pUniverseReport->which);
1609 static void print_external(int iLevel, Z_External *pExternal)
1611 if (pExternal != NULL)
1613 print_level(iLevel);
1614 printf("External: \n");
1616 print_oid(iLevel, "Direct Reference", pExternal->direct_reference);
1617 print_int(iLevel, "InDirect Reference", pExternal->indirect_reference);
1618 print_string(iLevel, "Descriptor", pExternal->descriptor);
1619 switch (pExternal->which)
1621 case Z_External_universeReport:
1622 print_universe_report(iLevel, pExternal->u.universeReport);
1626 print_level(iLevel);
1627 printf("Type: %d\n", pExternal->which);
1633 static int process_resourceControlRequest (Z_ResourceControlRequest *req)
1635 printf ("Received ResourceControlRequest.\n");
1636 print_referenceId(1, req->referenceId);
1637 print_int(1, "Suspended Flag", req->suspendedFlag);
1638 print_int(1, "Partial Results Available", req->partialResultsAvailable);
1639 print_int(1, "Response Required", req->responseRequired);
1640 print_int(1, "Triggered Request Flag", req->triggeredRequestFlag);
1641 print_external(1, req->resourceReport);
1645 void process_ESResponse(Z_ExtendedServicesResponse *res)
1648 switch (*res->operationStatus)
1650 case Z_ExtendedServicesResponse_done:
1653 case Z_ExtendedServicesResponse_accepted:
1654 printf ("accepted\n");
1656 case Z_ExtendedServicesResponse_failure:
1657 printf ("failure\n");
1658 display_diagrecs(res->diagnostics, res->num_diagnostics);
1661 printf ("unknown\n");
1663 if ( (*res->operationStatus != Z_ExtendedServicesResponse_failure) &&
1664 (res->num_diagnostics != 0) ) {
1665 display_diagrecs(res->diagnostics, res->num_diagnostics);
1667 print_refid (res->referenceId);
1668 if (res->taskPackage &&
1669 res->taskPackage->which == Z_External_extendedService)
1671 Z_TaskPackage *taskPackage = res->taskPackage->u.extendedService;
1672 Odr_oct *id = taskPackage->targetReference;
1673 Z_External *ext = taskPackage->taskSpecificParameters;
1677 printf ("Target Reference: ");
1678 print_stringn (id->buf, id->len);
1681 if (ext->which == Z_External_update)
1683 Z_IUUpdateTaskPackage *utp = ext->u.update->u.taskPackage;
1684 if (utp && utp->targetPart)
1686 Z_IUTargetPart *targetPart = utp->targetPart;
1689 for (i = 0; i<targetPart->num_taskPackageRecords; i++)
1692 Z_IUTaskPackageRecordStructure *tpr =
1693 targetPart->taskPackageRecords[i];
1694 printf ("task package record %d\n", i+1);
1695 if (tpr->which == Z_IUTaskPackageRecordStructure_record)
1697 display_record (tpr->u.record);
1701 printf ("other type\n");
1709 const char *get_ill_element (void *clientData, const char *element)
1714 static Z_External *create_external_itemRequest()
1716 struct ill_get_ctl ctl;
1717 ILL_ItemRequest *req;
1719 int item_request_size = 0;
1720 char *item_request_buf = 0;
1724 ctl.f = get_ill_element;
1726 req = ill_get_ItemRequest(&ctl, "ill", 0);
1728 printf ("ill_get_ItemRequest failed\n");
1730 if (!ill_ItemRequest (out, &req, 0, 0))
1734 ill_ItemRequest(print, &req, 0, 0);
1737 item_request_buf = odr_getbuf (out, &item_request_size, 0);
1738 if (item_request_buf)
1739 odr_setbuf (out, item_request_buf, item_request_size, 1);
1740 printf ("Couldn't encode ItemRequest, size %d\n", item_request_size);
1747 item_request_buf = odr_getbuf (out, &item_request_size, 0);
1748 oid.proto = PROTO_GENERAL;
1749 oid.oclass = CLASS_GENERAL;
1750 oid.value = VAL_ISO_ILL_1;
1752 r = (Z_External *) odr_malloc (out, sizeof(*r));
1753 r->direct_reference = odr_oiddup(out,oid_getoidbyent(&oid));
1754 r->indirect_reference = 0;
1756 r->which = Z_External_single;
1758 r->u.single_ASN1_type = (Odr_oct *)
1759 odr_malloc (out, sizeof(*r->u.single_ASN1_type));
1760 r->u.single_ASN1_type->buf = (unsigned char *)
1761 odr_malloc (out, item_request_size);
1762 r->u.single_ASN1_type->len = item_request_size;
1763 r->u.single_ASN1_type->size = item_request_size;
1764 memcpy (r->u.single_ASN1_type->buf, item_request_buf,
1767 do_hex_dump(item_request_buf,item_request_size);
1772 static Z_External *create_external_ILL_APDU(int which)
1774 struct ill_get_ctl ctl;
1777 int ill_request_size = 0;
1778 char *ill_request_buf = 0;
1782 ctl.f = get_ill_element;
1784 ill_apdu = ill_get_APDU(&ctl, "ill", 0);
1786 if (!ill_APDU (out, &ill_apdu, 0, 0))
1790 printf ("-------------------\n");
1791 ill_APDU(print, &ill_apdu, 0, 0);
1793 printf ("-------------------\n");
1795 ill_request_buf = odr_getbuf (out, &ill_request_size, 0);
1796 if (ill_request_buf)
1797 odr_setbuf (out, ill_request_buf, ill_request_size, 1);
1798 printf ("Couldn't encode ILL-Request, size %d\n", ill_request_size);
1804 ill_request_buf = odr_getbuf (out, &ill_request_size, 0);
1806 oid.proto = PROTO_GENERAL;
1807 oid.oclass = CLASS_GENERAL;
1808 oid.value = VAL_ISO_ILL_1;
1810 r = (Z_External *) odr_malloc (out, sizeof(*r));
1811 r->direct_reference = odr_oiddup(out,oid_getoidbyent(&oid));
1812 r->indirect_reference = 0;
1814 r->which = Z_External_single;
1816 r->u.single_ASN1_type = (Odr_oct *)
1817 odr_malloc (out, sizeof(*r->u.single_ASN1_type));
1818 r->u.single_ASN1_type->buf = (unsigned char *)
1819 odr_malloc (out, ill_request_size);
1820 r->u.single_ASN1_type->len = ill_request_size;
1821 r->u.single_ASN1_type->size = ill_request_size;
1822 memcpy (r->u.single_ASN1_type->buf, ill_request_buf, ill_request_size);
1823 /* printf ("len = %d\n", ill_request_size); */
1824 /* do_hex_dump(ill_request_buf,ill_request_size); */
1825 /* printf("--- end of extenal\n"); */
1832 static Z_External *create_ItemOrderExternal(const char *type, int itemno)
1834 Z_External *r = (Z_External *) odr_malloc(out, sizeof(Z_External));
1835 oident ItemOrderRequest;
1837 ItemOrderRequest.proto = PROTO_Z3950;
1838 ItemOrderRequest.oclass = CLASS_EXTSERV;
1839 ItemOrderRequest.value = VAL_ITEMORDER;
1841 r->direct_reference = odr_oiddup(out,oid_getoidbyent(&ItemOrderRequest));
1842 r->indirect_reference = 0;
1845 r->which = Z_External_itemOrder;
1847 r->u.itemOrder = (Z_ItemOrder *) odr_malloc(out,sizeof(Z_ItemOrder));
1848 memset(r->u.itemOrder, 0, sizeof(Z_ItemOrder));
1849 r->u.itemOrder->which=Z_IOItemOrder_esRequest;
1851 r->u.itemOrder->u.esRequest = (Z_IORequest *)
1852 odr_malloc(out,sizeof(Z_IORequest));
1853 memset(r->u.itemOrder->u.esRequest, 0, sizeof(Z_IORequest));
1855 r->u.itemOrder->u.esRequest->toKeep = (Z_IOOriginPartToKeep *)
1856 odr_malloc(out,sizeof(Z_IOOriginPartToKeep));
1857 memset(r->u.itemOrder->u.esRequest->toKeep, 0, sizeof(Z_IOOriginPartToKeep));
1858 r->u.itemOrder->u.esRequest->notToKeep = (Z_IOOriginPartNotToKeep *)
1859 odr_malloc(out,sizeof(Z_IOOriginPartNotToKeep));
1860 memset(r->u.itemOrder->u.esRequest->notToKeep, 0, sizeof(Z_IOOriginPartNotToKeep));
1862 r->u.itemOrder->u.esRequest->toKeep->supplDescription = NULL;
1863 r->u.itemOrder->u.esRequest->toKeep->contact = NULL;
1864 r->u.itemOrder->u.esRequest->toKeep->addlBilling = NULL;
1866 r->u.itemOrder->u.esRequest->notToKeep->resultSetItem =
1867 (Z_IOResultSetItem *) odr_malloc(out, sizeof(Z_IOResultSetItem));
1868 memset(r->u.itemOrder->u.esRequest->notToKeep->resultSetItem, 0, sizeof(Z_IOResultSetItem));
1869 r->u.itemOrder->u.esRequest->notToKeep->resultSetItem->resultSetId = "1";
1871 r->u.itemOrder->u.esRequest->notToKeep->resultSetItem->item =
1872 (int *) odr_malloc(out, sizeof(int));
1873 *r->u.itemOrder->u.esRequest->notToKeep->resultSetItem->item = itemno;
1875 if (!strcmp (type, "item") || !strcmp(type, "2"))
1877 printf ("using item-request\n");
1878 r->u.itemOrder->u.esRequest->notToKeep->itemRequest =
1879 create_external_itemRequest();
1881 else if (!strcmp(type, "ill") || !strcmp(type, "1"))
1883 printf ("using ILL-request\n");
1884 r->u.itemOrder->u.esRequest->notToKeep->itemRequest =
1885 create_external_ILL_APDU(ILL_APDU_ILL_Request);
1887 else if (!strcmp(type, "xml") || !strcmp(type, "3"))
1889 const char *xml_buf =
1891 " <type>request</type>\n"
1892 " <libraryNo>000200</libraryNo>\n"
1893 " <borrowerTicketNo> 1212 </borrowerTicketNo>\n"
1895 r->u.itemOrder->u.esRequest->notToKeep->itemRequest =
1896 z_ext_record (out, VAL_TEXT_XML, xml_buf, strlen(xml_buf));
1899 r->u.itemOrder->u.esRequest->notToKeep->itemRequest = 0;
1904 static int send_itemorder(const char *type, int itemno)
1906 Z_APDU *apdu = zget_APDU(out, Z_APDU_extendedServicesRequest);
1907 Z_ExtendedServicesRequest *req = apdu->u.extendedServicesRequest;
1908 oident ItemOrderRequest;
1910 ItemOrderRequest.proto = PROTO_Z3950;
1911 ItemOrderRequest.oclass = CLASS_EXTSERV;
1912 ItemOrderRequest.value = VAL_ITEMORDER;
1913 req->packageType = odr_oiddup(out,oid_getoidbyent(&ItemOrderRequest));
1914 req->packageName = esPackageName;
1916 req->taskSpecificParameters = create_ItemOrderExternal(type, itemno);
1922 static int only_z3950()
1924 if (protocol == PROTO_HTTP)
1926 printf ("Not supported by SRW\n");
1932 static int cmd_update_common(const char *arg, int version);
1934 static int cmd_update(const char *arg)
1936 return cmd_update_common(arg, 1);
1939 static int cmd_update0(const char *arg)
1941 return cmd_update_common(arg, 0);
1944 static int cmd_update_common(const char *arg, int version)
1946 Z_APDU *apdu = zget_APDU(out, Z_APDU_extendedServicesRequest );
1947 Z_ExtendedServicesRequest *req = apdu->u.extendedServicesRequest;
1951 char action[20], recid[20], fname[80];
1953 Z_External *record_this = 0;
1960 sscanf (arg, "%19s %19s %79s", action, recid, fname);
1962 if (!strcmp (action, "insert"))
1963 action_no = Z_IUOriginPartToKeep_recordInsert;
1964 else if (!strcmp (action, "replace"))
1965 action_no = Z_IUOriginPartToKeep_recordReplace;
1966 else if (!strcmp (action, "delete"))
1967 action_no = Z_IUOriginPartToKeep_recordDelete;
1968 else if (!strcmp (action, "update"))
1969 action_no = Z_IUOriginPartToKeep_specialUpdate;
1972 printf ("Bad action: %s\n", action);
1973 printf ("Possible values: insert, replace, delete, update\n");
1981 stat (fname, &status);
1982 if (S_ISREG(status.st_mode) && (inf = fopen(fname, "r")))
1984 size_t len = status.st_size;
1985 char *buf = (char *) xmalloc (len);
1987 fread (buf, 1, len, inf);
1991 record_this = z_ext_record (out, VAL_TEXT_XML, buf, len);
1997 printf ("File %s doesn't exist\n", fname);
2005 printf ("No last record (update ignored)\n");
2008 record_this = record_last;
2011 update_oid.proto = PROTO_Z3950;
2012 update_oid.oclass = CLASS_EXTSERV;
2014 update_oid.value = VAL_DBUPDATE0;
2016 update_oid.value = VAL_DBUPDATE;
2017 oid_ent_to_oid (&update_oid, oid);
2018 req->packageType = odr_oiddup(out,oid);
2019 req->packageName = esPackageName;
2021 req->referenceId = set_refid (out);
2023 r = req->taskSpecificParameters = (Z_External *)
2024 odr_malloc (out, sizeof(*r));
2025 r->direct_reference = odr_oiddup(out,oid);
2026 r->indirect_reference = 0;
2030 Z_IU0OriginPartToKeep *toKeep;
2031 Z_IU0SuppliedRecords *notToKeep;
2033 r->which = Z_External_update0;
2034 r->u.update0 = (Z_IU0Update *) odr_malloc(out, sizeof(*r->u.update0));
2035 r->u.update0->which = Z_IUUpdate_esRequest;
2036 r->u.update0->u.esRequest = (Z_IU0UpdateEsRequest *)
2037 odr_malloc(out, sizeof(*r->u.update0->u.esRequest));
2038 toKeep = r->u.update0->u.esRequest->toKeep = (Z_IU0OriginPartToKeep *)
2039 odr_malloc(out, sizeof(*r->u.update0->u.esRequest->toKeep));
2041 toKeep->databaseName = databaseNames[0];
2043 toKeep->elementSetName = 0;
2045 toKeep->action = (int *) odr_malloc(out, sizeof(*toKeep->action));
2046 *toKeep->action = action_no;
2048 notToKeep = r->u.update0->u.esRequest->notToKeep = (Z_IU0SuppliedRecords *)
2049 odr_malloc(out, sizeof(*r->u.update0->u.esRequest->notToKeep));
2051 notToKeep->elements = (Z_IU0SuppliedRecords_elem **)
2052 odr_malloc(out, sizeof(*notToKeep->elements));
2053 notToKeep->elements[0] = (Z_IU0SuppliedRecords_elem *)
2054 odr_malloc(out, sizeof(**notToKeep->elements));
2055 notToKeep->elements[0]->which = Z_IUSuppliedRecords_elem_opaque;
2058 notToKeep->elements[0]->u.opaque = (Odr_oct *)
2059 odr_malloc (out, sizeof(Odr_oct));
2060 notToKeep->elements[0]->u.opaque->buf = (unsigned char *) recid;
2061 notToKeep->elements[0]->u.opaque->size = strlen(recid);
2062 notToKeep->elements[0]->u.opaque->len = strlen(recid);
2065 notToKeep->elements[0]->u.opaque = 0;
2066 notToKeep->elements[0]->supplementalId = 0;
2067 notToKeep->elements[0]->correlationInfo = 0;
2068 notToKeep->elements[0]->record = record_this;
2072 Z_IUOriginPartToKeep *toKeep;
2073 Z_IUSuppliedRecords *notToKeep;
2075 r->which = Z_External_update;
2076 r->u.update = (Z_IUUpdate *) odr_malloc(out, sizeof(*r->u.update));
2077 r->u.update->which = Z_IUUpdate_esRequest;
2078 r->u.update->u.esRequest = (Z_IUUpdateEsRequest *)
2079 odr_malloc(out, sizeof(*r->u.update->u.esRequest));
2080 toKeep = r->u.update->u.esRequest->toKeep = (Z_IUOriginPartToKeep *)
2081 odr_malloc(out, sizeof(*r->u.update->u.esRequest->toKeep));
2083 toKeep->databaseName = databaseNames[0];
2085 toKeep->elementSetName = 0;
2086 toKeep->actionQualifier = 0;
2087 toKeep->action = (int *) odr_malloc(out, sizeof(*toKeep->action));
2088 *toKeep->action = action_no;
2090 notToKeep = r->u.update->u.esRequest->notToKeep = (Z_IUSuppliedRecords *)
2091 odr_malloc(out, sizeof(*r->u.update->u.esRequest->notToKeep));
2093 notToKeep->elements = (Z_IUSuppliedRecords_elem **)
2094 odr_malloc(out, sizeof(*notToKeep->elements));
2095 notToKeep->elements[0] = (Z_IUSuppliedRecords_elem *)
2096 odr_malloc(out, sizeof(**notToKeep->elements));
2097 notToKeep->elements[0]->which = Z_IUSuppliedRecords_elem_opaque;
2100 notToKeep->elements[0]->u.opaque = (Odr_oct *)
2101 odr_malloc (out, sizeof(Odr_oct));
2102 notToKeep->elements[0]->u.opaque->buf = (unsigned char *) recid;
2103 notToKeep->elements[0]->u.opaque->size = strlen(recid);
2104 notToKeep->elements[0]->u.opaque->len = strlen(recid);
2107 notToKeep->elements[0]->u.opaque = 0;
2108 notToKeep->elements[0]->supplementalId = 0;
2109 notToKeep->elements[0]->correlationInfo = 0;
2110 notToKeep->elements[0]->record = record_this;
2118 static int cmd_itemorder(const char *arg)
2125 if (sscanf (arg, "%10s %d", type, &itemno) != 2)
2128 printf("Item order request\n");
2130 send_itemorder(type, itemno);
2134 static void show_opt(const char *arg)
2136 printf ("%s ", arg);
2139 static int cmd_options(const char *arg)
2145 r = yaz_init_opt_encode(&z3950_options, arg, &pos);
2149 yaz_init_opt_decode(&z3950_options, show_opt);
2155 static int cmd_explain(const char *arg)
2157 if (protocol != PROTO_HTTP)
2168 /* save this for later .. when fetching individual records */
2169 sr = yaz_srw_get(out, Z_SRW_explain_request);
2177 static int cmd_find(const char *arg)
2181 printf("Find what?\n");
2184 if (protocol == PROTO_HTTP)
2191 if (!send_SRW_searchRequest(arg))
2204 printf("Not connected yet\n");
2208 if (!send_searchRequest(arg))
2214 static int cmd_delete(const char *arg)
2218 printf("Not connected yet\n");
2223 if (!send_deleteResultSetRequest(arg))
2228 static int cmd_ssub(const char *arg)
2230 if (!(smallSetUpperBound = atoi(arg)))
2235 static int cmd_lslb(const char *arg)
2239 if (!(largeSetLowerBound = atoi(arg)))
2244 static int cmd_mspn(const char *arg)
2248 if (!(mediumSetPresentNumber = atoi(arg)))
2253 static int cmd_status(const char *arg)
2255 printf("smallSetUpperBound: %d\n", smallSetUpperBound);
2256 printf("largeSetLowerBound: %d\n", largeSetLowerBound);
2257 printf("mediumSetPresentNumber: %d\n", mediumSetPresentNumber);
2261 static int cmd_setnames(const char *arg)
2263 if (*arg == '1') /* enable ? */
2265 else if (*arg == '0') /* disable ? */
2267 else if (setnumber < 0) /* no args, toggle .. */
2273 printf("Set numbering enabled.\n");
2275 printf("Set numbering disabled.\n");
2279 /* PRESENT SERVICE ----------------------------- */
2281 static void parse_show_args(const char *arg_c, char *setstring,
2282 int *start, int *number)
2287 strncpy(arg, arg_c, sizeof(arg)-1);
2288 arg[sizeof(arg)-1] = '\0';
2290 if ((p = strchr(arg, '+')))
2292 *number = atoi(p + 1);
2297 if (p && (p=strchr(p+1, '+')))
2298 strcpy (setstring, p+1);
2299 else if (setnumber >= 0)
2300 sprintf(setstring, "%d", setnumber);
2305 static int send_presentRequest(const char *arg)
2307 Z_APDU *apdu = zget_APDU(out, Z_APDU_presentRequest);
2308 Z_PresentRequest *req = apdu->u.presentRequest;
2309 Z_RecordComposition compo;
2313 char setstring[100];
2315 req->referenceId = set_refid (out);
2317 parse_show_args(arg, setstring, &setno, &nos);
2319 req->resultSetId = setstring;
2321 req->resultSetStartPoint = &setno;
2322 req->numberOfRecordsRequested = &nos;
2323 prefsyn.proto = protocol;
2324 prefsyn.oclass = CLASS_RECSYN;
2325 prefsyn.value = recordsyntax;
2326 req->preferredRecordSyntax =
2327 odr_oiddup (out, oid_ent_to_oid(&prefsyn, oid));
2333 prefschema.proto = protocol;
2334 prefschema.oclass = CLASS_SCHEMA;
2335 prefschema.value = oid_getvalbyname(record_schema);
2337 req->recordComposition = &compo;
2338 compo.which = Z_RecordComp_complex;
2339 compo.u.complex = (Z_CompSpec *)
2340 odr_malloc(out, sizeof(*compo.u.complex));
2341 compo.u.complex->selectAlternativeSyntax = (bool_t *)
2342 odr_malloc(out, sizeof(bool_t));
2343 *compo.u.complex->selectAlternativeSyntax = 0;
2345 compo.u.complex->generic = (Z_Specification *)
2346 odr_malloc(out, sizeof(*compo.u.complex->generic));
2347 compo.u.complex->generic->which = Z_Schema_oid;
2348 compo.u.complex->generic->schema.oid = (Odr_oid *)
2349 odr_oiddup(out, oid_ent_to_oid(&prefschema, oid));
2350 if (!compo.u.complex->generic->schema.oid)
2352 /* OID wasn't a schema! Try record syntax instead. */
2353 prefschema.oclass = CLASS_RECSYN;
2354 compo.u.complex->generic->schema.oid = (Odr_oid *)
2355 odr_oiddup(out, oid_ent_to_oid(&prefschema, oid));
2357 if (!elementSetNames)
2358 compo.u.complex->generic->elementSpec = 0;
2361 compo.u.complex->generic->elementSpec = (Z_ElementSpec *)
2362 odr_malloc(out, sizeof(Z_ElementSpec));
2363 compo.u.complex->generic->elementSpec->which =
2364 Z_ElementSpec_elementSetName;
2365 compo.u.complex->generic->elementSpec->u.elementSetName =
2366 elementSetNames->u.generic;
2368 compo.u.complex->num_dbSpecific = 0;
2369 compo.u.complex->dbSpecific = 0;
2370 compo.u.complex->num_recordSyntax = 0;
2371 compo.u.complex->recordSyntax = 0;
2373 else if (elementSetNames)
2375 req->recordComposition = &compo;
2376 compo.which = Z_RecordComp_simple;
2377 compo.u.simple = elementSetNames;
2380 printf("Sent presentRequest (%d+%d).\n", setno, nos);
2385 static int send_SRW_presentRequest(const char *arg)
2387 char setstring[100];
2389 Z_SRW_PDU *sr = srw_sr;
2393 parse_show_args(arg, setstring, &setno, &nos);
2394 sr->u.request->startRecord = odr_intdup(out, setno);
2395 sr->u.request->maximumRecords = odr_intdup(out, nos);
2397 sr->u.request->recordSchema = record_schema;
2398 return send_srw(sr);
2402 static void close_session (void)
2409 nmem_destroy (session_mem);
2418 void process_close(Z_Close *req)
2420 Z_APDU *apdu = zget_APDU(out, Z_APDU_close);
2421 Z_Close *res = apdu->u.close;
2423 static char *reasons[] =
2428 "cost limit reached",
2430 "security violation",
2437 printf("Reason: %s, message: %s\n", reasons[*req->closeReason],
2438 req->diagnosticInformation ? req->diagnosticInformation : "NULL");
2443 *res->closeReason = Z_Close_finished;
2445 printf("Sent response.\n");
2450 static int cmd_show(const char *arg)
2452 if (protocol == PROTO_HTTP)
2459 if (!send_SRW_presentRequest(arg))
2469 printf("Not connected yet\n");
2472 if (!send_presentRequest(arg))
2478 int cmd_quit(const char *arg)
2480 printf("See you later, alligator.\n");
2486 int cmd_cancel(const char *arg)
2488 Z_APDU *apdu = zget_APDU(out, Z_APDU_triggerResourceControlRequest);
2489 Z_TriggerResourceControlRequest *req =
2490 apdu->u.triggerResourceControlRequest;
2495 printf("Session not initialized yet\n");
2500 if (!ODR_MASK_GET(session->options, Z_Options_triggerResourceCtrl))
2502 printf("Target doesn't support cancel (trigger resource ctrl)\n");
2505 *req->requestedAction = Z_TriggerResourceCtrl_cancel;
2506 req->resultSetWanted = &rfalse;
2509 printf("Sent cancel request\n");
2513 int send_scanrequest(const char *query, int pp, int num, const char *term)
2515 Z_APDU *apdu = zget_APDU(out, Z_APDU_scanRequest);
2516 Z_ScanRequest *req = apdu->u.scanRequest;
2521 if (queryType == QueryType_CCL2RPN)
2525 struct ccl_rpn_node *rpn;
2527 rpn = ccl_find_str (bibset, query, &error, &pos);
2530 printf("CCL ERROR: %s\n", ccl_err_msg(error));
2533 bib1.proto = PROTO_Z3950;
2534 bib1.oclass = CLASS_ATTSET;
2535 bib1.value = VAL_BIB1;
2536 req->attributeSet = oid_ent_to_oid (&bib1, oid);
2537 if (!(req->termListAndStartPoint = ccl_scan_query (out, rpn)))
2539 printf("Couldn't convert CCL to Scan term\n");
2542 ccl_rpn_delete (rpn);
2546 YAZ_PQF_Parser pqf_parser = yaz_pqf_create ();
2548 if (!(req->termListAndStartPoint =
2549 yaz_pqf_scan(pqf_parser, out, &req->attributeSet, query)))
2551 const char *pqf_msg;
2553 int code = yaz_pqf_error (pqf_parser, &pqf_msg, &off);
2554 printf("%*s^\n", off+7, "");
2555 printf("Prefix query error: %s (code %d)\n", pqf_msg, code);
2556 yaz_pqf_destroy (pqf_parser);
2559 yaz_pqf_destroy (pqf_parser);
2563 if (req->termListAndStartPoint->term &&
2564 req->termListAndStartPoint->term->which == Z_Term_general &&
2565 req->termListAndStartPoint->term->u.general)
2567 req->termListAndStartPoint->term->u.general->buf =
2568 (unsigned char *) odr_strdup(out, term);
2569 req->termListAndStartPoint->term->u.general->len =
2570 req->termListAndStartPoint->term->u.general->size =
2574 req->referenceId = set_refid (out);
2575 req->num_databaseNames = num_databaseNames;
2576 req->databaseNames = databaseNames;
2577 req->numberOfTermsRequested = #
2578 req->preferredPositionInResponse = &pp;
2583 int send_sortrequest(const char *arg, int newset)
2585 Z_APDU *apdu = zget_APDU(out, Z_APDU_sortRequest);
2586 Z_SortRequest *req = apdu->u.sortRequest;
2587 Z_SortKeySpecList *sksl = (Z_SortKeySpecList *)
2588 odr_malloc (out, sizeof(*sksl));
2594 sprintf (setstring, "%d", setnumber);
2596 sprintf (setstring, "default");
2598 req->referenceId = set_refid (out);
2600 req->num_inputResultSetNames = 1;
2601 req->inputResultSetNames = (Z_InternationalString **)
2602 odr_malloc (out, sizeof(*req->inputResultSetNames));
2603 req->inputResultSetNames[0] = odr_strdup (out, setstring);
2605 if (newset && setnumber >= 0)
2606 sprintf (setstring, "%d", ++setnumber);
2608 req->sortedResultSetName = odr_strdup (out, setstring);
2610 req->sortSequence = yaz_sort_spec (out, arg);
2611 if (!req->sortSequence)
2613 printf ("Missing sort specifications\n");
2620 void display_term(Z_TermInfo *t)
2623 printf("%s", t->displayTerm);
2624 else if (t->term->which == Z_Term_general)
2626 printf("%.*s", t->term->u.general->len, t->term->u.general->buf);
2627 sprintf(last_scan_line, "%.*s", t->term->u.general->len,
2628 t->term->u.general->buf);
2631 printf("Term (not general)");
2632 if (t->globalOccurrences)
2633 printf (" (%d)\n", *t->globalOccurrences);
2638 void process_scanResponse(Z_ScanResponse *res)
2641 Z_Entry **entries = NULL;
2642 int num_entries = 0;
2644 printf("Received ScanResponse\n");
2645 print_refid (res->referenceId);
2646 printf("%d entries", *res->numberOfEntriesReturned);
2647 if (res->positionOfTerm)
2648 printf (", position=%d", *res->positionOfTerm);
2650 if (*res->scanStatus != Z_Scan_success)
2651 printf("Scan returned code %d\n", *res->scanStatus);
2654 if ((entries = res->entries->entries))
2655 num_entries = res->entries->num_entries;
2656 for (i = 0; i < num_entries; i++)
2658 int pos_term = res->positionOfTerm ? *res->positionOfTerm : -1;
2659 if (entries[i]->which == Z_Entry_termInfo)
2661 printf("%c ", i + 1 == pos_term ? '*' : ' ');
2662 display_term(entries[i]->u.termInfo);
2665 display_diagrecs(&entries[i]->u.surrogateDiagnostic, 1);
2667 if (res->entries->nonsurrogateDiagnostics)
2668 display_diagrecs (res->entries->nonsurrogateDiagnostics,
2669 res->entries->num_nonsurrogateDiagnostics);
2672 void process_sortResponse(Z_SortResponse *res)
2674 printf("Received SortResponse: status=");
2675 switch (*res->sortStatus)
2677 case Z_SortStatus_success:
2678 printf ("success"); break;
2679 case Z_SortStatus_partial_1:
2680 printf ("partial"); break;
2681 case Z_SortStatus_failure:
2682 printf ("failure"); break;
2684 printf ("unknown (%d)", *res->sortStatus);
2687 print_refid (res->referenceId);
2688 if (res->diagnostics)
2689 display_diagrecs(res->diagnostics,
2690 res->num_diagnostics);
2693 void process_deleteResultSetResponse (Z_DeleteResultSetResponse *res)
2695 printf("Got deleteResultSetResponse status=%d\n",
2696 *res->deleteOperationStatus);
2697 if (res->deleteListStatuses)
2700 for (i = 0; i < res->deleteListStatuses->num; i++)
2702 printf ("%s status=%d\n", res->deleteListStatuses->elements[i]->id,
2703 *res->deleteListStatuses->elements[i]->status);
2708 int cmd_sort_generic(const char *arg, int newset)
2712 printf("Session not initialized yet\n");
2717 if (!ODR_MASK_GET(session->options, Z_Options_sort))
2719 printf("Target doesn't support sort\n");
2724 if (send_sortrequest(arg, newset) < 0)
2731 int cmd_sort(const char *arg)
2733 return cmd_sort_generic (arg, 0);
2736 int cmd_sort_newset (const char *arg)
2738 return cmd_sort_generic (arg, 1);
2741 int cmd_scan(const char *arg)
2750 printf("Session not initialized yet\n");
2754 if (!ODR_MASK_GET(session->options, Z_Options_scan))
2756 printf("Target doesn't support scan\n");
2761 strcpy (last_scan_query, arg);
2762 if (send_scanrequest(arg, 1, 20, 0) < 0)
2767 if (send_scanrequest(last_scan_query, 1, 20, last_scan_line) < 0)
2773 int cmd_schema(const char *arg)
2775 xfree(record_schema);
2778 record_schema = xstrdup(arg);
2782 int cmd_format(const char *arg)
2787 printf("Usage: format <recordsyntax>\n");
2790 nsyntax = oid_getvalbyname (arg);
2791 if (strcmp(arg, "none") && nsyntax == VAL_NONE)
2793 printf ("unknown record syntax\n");
2796 recordsyntax = nsyntax;
2800 int cmd_elements(const char *arg)
2802 static Z_ElementSetNames esn;
2803 static char what[100];
2807 elementSetNames = 0;
2811 esn.which = Z_ElementSetNames_generic;
2812 esn.u.generic = what;
2813 elementSetNames = &esn;
2817 int cmd_attributeset(const char *arg)
2823 printf("Usage: attributeset <setname>\n");
2826 sscanf(arg, "%s", what);
2827 if (p_query_attset (what))
2829 printf("Unknown attribute set name\n");
2835 int cmd_querytype (const char *arg)
2837 if (!strcmp (arg, "ccl"))
2838 queryType = QueryType_CCL;
2839 else if (!strcmp (arg, "prefix") || !strcmp(arg, "rpn"))
2840 queryType = QueryType_Prefix;
2841 else if (!strcmp (arg, "ccl2rpn") || !strcmp (arg, "cclrpn"))
2842 queryType = QueryType_CCL2RPN;
2843 else if (!strcmp(arg, "cql"))
2844 queryType = QueryType_CQL;
2845 else if (!strcmp (arg, "cql2rpn") || !strcmp (arg, "cqlrpn"))
2846 queryType = QueryType_CQL2RPN;
2849 printf ("Querytype must be one of:\n");
2850 printf (" prefix - Prefix query\n");
2851 printf (" ccl - CCL query\n");
2852 printf (" ccl2rpn - CCL query converted to RPN\n");
2853 printf (" cql - CQL\n");
2854 printf (" cql2rpn - CQL query converted to RPN\n");
2860 int cmd_refid (const char *arg)
2866 refid = (char *) xmalloc (strlen(arg)+1);
2867 strcpy (refid, arg);
2872 int cmd_close(const char *arg)
2881 apdu = zget_APDU(out, Z_APDU_close);
2882 req = apdu->u.close;
2883 *req->closeReason = Z_Close_finished;
2885 printf("Sent close request.\n");
2890 int cmd_packagename(const char* arg)
2892 xfree (esPackageName);
2893 esPackageName = NULL;
2895 esPackageName = xstrdup(arg);
2899 int cmd_proxy(const char* arg)
2904 yazProxy = xstrdup (arg);
2908 int cmd_marccharset(const char *arg)
2913 if (sscanf(arg, "%29s", l1) < 1)
2915 xfree (marcCharset);
2917 if (strcmp(l1, "-"))
2918 marcCharset = xstrdup(l1);
2922 int cmd_charset(const char* arg)
2924 char l1[30], l2[30];
2927 if (sscanf(arg, "%29s %29s", l1, l2) < 1)
2929 printf("Current negotiation character set is `%s'\n",
2930 negotiationCharset ? negotiationCharset: "none");
2931 printf("Current output character set is `%s'\n",
2932 outputCharset ? outputCharset: "none");
2935 xfree (negotiationCharset);
2936 negotiationCharset = NULL;
2937 if (*l1 && strcmp(l1, "-"))
2939 negotiationCharset = xstrdup(l1);
2940 printf ("Character set negotiation : %s\n", negotiationCharset);
2943 printf ("Character set negotiation disabled\n");
2946 xfree (outputCharset);
2948 if (!strcmp(l2, "auto") && codeset)
2952 printf ("output charset: %s\n", codeset);
2953 outputCharset = xstrdup(codeset);
2958 printf ("No codeset found on this system\n");
2960 else if (strcmp(l2, "-"))
2961 outputCharset = xstrdup(l2);
2963 printf ("Output charset conversion disabled\n");
2969 int cmd_lang(const char* arg)
2972 printf("Current language is `%s'\n", (yazLang)?yazLang:NULL);
2979 yazLang = (char *) xmalloc (strlen(arg)+1);
2980 strcpy (yazLang, arg);
2985 int cmd_source(const char* arg)
2987 /* first should open the file and read one line at a time.. */
2989 char line[1024], *cp;
2992 fprintf(stderr,"Error in source command use a filename\n");
2996 includeFile = fopen (arg, "r");
2999 fprintf(stderr,"Unable to open file %s for reading\n",arg);
3003 while(!feof(includeFile)) {
3004 memset(line,0,sizeof(line));
3005 fgets(line,sizeof(line),includeFile);
3007 if(strlen(line) < 2) continue;
3008 if(line[0] == '#') continue;
3010 if ((cp = strrchr (line, '\n')))
3013 process_cmd_line(line);
3016 if(fclose(includeFile)<0) {
3017 perror("unable to close include file");
3023 int cmd_subshell(const char* args)
3028 system(getenv("SHELL"));
3034 int cmd_set_berfile(const char *arg)
3036 if (ber_file && ber_file != stdout && ber_file != stderr)
3038 if (!strcmp(arg, ""))
3040 else if (!strcmp(arg, "-"))
3043 ber_file = fopen(arg, "a");
3047 int cmd_set_apdufile(const char *arg)
3049 if(apdu_file && apdu_file != stderr && apdu_file != stderr)
3051 if (!strcmp(arg, ""))
3053 else if (!strcmp(arg, "-"))
3057 apdu_file = fopen(arg, "a");
3059 perror("unable to open apdu log file");
3062 odr_setprint(print, apdu_file);
3066 int cmd_set_cclfile(const char* arg)
3070 bibset = ccl_qual_mk ();
3071 inf = fopen (arg, "r");
3073 perror("unable to open CCL file");
3076 ccl_qual_file (bibset, inf);
3079 strcpy(ccl_fields,arg);
3083 int cmd_set_cqlfile(const char* arg)
3085 cql_transform_t newcqltrans;
3087 if ((newcqltrans = cql_transform_open_fname(arg)) == 0) {
3088 perror("unable to open CQL file");
3092 cql_transform_close(cqltrans);
3094 cqltrans = newcqltrans;
3095 strcpy(cql_fields, arg);
3099 int cmd_set_auto_reconnect(const char* arg)
3101 if(strlen(arg)==0) {
3102 auto_reconnect = ! auto_reconnect;
3103 } else if(strcmp(arg,"on")==0) {
3105 } else if(strcmp(arg,"off")==0) {
3108 printf("Error use on or off\n");
3113 printf("Set auto reconnect enabled.\n");
3115 printf("Set auto reconnect disabled.\n");
3120 int cmd_set_marcdump(const char* arg)
3122 if(marc_file && marc_file != stderr) { /* don't close stdout*/
3126 if (!strcmp(arg, ""))
3128 else if (!strcmp(arg, "-"))
3132 marc_file = fopen(arg, "a");
3134 perror("unable to open marc log file");
3140 this command takes 3 arge {name class oid}
3142 int cmd_register_oid(const char* args) {
3147 {"appctx",CLASS_APPCTX},
3148 {"absyn",CLASS_ABSYN},
3149 {"attset",CLASS_ATTSET},
3150 {"transyn",CLASS_TRANSYN},
3151 {"diagset",CLASS_DIAGSET},
3152 {"recsyn",CLASS_RECSYN},
3153 {"resform",CLASS_RESFORM},
3154 {"accform",CLASS_ACCFORM},
3155 {"extserv",CLASS_EXTSERV},
3156 {"userinfo",CLASS_USERINFO},
3157 {"elemspec",CLASS_ELEMSPEC},
3158 {"varset",CLASS_VARSET},
3159 {"schema",CLASS_SCHEMA},
3160 {"tagset",CLASS_TAGSET},
3161 {"general",CLASS_GENERAL},
3162 {0,(enum oid_class) 0}
3164 char oname_str[101], oclass_str[101], oid_str[101];
3167 oid_class oidclass = CLASS_GENERAL;
3168 int val = 0, oid[OID_SIZE];
3169 struct oident * new_oident=NULL;
3171 if (sscanf (args, "%100[^ ] %100[^ ] %100s",
3172 oname_str,oclass_str, oid_str) < 1) {
3173 printf("Error in regristrate command \n");
3177 for (i = 0; oid_classes[i].className; i++) {
3178 if (!strcmp(oid_classes[i].className, oclass_str))
3180 oidclass=oid_classes[i].oclass;
3185 if(!(oid_classes[i].className)) {
3186 printf("Unknonwn oid class %s\n",oclass_str);
3194 while (isdigit (*name))
3196 val = val*10 + (*name - '0');
3209 new_oident=oid_addent (oid,PROTO_GENERAL,oidclass,oname_str,VAL_DYNAMIC);
3210 if(strcmp(new_oident->desc,oname_str)) {
3211 fprintf(stderr,"oid is already named as %s, regristration faild\n",
3217 int cmd_push_command(const char* arg)
3219 #if HAVE_READLINE_HISTORY_H
3223 fprintf(stderr,"Not compiled with the readline/history module\n");
3228 void source_rcfile()
3230 /* Look for a $HOME/.yazclientrc and source it if it exists */
3231 struct stat statbuf;
3233 char* homedir=getenv("HOME");
3235 if(!homedir) return;
3237 sprintf(buffer,"%s/.yazclientrc",homedir);
3239 if(stat(buffer,&statbuf)==0) {
3243 if(stat(".yazclientrc",&statbuf)==0) {
3244 cmd_source(".yazclientrc");
3249 static void initialize(void)
3254 if (!(out = odr_createmem(ODR_ENCODE)) ||
3255 !(in = odr_createmem(ODR_DECODE)) ||
3256 !(print = odr_createmem(ODR_PRINT)))
3258 fprintf(stderr, "failed to allocate ODR streams\n");
3263 setvbuf(stdout, 0, _IONBF, 0);
3265 odr_setprint(print, apdu_file);
3267 bibset = ccl_qual_mk ();
3268 inf = fopen (ccl_fields, "r");
3271 ccl_qual_file (bibset, inf);
3275 cqltrans = cql_transform_open_fname(cql_fields);
3276 /* If this fails, no problem: we detect cqltrans == 0 later */
3278 #if HAVE_READLINE_READLINE_H
3279 rl_attempted_completion_function = (CPPFunction*)readline_completer;
3283 for(i=0; i<maxOtherInfosSupported; ++i) {
3284 extraOtherInfos[i].oidval = -1;
3291 #if HAVE_GETTIMEOFDAY
3292 struct timeval tv_start, tv_end;
3296 static void handle_srw_record(Z_SRW_record *rec)
3298 if (rec->recordPosition)
3300 printf ("pos=%d", *rec->recordPosition);
3301 setno = *rec->recordPosition + 1;
3303 if (rec->recordSchema)
3304 printf (" schema=%s", rec->recordSchema);
3306 if (rec->recordData_buf && rec->recordData_len)
3307 fwrite(rec->recordData_buf, 1, rec->recordData_len, stdout);
3309 printf ("No data!");
3313 static void handle_srw_explain_response(Z_SRW_explainResponse *res)
3315 handle_srw_record(&res->record);
3318 static void handle_srw_response(Z_SRW_searchRetrieveResponse *res)
3322 printf ("Received SRW SearchRetrieve Response\n");
3324 for (i = 0; i<res->num_diagnostics; i++)
3326 printf ("SRW diagnostic %d %s\n",
3327 *res->diagnostics[i].code,
3328 yaz_diag_srw_str(*res->diagnostics[i].code));
3330 if (res->diagnostics[i].details)
3331 printf ("Details: %s\n", res->diagnostics[i].details);
3333 if (res->numberOfRecords)
3334 printf ("Number of hits: %d\n", *res->numberOfRecords);
3335 for (i = 0; i<res->num_records; i++)
3336 handle_srw_record(res->records + i);
3339 static void http_response(Z_HTTP_Response *hres)
3342 const char *content_type = z_HTTP_header_lookup(hres->headers,
3344 const char *connection_head = z_HTTP_header_lookup(hres->headers,
3346 if (content_type && !yaz_strcmp_del("text/xml", content_type, "; "))
3348 Z_SOAP *soap_package = 0;
3349 ODR o = odr_createmem(ODR_DECODE);
3350 Z_SOAP_Handler soap_handlers[2] = {
3351 {"http://www.loc.gov/zing/srw/", 0,
3352 (Z_SOAP_fun) yaz_srw_codec},
3355 ret = z_soap_codec(o, &soap_package,
3356 &hres->content_buf, &hres->content_len,
3358 if (!ret && soap_package->which == Z_SOAP_generic &&
3359 soap_package->u.generic->no == 0)
3361 Z_SRW_PDU *sr = soap_package->u.generic->p;
3362 if (sr->which == Z_SRW_searchRetrieve_response)
3363 handle_srw_response(sr->u.response);
3364 else if (sr->which == Z_SRW_explain_response)
3365 handle_srw_explain_response(sr->u.explain_response);
3369 else if (soap_package && (soap_package->which == Z_SOAP_fault
3370 || soap_package->which == Z_SOAP_error))
3372 printf ("HTTP Error Status=%d\n", hres->code);
3373 printf ("SOAP Fault code %s\n",
3374 soap_package->u.fault->fault_code);
3375 printf ("SOAP Fault string %s\n",
3376 soap_package->u.fault->fault_string);
3377 if (soap_package->u.fault->details)
3378 printf ("SOAP Details %s\n",
3379 soap_package->u.fault->details);
3387 if (hres->code != 200)
3389 printf ("HTTP Error Status=%d\n", hres->code);
3393 printf ("Decoding of SRW package failed\n");
3399 if (!strcmp(hres->version, "1.0"))
3401 /* HTTP 1.0: only if Keep-Alive we stay alive.. */
3402 if (!connection_head || strcmp(connection_head, "Keep-Alive"))
3407 /* HTTP 1.1: only if no close we stay alive .. */
3408 if (connection_head && !strcmp(connection_head, "close"))
3415 void wait_and_handle_response()
3417 int reconnect_ok = 1;
3420 int netbufferlen = 0;
3425 res = cs_get(conn, &netbuffer, &netbufferlen);
3426 if (reconnect_ok && res <= 0 && protocol == PROTO_HTTP)
3437 buf_out = odr_getbuf(out, &len_out, 0);
3439 do_hex_dump(buf_out, len_out);
3441 cs_put(conn, buf_out, len_out);
3449 printf("Target closed connection\n");
3454 odr_reset(in); /* release APDU from last round */
3456 do_hex_dump(netbuffer, res);
3457 odr_setbuf(in, netbuffer, res, 0);
3459 if (!z_GDU(in, &gdu, 0, 0))
3461 FILE *f = ber_file ? ber_file : stdout;
3462 odr_perror(in, "Decoding incoming APDU");
3463 fprintf(f, "[Near %d]\n", odr_offset(in));
3464 fprintf(f, "Packet dump:\n---------\n");
3465 odr_dumpBER(f, netbuffer, res);
3466 fprintf(f, "---------\n");
3469 z_GDU(print, &gdu, 0, 0);
3472 if (conn && cs_more(conn))
3477 odr_dumpBER(ber_file, netbuffer, res);
3478 if (apdu_file && !z_GDU(print, &gdu, 0, 0))
3480 odr_perror(print, "Failed to print incoming APDU");
3484 if (gdu->which == Z_GDU_Z3950)
3486 Z_APDU *apdu = gdu->u.z3950;
3489 case Z_APDU_initResponse:
3490 process_initResponse(apdu->u.initResponse);
3492 case Z_APDU_searchResponse:
3493 process_searchResponse(apdu->u.searchResponse);
3495 case Z_APDU_scanResponse:
3496 process_scanResponse(apdu->u.scanResponse);
3498 case Z_APDU_presentResponse:
3499 print_refid (apdu->u.presentResponse->referenceId);
3501 *apdu->u.presentResponse->numberOfRecordsReturned;
3502 if (apdu->u.presentResponse->records)
3503 display_records(apdu->u.presentResponse->records);
3505 printf("No records.\n");
3506 printf ("nextResultSetPosition = %d\n",
3507 *apdu->u.presentResponse->nextResultSetPosition);
3509 case Z_APDU_sortResponse:
3510 process_sortResponse(apdu->u.sortResponse);
3512 case Z_APDU_extendedServicesResponse:
3513 printf("Got extended services response\n");
3514 process_ESResponse(apdu->u.extendedServicesResponse);
3517 printf("Target has closed the association.\n");
3518 process_close(apdu->u.close);
3520 case Z_APDU_resourceControlRequest:
3521 process_resourceControlRequest
3522 (apdu->u.resourceControlRequest);
3524 case Z_APDU_deleteResultSetResponse:
3525 process_deleteResultSetResponse(apdu->u.
3526 deleteResultSetResponse);
3529 printf("Received unknown APDU type (%d).\n",
3535 else if (gdu->which == Z_GDU_HTTP_Response)
3537 http_response(gdu->u.HTTP_Response);
3540 if (conn && !cs_more(conn))
3545 #if HAVE_GETTIMEOFDAY
3546 gettimeofday (&tv_end, 0);
3548 printf ("S/U S/U=%ld/%ld %ld/%ld",
3549 (long) tv_start.tv_sec,
3550 (long) tv_start.tv_usec,
3551 (long) tv_end.tv_sec,
3552 (long) tv_end.tv_usec);
3554 printf ("Elapsed: %.6f\n",
3555 (double) tv_end.tv_usec / 1e6 + tv_end.tv_sec -
3556 ((double) tv_start.tv_usec / 1e6 + tv_start.tv_sec));
3563 int cmd_cclparse(const char* arg)
3566 struct ccl_rpn_node *rpn=NULL;
3569 rpn = ccl_find_str (bibset, arg, &error, &pos);
3572 printf ("%*s^ - ", 3+strlen(last_cmd)+1+pos, " ");
3573 printf ("%s\n", ccl_err_msg (error));
3579 ccl_pr_tree(rpn, stdout);
3583 ccl_rpn_delete(rpn);
3591 int cmd_set_otherinfo(const char* args)
3593 char oid[101], otherinfoString[101];
3598 sscan_res = sscanf (args, "%d %100[^ ] %100s", &otherinfoNo, oid, otherinfoString);
3600 /* reset this otherinfo */
3601 if(otherinfoNo>=maxOtherInfosSupported) {
3602 printf("Error otherinfo index to large (%d>%d)\n",otherinfoNo,maxOtherInfosSupported);
3604 extraOtherInfos[otherinfoNo].oidval = -1;
3605 if(extraOtherInfos[otherinfoNo].value) free(extraOtherInfos[otherinfoNo].value);
3609 printf("Error in set_otherinfo command \n");
3613 if(otherinfoNo>=maxOtherInfosSupported) {
3614 printf("Error otherinfo index to large (%d>%d)\n",otherinfoNo,maxOtherInfosSupported);
3617 oidval = oid_getvalbyname (oid);
3619 printf("Error in set_otherinfo command unknown oid %s \n",oid);
3622 extraOtherInfos[otherinfoNo].oidval = oidval;
3623 if(extraOtherInfos[otherinfoNo].value) free(extraOtherInfos[otherinfoNo].value);
3624 extraOtherInfos[otherinfoNo].value = strdup(otherinfoString);
3629 int cmd_list_otherinfo(const char* args)
3633 if(strlen(args)>0) {
3635 if( i >= maxOtherInfosSupported ) {
3636 printf("Error otherinfo index to large (%d>%d)\n",i,maxOtherInfosSupported);
3640 if(extraOtherInfos[i].oidval != -1)
3641 printf(" otherinfo %d %s %s\n",
3643 yaz_z3950_oid_value_to_str(
3644 (enum oid_value) extraOtherInfos[i].oidval,
3646 extraOtherInfos[i].value);
3649 for(i=0; i<maxOtherInfosSupported; ++i) {
3650 if(extraOtherInfos[i].oidval != -1)
3651 printf(" otherinfo %d %s %s\n",
3653 yaz_z3950_oid_value_to_str(
3654 (enum oid_value) extraOtherInfos[i].oidval,
3656 extraOtherInfos[i].value);
3664 int cmd_list_all(const char* args) {
3667 /* connection options */
3669 printf("Connected to : %s\n",last_open_command);
3671 if(last_open_command)
3672 printf("Not connected to : %s\n",last_open_command);
3674 printf("Not connected : \n");
3677 if(yazProxy) printf("using proxy : %s\n",yazProxy);
3679 printf("auto_reconnect : %s\n",auto_reconnect?"on":"off");
3682 printf("Authentication : none\n");
3684 switch(auth->which) {
3685 case Z_IdAuthentication_idPass:
3686 printf("Authentication : IdPass\n");
3687 printf(" Login User : %s\n",auth->u.idPass->userId?auth->u.idPass->userId:"");
3688 printf(" Login Group : %s\n",auth->u.idPass->groupId?auth->u.idPass->groupId:"");
3689 printf(" Password : %s\n",auth->u.idPass->password?auth->u.idPass->password:"");
3691 case Z_IdAuthentication_open:
3692 printf("Authentication : psOpen\n");
3693 printf(" Open string : %s\n",auth->u.open);
3696 printf("Authentication : Unknown\n");
3699 if (negotiationCharset)
3700 printf("Neg. Character set : `%s'\n", negotiationCharset);
3704 for (i = 0; i<num_databaseNames; i++) printf("%s ",databaseNames[i]);
3708 printf("CCL file : %s\n",ccl_fields);
3709 printf("CQL file : %s\n",cql_fields);
3710 printf("Query type : %s\n",query_type_as_string(queryType));
3712 printf("Named Result Sets : %s\n",setnumber==-1?"off":"on");
3714 /* piggy back options */
3715 printf("ssub/lslb/mspn : %d/%d/%d\n",smallSetUpperBound,largeSetLowerBound,mediumSetPresentNumber);
3717 /* print present related options */
3718 printf("Format : %s\n",yaz_z3950_oid_value_to_str(recordsyntax,CLASS_RECSYN));
3719 printf("Schema : %s\n",record_schema ? record_schema : "not set");
3720 printf("Elements : %s\n",elementSetNames?elementSetNames->u.generic:"");
3722 /* loging options */
3723 printf("APDU log : %s\n",apdu_file?"on":"off");
3724 printf("Record log : %s\n",marc_file?"on":"off");
3727 printf("Other Info: \n");
3728 cmd_list_otherinfo("");
3733 int cmd_clear_otherinfo(const char* args)
3735 if(strlen(args)>0) {
3737 otherinfoNo = atoi(args);
3738 if( otherinfoNo >= maxOtherInfosSupported ) {
3739 printf("Error otherinfo index to large (%d>%d)\n",otherinfoNo,maxOtherInfosSupported);
3743 if(extraOtherInfos[otherinfoNo].oidval != -1) {
3744 /* only clear if set. */
3745 extraOtherInfos[otherinfoNo].oidval=-1;
3746 free(extraOtherInfos[otherinfoNo].value);
3751 for(i=0; i<maxOtherInfosSupported; ++i) {
3752 if (extraOtherInfos[i].oidval!=-1 ) {
3753 extraOtherInfos[i].oidval=-1;
3754 free(extraOtherInfos[i].value);
3761 static int cmd_help (const char *line);
3763 typedef char *(*completerFunctionType)(const char *text, int state);
3767 int (*fun)(const char *arg);
3769 completerFunctionType rl_completerfunction;
3770 int complete_filenames;
3771 char **local_tabcompletes;
3773 {"open", cmd_open, "('tcp'|'ssl')':<host>[':'<port>][/<db>]",NULL,0,NULL},
3774 {"quit", cmd_quit, "",NULL,0,NULL},
3775 {"find", cmd_find, "<query>",NULL,0,NULL},
3776 {"delete", cmd_delete, "<setname>",NULL,0,NULL},
3777 {"base", cmd_base, "<base-name>",NULL,0,NULL},
3778 {"show", cmd_show, "<rec#>['+'<#recs>['+'<setname>]]",NULL,0,NULL},
3779 {"scan", cmd_scan, "<term>",NULL,0,NULL},
3780 {"sort", cmd_sort, "<sortkey> <flag> <sortkey> <flag> ...",NULL,0,NULL},
3781 {"sort+", cmd_sort_newset, "<sortkey> <flag> <sortkey> <flag> ...",NULL,0,NULL},
3782 {"authentication", cmd_authentication, "<acctstring>",NULL,0,NULL},
3783 {"lslb", cmd_lslb, "<largeSetLowerBound>",NULL,0,NULL},
3784 {"ssub", cmd_ssub, "<smallSetUpperBound>",NULL,0,NULL},
3785 {"mspn", cmd_mspn, "<mediumSetPresentNumber>",NULL,0,NULL},
3786 {"status", cmd_status, "",NULL,0,NULL},
3787 {"setnames", cmd_setnames, "",NULL,0,NULL},
3788 {"cancel", cmd_cancel, "",NULL,0,NULL},
3789 {"format", cmd_format, "<recordsyntax>",complete_format,0,NULL},
3790 {"schema", cmd_schema, "<schema>",complete_schema,0,NULL},
3791 {"elements", cmd_elements, "<elementSetName>",NULL,0,NULL},
3792 {"close", cmd_close, "",NULL,0,NULL},
3793 {"attributeset", cmd_attributeset, "<attrset>",complete_attributeset,0,NULL},
3794 {"querytype", cmd_querytype, "<type>",complete_querytype,0,NULL},
3795 {"refid", cmd_refid, "<id>",NULL,0,NULL},
3796 {"itemorder", cmd_itemorder, "ill|item <itemno>",NULL,0,NULL},
3797 {"update", cmd_update, "<action> <recid> [<file>]",NULL,0,NULL},
3798 {"update0", cmd_update0, "<action> <recid> [<file>]",NULL,0,NULL},
3799 {"packagename", cmd_packagename, "<packagename>",NULL,0,NULL},
3800 {"proxy", cmd_proxy, "[('tcp'|'ssl')]<host>[':'<port>]",NULL,0,NULL},
3801 {"charset", cmd_charset, "<nego_charset> <output_charset>",NULL,0,NULL},
3802 {"marccharset", cmd_marccharset, "<charset_name>",NULL,0,NULL},
3803 {"lang", cmd_lang, "<language_code>",NULL,0,NULL},
3804 {".", cmd_source, "<filename>",NULL,1,NULL},
3805 {"!", cmd_subshell, "Subshell command",NULL,1,NULL},
3806 {"set_apdufile", cmd_set_apdufile, "<filename>",NULL,1,NULL},
3807 {"set_berfile", cmd_set_berfile, "<filename>",NULL,1,NULL},
3808 {"set_marcdump", cmd_set_marcdump," <filename>",NULL,1,NULL},
3809 {"set_cclfile", cmd_set_cclfile," <filename>",NULL,1,NULL},
3810 {"set_cqlfile", cmd_set_cqlfile," <filename>",NULL,1,NULL},
3811 {"set_auto_reconnect", cmd_set_auto_reconnect," on|off",complete_auto_reconnect,1,NULL},
3812 {"set_otherinfo", cmd_set_otherinfo,"<otherinfoinddex> <oid> <string>",NULL,0,NULL},
3813 {"register_oid", cmd_register_oid,"<name> <class> <oid>",NULL,0,NULL},
3814 {"push_command", cmd_push_command,"<command>",command_generator,0,NULL},
3815 {"register_tab", cmd_register_tab,"<commandname> <tab>",command_generator,0,NULL},
3816 {"cclparse", cmd_cclparse,"<ccl find command>",NULL,0,NULL},
3817 {"list_otherinfo",cmd_list_otherinfo,"[otherinfoinddex]",NULL,0,NULL},
3818 {"list_all",cmd_list_all,"",NULL,0,NULL},
3819 {"clear_otherinfo",cmd_clear_otherinfo,"",NULL,0,NULL},
3820 /* Server Admin Functions */
3821 {"adm-reindex", cmd_adm_reindex, "<database-name>",NULL,0,NULL},
3822 {"adm-truncate", cmd_adm_truncate, "('database'|'index')<object-name>",NULL,0,NULL},
3823 {"adm-create", cmd_adm_create, "",NULL,0,NULL},
3824 {"adm-drop", cmd_adm_drop, "('database'|'index')<object-name>",NULL,0,NULL},
3825 {"adm-import", cmd_adm_import, "<record-type> <dir> <pattern>",NULL,0,NULL},
3826 {"adm-refresh", cmd_adm_refresh, "",NULL,0,NULL},
3827 {"adm-commit", cmd_adm_commit, "",NULL,0,NULL},
3828 {"adm-shutdown", cmd_adm_shutdown, "",NULL,0,NULL},
3829 {"adm-startup", cmd_adm_startup, "",NULL,0,NULL},
3830 {"explain", cmd_explain, "", NULL, 0, NULL},
3831 {"options", cmd_options, "", NULL, 0, NULL},
3832 {"help", cmd_help, "", NULL,0,NULL},
3836 static int cmd_help (const char *line)
3842 sscanf (line, "%20s", topic);
3845 printf("Commands:\n");
3846 for (i = 0; cmd_array[i].cmd; i++)
3847 if (*topic == 0 || strcmp (topic, cmd_array[i].cmd) == 0)
3848 printf(" %s %s\n", cmd_array[i].cmd, cmd_array[i].ad);
3849 if (strcmp (topic, "find") == 0)
3852 printf (" \"term\" Simple Term\n");
3853 printf (" @attr [attset] type=value op Attribute\n");
3854 printf (" @and opl opr And\n");
3855 printf (" @or opl opr Or\n");
3856 printf (" @not opl opr And-Not\n");
3857 printf (" @set set Result set\n");
3859 printf ("Bib-1 attribute types\n");
3861 printf ("4=Title 7=ISBN 8=ISSN 30=Date 62=Abstract 1003=Author 1016=Any\n");
3862 printf ("2=Relation: ");
3863 printf ("1< 2<= 3= 4>= 5> 6!= 102=Relevance\n");
3864 printf ("3=Position: ");
3865 printf ("1=First in Field 2=First in subfield 3=Any position\n");
3866 printf ("4=Structure: ");
3867 printf ("1=Phrase 2=Word 3=Key 4=Year 5=Date 6=WordList\n");
3868 printf ("5=Truncation: ");
3869 printf ("1=Right 2=Left 3=L&R 100=No 101=# 102=Re-1 103=Re-2\n");
3870 printf ("6=Completeness:");
3871 printf ("1=Incomplete subfield 2=Complete subfield 3=Complete field\n");
3876 int cmd_register_tab(const char* arg) {
3878 char command[101], tabargument[101];
3883 if (sscanf (arg, "%100s %100s", command, tabargument) < 1) {
3887 /* locate the amdn in the list */
3888 for (i = 0; cmd_array[i].cmd; i++) {
3889 if (!strncmp(cmd_array[i].cmd, command, strlen(command))) {
3894 if(!cmd_array[i].cmd) {
3895 fprintf(stderr,"Unknown command %s\n",command);
3900 if(!cmd_array[i].local_tabcompletes)
3901 cmd_array[i].local_tabcompletes = (char **) calloc(1,sizeof(char**));
3905 tabslist = cmd_array[i].local_tabcompletes;
3906 for(;tabslist && *tabslist;tabslist++) {
3910 cmd_array[i].local_tabcompletes = (char **)
3911 realloc(cmd_array[i].local_tabcompletes,(num_of_tabs+2)*sizeof(char**));
3912 tabslist=cmd_array[i].local_tabcompletes;
3913 tabslist[num_of_tabs]=strdup(tabargument);
3914 tabslist[num_of_tabs+1]=NULL;
3919 void process_cmd_line(char* line)
3922 char word[32], arg[1024];
3924 #if HAVE_GETTIMEOFDAY
3925 gettimeofday (&tv_start, 0);
3928 if ((res = sscanf(line, "%31s %1023[^;]", word, arg)) <= 0)
3930 strcpy(word, last_cmd);
3935 strcpy(last_cmd, word);
3937 /* removed tailing spaces from the arg command */
3940 char* lastnonspace=NULL;
3948 *(++lastnonspace) = 0;
3951 for (i = 0; cmd_array[i].cmd; i++)
3952 if (!strncmp(cmd_array[i].cmd, word, strlen(word)))
3954 res = (*cmd_array[i].fun)(arg);
3958 if (!cmd_array[i].cmd) /* dump our help-screen */
3960 printf("Unknown command: %s.\n", word);
3961 printf("use help for list of commands\n");
3962 /* cmd_help (""); */
3966 if(apdu_file) fflush(apdu_file);
3969 wait_and_handle_response();
3978 char *command_generator(const char *text, int state)
3984 for( ; cmd_array[idx].cmd; ++idx) {
3985 if (!strncmp(cmd_array[idx].cmd,text,strlen(text))) {
3986 ++idx; /* skip this entry on the next run */
3987 return strdup(cmd_array[idx-1].cmd);
3995 This function only known how to complete on the first word
3997 char ** readline_completer(char *text, int start, int end) {
3998 #if HAVE_READLINE_READLINE_H
4000 completerFunctionType completerToUse;
4003 #if HAVE_READLINE_RL_COMPLETION_MATCHES
4004 char** res=rl_completion_matches(text,
4007 char** res=completion_matches(text,
4008 (CPFunction*)command_generator);
4010 rl_attempted_completion_over = 1;
4013 char arg[1024],word[32];
4015 if ((res = sscanf(rl_line_buffer, "%31s %1023[^;]", word, arg)) <= 0) {
4016 rl_attempted_completion_over = 1;
4020 for (i = 0; cmd_array[i].cmd; i++) {
4021 if (!strncmp(cmd_array[i].cmd, word, strlen(word))) {
4026 if(!cmd_array[i].cmd) return NULL;
4028 curret_global_list = cmd_array[i].local_tabcompletes;
4030 completerToUse = cmd_array[i].rl_completerfunction;
4031 if(completerToUse==NULL) /* if no pr. command completer is defined use the default completer */
4032 completerToUse = default_completer;
4034 if(completerToUse) {
4035 #ifdef HAVE_READLINE_RL_COMPLETION_MATCHES
4037 rl_completion_matches(text,
4041 completion_matches(text,
4042 (CPFunction*)completerToUse);
4044 if(!cmd_array[i].complete_filenames)
4045 rl_attempted_completion_over = 1;
4048 if(!cmd_array[i].complete_filenames)
4049 rl_attempted_completion_over = 1;
4059 static void client(void)
4065 #if HAVE_GETTIMEOFDAY
4066 gettimeofday (&tv_start, 0);
4071 char *line_in = NULL;
4072 #if HAVE_READLINE_READLINE_H
4075 line_in=readline(C_PROMPT);
4078 #if HAVE_READLINE_HISTORY_H
4080 add_history(line_in);
4082 strncpy(line, line_in, 1023);
4091 if (!fgets(line, 1023, stdin))
4093 if ((end_p = strchr (line, '\n')))
4096 process_cmd_line(line);
4100 static void show_version(void)
4104 yaz_version(vstr, 0);
4105 printf ("YAZ version: %s\n", YAZ_VERSION);
4106 if (strcmp(vstr, YAZ_VERSION))
4107 printf ("YAZ DLL/SO: %s\n", vstr);
4111 int main(int argc, char **argv)
4114 char *open_command = 0;
4115 char *auth_command = 0;
4120 if (!setlocale(LC_CTYPE, ""))
4121 fprintf (stderr, "setlocale failed\n");
4125 codeset = nl_langinfo(CODESET);
4129 outputCharset = xstrdup(codeset);
4131 ODR_MASK_SET(&z3950_options, Z_Options_search);
4132 ODR_MASK_SET(&z3950_options, Z_Options_present);
4133 ODR_MASK_SET(&z3950_options, Z_Options_namedResultSets);
4134 ODR_MASK_SET(&z3950_options, Z_Options_triggerResourceCtrl);
4135 ODR_MASK_SET(&z3950_options, Z_Options_scan);
4136 ODR_MASK_SET(&z3950_options, Z_Options_sort);
4137 ODR_MASK_SET(&z3950_options, Z_Options_extendedServices);
4138 ODR_MASK_SET(&z3950_options, Z_Options_delSet);
4140 while ((ret = options("k:c:q:a:b:m:v:p:u:t:Vxd:", argv, argc, &arg)) != -2)
4147 open_command = (char *) xmalloc (strlen(arg)+6);
4148 strcpy (open_command, "open ");
4149 strcat (open_command, arg);
4153 dump_file_prefix = arg;
4156 kilobytes = atoi(arg);
4159 if (!(marc_file = fopen (arg, "a")))
4166 outputCharset = xstrdup(arg);
4169 strncpy (ccl_fields, arg, sizeof(ccl_fields)-1);
4170 ccl_fields[sizeof(ccl_fields)-1] = '\0';
4173 strncpy (cql_fields, arg, sizeof(cql_fields)-1);
4174 cql_fields[sizeof(cql_fields)-1] = '\0';
4177 if (!strcmp(arg, "-"))
4180 ber_file=fopen(arg, "a");
4183 if (!strcmp(arg, "-"))
4186 apdu_file=fopen(arg, "a");
4192 yazProxy=strdup(arg);
4197 auth_command = (char *) xmalloc (strlen(arg)+6);
4198 strcpy (auth_command, "auth ");
4199 strcat (auth_command, arg);
4203 yaz_log_init(yaz_log_mask_str(arg), "", 0);
4209 fprintf (stderr, "Usage: %s [-m <marclog>] [ -a <apdulog>] "
4210 "[-b berdump] [-c cclfields] \n"
4211 "[-q cqlfields] [-p <proxy-addr>] [-u <auth>] "
4212 "[-k size] [-d dump] [-V] [<server-addr>]\n",
4220 #ifdef HAVE_GETTIMEOFDAY
4221 gettimeofday (&tv_start, 0);
4223 process_cmd_line (auth_command);
4224 #if HAVE_READLINE_HISTORY_H
4225 add_history(auth_command);
4227 xfree(auth_command);
4231 #ifdef HAVE_GETTIMEOFDAY
4232 gettimeofday (&tv_start, 0);
4234 process_cmd_line (open_command);
4235 #if HAVE_READLINE_HISTORY_H
4236 add_history(open_command);
4238 xfree(open_command);
4249 * vim600: sw=4 ts=8 fdm=marker
4250 * vim<600: sw=4 ts=8