2 * Copyright (c) 1995-2003, Index Data
3 * See the file LICENSE for details.
5 * $Id: client.c,v 1.216 2003-12-20 00:51:19 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 *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;
107 static char cur_host[200];
117 static QueryType queryType = QueryType_Prefix;
119 static CCL_bibset bibset; /* CCL bibset handle */
120 static cql_transform_t cqltrans; /* CQL context-set handle */
122 #if HAVE_READLINE_COMPLETION_OVER
125 /* readline doesn't have this var. Define it ourselves. */
126 int rl_attempted_completion_over = 0;
129 /* set this one to 1, to avoid decode of unknown MARCs */
130 #define AVOID_MARC_DECODE 1
132 #define maxOtherInfosSupported 10
136 } extraOtherInfos[maxOtherInfosSupported];
139 void process_cmd_line(char* line);
140 char ** readline_completer(char *text, int start, int end);
141 char *command_generator(const char *text, int state);
142 char** curret_global_list=NULL;
143 int cmd_register_tab(const char* arg);
145 static void close_session (void);
147 ODR getODROutputStream()
152 const char* query_type_as_string(QueryType q)
155 case QueryType_Prefix: return "prefix (RPN sent to server)";
156 case QueryType_CCL: return "CCL (CCL sent to server) ";
157 case QueryType_CCL2RPN: return "CCL -> RPN (RPN sent to server)";
158 case QueryType_CQL: return "CQL (CQL sent to server)";
159 case QueryType_CQL2RPN: return "CQL -> RPN (RPN sent to server)";
161 return "unknown Query type internal yaz-client error";
165 static void do_hex_dump(const char* buf, int len)
170 for( i=0; i<len ; i=i+16 )
173 for(x=0 ; i+x<len && x<16; ++x)
175 printf("%2.2X ",(unsigned int)((unsigned char)buf[i+x]));
180 if (dump_file_prefix)
183 if (++no < 1000 && strlen(dump_file_prefix) < 500)
187 sprintf (fname, "%s.%03d.raw", dump_file_prefix, no);
188 of = fopen(fname, "wb");
190 fwrite (buf, 1, len, of);
197 void add_otherInfos(Z_APDU *a)
199 Z_OtherInformation **oi;
203 for(i=0; i<maxOtherInfosSupported; ++i)
205 if(extraOtherInfos[i].oidval != -1)
206 yaz_oi_set_string_oidval(oi, out, extraOtherInfos[i].oidval,
207 1, extraOtherInfos[i].value);
211 int send_apdu(Z_APDU *a)
220 z_APDU(print, &a, 0, 0);
223 if (!z_APDU(out, &a, 0, 0))
225 odr_perror(out, "Encoding APDU");
229 buf = odr_getbuf(out, &len, 0);
231 odr_dumpBER(ber_file, buf, len);
232 /* printf ("sending APDU of size %d\n", len); */
233 do_hex_dump(buf, len);
234 if (cs_put(conn, buf, len) < 0)
236 fprintf(stderr, "cs_put: %s", cs_errmsg(cs_errno(conn)));
240 odr_reset(out); /* release the APDU structure */
244 static void print_stringn(const unsigned char *buf, size_t len)
247 for (i = 0; i<len; i++)
248 if ((buf[i] <= 126 && buf[i] >= 32) || strchr ("\n\r\t\f", buf[i]))
249 printf ("%c", buf[i]);
251 printf ("\\X%02X", buf[i]);
254 static void print_refid (Z_ReferenceId *id)
258 printf ("Reference Id: ");
259 print_stringn (id->buf, id->len);
264 static Z_ReferenceId *set_refid (ODR out)
269 id = (Z_ReferenceId *) odr_malloc (out, sizeof(*id));
270 id->size = id->len = strlen(refid);
271 id->buf = (unsigned char *) odr_malloc (out, id->len);
272 memcpy (id->buf, refid, id->len);
276 /* INIT SERVICE ------------------------------- */
278 static void send_initRequest(const char* type_and_host)
280 Z_APDU *apdu = zget_APDU(out, Z_APDU_initRequest);
281 Z_InitRequest *req = apdu->u.initRequest;
283 ODR_MASK_SET(req->options, Z_Options_search);
284 ODR_MASK_SET(req->options, Z_Options_present);
285 ODR_MASK_SET(req->options, Z_Options_namedResultSets);
286 ODR_MASK_SET(req->options, Z_Options_triggerResourceCtrl);
287 ODR_MASK_SET(req->options, Z_Options_scan);
288 ODR_MASK_SET(req->options, Z_Options_sort);
289 ODR_MASK_SET(req->options, Z_Options_extendedServices);
290 ODR_MASK_SET(req->options, Z_Options_delSet);
292 ODR_MASK_SET(req->protocolVersion, Z_ProtocolVersion_1);
293 ODR_MASK_SET(req->protocolVersion, Z_ProtocolVersion_2);
294 ODR_MASK_SET(req->protocolVersion, Z_ProtocolVersion_3);
296 *req->maximumRecordSize = 1024*kilobytes;
297 *req->preferredMessageSize = 1024*kilobytes;
299 req->idAuthentication = auth;
301 req->referenceId = set_refid (out);
304 yaz_oi_set_string_oidval(&req->otherInfo, out, VAL_PROXY,
307 if (negotiationCharset || yazLang) {
308 Z_OtherInformation **p;
309 Z_OtherInformationUnit *p0;
311 yaz_oi_APDU(apdu, &p);
313 if ((p0=yaz_oi_update(p, out, NULL, 0, 0))) {
314 ODR_MASK_SET(req->options, Z_Options_negotiationModel);
316 p0->which = Z_OtherInfo_externallyDefinedInfo;
317 p0->information.externallyDefinedInfo =
318 yaz_set_proposal_charneg(
320 (const char**)&negotiationCharset,
321 negotiationCharset ? 1 : 0,
322 (const char**)&yazLang, yazLang ? 1 : 0, 1);
327 printf("Sent initrequest.\n");
331 /* These two are used only from process_initResponse() */
332 static void render_initUserInfo(Z_OtherInformation *ui1);
333 static void render_diag(Z_DiagnosticFormat *diag);
335 static int process_initResponse(Z_InitResponse *res)
338 /* save session parameters for later use */
339 session_mem = odr_extract_mem(in);
342 for (ver = 0; ver<5; ver++)
343 if (!ODR_MASK_GET(res->protocolVersion, ver))
347 printf("Connection rejected by v%d target.\n", ver);
349 printf("Connection accepted by v%d target.\n", ver);
350 if (res->implementationId)
351 printf("ID : %s\n", res->implementationId);
352 if (res->implementationName)
353 printf("Name : %s\n", res->implementationName);
354 if (res->implementationVersion)
355 printf("Version: %s\n", res->implementationVersion);
356 if (res->userInformationField)
358 Z_External *uif = res->userInformationField;
359 if (uif->which == Z_External_userInfo1) {
360 render_initUserInfo(uif->u.userInfo1);
362 printf("UserInformationfield:\n");
363 if (!z_External(print, (Z_External**)&uif, 0, 0)) {
364 odr_perror(print, "Printing userinfo\n");
367 if (uif->which == Z_External_octet) {
368 printf("Guessing visiblestring:\n");
369 printf("'%s'\n", uif->u. octet_aligned->buf);
370 } else if (uif->which == Z_External_single) {
371 /* Peek at any private Init-diagnostic APDUs */
372 Odr_any *sat = uif->u.single_ASN1_type;
373 printf("### NAUGHTY: External is '%s'\n", sat->buf);
379 if (ODR_MASK_GET(res->options, Z_Options_search))
381 if (ODR_MASK_GET(res->options, Z_Options_present))
383 if (ODR_MASK_GET(res->options, Z_Options_delSet))
385 if (ODR_MASK_GET(res->options, Z_Options_resourceReport))
386 printf (" resourceReport");
387 if (ODR_MASK_GET(res->options, Z_Options_resourceCtrl))
388 printf (" resourceCtrl");
389 if (ODR_MASK_GET(res->options, Z_Options_accessCtrl))
390 printf (" accessCtrl");
391 if (ODR_MASK_GET(res->options, Z_Options_scan))
393 if (ODR_MASK_GET(res->options, Z_Options_sort))
395 if (ODR_MASK_GET(res->options, Z_Options_extendedServices))
396 printf (" extendedServices");
397 if (ODR_MASK_GET(res->options, Z_Options_level_1Segmentation))
398 printf (" level1Segmentation");
399 if (ODR_MASK_GET(res->options, Z_Options_level_2Segmentation))
400 printf (" level2Segmentation");
401 if (ODR_MASK_GET(res->options, Z_Options_concurrentOperations))
402 printf (" concurrentOperations");
403 if (ODR_MASK_GET(res->options, Z_Options_namedResultSets))
405 printf (" namedResultSets");
408 if (ODR_MASK_GET(res->options, Z_Options_encapsulation))
409 printf (" encapsulation");
410 if (ODR_MASK_GET(res->options, Z_Options_resultCount))
411 printf (" resultCount");
412 if (ODR_MASK_GET(res->options, Z_Options_negotiationModel))
413 printf (" negotiationModel");
414 if (ODR_MASK_GET(res->options, Z_Options_duplicateDetection))
415 printf (" duplicateDetection");
416 if (ODR_MASK_GET(res->options, Z_Options_queryType104))
417 printf (" queryType104");
420 if (ODR_MASK_GET(res->options, Z_Options_negotiationModel)) {
422 Z_CharSetandLanguageNegotiation *p =
423 yaz_get_charneg_record(res->otherInfo);
427 char *charset=NULL, *lang=NULL;
430 yaz_get_response_charneg(session_mem, p, &charset, &lang,
433 if (outputCharset && negotiationCharset) {
434 odr_set_charset (out, charset, outputCharset);
435 odr_set_charset (in, outputCharset, charset);
438 odr_set_charset (out, 0, 0);
439 odr_set_charset (in, 0, 0);
442 printf("Accepted character set : %s\n", charset);
443 printf("Accepted code language : %s\n", lang ? lang : "none");
444 printf("Accepted records in ...: %d\n", selected );
452 static void render_initUserInfo(Z_OtherInformation *ui1) {
454 printf("Init response contains %d otherInfo unit%s:\n",
455 ui1->num_elements, ui1->num_elements == 1 ? "" : "s");
457 for (i = 0; i < ui1->num_elements; i++) {
458 Z_OtherInformationUnit *unit = ui1->list[i];
459 printf(" %d: otherInfo unit contains ", i+1);
460 if (unit->which == Z_OtherInfo_externallyDefinedInfo &&
461 unit->information.externallyDefinedInfo->which ==
463 render_diag(unit->information.externallyDefinedInfo->u.diag1);
465 printf("unsupported otherInfo unit type %d\n", unit->which);
471 /* ### should this share code with display_diagrecs()? */
472 static void render_diag(Z_DiagnosticFormat *diag) {
475 printf("%d diagnostic%s:\n", diag->num, diag->num == 1 ? "" : "s");
476 for (i = 0; i < diag->num; i++) {
477 Z_DiagnosticFormat_s *ds = diag->elements[i];
478 printf(" %d: ", i+1);
480 case Z_DiagnosticFormat_s_defaultDiagRec: {
481 Z_DefaultDiagFormat *dd = ds->u.defaultDiagRec;
482 /* ### should check `dd->diagnosticSetId' */
483 printf("code=%d (%s)", *dd->condition,
484 diagbib1_str(*dd->condition));
485 /* Both types of addinfo are the same, so use type-pun */
486 if (dd->u.v2Addinfo != 0)
487 printf(",\n\taddinfo='%s'", dd->u.v2Addinfo);
490 case Z_DiagnosticFormat_s_explicitDiagnostic:
491 printf("Explicit diagnostic (not supported)");
494 printf("Unrecognised diagnostic type %d", ds->which);
498 if (ds->message != 0)
499 printf(", message='%s'", ds->message);
505 static int set_base(const char *arg)
510 for (i = 0; i<num_databaseNames; i++)
511 xfree (databaseNames[i]);
512 num_databaseNames = 0;
516 if (!(cp = strchr(arg, ' ')))
517 cp = arg + strlen(arg);
520 databaseNames[num_databaseNames] = (char *)xmalloc (1 + cp - arg);
521 memcpy (databaseNames[num_databaseNames], arg, cp - arg);
522 databaseNames[num_databaseNames][cp - arg] = '\0';
524 for (cp1 = databaseNames[num_databaseNames]; *cp1 ; cp1++)
533 if (num_databaseNames == 0)
535 num_databaseNames = 1;
536 databaseNames[0] = xstrdup("");
541 static int cmd_base(const char *arg)
545 printf("Usage: base <database> <database> ...\n");
548 return set_base(arg);
551 void cmd_open_remember_last_open_command(const char* arg, char* new_open_command)
553 if(last_open_command != arg)
555 if(last_open_command) xfree(last_open_command);
556 last_open_command = xstrdup(new_open_command);
560 int session_connect(const char *arg)
563 char type_and_host[101];
564 const char *basep = 0;
571 nmem_destroy (session_mem);
575 cs_get_host_args(arg, &basep);
577 strncpy(type_and_host, arg, sizeof(type_and_host)-1);
578 type_and_host[sizeof(type_and_host)-1] = '\0';
580 cmd_open_remember_last_open_command(arg,type_and_host);
583 conn = cs_create_host(yazProxy, 1, &add);
585 conn = cs_create_host(arg, 1, &add);
588 printf ("Couldn't create comstack\n");
593 if (conn->protocol == PROTO_HTTP)
595 printf ("SRW/HTTP not enabled in this YAZ\n");
601 protocol = conn->protocol;
602 if (conn->protocol == PROTO_HTTP)
606 printf("Connecting...");
608 if (cs_connect(conn, add) < 0)
610 printf ("error = %s\n", cs_strerror(conn));
611 if (conn->cerrno == CSYSERR)
614 yaz_strerror(msg, sizeof(msg));
615 printf ("%s\n", msg);
624 if (protocol == PROTO_Z3950)
626 send_initRequest(type_and_host);
632 int cmd_open(const char *arg)
636 strncpy (cur_host, arg, sizeof(cur_host)-1);
637 cur_host[sizeof(cur_host)-1] = 0;
639 return session_connect(cur_host);
646 if(!( auto_reconnect && last_open_command) ) return ;
648 open_command = (char *) xmalloc (strlen(last_open_command)+6);
649 strcpy (open_command, "open ");
651 strcat (open_command, last_open_command);
653 process_cmd_line(open_command);
658 int cmd_authentication(const char *arg)
660 static Z_IdAuthentication au;
661 static char user[40], group[40], pass[40];
662 static Z_IdPass idPass;
667 printf("Auth field set to null\n");
671 r = sscanf (arg, "%39s %39s %39s", user, group, pass);
674 printf("Authentication set to null\n");
680 if (!strcmp(user, "-")) {
681 au.which = Z_IdAuthentication_anonymous;
682 printf("Authentication set to Anonymous\n");
684 au.which = Z_IdAuthentication_open;
686 printf("Authentication set to Open (%s)\n", user);
692 au.which = Z_IdAuthentication_idPass;
693 au.u.idPass = &idPass;
694 idPass.groupId = NULL;
695 idPass.userId = user;
696 idPass.password = group;
697 printf("Authentication set to User (%s), Pass (%s)\n", user, group);
702 au.which = Z_IdAuthentication_idPass;
703 au.u.idPass = &idPass;
704 idPass.groupId = group;
705 idPass.userId = user;
706 idPass.password = pass;
707 printf("Authentication set to User (%s), Group (%s), Pass (%s)\n",
713 /* SEARCH SERVICE ------------------------------ */
714 static void display_record(Z_External *r);
716 static void print_record(const unsigned char *buf, size_t len)
719 print_stringn (buf, len);
720 /* add newline if not already added ... */
721 if (i <= 0 || buf[i-1] != '\n')
725 static void display_record(Z_External *r)
727 oident *ent = oid_getentbyoid(r->direct_reference);
731 * Tell the user what we got.
733 if (r->direct_reference)
735 printf("Record type: ");
737 printf("%s\n", ent->desc);
738 else if (!odr_oid(print, &r->direct_reference, 0, 0))
740 odr_perror(print, "print oid");
744 /* Check if this is a known, ASN.1 type tucked away in an octet string */
745 if (ent && r->which == Z_External_octet)
747 Z_ext_typeent *type = z_ext_getentbyref(ent->value);
753 * Call the given decoder to process the record.
755 odr_setbuf(in, (char*)r->u.octet_aligned->buf,
756 r->u.octet_aligned->len, 0);
757 if (!(*type->fun)(in, (char **)&rr, 0, 0))
759 odr_perror(in, "Decoding constructed record.");
760 fprintf(stdout, "[Near %d]\n", odr_offset(in));
761 fprintf(stdout, "Packet dump:\n---------\n");
762 odr_dumpBER(stdout, (char*)r->u.octet_aligned->buf,
763 r->u.octet_aligned->len);
764 fprintf(stdout, "---------\n");
766 /* note just ignores the error ant print the bytes form the octet_aligned later */
769 * Note: we throw away the original, BER-encoded record here.
770 * Do something else with it if you want to keep it.
772 r->u.sutrs = (Z_SUTRS *) rr; /* we don't actually check the type here. */
773 r->which = type->what;
777 if (ent && ent->oclass != CLASS_RECSYN)
779 if (ent && ent->value == VAL_SOIF)
780 print_record((const unsigned char *) r->u.octet_aligned->buf,
781 r->u.octet_aligned->len);
782 else if (r->which == Z_External_octet)
784 const char *octet_buf = (char*)r->u.octet_aligned->buf;
785 if (ent->value == VAL_TEXT_XML || ent->value == VAL_APPLICATION_XML ||
786 ent->value == VAL_HTML)
788 print_record((const unsigned char *) octet_buf,
789 r->u.octet_aligned->len);
791 else if (ent->value == VAL_POSTSCRIPT)
793 int size = r->u.octet_aligned->len;
796 print_record((const unsigned char *) octet_buf, size);
801 #if AVOID_MARC_DECODE
802 /* primitive check for a marc OID 5.1-29 except 16 */
803 ent->oidsuffix[0] == 5 && ent->oidsuffix[1] < 30 &&
804 ent->oidsuffix[1] != 16
813 yaz_marc_t mt = yaz_marc_create();
815 if (yaz_marc_decode_buf(mt, octet_buf,r->u.octet_aligned->len,
819 if (marcCharset && !strcmp(marcCharset, "auto"))
821 if (ent->value == VAL_USMARC)
823 if (octet_buf[9] == 'a')
831 else if (marcCharset)
833 if (outputCharset && from)
835 cd = yaz_iconv_open(outputCharset, from);
836 printf ("convert from %s to %s", from,
839 printf (" unsupported\n");
844 fwrite (result, 1, rlen, stdout);
848 size_t inbytesleft = rlen;
849 const char *inp = result;
853 size_t outbytesleft = sizeof(outbuf);
857 r = yaz_iconv (cd, (char**) &inp,
859 &outp, &outbytesleft);
860 if (r == (size_t) (-1))
862 int e = yaz_iconv_error(cd);
863 if (e != YAZ_ICONV_E2BIG)
866 fwrite (outbuf, outp - outbuf, 1, stdout);
872 printf ("bad MARC. Dumping as it is:\n");
873 print_record((const unsigned char*) octet_buf,
874 r->u.octet_aligned->len);
876 yaz_marc_destroy(mt);
882 print_record((const unsigned char*) octet_buf,
883 r->u.octet_aligned->len);
887 fwrite (octet_buf, 1, r->u.octet_aligned->len, marc_file);
889 else if (ent && ent->value == VAL_SUTRS)
891 if (r->which != Z_External_sutrs)
893 printf("Expecting single SUTRS type for SUTRS.\n");
896 print_record(r->u.sutrs->buf, r->u.sutrs->len);
898 else if (ent && ent->value == VAL_GRS1)
901 if (r->which != Z_External_grs1)
903 printf("Expecting single GRS type for GRS.\n");
907 yaz_display_grs1(w, r->u.grs1, 0);
911 else if ( /* OPAC display not complete yet .. */
912 ent && ent->value == VAL_OPAC)
915 if (r->u.opac->bibliographicRecord)
916 display_record(r->u.opac->bibliographicRecord);
917 for (i = 0; i<r->u.opac->num_holdingsData; i++)
919 Z_HoldingsRecord *h = r->u.opac->holdingsData[i];
920 if (h->which == Z_HoldingsRecord_marcHoldingsRecord)
922 printf ("MARC holdings %d\n", i);
923 display_record(h->u.marcHoldingsRecord);
925 else if (h->which == Z_HoldingsRecord_holdingsAndCirc)
929 Z_HoldingsAndCircData *data = h->u.holdingsAndCirc;
931 printf ("Data holdings %d\n", i);
932 if (data->typeOfRecord)
933 printf ("typeOfRecord: %s\n", data->typeOfRecord);
934 if (data->encodingLevel)
935 printf ("encodingLevel: %s\n", data->encodingLevel);
936 if (data->receiptAcqStatus)
937 printf ("receiptAcqStatus: %s\n", data->receiptAcqStatus);
938 if (data->generalRetention)
939 printf ("generalRetention: %s\n", data->generalRetention);
940 if (data->completeness)
941 printf ("completeness: %s\n", data->completeness);
942 if (data->dateOfReport)
943 printf ("dateOfReport: %s\n", data->dateOfReport);
945 printf ("nucCode: %s\n", data->nucCode);
946 if (data->localLocation)
947 printf ("localLocation: %s\n", data->localLocation);
948 if (data->shelvingLocation)
949 printf ("shelvingLocation: %s\n", data->shelvingLocation);
950 if (data->callNumber)
951 printf ("callNumber: %s\n", data->callNumber);
952 if (data->copyNumber)
953 printf ("copyNumber: %s\n", data->copyNumber);
954 if (data->publicNote)
955 printf ("publicNote: %s\n", data->publicNote);
956 if (data->reproductionNote)
957 printf ("reproductionNote: %s\n", data->reproductionNote);
958 if (data->termsUseRepro)
959 printf ("termsUseRepro: %s\n", data->termsUseRepro);
960 if (data->enumAndChron)
961 printf ("enumAndChron: %s\n", data->enumAndChron);
962 for (j = 0; j<data->num_volumes; j++)
964 printf ("volume %d\n", j);
965 if (data->volumes[j]->enumeration)
966 printf (" enumeration: %s\n",
967 data->volumes[j]->enumeration);
968 if (data->volumes[j]->chronology)
969 printf (" chronology: %s\n",
970 data->volumes[j]->chronology);
971 if (data->volumes[j]->enumAndChron)
972 printf (" enumAndChron: %s\n",
973 data->volumes[j]->enumAndChron);
975 for (j = 0; j<data->num_circulationData; j++)
977 printf ("circulation %d\n", j);
978 if (data->circulationData[j]->availableNow)
979 printf (" availableNow: %d\n",
980 *data->circulationData[j]->availableNow);
981 if (data->circulationData[j]->availablityDate)
982 printf (" availabiltyDate: %s\n",
983 data->circulationData[j]->availablityDate);
984 if (data->circulationData[j]->availableThru)
985 printf (" availableThru: %s\n",
986 data->circulationData[j]->availableThru);
987 if (data->circulationData[j]->restrictions)
988 printf (" restrictions: %s\n",
989 data->circulationData[j]->restrictions);
990 if (data->circulationData[j]->itemId)
991 printf (" itemId: %s\n",
992 data->circulationData[j]->itemId);
993 if (data->circulationData[j]->renewable)
994 printf (" renewable: %d\n",
995 *data->circulationData[j]->renewable);
996 if (data->circulationData[j]->onHold)
997 printf (" onHold: %d\n",
998 *data->circulationData[j]->onHold);
999 if (data->circulationData[j]->enumAndChron)
1000 printf (" enumAndChron: %s\n",
1001 data->circulationData[j]->enumAndChron);
1002 if (data->circulationData[j]->midspine)
1003 printf (" midspine: %s\n",
1004 data->circulationData[j]->midspine);
1005 if (data->circulationData[j]->temporaryLocation)
1006 printf (" temporaryLocation: %s\n",
1007 data->circulationData[j]->temporaryLocation);
1014 printf("Unknown record representation.\n");
1015 if (!z_External(print, &r, 0, 0))
1017 odr_perror(print, "Printing external");
1023 static void display_diagrecs(Z_DiagRec **pp, int num)
1027 Z_DefaultDiagFormat *r;
1029 printf("Diagnostic message(s) from database:\n");
1030 for (i = 0; i<num; i++)
1032 Z_DiagRec *p = pp[i];
1033 if (p->which != Z_DiagRec_defaultFormat)
1035 printf("Diagnostic record not in default format.\n");
1039 r = p->u.defaultFormat;
1040 if (!(ent = oid_getentbyoid(r->diagnosticSetId)) ||
1041 ent->oclass != CLASS_DIAGSET || ent->value != VAL_BIB1)
1042 printf("Missing or unknown diagset\n");
1043 printf(" [%d] %s", *r->condition, diagbib1_str(*r->condition));
1046 case Z_DefaultDiagFormat_v2Addinfo:
1047 printf (" -- v2 addinfo '%s'\n", r->u.v2Addinfo);
1049 case Z_DefaultDiagFormat_v3Addinfo:
1050 printf (" -- v3 addinfo '%s'\n", r->u.v3Addinfo);
1057 static void display_nameplusrecord(Z_NamePlusRecord *p)
1059 if (p->databaseName)
1060 printf("[%s]", p->databaseName);
1061 if (p->which == Z_NamePlusRecord_surrogateDiagnostic)
1062 display_diagrecs(&p->u.surrogateDiagnostic, 1);
1063 else if (p->which == Z_NamePlusRecord_databaseRecord)
1064 display_record(p->u.databaseRecord);
1067 static void display_records(Z_Records *p)
1071 if (p->which == Z_Records_NSD)
1073 Z_DiagRec dr, *dr_p = &dr;
1074 dr.which = Z_DiagRec_defaultFormat;
1075 dr.u.defaultFormat = p->u.nonSurrogateDiagnostic;
1076 display_diagrecs (&dr_p, 1);
1078 else if (p->which == Z_Records_multipleNSD)
1079 display_diagrecs (p->u.multipleNonSurDiagnostics->diagRecs,
1080 p->u.multipleNonSurDiagnostics->num_diagRecs);
1083 printf("Records: %d\n", p->u.databaseOrSurDiagnostics->num_records);
1084 for (i = 0; i < p->u.databaseOrSurDiagnostics->num_records; i++)
1085 display_nameplusrecord(p->u.databaseOrSurDiagnostics->records[i]);
1089 static int send_deleteResultSetRequest(const char *arg)
1094 Z_APDU *apdu = zget_APDU(out, Z_APDU_deleteResultSetRequest);
1095 Z_DeleteResultSetRequest *req = apdu->u.deleteResultSetRequest;
1097 req->referenceId = set_refid (out);
1099 req->num_resultSetList =
1100 sscanf (arg, "%30s %30s %30s %30s %30s %30s %30s %30s",
1101 names[0], names[1], names[2], names[3],
1102 names[4], names[5], names[6], names[7]);
1104 req->deleteFunction = (int *)
1105 odr_malloc (out, sizeof(*req->deleteFunction));
1106 if (req->num_resultSetList > 0)
1108 *req->deleteFunction = Z_DeleteRequest_list;
1109 req->resultSetList = (char **)
1110 odr_malloc (out, sizeof(*req->resultSetList)*
1111 req->num_resultSetList);
1112 for (i = 0; i<req->num_resultSetList; i++)
1113 req->resultSetList[i] = names[i];
1117 *req->deleteFunction = Z_DeleteRequest_all;
1118 req->resultSetList = 0;
1122 printf("Sent deleteResultSetRequest.\n");
1127 static int send_srw(Z_SRW_PDU *sr)
1129 const char *charset = negotiationCharset;
1130 const char *host_port = cur_host;
1133 Z_SOAP_Handler h[2] = {
1134 {"http://www.loc.gov/zing/srw/", 0, (Z_SOAP_fun) yaz_srw_codec},
1137 ODR o = odr_createmem(ODR_ENCODE);
1139 Z_SOAP *p = odr_malloc(o, sizeof(*p));
1142 path = odr_malloc(out, strlen(databaseNames[0])+2);
1144 strcpy(path+1, databaseNames[0]);
1146 gdu = z_get_HTTP_Request(out);
1147 gdu->u.HTTP_Request->path = odr_strdup(out, path);
1151 const char *cp0 = strstr(host_port, "://");
1152 const char *cp1 = 0;
1158 cp1 = strchr(cp0, '/');
1160 cp1 = cp0+strlen(cp0);
1164 char *h = odr_malloc(out, cp1 - cp0 + 1);
1165 memcpy (h, cp0, cp1 - cp0);
1167 z_HTTP_header_add(out, &gdu->u.HTTP_Request->headers,
1172 strcpy(ctype, "text/xml");
1173 if (charset && strlen(charset) < 20)
1175 strcat(ctype, "; charset=");
1176 strcat(ctype, charset);
1178 z_HTTP_header_add(out, &gdu->u.HTTP_Request->headers,
1179 "Content-Type", ctype);
1180 z_HTTP_header_add(out, &gdu->u.HTTP_Request->headers,
1181 "SOAPAction", "\"\"");
1182 p->which = Z_SOAP_generic;
1183 p->u.generic = odr_malloc(o, sizeof(*p->u.generic));
1184 p->u.generic->no = 0;
1185 p->u.generic->ns = 0;
1186 p->u.generic->p = sr;
1187 p->ns = "http://schemas.xmlsoap.org/soap/envelope/";
1189 ret = z_soap_codec_enc(o, &p,
1190 &gdu->u.HTTP_Request->content_buf,
1191 &gdu->u.HTTP_Request->content_len, h,
1194 if (z_GDU(out, &gdu, 0, 0))
1200 if (apdu_file && !z_GDU(print, &gdu, 0, 0))
1201 printf ("Failed to print outgoing APDU\n");
1202 buf_out = odr_getbuf(out, &len_out, 0);
1204 /* we don't odr_reset(out), since we may need the buffer again */
1206 do_hex_dump(buf_out, len_out);
1208 r = cs_put(conn, buf_out, len_out);
1220 static int send_SRW_searchRequest(const char *arg)
1226 assert(srw_sr_odr_out == 0);
1227 srw_sr_odr_out = odr_createmem(ODR_ENCODE);
1229 odr_reset(srw_sr_odr_out);
1233 /* save this for later .. when fetching individual records */
1234 srw_sr = sr = yaz_srw_get(srw_sr_odr_out, Z_SRW_searchRetrieve_request);
1235 sr->u.request->query_type = Z_SRW_query_type_cql;
1236 sr->u.request->query.cql = odr_strdup(srw_sr_odr_out, arg);
1238 sr = yaz_srw_get(out, Z_SRW_searchRetrieve_request);
1239 sr->u.request->query_type = Z_SRW_query_type_cql;
1240 sr->u.request->query.cql = odr_strdup(out, arg);
1242 sr->u.request->recordSchema = schema;
1243 return send_srw(sr);
1247 static int send_searchRequest(const char *arg)
1249 Z_APDU *apdu = zget_APDU(out, Z_APDU_searchRequest);
1250 Z_SearchRequest *req = apdu->u.searchRequest;
1253 struct ccl_rpn_node *rpn = NULL;
1255 char setstring[100];
1256 Z_RPNQuery *RPNquery;
1258 YAZ_PQF_Parser pqf_parser;
1260 QueryType myQueryType = queryType;
1263 if (myQueryType == QueryType_CCL2RPN)
1265 rpn = ccl_find_str(bibset, arg, &error, &pos);
1268 printf("CCL ERROR: %s\n", ccl_err_msg(error));
1271 } else if (myQueryType == QueryType_CQL2RPN) {
1272 /* ### All this code should be wrapped in a utility function */
1274 struct cql_node *node;
1275 const char *addinfo;
1276 if (cqltrans == 0) {
1277 printf("Can't use CQL: no translation file. Try set_cqlfile\n");
1280 parser = cql_parser_create();
1281 if ((error = cql_parser_string(parser, arg)) != 0) {
1282 printf("Can't parse CQL: must be a syntax error\n");
1285 node = cql_parser_result(parser);
1286 if ((error = cql_transform_buf(cqltrans, node, pqfbuf,
1287 sizeof pqfbuf)) != 0) {
1288 error = cql_transform_error(cqltrans, &addinfo);
1289 printf ("Can't convert CQL to PQF: %s (addinfo=%s)\n",
1290 cql_strerror(error), addinfo);
1294 myQueryType = QueryType_Prefix;
1297 req->referenceId = set_refid (out);
1298 if (!strcmp(arg, "@big")) /* strictly for troublemaking */
1300 static unsigned char big[2100];
1301 static Odr_oct bigo;
1303 /* send a very big referenceid to test transport stack etc. */
1304 memset(big, 'A', 2100);
1305 bigo.len = bigo.size = 2100;
1307 req->referenceId = &bigo;
1312 sprintf(setstring, "%d", ++setnumber);
1313 req->resultSetName = setstring;
1315 *req->smallSetUpperBound = smallSetUpperBound;
1316 *req->largeSetLowerBound = largeSetLowerBound;
1317 *req->mediumSetPresentNumber = mediumSetPresentNumber;
1318 if (smallSetUpperBound > 0 || (largeSetLowerBound > 1 &&
1319 mediumSetPresentNumber > 0))
1323 prefsyn.proto = protocol;
1324 prefsyn.oclass = CLASS_RECSYN;
1325 prefsyn.value = recordsyntax;
1326 req->preferredRecordSyntax =
1327 odr_oiddup(out, oid_ent_to_oid(&prefsyn, oid));
1328 req->smallSetElementSetNames =
1329 req->mediumSetElementSetNames = elementSetNames;
1331 req->num_databaseNames = num_databaseNames;
1332 req->databaseNames = databaseNames;
1334 req->query = &query;
1336 switch (myQueryType)
1338 case QueryType_Prefix:
1339 query.which = Z_Query_type_1;
1340 pqf_parser = yaz_pqf_create ();
1341 RPNquery = yaz_pqf_parse (pqf_parser, out, arg);
1344 const char *pqf_msg;
1346 int code = yaz_pqf_error (pqf_parser, &pqf_msg, &off);
1347 printf("%*s^\n", off+4, "");
1348 printf("Prefix query error: %s (code %d)\n", pqf_msg, code);
1350 yaz_pqf_destroy (pqf_parser);
1353 yaz_pqf_destroy (pqf_parser);
1354 query.u.type_1 = RPNquery;
1357 query.which = Z_Query_type_2;
1358 query.u.type_2 = &ccl_query;
1359 ccl_query.buf = (unsigned char*) arg;
1360 ccl_query.len = strlen(arg);
1362 case QueryType_CCL2RPN:
1363 query.which = Z_Query_type_1;
1364 RPNquery = ccl_rpn_query(out, rpn);
1367 printf ("Couldn't convert from CCL to RPN\n");
1370 query.u.type_1 = RPNquery;
1371 ccl_rpn_delete (rpn);
1374 query.which = Z_Query_type_104;
1375 ext = (Z_External *) odr_malloc(out, sizeof(*ext));
1376 ext->direct_reference = odr_getoidbystr(out, "1.2.840.10003.16.2");
1377 ext->indirect_reference = 0;
1378 ext->descriptor = 0;
1379 ext->which = Z_External_CQL;
1380 ext->u.cql = odr_strdup(out, arg);
1381 query.u.type_104 = ext;
1384 printf ("Unsupported query type\n");
1387 if (send_apdu(apdu))
1388 printf("Sent searchRequest.\n");
1393 /* display Query Expression as part of searchResult-1 */
1394 static void display_queryExpression (Z_QueryExpression *qe)
1398 if (qe->which == Z_QueryExpression_term)
1400 if (qe->u.term->queryTerm)
1402 Z_Term *term = qe->u.term->queryTerm;
1403 switch (term->which)
1405 case Z_Term_general:
1406 printf (" %.*s", term->u.general->len, term->u.general->buf);
1408 case Z_Term_characterString:
1409 printf (" %s", term->u.characterString);
1411 case Z_Term_numeric:
1412 printf (" %d", *term->u.numeric);
1422 /* see if we can find USR:SearchResult-1 */
1423 static void display_searchResult (Z_OtherInformation *o)
1428 for (i = 0; i < o->num_elements; i++)
1430 if (o->list[i]->which == Z_OtherInfo_externallyDefinedInfo)
1432 Z_External *ext = o->list[i]->information.externallyDefinedInfo;
1434 if (ext->which == Z_External_searchResult1)
1437 Z_SearchInfoReport *sr = ext->u.searchResult1;
1438 printf ("SearchResult-1:");
1439 for (j = 0; j < sr->num; j++)
1441 if (!sr->elements[j]->subqueryExpression)
1443 display_queryExpression (
1444 sr->elements[j]->subqueryExpression);
1445 display_queryExpression (
1446 sr->elements[j]->subqueryInterpretation);
1447 display_queryExpression (
1448 sr->elements[j]->subqueryRecommendation);
1449 if (sr->elements[j]->subqueryCount)
1450 printf ("(%d)", *sr->elements[j]->subqueryCount);
1458 static int process_searchResponse(Z_SearchResponse *res)
1460 printf ("Received SearchResponse.\n");
1461 print_refid (res->referenceId);
1462 if (*res->searchStatus)
1463 printf("Search was a success.\n");
1465 printf("Search was a bloomin' failure.\n");
1466 printf("Number of hits: %d", *res->resultCount);
1468 printf (", setno %d", setnumber);
1470 display_searchResult (res->additionalSearchInfo);
1471 printf("records returned: %d\n",
1472 *res->numberOfRecordsReturned);
1473 setno += *res->numberOfRecordsReturned;
1475 display_records(res->records);
1479 static void print_level(int iLevel)
1482 for (i = 0; i < iLevel * 4; i++)
1486 static void print_int(int iLevel, const char *pTag, int *pInt)
1490 print_level(iLevel);
1491 printf("%s: %d\n", pTag, *pInt);
1495 static void print_string(int iLevel, const char *pTag, const char *pString)
1497 if (pString != NULL)
1499 print_level(iLevel);
1500 printf("%s: %s\n", pTag, pString);
1504 static void print_oid(int iLevel, const char *pTag, Odr_oid *pOid)
1510 print_level(iLevel);
1511 printf("%s:", pTag);
1512 for (; *pInt != -1; pInt++)
1513 printf(" %d", *pInt);
1518 static void print_referenceId(int iLevel, Z_ReferenceId *referenceId)
1520 if (referenceId != NULL)
1524 print_level(iLevel);
1525 printf("Ref Id (%d, %d): ", referenceId->len, referenceId->size);
1526 for (i = 0; i < referenceId->len; i++)
1527 printf("%c", referenceId->buf[i]);
1532 static void print_string_or_numeric(int iLevel, const char *pTag, Z_StringOrNumeric *pStringNumeric)
1534 if (pStringNumeric != NULL)
1536 switch (pStringNumeric->which)
1538 case Z_StringOrNumeric_string:
1539 print_string(iLevel, pTag, pStringNumeric->u.string);
1542 case Z_StringOrNumeric_numeric:
1543 print_int(iLevel, pTag, pStringNumeric->u.numeric);
1547 print_level(iLevel);
1548 printf("%s: valid type for Z_StringOrNumeric\n", pTag);
1554 static void print_universe_report_duplicate(
1556 Z_UniverseReportDuplicate *pUniverseReportDuplicate)
1558 if (pUniverseReportDuplicate != NULL)
1560 print_level(iLevel);
1561 printf("Universe Report Duplicate: \n");
1563 print_string_or_numeric(iLevel, "Hit No",
1564 pUniverseReportDuplicate->hitno);
1568 static void print_universe_report_hits(
1570 Z_UniverseReportHits *pUniverseReportHits)
1572 if (pUniverseReportHits != NULL)
1574 print_level(iLevel);
1575 printf("Universe Report Hits: \n");
1577 print_string_or_numeric(iLevel, "Database",
1578 pUniverseReportHits->database);
1579 print_string_or_numeric(iLevel, "Hits", pUniverseReportHits->hits);
1583 static void print_universe_report(int iLevel, Z_UniverseReport *pUniverseReport)
1585 if (pUniverseReport != NULL)
1587 print_level(iLevel);
1588 printf("Universe Report: \n");
1590 print_int(iLevel, "Total Hits", pUniverseReport->totalHits);
1591 switch (pUniverseReport->which)
1593 case Z_UniverseReport_databaseHits:
1594 print_universe_report_hits(iLevel,
1595 pUniverseReport->u.databaseHits);
1598 case Z_UniverseReport_duplicate:
1599 print_universe_report_duplicate(iLevel,
1600 pUniverseReport->u.duplicate);
1604 print_level(iLevel);
1605 printf("Type: %d\n", pUniverseReport->which);
1611 static void print_external(int iLevel, Z_External *pExternal)
1613 if (pExternal != NULL)
1615 print_level(iLevel);
1616 printf("External: \n");
1618 print_oid(iLevel, "Direct Reference", pExternal->direct_reference);
1619 print_int(iLevel, "InDirect Reference", pExternal->indirect_reference);
1620 print_string(iLevel, "Descriptor", pExternal->descriptor);
1621 switch (pExternal->which)
1623 case Z_External_universeReport:
1624 print_universe_report(iLevel, pExternal->u.universeReport);
1628 print_level(iLevel);
1629 printf("Type: %d\n", pExternal->which);
1635 static int process_resourceControlRequest (Z_ResourceControlRequest *req)
1637 printf ("Received ResourceControlRequest.\n");
1638 print_referenceId(1, req->referenceId);
1639 print_int(1, "Suspended Flag", req->suspendedFlag);
1640 print_int(1, "Partial Results Available", req->partialResultsAvailable);
1641 print_int(1, "Response Required", req->responseRequired);
1642 print_int(1, "Triggered Request Flag", req->triggeredRequestFlag);
1643 print_external(1, req->resourceReport);
1647 void process_ESResponse(Z_ExtendedServicesResponse *res)
1650 switch (*res->operationStatus)
1652 case Z_ExtendedServicesResponse_done:
1655 case Z_ExtendedServicesResponse_accepted:
1656 printf ("accepted\n");
1658 case Z_ExtendedServicesResponse_failure:
1659 printf ("failure\n");
1660 display_diagrecs(res->diagnostics, res->num_diagnostics);
1663 printf ("unknown\n");
1665 if ( (*res->operationStatus != Z_ExtendedServicesResponse_failure) &&
1666 (res->num_diagnostics != 0) ) {
1667 display_diagrecs(res->diagnostics, res->num_diagnostics);
1669 print_refid (res->referenceId);
1670 if (res->taskPackage &&
1671 res->taskPackage->which == Z_External_extendedService)
1673 Z_TaskPackage *taskPackage = res->taskPackage->u.extendedService;
1674 Odr_oct *id = taskPackage->targetReference;
1675 Z_External *ext = taskPackage->taskSpecificParameters;
1679 printf ("Target Reference: ");
1680 print_stringn (id->buf, id->len);
1683 if (ext->which == Z_External_update)
1685 Z_IUUpdateTaskPackage *utp = ext->u.update->u.taskPackage;
1686 if (utp && utp->targetPart)
1688 Z_IUTargetPart *targetPart = utp->targetPart;
1691 for (i = 0; i<targetPart->num_taskPackageRecords; i++)
1694 Z_IUTaskPackageRecordStructure *tpr =
1695 targetPart->taskPackageRecords[i];
1696 printf ("task package record %d\n", i+1);
1697 if (tpr->which == Z_IUTaskPackageRecordStructure_record)
1699 display_record (tpr->u.record);
1703 printf ("other type\n");
1711 const char *get_ill_element (void *clientData, const char *element)
1716 static Z_External *create_external_itemRequest()
1718 struct ill_get_ctl ctl;
1719 ILL_ItemRequest *req;
1721 int item_request_size = 0;
1722 char *item_request_buf = 0;
1726 ctl.f = get_ill_element;
1728 req = ill_get_ItemRequest(&ctl, "ill", 0);
1730 printf ("ill_get_ItemRequest failed\n");
1732 if (!ill_ItemRequest (out, &req, 0, 0))
1736 ill_ItemRequest(print, &req, 0, 0);
1739 item_request_buf = odr_getbuf (out, &item_request_size, 0);
1740 if (item_request_buf)
1741 odr_setbuf (out, item_request_buf, item_request_size, 1);
1742 printf ("Couldn't encode ItemRequest, size %d\n", item_request_size);
1749 item_request_buf = odr_getbuf (out, &item_request_size, 0);
1750 oid.proto = PROTO_GENERAL;
1751 oid.oclass = CLASS_GENERAL;
1752 oid.value = VAL_ISO_ILL_1;
1754 r = (Z_External *) odr_malloc (out, sizeof(*r));
1755 r->direct_reference = odr_oiddup(out,oid_getoidbyent(&oid));
1756 r->indirect_reference = 0;
1758 r->which = Z_External_single;
1760 r->u.single_ASN1_type = (Odr_oct *)
1761 odr_malloc (out, sizeof(*r->u.single_ASN1_type));
1762 r->u.single_ASN1_type->buf = (unsigned char *)
1763 odr_malloc (out, item_request_size);
1764 r->u.single_ASN1_type->len = item_request_size;
1765 r->u.single_ASN1_type->size = item_request_size;
1766 memcpy (r->u.single_ASN1_type->buf, item_request_buf,
1769 do_hex_dump(item_request_buf,item_request_size);
1774 static Z_External *create_external_ILL_APDU(int which)
1776 struct ill_get_ctl ctl;
1779 int ill_request_size = 0;
1780 char *ill_request_buf = 0;
1784 ctl.f = get_ill_element;
1786 ill_apdu = ill_get_APDU(&ctl, "ill", 0);
1788 if (!ill_APDU (out, &ill_apdu, 0, 0))
1792 printf ("-------------------\n");
1793 ill_APDU(print, &ill_apdu, 0, 0);
1795 printf ("-------------------\n");
1797 ill_request_buf = odr_getbuf (out, &ill_request_size, 0);
1798 if (ill_request_buf)
1799 odr_setbuf (out, ill_request_buf, ill_request_size, 1);
1800 printf ("Couldn't encode ILL-Request, size %d\n", ill_request_size);
1806 ill_request_buf = odr_getbuf (out, &ill_request_size, 0);
1808 oid.proto = PROTO_GENERAL;
1809 oid.oclass = CLASS_GENERAL;
1810 oid.value = VAL_ISO_ILL_1;
1812 r = (Z_External *) odr_malloc (out, sizeof(*r));
1813 r->direct_reference = odr_oiddup(out,oid_getoidbyent(&oid));
1814 r->indirect_reference = 0;
1816 r->which = Z_External_single;
1818 r->u.single_ASN1_type = (Odr_oct *)
1819 odr_malloc (out, sizeof(*r->u.single_ASN1_type));
1820 r->u.single_ASN1_type->buf = (unsigned char *)
1821 odr_malloc (out, ill_request_size);
1822 r->u.single_ASN1_type->len = ill_request_size;
1823 r->u.single_ASN1_type->size = ill_request_size;
1824 memcpy (r->u.single_ASN1_type->buf, ill_request_buf, ill_request_size);
1825 /* printf ("len = %d\n", ill_request_size); */
1826 /* do_hex_dump(ill_request_buf,ill_request_size); */
1827 /* printf("--- end of extenal\n"); */
1834 static Z_External *create_ItemOrderExternal(const char *type, int itemno)
1836 Z_External *r = (Z_External *) odr_malloc(out, sizeof(Z_External));
1837 oident ItemOrderRequest;
1839 ItemOrderRequest.proto = PROTO_Z3950;
1840 ItemOrderRequest.oclass = CLASS_EXTSERV;
1841 ItemOrderRequest.value = VAL_ITEMORDER;
1843 r->direct_reference = odr_oiddup(out,oid_getoidbyent(&ItemOrderRequest));
1844 r->indirect_reference = 0;
1847 r->which = Z_External_itemOrder;
1849 r->u.itemOrder = (Z_ItemOrder *) odr_malloc(out,sizeof(Z_ItemOrder));
1850 memset(r->u.itemOrder, 0, sizeof(Z_ItemOrder));
1851 r->u.itemOrder->which=Z_IOItemOrder_esRequest;
1853 r->u.itemOrder->u.esRequest = (Z_IORequest *)
1854 odr_malloc(out,sizeof(Z_IORequest));
1855 memset(r->u.itemOrder->u.esRequest, 0, sizeof(Z_IORequest));
1857 r->u.itemOrder->u.esRequest->toKeep = (Z_IOOriginPartToKeep *)
1858 odr_malloc(out,sizeof(Z_IOOriginPartToKeep));
1859 memset(r->u.itemOrder->u.esRequest->toKeep, 0, sizeof(Z_IOOriginPartToKeep));
1860 r->u.itemOrder->u.esRequest->notToKeep = (Z_IOOriginPartNotToKeep *)
1861 odr_malloc(out,sizeof(Z_IOOriginPartNotToKeep));
1862 memset(r->u.itemOrder->u.esRequest->notToKeep, 0, sizeof(Z_IOOriginPartNotToKeep));
1864 r->u.itemOrder->u.esRequest->toKeep->supplDescription = NULL;
1865 r->u.itemOrder->u.esRequest->toKeep->contact = NULL;
1866 r->u.itemOrder->u.esRequest->toKeep->addlBilling = NULL;
1868 r->u.itemOrder->u.esRequest->notToKeep->resultSetItem =
1869 (Z_IOResultSetItem *) odr_malloc(out, sizeof(Z_IOResultSetItem));
1870 memset(r->u.itemOrder->u.esRequest->notToKeep->resultSetItem, 0, sizeof(Z_IOResultSetItem));
1871 r->u.itemOrder->u.esRequest->notToKeep->resultSetItem->resultSetId = "1";
1873 r->u.itemOrder->u.esRequest->notToKeep->resultSetItem->item =
1874 (int *) odr_malloc(out, sizeof(int));
1875 *r->u.itemOrder->u.esRequest->notToKeep->resultSetItem->item = itemno;
1877 if (!strcmp (type, "item") || !strcmp(type, "2"))
1879 printf ("using item-request\n");
1880 r->u.itemOrder->u.esRequest->notToKeep->itemRequest =
1881 create_external_itemRequest();
1883 else if (!strcmp(type, "ill") || !strcmp(type, "1"))
1885 printf ("using ILL-request\n");
1886 r->u.itemOrder->u.esRequest->notToKeep->itemRequest =
1887 create_external_ILL_APDU(ILL_APDU_ILL_Request);
1889 else if (!strcmp(type, "xml") || !strcmp(type, "3"))
1891 const char *xml_buf =
1893 " <type>request</type>\n"
1894 " <libraryNo>000200</libraryNo>\n"
1895 " <borrowerTicketNo> 1212 </borrowerTicketNo>\n"
1897 r->u.itemOrder->u.esRequest->notToKeep->itemRequest =
1898 z_ext_record (out, VAL_TEXT_XML, xml_buf, strlen(xml_buf));
1901 r->u.itemOrder->u.esRequest->notToKeep->itemRequest = 0;
1906 static int send_itemorder(const char *type, int itemno)
1908 Z_APDU *apdu = zget_APDU(out, Z_APDU_extendedServicesRequest);
1909 Z_ExtendedServicesRequest *req = apdu->u.extendedServicesRequest;
1910 oident ItemOrderRequest;
1912 ItemOrderRequest.proto = PROTO_Z3950;
1913 ItemOrderRequest.oclass = CLASS_EXTSERV;
1914 ItemOrderRequest.value = VAL_ITEMORDER;
1915 req->packageType = odr_oiddup(out,oid_getoidbyent(&ItemOrderRequest));
1916 req->packageName = esPackageName;
1918 req->taskSpecificParameters = create_ItemOrderExternal(type, itemno);
1924 static int only_z3950()
1926 if (protocol == PROTO_HTTP)
1928 printf ("Not supported by SRW\n");
1934 static int cmd_update_common(const char *arg, int version);
1936 static int cmd_update(const char *arg)
1938 return cmd_update_common(arg, 1);
1941 static int cmd_update0(const char *arg)
1943 return cmd_update_common(arg, 0);
1946 static int cmd_update_common(const char *arg, int version)
1948 Z_APDU *apdu = zget_APDU(out, Z_APDU_extendedServicesRequest );
1949 Z_ExtendedServicesRequest *req = apdu->u.extendedServicesRequest;
1953 char action[20], recid[20], fname[80];
1955 Z_External *record_this = 0;
1962 sscanf (arg, "%19s %19s %79s", action, recid, fname);
1964 if (!strcmp (action, "insert"))
1965 action_no = Z_IUOriginPartToKeep_recordInsert;
1966 else if (!strcmp (action, "replace"))
1967 action_no = Z_IUOriginPartToKeep_recordReplace;
1968 else if (!strcmp (action, "delete"))
1969 action_no = Z_IUOriginPartToKeep_recordDelete;
1970 else if (!strcmp (action, "update"))
1971 action_no = Z_IUOriginPartToKeep_specialUpdate;
1974 printf ("Bad action: %s\n", action);
1975 printf ("Possible values: insert, replace, delete, update\n");
1983 stat (fname, &status);
1984 if (S_ISREG(status.st_mode) && (inf = fopen(fname, "r")))
1986 size_t len = status.st_size;
1987 char *buf = (char *) xmalloc (len);
1989 fread (buf, 1, len, inf);
1993 record_this = z_ext_record (out, VAL_TEXT_XML, buf, len);
1999 printf ("File %s doesn't exist\n", fname);
2007 printf ("No last record (update ignored)\n");
2010 record_this = record_last;
2013 update_oid.proto = PROTO_Z3950;
2014 update_oid.oclass = CLASS_EXTSERV;
2016 update_oid.value = VAL_DBUPDATE0;
2018 update_oid.value = VAL_DBUPDATE;
2019 oid_ent_to_oid (&update_oid, oid);
2020 req->packageType = odr_oiddup(out,oid);
2021 req->packageName = esPackageName;
2023 req->referenceId = set_refid (out);
2025 r = req->taskSpecificParameters = (Z_External *)
2026 odr_malloc (out, sizeof(*r));
2027 r->direct_reference = odr_oiddup(out,oid);
2028 r->indirect_reference = 0;
2032 Z_IU0OriginPartToKeep *toKeep;
2033 Z_IU0SuppliedRecords *notToKeep;
2035 r->which = Z_External_update0;
2036 r->u.update0 = (Z_IU0Update *) odr_malloc(out, sizeof(*r->u.update0));
2037 r->u.update0->which = Z_IUUpdate_esRequest;
2038 r->u.update0->u.esRequest = (Z_IU0UpdateEsRequest *)
2039 odr_malloc(out, sizeof(*r->u.update0->u.esRequest));
2040 toKeep = r->u.update0->u.esRequest->toKeep = (Z_IU0OriginPartToKeep *)
2041 odr_malloc(out, sizeof(*r->u.update0->u.esRequest->toKeep));
2043 toKeep->databaseName = databaseNames[0];
2045 toKeep->elementSetName = 0;
2047 toKeep->action = (int *) odr_malloc(out, sizeof(*toKeep->action));
2048 *toKeep->action = action_no;
2050 notToKeep = r->u.update0->u.esRequest->notToKeep = (Z_IU0SuppliedRecords *)
2051 odr_malloc(out, sizeof(*r->u.update0->u.esRequest->notToKeep));
2053 notToKeep->elements = (Z_IU0SuppliedRecords_elem **)
2054 odr_malloc(out, sizeof(*notToKeep->elements));
2055 notToKeep->elements[0] = (Z_IU0SuppliedRecords_elem *)
2056 odr_malloc(out, sizeof(**notToKeep->elements));
2057 notToKeep->elements[0]->which = Z_IUSuppliedRecords_elem_opaque;
2060 notToKeep->elements[0]->u.opaque = (Odr_oct *)
2061 odr_malloc (out, sizeof(Odr_oct));
2062 notToKeep->elements[0]->u.opaque->buf = (unsigned char *) recid;
2063 notToKeep->elements[0]->u.opaque->size = strlen(recid);
2064 notToKeep->elements[0]->u.opaque->len = strlen(recid);
2067 notToKeep->elements[0]->u.opaque = 0;
2068 notToKeep->elements[0]->supplementalId = 0;
2069 notToKeep->elements[0]->correlationInfo = 0;
2070 notToKeep->elements[0]->record = record_this;
2074 Z_IUOriginPartToKeep *toKeep;
2075 Z_IUSuppliedRecords *notToKeep;
2077 r->which = Z_External_update;
2078 r->u.update = (Z_IUUpdate *) odr_malloc(out, sizeof(*r->u.update));
2079 r->u.update->which = Z_IUUpdate_esRequest;
2080 r->u.update->u.esRequest = (Z_IUUpdateEsRequest *)
2081 odr_malloc(out, sizeof(*r->u.update->u.esRequest));
2082 toKeep = r->u.update->u.esRequest->toKeep = (Z_IUOriginPartToKeep *)
2083 odr_malloc(out, sizeof(*r->u.update->u.esRequest->toKeep));
2085 toKeep->databaseName = databaseNames[0];
2087 toKeep->elementSetName = 0;
2088 toKeep->actionQualifier = 0;
2089 toKeep->action = (int *) odr_malloc(out, sizeof(*toKeep->action));
2090 *toKeep->action = action_no;
2092 notToKeep = r->u.update->u.esRequest->notToKeep = (Z_IUSuppliedRecords *)
2093 odr_malloc(out, sizeof(*r->u.update->u.esRequest->notToKeep));
2095 notToKeep->elements = (Z_IUSuppliedRecords_elem **)
2096 odr_malloc(out, sizeof(*notToKeep->elements));
2097 notToKeep->elements[0] = (Z_IUSuppliedRecords_elem *)
2098 odr_malloc(out, sizeof(**notToKeep->elements));
2099 notToKeep->elements[0]->which = Z_IUSuppliedRecords_elem_opaque;
2102 notToKeep->elements[0]->u.opaque = (Odr_oct *)
2103 odr_malloc (out, sizeof(Odr_oct));
2104 notToKeep->elements[0]->u.opaque->buf = (unsigned char *) recid;
2105 notToKeep->elements[0]->u.opaque->size = strlen(recid);
2106 notToKeep->elements[0]->u.opaque->len = strlen(recid);
2109 notToKeep->elements[0]->u.opaque = 0;
2110 notToKeep->elements[0]->supplementalId = 0;
2111 notToKeep->elements[0]->correlationInfo = 0;
2112 notToKeep->elements[0]->record = record_this;
2120 static int cmd_itemorder(const char *arg)
2127 if (sscanf (arg, "%10s %d", type, &itemno) != 2)
2130 printf("Item order request\n");
2132 send_itemorder(type, itemno);
2136 static int cmd_explain(const char *arg)
2138 if (protocol != PROTO_HTTP)
2149 /* save this for later .. when fetching individual records */
2150 sr = yaz_srw_get(out, Z_SRW_explain_request);
2159 static int cmd_find(const char *arg)
2163 printf("Find what?\n");
2166 if (protocol == PROTO_HTTP)
2171 if (!send_SRW_searchRequest(arg))
2184 printf("Not connected yet\n");
2188 if (!send_searchRequest(arg))
2194 static int cmd_delete(const char *arg)
2198 printf("Not connected yet\n");
2203 if (!send_deleteResultSetRequest(arg))
2208 static int cmd_ssub(const char *arg)
2210 if (!(smallSetUpperBound = atoi(arg)))
2215 static int cmd_lslb(const char *arg)
2219 if (!(largeSetLowerBound = atoi(arg)))
2224 static int cmd_mspn(const char *arg)
2228 if (!(mediumSetPresentNumber = atoi(arg)))
2233 static int cmd_status(const char *arg)
2235 printf("smallSetUpperBound: %d\n", smallSetUpperBound);
2236 printf("largeSetLowerBound: %d\n", largeSetLowerBound);
2237 printf("mediumSetPresentNumber: %d\n", mediumSetPresentNumber);
2241 static int cmd_setnames(const char *arg)
2243 if (*arg == '1') /* enable ? */
2245 else if (*arg == '0') /* disable ? */
2247 else if (setnumber < 0) /* no args, toggle .. */
2253 printf("Set numbering enabled.\n");
2255 printf("Set numbering disabled.\n");
2259 /* PRESENT SERVICE ----------------------------- */
2261 static void parse_show_args(const char *arg_c, char *setstring,
2262 int *start, int *number)
2267 strncpy(arg, arg_c, sizeof(arg)-1);
2268 arg[sizeof(arg)-1] = '\0';
2270 if ((p = strchr(arg, '+')))
2272 *number = atoi(p + 1);
2277 if (p && (p=strchr(p+1, '+')))
2278 strcpy (setstring, p+1);
2279 else if (setnumber >= 0)
2280 sprintf(setstring, "%d", setnumber);
2285 static int send_presentRequest(const char *arg)
2287 Z_APDU *apdu = zget_APDU(out, Z_APDU_presentRequest);
2288 Z_PresentRequest *req = apdu->u.presentRequest;
2289 Z_RecordComposition compo;
2293 char setstring[100];
2295 req->referenceId = set_refid (out);
2297 parse_show_args(arg, setstring, &setno, &nos);
2299 req->resultSetId = setstring;
2301 req->resultSetStartPoint = &setno;
2302 req->numberOfRecordsRequested = &nos;
2303 prefsyn.proto = protocol;
2304 prefsyn.oclass = CLASS_RECSYN;
2305 prefsyn.value = recordsyntax;
2306 req->preferredRecordSyntax =
2307 odr_oiddup (out, oid_ent_to_oid(&prefsyn, oid));
2313 prefschema.proto = protocol;
2314 prefschema.oclass = CLASS_SCHEMA;
2315 prefschema.value = oid_getvalbyname(schema);
2317 req->recordComposition = &compo;
2318 compo.which = Z_RecordComp_complex;
2319 compo.u.complex = (Z_CompSpec *)
2320 odr_malloc(out, sizeof(*compo.u.complex));
2321 compo.u.complex->selectAlternativeSyntax = (bool_t *)
2322 odr_malloc(out, sizeof(bool_t));
2323 *compo.u.complex->selectAlternativeSyntax = 0;
2325 compo.u.complex->generic = (Z_Specification *)
2326 odr_malloc(out, sizeof(*compo.u.complex->generic));
2327 compo.u.complex->generic->which = Z_Schema_oid;
2328 compo.u.complex->generic->schema.oid = (Odr_oid *)
2329 odr_oiddup(out, oid_ent_to_oid(&prefschema, oid));
2330 if (!compo.u.complex->generic->schema.oid)
2332 /* OID wasn't a schema! Try record syntax instead. */
2333 prefschema.oclass = CLASS_RECSYN;
2334 compo.u.complex->generic->schema.oid = (Odr_oid *)
2335 odr_oiddup(out, oid_ent_to_oid(&prefschema, oid));
2337 if (!elementSetNames)
2338 compo.u.complex->generic->elementSpec = 0;
2341 compo.u.complex->generic->elementSpec = (Z_ElementSpec *)
2342 odr_malloc(out, sizeof(Z_ElementSpec));
2343 compo.u.complex->generic->elementSpec->which =
2344 Z_ElementSpec_elementSetName;
2345 compo.u.complex->generic->elementSpec->u.elementSetName =
2346 elementSetNames->u.generic;
2348 compo.u.complex->num_dbSpecific = 0;
2349 compo.u.complex->dbSpecific = 0;
2350 compo.u.complex->num_recordSyntax = 0;
2351 compo.u.complex->recordSyntax = 0;
2353 else if (elementSetNames)
2355 req->recordComposition = &compo;
2356 compo.which = Z_RecordComp_simple;
2357 compo.u.simple = elementSetNames;
2360 printf("Sent presentRequest (%d+%d).\n", setno, nos);
2365 static int send_SRW_presentRequest(const char *arg)
2367 char setstring[100];
2369 Z_SRW_PDU *sr = srw_sr;
2373 parse_show_args(arg, setstring, &setno, &nos);
2374 sr->u.request->startRecord = odr_intdup(out, setno);
2375 sr->u.request->maximumRecords = odr_intdup(out, nos);
2377 sr->u.request->recordSchema = schema;
2378 return send_srw(sr);
2382 static void close_session (void)
2389 nmem_destroy (session_mem);
2398 void process_close(Z_Close *req)
2400 Z_APDU *apdu = zget_APDU(out, Z_APDU_close);
2401 Z_Close *res = apdu->u.close;
2403 static char *reasons[] =
2408 "cost limit reached",
2410 "security violation",
2417 printf("Reason: %s, message: %s\n", reasons[*req->closeReason],
2418 req->diagnosticInformation ? req->diagnosticInformation : "NULL");
2423 *res->closeReason = Z_Close_finished;
2425 printf("Sent response.\n");
2430 static int cmd_show(const char *arg)
2432 if (protocol == PROTO_HTTP)
2437 if (!send_SRW_presentRequest(arg))
2447 printf("Not connected yet\n");
2450 if (!send_presentRequest(arg))
2456 int cmd_quit(const char *arg)
2458 printf("See you later, alligator.\n");
2464 int cmd_cancel(const char *arg)
2466 Z_APDU *apdu = zget_APDU(out, Z_APDU_triggerResourceControlRequest);
2467 Z_TriggerResourceControlRequest *req =
2468 apdu->u.triggerResourceControlRequest;
2473 printf("Session not initialized yet\n");
2478 if (!ODR_MASK_GET(session->options, Z_Options_triggerResourceCtrl))
2480 printf("Target doesn't support cancel (trigger resource ctrl)\n");
2483 *req->requestedAction = Z_TriggerResourceCtrl_cancel;
2484 req->resultSetWanted = &rfalse;
2487 printf("Sent cancel request\n");
2491 int send_scanrequest(const char *query, int pp, int num, const char *term)
2493 Z_APDU *apdu = zget_APDU(out, Z_APDU_scanRequest);
2494 Z_ScanRequest *req = apdu->u.scanRequest;
2499 if (queryType == QueryType_CCL2RPN)
2503 struct ccl_rpn_node *rpn;
2505 rpn = ccl_find_str (bibset, query, &error, &pos);
2508 printf("CCL ERROR: %s\n", ccl_err_msg(error));
2511 bib1.proto = PROTO_Z3950;
2512 bib1.oclass = CLASS_ATTSET;
2513 bib1.value = VAL_BIB1;
2514 req->attributeSet = oid_ent_to_oid (&bib1, oid);
2515 if (!(req->termListAndStartPoint = ccl_scan_query (out, rpn)))
2517 printf("Couldn't convert CCL to Scan term\n");
2520 ccl_rpn_delete (rpn);
2524 YAZ_PQF_Parser pqf_parser = yaz_pqf_create ();
2526 if (!(req->termListAndStartPoint =
2527 yaz_pqf_scan(pqf_parser, out, &req->attributeSet, query)))
2529 const char *pqf_msg;
2531 int code = yaz_pqf_error (pqf_parser, &pqf_msg, &off);
2532 printf("%*s^\n", off+7, "");
2533 printf("Prefix query error: %s (code %d)\n", pqf_msg, code);
2534 yaz_pqf_destroy (pqf_parser);
2537 yaz_pqf_destroy (pqf_parser);
2541 if (req->termListAndStartPoint->term &&
2542 req->termListAndStartPoint->term->which == Z_Term_general &&
2543 req->termListAndStartPoint->term->u.general)
2545 req->termListAndStartPoint->term->u.general->buf =
2546 (unsigned char *) odr_strdup(out, term);
2547 req->termListAndStartPoint->term->u.general->len =
2548 req->termListAndStartPoint->term->u.general->size =
2552 req->referenceId = set_refid (out);
2553 req->num_databaseNames = num_databaseNames;
2554 req->databaseNames = databaseNames;
2555 req->numberOfTermsRequested = #
2556 req->preferredPositionInResponse = &pp;
2561 int send_sortrequest(const char *arg, int newset)
2563 Z_APDU *apdu = zget_APDU(out, Z_APDU_sortRequest);
2564 Z_SortRequest *req = apdu->u.sortRequest;
2565 Z_SortKeySpecList *sksl = (Z_SortKeySpecList *)
2566 odr_malloc (out, sizeof(*sksl));
2572 sprintf (setstring, "%d", setnumber);
2574 sprintf (setstring, "default");
2576 req->referenceId = set_refid (out);
2578 req->num_inputResultSetNames = 1;
2579 req->inputResultSetNames = (Z_InternationalString **)
2580 odr_malloc (out, sizeof(*req->inputResultSetNames));
2581 req->inputResultSetNames[0] = odr_strdup (out, setstring);
2583 if (newset && setnumber >= 0)
2584 sprintf (setstring, "%d", ++setnumber);
2586 req->sortedResultSetName = odr_strdup (out, setstring);
2588 req->sortSequence = yaz_sort_spec (out, arg);
2589 if (!req->sortSequence)
2591 printf ("Missing sort specifications\n");
2598 void display_term(Z_TermInfo *t)
2601 printf("%s", t->displayTerm);
2602 else if (t->term->which == Z_Term_general)
2604 printf("%.*s", t->term->u.general->len, t->term->u.general->buf);
2605 sprintf(last_scan_line, "%.*s", t->term->u.general->len,
2606 t->term->u.general->buf);
2609 printf("Term (not general)");
2610 if (t->globalOccurrences)
2611 printf (" (%d)\n", *t->globalOccurrences);
2616 void process_scanResponse(Z_ScanResponse *res)
2619 Z_Entry **entries = NULL;
2620 int num_entries = 0;
2622 printf("Received ScanResponse\n");
2623 print_refid (res->referenceId);
2624 printf("%d entries", *res->numberOfEntriesReturned);
2625 if (res->positionOfTerm)
2626 printf (", position=%d", *res->positionOfTerm);
2628 if (*res->scanStatus != Z_Scan_success)
2629 printf("Scan returned code %d\n", *res->scanStatus);
2632 if ((entries = res->entries->entries))
2633 num_entries = res->entries->num_entries;
2634 for (i = 0; i < num_entries; i++)
2636 int pos_term = res->positionOfTerm ? *res->positionOfTerm : -1;
2637 if (entries[i]->which == Z_Entry_termInfo)
2639 printf("%c ", i + 1 == pos_term ? '*' : ' ');
2640 display_term(entries[i]->u.termInfo);
2643 display_diagrecs(&entries[i]->u.surrogateDiagnostic, 1);
2645 if (res->entries->nonsurrogateDiagnostics)
2646 display_diagrecs (res->entries->nonsurrogateDiagnostics,
2647 res->entries->num_nonsurrogateDiagnostics);
2650 void process_sortResponse(Z_SortResponse *res)
2652 printf("Received SortResponse: status=");
2653 switch (*res->sortStatus)
2655 case Z_SortStatus_success:
2656 printf ("success"); break;
2657 case Z_SortStatus_partial_1:
2658 printf ("partial"); break;
2659 case Z_SortStatus_failure:
2660 printf ("failure"); break;
2662 printf ("unknown (%d)", *res->sortStatus);
2665 print_refid (res->referenceId);
2666 if (res->diagnostics)
2667 display_diagrecs(res->diagnostics,
2668 res->num_diagnostics);
2671 void process_deleteResultSetResponse (Z_DeleteResultSetResponse *res)
2673 printf("Got deleteResultSetResponse status=%d\n",
2674 *res->deleteOperationStatus);
2675 if (res->deleteListStatuses)
2678 for (i = 0; i < res->deleteListStatuses->num; i++)
2680 printf ("%s status=%d\n", res->deleteListStatuses->elements[i]->id,
2681 *res->deleteListStatuses->elements[i]->status);
2686 int cmd_sort_generic(const char *arg, int newset)
2690 printf("Session not initialized yet\n");
2695 if (!ODR_MASK_GET(session->options, Z_Options_sort))
2697 printf("Target doesn't support sort\n");
2702 if (send_sortrequest(arg, newset) < 0)
2709 int cmd_sort(const char *arg)
2711 return cmd_sort_generic (arg, 0);
2714 int cmd_sort_newset (const char *arg)
2716 return cmd_sort_generic (arg, 1);
2719 int cmd_scan(const char *arg)
2728 printf("Session not initialized yet\n");
2732 if (!ODR_MASK_GET(session->options, Z_Options_scan))
2734 printf("Target doesn't support scan\n");
2739 strcpy (last_scan_query, arg);
2740 if (send_scanrequest(arg, 1, 20, 0) < 0)
2745 if (send_scanrequest(last_scan_query, 1, 20, last_scan_line) < 0)
2751 int cmd_schema(const char *arg)
2756 schema = xstrdup(arg);
2760 int cmd_format(const char *arg)
2765 printf("Usage: format <recordsyntax>\n");
2768 nsyntax = oid_getvalbyname (arg);
2769 if (strcmp(arg, "none") && nsyntax == VAL_NONE)
2771 printf ("unknown record syntax\n");
2774 recordsyntax = nsyntax;
2778 int cmd_elements(const char *arg)
2780 static Z_ElementSetNames esn;
2781 static char what[100];
2785 elementSetNames = 0;
2789 esn.which = Z_ElementSetNames_generic;
2790 esn.u.generic = what;
2791 elementSetNames = &esn;
2795 int cmd_attributeset(const char *arg)
2801 printf("Usage: attributeset <setname>\n");
2804 sscanf(arg, "%s", what);
2805 if (p_query_attset (what))
2807 printf("Unknown attribute set name\n");
2813 int cmd_querytype (const char *arg)
2815 if (!strcmp (arg, "ccl"))
2816 queryType = QueryType_CCL;
2817 else if (!strcmp (arg, "prefix") || !strcmp(arg, "rpn"))
2818 queryType = QueryType_Prefix;
2819 else if (!strcmp (arg, "ccl2rpn") || !strcmp (arg, "cclrpn"))
2820 queryType = QueryType_CCL2RPN;
2821 else if (!strcmp(arg, "cql"))
2822 queryType = QueryType_CQL;
2823 else if (!strcmp (arg, "cql2rpn") || !strcmp (arg, "cqlrpn"))
2824 queryType = QueryType_CQL2RPN;
2827 printf ("Querytype must be one of:\n");
2828 printf (" prefix - Prefix query\n");
2829 printf (" ccl - CCL query\n");
2830 printf (" ccl2rpn - CCL query converted to RPN\n");
2831 printf (" cql - CQL\n");
2832 printf (" cql2rpn - CQL query converted to RPN\n");
2838 int cmd_refid (const char *arg)
2844 refid = (char *) xmalloc (strlen(arg)+1);
2845 strcpy (refid, arg);
2850 int cmd_close(const char *arg)
2859 apdu = zget_APDU(out, Z_APDU_close);
2860 req = apdu->u.close;
2861 *req->closeReason = Z_Close_finished;
2863 printf("Sent close request.\n");
2868 int cmd_packagename(const char* arg)
2870 xfree (esPackageName);
2871 esPackageName = NULL;
2873 esPackageName = xstrdup(arg);
2877 int cmd_proxy(const char* arg)
2882 yazProxy = xstrdup (arg);
2886 int cmd_marccharset(const char *arg)
2891 if (sscanf(arg, "%29s", l1) < 1)
2893 xfree (marcCharset);
2895 if (strcmp(l1, "-"))
2896 marcCharset = xstrdup(l1);
2900 int cmd_charset(const char* arg)
2902 char l1[30], l2[30];
2905 if (sscanf(arg, "%29s %29s", l1, l2) < 1)
2907 printf("Current negotiation character set is `%s'\n",
2908 negotiationCharset ? negotiationCharset: "none");
2909 printf("Current output character set is `%s'\n",
2910 outputCharset ? outputCharset: "none");
2913 xfree (negotiationCharset);
2914 negotiationCharset = NULL;
2915 if (*l1 && strcmp(l1, "-"))
2917 negotiationCharset = xstrdup(l1);
2918 printf ("Character set negotiation : %s\n", negotiationCharset);
2921 printf ("Character set negotiation disabled\n");
2924 xfree (outputCharset);
2926 if (!strcmp(l2, "auto") && codeset)
2930 printf ("output charset: %s\n", codeset);
2931 outputCharset = xstrdup(codeset);
2936 printf ("No codeset found on this system\n");
2938 else if (strcmp(l2, "-"))
2939 outputCharset = xstrdup(l2);
2941 printf ("Output charset conversion disabled\n");
2947 int cmd_lang(const char* arg)
2950 printf("Current language is `%s'\n", (yazLang)?yazLang:NULL);
2957 yazLang = (char *) xmalloc (strlen(arg)+1);
2958 strcpy (yazLang, arg);
2963 int cmd_source(const char* arg)
2965 /* first should open the file and read one line at a time.. */
2967 char line[1024], *cp;
2970 fprintf(stderr,"Error in source command use a filename\n");
2974 includeFile = fopen (arg, "r");
2977 fprintf(stderr,"Unable to open file %s for reading\n",arg);
2981 while(!feof(includeFile)) {
2982 memset(line,0,sizeof(line));
2983 fgets(line,sizeof(line),includeFile);
2985 if(strlen(line) < 2) continue;
2986 if(line[0] == '#') continue;
2988 if ((cp = strrchr (line, '\n')))
2991 process_cmd_line(line);
2994 if(fclose(includeFile)<0) {
2995 perror("unable to close include file");
3001 int cmd_subshell(const char* args)
3006 system(getenv("SHELL"));
3012 int cmd_set_berfile(const char *arg)
3014 if (ber_file && ber_file != stdout && ber_file != stderr)
3016 if (!strcmp(arg, ""))
3018 else if (!strcmp(arg, "-"))
3021 ber_file = fopen(arg, "a");
3025 int cmd_set_apdufile(const char *arg)
3027 if(apdu_file && apdu_file != stderr && apdu_file != stderr)
3029 if (!strcmp(arg, ""))
3031 else if (!strcmp(arg, "-"))
3035 apdu_file = fopen(arg, "a");
3037 perror("unable to open apdu log file");
3040 odr_setprint(print, apdu_file);
3044 int cmd_set_cclfile(const char* arg)
3048 bibset = ccl_qual_mk ();
3049 inf = fopen (arg, "r");
3051 perror("unable to open CCL file");
3054 ccl_qual_file (bibset, inf);
3057 strcpy(ccl_fields,arg);
3061 int cmd_set_cqlfile(const char* arg)
3063 cql_transform_t newcqltrans;
3065 if ((newcqltrans = cql_transform_open_fname(arg)) == 0) {
3066 perror("unable to open CQL file");
3070 cql_transform_close(cqltrans);
3072 cqltrans = newcqltrans;
3073 strcpy(cql_fields, arg);
3077 int cmd_set_auto_reconnect(const char* arg)
3079 if(strlen(arg)==0) {
3080 auto_reconnect = ! auto_reconnect;
3081 } else if(strcmp(arg,"on")==0) {
3083 } else if(strcmp(arg,"off")==0) {
3086 printf("Error use on or off\n");
3091 printf("Set auto reconnect enabled.\n");
3093 printf("Set auto reconnect disabled.\n");
3098 int cmd_set_marcdump(const char* arg)
3100 if(marc_file && marc_file != stderr) { /* don't close stdout*/
3104 if (!strcmp(arg, ""))
3106 else if (!strcmp(arg, "-"))
3110 marc_file = fopen(arg, "a");
3112 perror("unable to open marc log file");
3118 this command takes 3 arge {name class oid}
3120 int cmd_register_oid(const char* args) {
3125 {"appctx",CLASS_APPCTX},
3126 {"absyn",CLASS_ABSYN},
3127 {"attset",CLASS_ATTSET},
3128 {"transyn",CLASS_TRANSYN},
3129 {"diagset",CLASS_DIAGSET},
3130 {"recsyn",CLASS_RECSYN},
3131 {"resform",CLASS_RESFORM},
3132 {"accform",CLASS_ACCFORM},
3133 {"extserv",CLASS_EXTSERV},
3134 {"userinfo",CLASS_USERINFO},
3135 {"elemspec",CLASS_ELEMSPEC},
3136 {"varset",CLASS_VARSET},
3137 {"schema",CLASS_SCHEMA},
3138 {"tagset",CLASS_TAGSET},
3139 {"general",CLASS_GENERAL},
3140 {0,(enum oid_class) 0}
3142 char oname_str[101], oclass_str[101], oid_str[101];
3145 oid_class oidclass = CLASS_GENERAL;
3146 int val = 0, oid[OID_SIZE];
3147 struct oident * new_oident=NULL;
3149 if (sscanf (args, "%100[^ ] %100[^ ] %100s",
3150 oname_str,oclass_str, oid_str) < 1) {
3151 printf("Error in regristrate command \n");
3155 for (i = 0; oid_classes[i].className; i++) {
3156 if (!strcmp(oid_classes[i].className, oclass_str))
3158 oidclass=oid_classes[i].oclass;
3163 if(!(oid_classes[i].className)) {
3164 printf("Unknonwn oid class %s\n",oclass_str);
3172 while (isdigit (*name))
3174 val = val*10 + (*name - '0');
3187 new_oident=oid_addent (oid,PROTO_GENERAL,oidclass,oname_str,VAL_DYNAMIC);
3188 if(strcmp(new_oident->desc,oname_str)) {
3189 fprintf(stderr,"oid is already named as %s, regristration faild\n",
3195 int cmd_push_command(const char* arg)
3197 #if HAVE_READLINE_HISTORY_H
3201 fprintf(stderr,"Not compiled with the readline/history module\n");
3206 void source_rcfile()
3208 /* Look for a $HOME/.yazclientrc and source it if it exists */
3209 struct stat statbuf;
3211 char* homedir=getenv("HOME");
3213 if(!homedir) return;
3215 sprintf(buffer,"%s/.yazclientrc",homedir);
3217 if(stat(buffer,&statbuf)==0) {
3221 if(stat(".yazclientrc",&statbuf)==0) {
3222 cmd_source(".yazclientrc");
3227 static void initialize(void)
3232 if (!(out = odr_createmem(ODR_ENCODE)) ||
3233 !(in = odr_createmem(ODR_DECODE)) ||
3234 !(print = odr_createmem(ODR_PRINT)))
3236 fprintf(stderr, "failed to allocate ODR streams\n");
3241 setvbuf(stdout, 0, _IONBF, 0);
3243 odr_setprint(print, apdu_file);
3245 bibset = ccl_qual_mk ();
3246 inf = fopen (ccl_fields, "r");
3249 ccl_qual_file (bibset, inf);
3253 cqltrans = cql_transform_open_fname(cql_fields);
3254 /* If this fails, no problem: we detect cqltrans == 0 later */
3256 #if HAVE_READLINE_READLINE_H
3257 rl_attempted_completion_function = (CPPFunction*)readline_completer;
3261 for(i=0; i<maxOtherInfosSupported; ++i) {
3262 extraOtherInfos[i].oidval = -1;
3269 #if HAVE_GETTIMEOFDAY
3270 struct timeval tv_start, tv_end;
3274 static void handle_srw_record(Z_SRW_record *rec)
3276 if (rec->recordPosition)
3278 printf ("pos=%d", *rec->recordPosition);
3279 setno = *rec->recordPosition + 1;
3281 if (rec->recordSchema)
3282 printf (" schema=%s", rec->recordSchema);
3284 if (rec->recordData_buf && rec->recordData_len)
3286 fwrite(rec->recordData_buf, 1, rec->recordData_len, stdout);
3291 static void handle_srw_explain_response(Z_SRW_explainResponse *res)
3293 handle_srw_record(&res->record);
3296 static void handle_srw_response(Z_SRW_searchRetrieveResponse *res)
3300 printf ("Received SRW SearchRetrieve Response\n");
3302 for (i = 0; i<res->num_diagnostics; i++)
3304 printf ("SRW diagnostic %d %s\n",
3305 *res->diagnostics[i].code,
3306 yaz_diag_srw_str(*res->diagnostics[i].code));
3308 if (res->diagnostics[i].details)
3309 printf ("Details: %s\n", res->diagnostics[i].details);
3311 if (res->numberOfRecords)
3312 printf ("Number of hits: %d\n", *res->numberOfRecords);
3313 for (i = 0; i<res->num_records; i++)
3314 handle_srw_record(res->records + i);
3317 static void http_response(Z_HTTP_Response *hres)
3320 const char *content_type = z_HTTP_header_lookup(hres->headers,
3322 const char *connection_head = z_HTTP_header_lookup(hres->headers,
3324 if (content_type && !yaz_strcmp_del("text/xml", content_type, "; "))
3326 Z_SOAP *soap_package = 0;
3327 ODR o = odr_createmem(ODR_DECODE);
3328 Z_SOAP_Handler soap_handlers[2] = {
3329 {"http://www.loc.gov/zing/srw/", 0,
3330 (Z_SOAP_fun) yaz_srw_codec},
3333 ret = z_soap_codec(o, &soap_package,
3334 &hres->content_buf, &hres->content_len,
3336 if (!ret && soap_package->which == Z_SOAP_generic &&
3337 soap_package->u.generic->no == 0)
3339 Z_SRW_PDU *sr = soap_package->u.generic->p;
3340 if (sr->which == Z_SRW_searchRetrieve_response)
3341 handle_srw_response(sr->u.response);
3342 else if (sr->which == Z_SRW_explain_response)
3343 handle_srw_explain_response(sr->u.explain_response);
3347 else if (soap_package && (soap_package->which == Z_SOAP_fault
3348 || soap_package->which == Z_SOAP_error))
3350 printf ("HTTP Error Status=%d\n", hres->code);
3351 printf ("SOAP Fault code %s\n",
3352 soap_package->u.fault->fault_code);
3353 printf ("SOAP Fault string %s\n",
3354 soap_package->u.fault->fault_string);
3355 if (soap_package->u.fault->details)
3356 printf ("SOAP Details %s\n",
3357 soap_package->u.fault->details);
3365 if (hres->code != 200)
3367 printf ("HTTP Error Status=%d\n", hres->code);
3371 printf ("Decoding of SRW package failed\n");
3377 if (!strcmp(hres->version, "1.0"))
3379 /* HTTP 1.0: only if Keep-Alive we stay alive.. */
3380 if (!connection_head || strcmp(connection_head, "Keep-Alive"))
3385 /* HTTP 1.1: only if no close we stay alive .. */
3386 if (connection_head && !strcmp(connection_head, "close"))
3393 void wait_and_handle_response()
3395 int reconnect_ok = 1;
3398 int netbufferlen = 0;
3403 res = cs_get(conn, &netbuffer, &netbufferlen);
3404 if (reconnect_ok && res <= 0 && protocol == PROTO_HTTP)
3415 buf_out = odr_getbuf(out, &len_out, 0);
3417 do_hex_dump(buf_out, len_out);
3419 cs_put(conn, buf_out, len_out);
3427 printf("Target closed connection\n");
3432 odr_reset(in); /* release APDU from last round */
3434 do_hex_dump(netbuffer, res);
3435 odr_setbuf(in, netbuffer, res, 0);
3437 if (!z_GDU(in, &gdu, 0, 0))
3439 FILE *f = ber_file ? ber_file : stdout;
3440 odr_perror(in, "Decoding incoming APDU");
3441 fprintf(f, "[Near %d]\n", odr_offset(in));
3442 fprintf(f, "Packet dump:\n---------\n");
3443 odr_dumpBER(f, netbuffer, res);
3444 fprintf(f, "---------\n");
3446 z_GDU(print, &gdu, 0, 0);
3447 if (conn && cs_more(conn))
3452 odr_dumpBER(ber_file, netbuffer, res);
3453 if (apdu_file && !z_GDU(print, &gdu, 0, 0))
3455 odr_perror(print, "Failed to print incoming APDU");
3459 if (gdu->which == Z_GDU_Z3950)
3461 Z_APDU *apdu = gdu->u.z3950;
3464 case Z_APDU_initResponse:
3465 process_initResponse(apdu->u.initResponse);
3467 case Z_APDU_searchResponse:
3468 process_searchResponse(apdu->u.searchResponse);
3470 case Z_APDU_scanResponse:
3471 process_scanResponse(apdu->u.scanResponse);
3473 case Z_APDU_presentResponse:
3474 print_refid (apdu->u.presentResponse->referenceId);
3476 *apdu->u.presentResponse->numberOfRecordsReturned;
3477 if (apdu->u.presentResponse->records)
3478 display_records(apdu->u.presentResponse->records);
3480 printf("No records.\n");
3481 printf ("nextResultSetPosition = %d\n",
3482 *apdu->u.presentResponse->nextResultSetPosition);
3484 case Z_APDU_sortResponse:
3485 process_sortResponse(apdu->u.sortResponse);
3487 case Z_APDU_extendedServicesResponse:
3488 printf("Got extended services response\n");
3489 process_ESResponse(apdu->u.extendedServicesResponse);
3492 printf("Target has closed the association.\n");
3493 process_close(apdu->u.close);
3495 case Z_APDU_resourceControlRequest:
3496 process_resourceControlRequest
3497 (apdu->u.resourceControlRequest);
3499 case Z_APDU_deleteResultSetResponse:
3500 process_deleteResultSetResponse(apdu->u.
3501 deleteResultSetResponse);
3504 printf("Received unknown APDU type (%d).\n",
3510 else if (gdu->which == Z_GDU_HTTP_Response)
3512 http_response(gdu->u.HTTP_Response);
3515 if (conn && !cs_more(conn))
3520 #if HAVE_GETTIMEOFDAY
3521 gettimeofday (&tv_end, 0);
3523 printf ("S/U S/U=%ld/%ld %ld/%ld",
3524 (long) tv_start.tv_sec,
3525 (long) tv_start.tv_usec,
3526 (long) tv_end.tv_sec,
3527 (long) tv_end.tv_usec);
3529 printf ("Elapsed: %.6f\n",
3530 (double) tv_end.tv_usec / 1e6 + tv_end.tv_sec -
3531 ((double) tv_start.tv_usec / 1e6 + tv_start.tv_sec));
3538 int cmd_cclparse(const char* arg)
3541 struct ccl_rpn_node *rpn=NULL;
3544 rpn = ccl_find_str (bibset, arg, &error, &pos);
3547 printf ("%*s^ - ", 3+strlen(last_cmd)+1+pos, " ");
3548 printf ("%s\n", ccl_err_msg (error));
3554 ccl_pr_tree(rpn, stdout);
3558 ccl_rpn_delete(rpn);
3566 int cmd_set_otherinfo(const char* args)
3568 char oid[101], otherinfoString[101];
3573 sscan_res = sscanf (args, "%d %100[^ ] %100s", &otherinfoNo, oid, otherinfoString);
3575 /* reset this otherinfo */
3576 if(otherinfoNo>=maxOtherInfosSupported) {
3577 printf("Error otherinfo index to large (%d>%d)\n",otherinfoNo,maxOtherInfosSupported);
3579 extraOtherInfos[otherinfoNo].oidval = -1;
3580 if(extraOtherInfos[otherinfoNo].value) free(extraOtherInfos[otherinfoNo].value);
3584 printf("Error in set_otherinfo command \n");
3588 if(otherinfoNo>=maxOtherInfosSupported) {
3589 printf("Error otherinfo index to large (%d>%d)\n",otherinfoNo,maxOtherInfosSupported);
3592 oidval = oid_getvalbyname (oid);
3594 printf("Error in set_otherinfo command unknown oid %s \n",oid);
3597 extraOtherInfos[otherinfoNo].oidval = oidval;
3598 if(extraOtherInfos[otherinfoNo].value) free(extraOtherInfos[otherinfoNo].value);
3599 extraOtherInfos[otherinfoNo].value = strdup(otherinfoString);
3604 int cmd_list_otherinfo(const char* args)
3608 if(strlen(args)>0) {
3610 if( i >= maxOtherInfosSupported ) {
3611 printf("Error otherinfo index to large (%d>%d)\n",i,maxOtherInfosSupported);
3615 if(extraOtherInfos[i].oidval != -1)
3616 printf(" otherinfo %d %s %s\n",
3618 yaz_z3950_oid_value_to_str(
3619 (enum oid_value) extraOtherInfos[i].oidval,
3621 extraOtherInfos[i].value);
3624 for(i=0; i<maxOtherInfosSupported; ++i) {
3625 if(extraOtherInfos[i].oidval != -1)
3626 printf(" otherinfo %d %s %s\n",
3628 yaz_z3950_oid_value_to_str(
3629 (enum oid_value) extraOtherInfos[i].oidval,
3631 extraOtherInfos[i].value);
3639 int cmd_list_all(const char* args) {
3642 /* connection options */
3644 printf("Connected to : %s\n",last_open_command);
3646 if(last_open_command)
3647 printf("Not connected to : %s\n",last_open_command);
3649 printf("Not connected : \n");
3652 if(yazProxy) printf("using proxy : %s\n",yazProxy);
3654 printf("auto_reconnect : %s\n",auto_reconnect?"on":"off");
3657 printf("Authentication : none\n");
3659 switch(auth->which) {
3660 case Z_IdAuthentication_idPass:
3661 printf("Authentication : IdPass\n");
3662 printf(" Login User : %s\n",auth->u.idPass->userId?auth->u.idPass->userId:"");
3663 printf(" Login Group : %s\n",auth->u.idPass->groupId?auth->u.idPass->groupId:"");
3664 printf(" Password : %s\n",auth->u.idPass->password?auth->u.idPass->password:"");
3666 case Z_IdAuthentication_open:
3667 printf("Authentication : psOpen\n");
3668 printf(" Open string : %s\n",auth->u.open);
3671 printf("Authentication : Unknown\n");
3674 if (negotiationCharset)
3675 printf("Neg. Character set : `%s'\n", negotiationCharset);
3679 for (i = 0; i<num_databaseNames; i++) printf("%s ",databaseNames[i]);
3683 printf("CCL file : %s\n",ccl_fields);
3684 printf("CQL file : %s\n",cql_fields);
3685 printf("Query type : %s\n",query_type_as_string(queryType));
3687 printf("Named Result Sets : %s\n",setnumber==-1?"off":"on");
3689 /* piggy back options */
3690 printf("ssub/lslb/mspn : %d/%d/%d\n",smallSetUpperBound,largeSetLowerBound,mediumSetPresentNumber);
3692 /* print present related options */
3693 printf("Format : %s\n",yaz_z3950_oid_value_to_str(recordsyntax,CLASS_RECSYN));
3694 printf("Schema : %s\n",schema);
3695 printf("Elements : %s\n",elementSetNames?elementSetNames->u.generic:"");
3697 /* loging options */
3698 printf("APDU log : %s\n",apdu_file?"on":"off");
3699 printf("Record log : %s\n",marc_file?"on":"off");
3702 printf("Other Info: \n");
3703 cmd_list_otherinfo("");
3708 int cmd_clear_otherinfo(const char* args)
3710 if(strlen(args)>0) {
3712 otherinfoNo = atoi(args);
3713 if( otherinfoNo >= maxOtherInfosSupported ) {
3714 printf("Error otherinfo index to large (%d>%d)\n",otherinfoNo,maxOtherInfosSupported);
3718 if(extraOtherInfos[otherinfoNo].oidval != -1) {
3719 /* only clear if set. */
3720 extraOtherInfos[otherinfoNo].oidval=-1;
3721 free(extraOtherInfos[otherinfoNo].value);
3726 for(i=0; i<maxOtherInfosSupported; ++i) {
3727 if (extraOtherInfos[i].oidval!=-1 ) {
3728 extraOtherInfos[i].oidval=-1;
3729 free(extraOtherInfos[i].value);
3736 static int cmd_help (const char *line);
3738 typedef char *(*completerFunctionType)(const char *text, int state);
3742 int (*fun)(const char *arg);
3744 completerFunctionType rl_completerfunction;
3745 int complete_filenames;
3746 char **local_tabcompletes;
3748 {"open", cmd_open, "('tcp'|'ssl')':<host>[':'<port>][/<db>]",NULL,0,NULL},
3749 {"quit", cmd_quit, "",NULL,0,NULL},
3750 {"find", cmd_find, "<query>",NULL,0,NULL},
3751 {"delete", cmd_delete, "<setname>",NULL,0,NULL},
3752 {"base", cmd_base, "<base-name>",NULL,0,NULL},
3753 {"show", cmd_show, "<rec#>['+'<#recs>['+'<setname>]]",NULL,0,NULL},
3754 {"scan", cmd_scan, "<term>",NULL,0,NULL},
3755 {"sort", cmd_sort, "<sortkey> <flag> <sortkey> <flag> ...",NULL,0,NULL},
3756 {"sort+", cmd_sort_newset, "<sortkey> <flag> <sortkey> <flag> ...",NULL,0,NULL},
3757 {"authentication", cmd_authentication, "<acctstring>",NULL,0,NULL},
3758 {"lslb", cmd_lslb, "<largeSetLowerBound>",NULL,0,NULL},
3759 {"ssub", cmd_ssub, "<smallSetUpperBound>",NULL,0,NULL},
3760 {"mspn", cmd_mspn, "<mediumSetPresentNumber>",NULL,0,NULL},
3761 {"status", cmd_status, "",NULL,0,NULL},
3762 {"setnames", cmd_setnames, "",NULL,0,NULL},
3763 {"cancel", cmd_cancel, "",NULL,0,NULL},
3764 {"format", cmd_format, "<recordsyntax>",complete_format,0,NULL},
3765 {"schema", cmd_schema, "<schema>",complete_schema,0,NULL},
3766 {"elements", cmd_elements, "<elementSetName>",NULL,0,NULL},
3767 {"close", cmd_close, "",NULL,0,NULL},
3768 {"attributeset", cmd_attributeset, "<attrset>",complete_attributeset,0,NULL},
3769 {"querytype", cmd_querytype, "<type>",complete_querytype,0,NULL},
3770 {"refid", cmd_refid, "<id>",NULL,0,NULL},
3771 {"itemorder", cmd_itemorder, "ill|item <itemno>",NULL,0,NULL},
3772 {"update", cmd_update, "<action> <recid> [<file>]",NULL,0,NULL},
3773 {"update0", cmd_update0, "<action> <recid> [<file>]",NULL,0,NULL},
3774 {"packagename", cmd_packagename, "<packagename>",NULL,0,NULL},
3775 {"proxy", cmd_proxy, "[('tcp'|'ssl')]<host>[':'<port>]",NULL,0,NULL},
3776 {"charset", cmd_charset, "<nego_charset> <output_charset>",NULL,0,NULL},
3777 {"marccharset", cmd_marccharset, "<charset_name>",NULL,0,NULL},
3778 {"lang", cmd_lang, "<language_code>",NULL,0,NULL},
3779 {".", cmd_source, "<filename>",NULL,1,NULL},
3780 {"!", cmd_subshell, "Subshell command",NULL,1,NULL},
3781 {"set_apdufile", cmd_set_apdufile, "<filename>",NULL,1,NULL},
3782 {"set_berfile", cmd_set_berfile, "<filename>",NULL,1,NULL},
3783 {"set_marcdump", cmd_set_marcdump," <filename>",NULL,1,NULL},
3784 {"set_cclfile", cmd_set_cclfile," <filename>",NULL,1,NULL},
3785 {"set_cqlfile", cmd_set_cqlfile," <filename>",NULL,1,NULL},
3786 {"set_auto_reconnect", cmd_set_auto_reconnect," on|off",complete_auto_reconnect,1,NULL},
3787 {"set_otherinfo", cmd_set_otherinfo,"<otherinfoinddex> <oid> <string>",NULL,0,NULL},
3788 {"register_oid", cmd_register_oid,"<name> <class> <oid>",NULL,0,NULL},
3789 {"push_command", cmd_push_command,"<command>",command_generator,0,NULL},
3790 {"register_tab", cmd_register_tab,"<commandname> <tab>",command_generator,0,NULL},
3791 {"cclparse", cmd_cclparse,"<ccl find command>",NULL,0,NULL},
3792 {"list_otherinfo",cmd_list_otherinfo,"[otherinfoinddex]",NULL,0,NULL},
3793 {"list_all",cmd_list_all,"",NULL,0,NULL},
3794 {"clear_otherinfo",cmd_clear_otherinfo,"",NULL,0,NULL},
3795 /* Server Admin Functions */
3796 {"adm-reindex", cmd_adm_reindex, "<database-name>",NULL,0,NULL},
3797 {"adm-truncate", cmd_adm_truncate, "('database'|'index')<object-name>",NULL,0,NULL},
3798 {"adm-create", cmd_adm_create, "",NULL,0,NULL},
3799 {"adm-drop", cmd_adm_drop, "('database'|'index')<object-name>",NULL,0,NULL},
3800 {"adm-import", cmd_adm_import, "<record-type> <dir> <pattern>",NULL,0,NULL},
3801 {"adm-refresh", cmd_adm_refresh, "",NULL,0,NULL},
3802 {"adm-commit", cmd_adm_commit, "",NULL,0,NULL},
3803 {"adm-shutdown", cmd_adm_shutdown, "",NULL,0,NULL},
3804 {"adm-startup", cmd_adm_startup, "",NULL,0,NULL},
3805 {"explain", cmd_explain, "", NULL, 0, NULL},
3806 {"help", cmd_help, "", NULL,0,NULL},
3810 static int cmd_help (const char *line)
3816 sscanf (line, "%20s", topic);
3819 printf("Commands:\n");
3820 for (i = 0; cmd_array[i].cmd; i++)
3821 if (*topic == 0 || strcmp (topic, cmd_array[i].cmd) == 0)
3822 printf(" %s %s\n", cmd_array[i].cmd, cmd_array[i].ad);
3823 if (strcmp (topic, "find") == 0)
3826 printf (" \"term\" Simple Term\n");
3827 printf (" @attr [attset] type=value op Attribute\n");
3828 printf (" @and opl opr And\n");
3829 printf (" @or opl opr Or\n");
3830 printf (" @not opl opr And-Not\n");
3831 printf (" @set set Result set\n");
3833 printf ("Bib-1 attribute types\n");
3835 printf ("4=Title 7=ISBN 8=ISSN 30=Date 62=Abstract 1003=Author 1016=Any\n");
3836 printf ("2=Relation: ");
3837 printf ("1< 2<= 3= 4>= 5> 6!= 102=Relevance\n");
3838 printf ("3=Position: ");
3839 printf ("1=First in Field 2=First in subfield 3=Any position\n");
3840 printf ("4=Structure: ");
3841 printf ("1=Phrase 2=Word 3=Key 4=Year 5=Date 6=WordList\n");
3842 printf ("5=Truncation: ");
3843 printf ("1=Right 2=Left 3=L&R 100=No 101=# 102=Re-1 103=Re-2\n");
3844 printf ("6=Completeness:");
3845 printf ("1=Incomplete subfield 2=Complete subfield 3=Complete field\n");
3850 int cmd_register_tab(const char* arg) {
3852 char command[101], tabargument[101];
3857 if (sscanf (arg, "%100s %100s", command, tabargument) < 1) {
3861 /* locate the amdn in the list */
3862 for (i = 0; cmd_array[i].cmd; i++) {
3863 if (!strncmp(cmd_array[i].cmd, command, strlen(command))) {
3868 if(!cmd_array[i].cmd) {
3869 fprintf(stderr,"Unknown command %s\n",command);
3874 if(!cmd_array[i].local_tabcompletes)
3875 cmd_array[i].local_tabcompletes = (char **) calloc(1,sizeof(char**));
3879 tabslist = cmd_array[i].local_tabcompletes;
3880 for(;tabslist && *tabslist;tabslist++) {
3884 cmd_array[i].local_tabcompletes = (char **)
3885 realloc(cmd_array[i].local_tabcompletes,(num_of_tabs+2)*sizeof(char**));
3886 tabslist=cmd_array[i].local_tabcompletes;
3887 tabslist[num_of_tabs]=strdup(tabargument);
3888 tabslist[num_of_tabs+1]=NULL;
3893 void process_cmd_line(char* line)
3896 char word[32], arg[1024];
3898 #if HAVE_GETTIMEOFDAY
3899 gettimeofday (&tv_start, 0);
3902 if ((res = sscanf(line, "%31s %1023[^;]", word, arg)) <= 0)
3904 strcpy(word, last_cmd);
3909 strcpy(last_cmd, word);
3911 /* removed tailing spaces from the arg command */
3914 char* lastnonspace=NULL;
3922 *(++lastnonspace) = 0;
3925 for (i = 0; cmd_array[i].cmd; i++)
3926 if (!strncmp(cmd_array[i].cmd, word, strlen(word)))
3928 res = (*cmd_array[i].fun)(arg);
3932 if (!cmd_array[i].cmd) /* dump our help-screen */
3934 printf("Unknown command: %s.\n", word);
3935 printf("use help for list of commands\n");
3936 /* cmd_help (""); */
3940 if(apdu_file) fflush(apdu_file);
3943 wait_and_handle_response();
3952 char *command_generator(const char *text, int state)
3958 for( ; cmd_array[idx].cmd; ++idx) {
3959 if (!strncmp(cmd_array[idx].cmd,text,strlen(text))) {
3960 ++idx; /* skip this entry on the next run */
3961 return strdup(cmd_array[idx-1].cmd);
3969 This function only known how to complete on the first word
3971 char ** readline_completer(char *text, int start, int end) {
3972 #if HAVE_READLINE_READLINE_H
3974 completerFunctionType completerToUse;
3977 #if HAVE_READLINE_RL_COMPLETION_MATCHES
3978 char** res=rl_completion_matches(text,
3981 char** res=completion_matches(text,
3982 (CPFunction*)command_generator);
3984 rl_attempted_completion_over = 1;
3987 char arg[1024],word[32];
3989 if ((res = sscanf(rl_line_buffer, "%31s %1023[^;]", word, arg)) <= 0) {
3990 rl_attempted_completion_over = 1;
3994 for (i = 0; cmd_array[i].cmd; i++) {
3995 if (!strncmp(cmd_array[i].cmd, word, strlen(word))) {
4000 if(!cmd_array[i].cmd) return NULL;
4002 curret_global_list = cmd_array[i].local_tabcompletes;
4004 completerToUse = cmd_array[i].rl_completerfunction;
4005 if(completerToUse==NULL) /* if no pr. command completer is defined use the default completer */
4006 completerToUse = default_completer;
4008 if(completerToUse) {
4009 #ifdef HAVE_READLINE_RL_COMPLETION_MATCHES
4011 rl_completion_matches(text,
4015 completion_matches(text,
4016 (CPFunction*)completerToUse);
4018 if(!cmd_array[i].complete_filenames)
4019 rl_attempted_completion_over = 1;
4022 if(!cmd_array[i].complete_filenames)
4023 rl_attempted_completion_over = 1;
4033 static void client(void)
4039 #if HAVE_GETTIMEOFDAY
4040 gettimeofday (&tv_start, 0);
4045 char *line_in = NULL;
4046 #if HAVE_READLINE_READLINE_H
4049 line_in=readline(C_PROMPT);
4052 #if HAVE_READLINE_HISTORY_H
4054 add_history(line_in);
4056 strncpy(line, line_in, 1023);
4065 if (!fgets(line, 1023, stdin))
4067 if ((end_p = strchr (line, '\n')))
4070 process_cmd_line(line);
4074 static void show_version(void)
4078 yaz_version(vstr, 0);
4079 printf ("YAZ version: %s\n", YAZ_VERSION);
4080 if (strcmp(vstr, YAZ_VERSION))
4081 printf ("YAZ DLL/SO: %s\n", vstr);
4085 int main(int argc, char **argv)
4088 char *open_command = 0;
4089 char *auth_command = 0;
4094 if (!setlocale(LC_CTYPE, ""))
4095 fprintf (stderr, "setlocale failed\n");
4099 codeset = nl_langinfo(CODESET);
4103 outputCharset = xstrdup(codeset);
4105 while ((ret = options("k:c:q:a:b:m:v:p:u:t:Vxd:", argv, argc, &arg)) != -2)
4112 open_command = (char *) xmalloc (strlen(arg)+6);
4113 strcpy (open_command, "open ");
4114 strcat (open_command, arg);
4118 dump_file_prefix = arg;
4121 kilobytes = atoi(arg);
4124 if (!(marc_file = fopen (arg, "a")))
4131 outputCharset = xstrdup(arg);
4134 strncpy (ccl_fields, arg, sizeof(ccl_fields)-1);
4135 ccl_fields[sizeof(ccl_fields)-1] = '\0';
4138 strncpy (cql_fields, arg, sizeof(cql_fields)-1);
4139 cql_fields[sizeof(cql_fields)-1] = '\0';
4142 if (!strcmp(arg, "-"))
4145 ber_file=fopen(arg, "a");
4148 if (!strcmp(arg, "-"))
4151 apdu_file=fopen(arg, "a");
4157 yazProxy=strdup(arg);
4162 auth_command = (char *) xmalloc (strlen(arg)+6);
4163 strcpy (auth_command, "auth ");
4164 strcat (auth_command, arg);
4168 yaz_log_init(yaz_log_mask_str(arg), "", 0);
4174 fprintf (stderr, "Usage: %s [-m <marclog>] [ -a <apdulog>] "
4175 "[-b berdump] [-c cclfields] \n"
4176 "[-q cqlfields] [-p <proxy-addr>] [-u <auth>] "
4177 "[-k size] [-d dump] [-V] [<server-addr>]\n",
4185 #ifdef HAVE_GETTIMEOFDAY
4186 gettimeofday (&tv_start, 0);
4188 process_cmd_line (auth_command);
4189 #if HAVE_READLINE_HISTORY_H
4190 add_history(auth_command);
4192 xfree(auth_command);
4196 #ifdef HAVE_GETTIMEOFDAY
4197 gettimeofday (&tv_start, 0);
4199 process_cmd_line (open_command);
4200 #if HAVE_READLINE_HISTORY_H
4201 add_history(open_command);
4203 xfree(open_command);
4214 * vim600: sw=4 ts=8 fdm=marker
4215 * vim<600: sw=4 ts=8