2 * Copyright (c) 1995-2003, Index Data
3 * See the file LICENSE for details.
5 * $Id: client.c,v 1.211 2003-10-21 12:44:42 mike 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;
115 static QueryType queryType = QueryType_Prefix;
117 static CCL_bibset bibset; /* CCL bibset handle */
118 static cql_transform_t cqltrans; /* CQL qualifier-set handle */
120 #if HAVE_READLINE_COMPLETION_OVER
123 /* readline doesn't have this var. Define it ourselves. */
124 int rl_attempted_completion_over = 0;
127 /* set this one to 1, to avoid decode of unknown MARCs */
128 #define AVOID_MARC_DECODE 1
130 #define maxOtherInfosSupported 10
134 } extraOtherInfos[maxOtherInfosSupported];
137 void process_cmd_line(char* line);
138 char ** readline_completer(char *text, int start, int end);
139 char *command_generator(const char *text, int state);
140 char** curret_global_list=NULL;
141 int cmd_register_tab(const char* arg);
143 static void close_session (void);
145 ODR getODROutputStream()
150 const char* query_type_as_string(QueryType q)
153 case QueryType_Prefix: return "prefix (RPN sent to server)";
154 case QueryType_CCL: return "CCL (CCL sent to server) ";
155 case QueryType_CCL2RPN: return "CCL -> RPN (RPN sent to server)";
156 case QueryType_CQL: return "CQL (CQL sent to server)";
157 case QueryType_CQL2RPN: return "CQL -> RPN (RPN sent to server)";
159 return "unknown Query type internal yaz-client error";
163 static void do_hex_dump(const char* buf, int len)
168 for( i=0; i<len ; i=i+16 )
171 for(x=0 ; i+x<len && x<16; ++x)
173 printf("%2.2X ",(unsigned int)((unsigned char)buf[i+x]));
178 if (dump_file_prefix)
181 if (++no < 1000 && strlen(dump_file_prefix) < 500)
185 sprintf (fname, "%s.%03d.raw", dump_file_prefix, no);
186 of = fopen(fname, "wb");
188 fwrite (buf, 1, len, of);
195 void add_otherInfos(Z_APDU *a)
197 Z_OtherInformation **oi;
201 for(i=0; i<maxOtherInfosSupported; ++i)
203 if(extraOtherInfos[i].oidval != -1)
204 yaz_oi_set_string_oidval(oi, out, extraOtherInfos[i].oidval,
205 1, extraOtherInfos[i].value);
209 int send_apdu(Z_APDU *a)
218 z_APDU(print, &a, 0, 0);
221 if (!z_APDU(out, &a, 0, 0))
223 odr_perror(out, "Encoding APDU");
227 buf = odr_getbuf(out, &len, 0);
229 odr_dumpBER(ber_file, buf, len);
230 /* printf ("sending APDU of size %d\n", len); */
231 do_hex_dump(buf, len);
232 if (cs_put(conn, buf, len) < 0)
234 fprintf(stderr, "cs_put: %s", cs_errmsg(cs_errno(conn)));
238 odr_reset(out); /* release the APDU structure */
242 static void print_stringn(const unsigned char *buf, size_t len)
245 for (i = 0; i<len; i++)
246 if ((buf[i] <= 126 && buf[i] >= 32) || strchr ("\n\r\t\f", buf[i]))
247 printf ("%c", buf[i]);
249 printf ("\\X%02X", buf[i]);
252 static void print_refid (Z_ReferenceId *id)
256 printf ("Reference Id: ");
257 print_stringn (id->buf, id->len);
262 static Z_ReferenceId *set_refid (ODR out)
267 id = (Z_ReferenceId *) odr_malloc (out, sizeof(*id));
268 id->size = id->len = strlen(refid);
269 id->buf = (unsigned char *) odr_malloc (out, id->len);
270 memcpy (id->buf, refid, id->len);
274 /* INIT SERVICE ------------------------------- */
276 static void send_initRequest(const char* type_and_host)
278 Z_APDU *apdu = zget_APDU(out, Z_APDU_initRequest);
279 Z_InitRequest *req = apdu->u.initRequest;
281 ODR_MASK_SET(req->options, Z_Options_search);
282 ODR_MASK_SET(req->options, Z_Options_present);
283 ODR_MASK_SET(req->options, Z_Options_namedResultSets);
284 ODR_MASK_SET(req->options, Z_Options_triggerResourceCtrl);
285 ODR_MASK_SET(req->options, Z_Options_scan);
286 ODR_MASK_SET(req->options, Z_Options_sort);
287 ODR_MASK_SET(req->options, Z_Options_extendedServices);
288 ODR_MASK_SET(req->options, Z_Options_delSet);
290 ODR_MASK_SET(req->protocolVersion, Z_ProtocolVersion_1);
291 ODR_MASK_SET(req->protocolVersion, Z_ProtocolVersion_2);
292 ODR_MASK_SET(req->protocolVersion, Z_ProtocolVersion_3);
294 *req->maximumRecordSize = 1024*kilobytes;
295 *req->preferredMessageSize = 1024*kilobytes;
297 req->idAuthentication = auth;
299 req->referenceId = set_refid (out);
302 yaz_oi_set_string_oidval(&req->otherInfo, out, VAL_PROXY,
305 if (negotiationCharset || yazLang) {
306 Z_OtherInformation **p;
307 Z_OtherInformationUnit *p0;
309 yaz_oi_APDU(apdu, &p);
311 if ((p0=yaz_oi_update(p, out, NULL, 0, 0))) {
312 ODR_MASK_SET(req->options, Z_Options_negotiationModel);
314 p0->which = Z_OtherInfo_externallyDefinedInfo;
315 p0->information.externallyDefinedInfo =
316 yaz_set_proposal_charneg(
318 (const char**)&negotiationCharset,
319 negotiationCharset ? 1 : 0,
320 (const char**)&yazLang, yazLang ? 1 : 0, 1);
325 printf("Sent initrequest.\n");
329 /* These two are used only from process_initResponse() */
330 static void render_initUserInfo(Z_OtherInformation *ui1);
331 static void render_diag(Z_DiagnosticFormat *diag);
333 static int process_initResponse(Z_InitResponse *res)
336 /* save session parameters for later use */
337 session_mem = odr_extract_mem(in);
340 for (ver = 0; ver<5; ver++)
341 if (!ODR_MASK_GET(res->protocolVersion, ver))
345 printf("Connection rejected by v%d target.\n", ver);
347 printf("Connection accepted by v%d target.\n", ver);
348 if (res->implementationId)
349 printf("ID : %s\n", res->implementationId);
350 if (res->implementationName)
351 printf("Name : %s\n", res->implementationName);
352 if (res->implementationVersion)
353 printf("Version: %s\n", res->implementationVersion);
354 if (res->userInformationField)
356 Z_External *uif = res->userInformationField;
357 if (uif->which == Z_External_userInfo1) {
358 render_initUserInfo(uif->u.userInfo1);
360 printf("UserInformationfield:\n");
361 if (!z_External(print, (Z_External**)&uif, 0, 0)) {
362 odr_perror(print, "Printing userinfo\n");
365 if (uif->which == Z_External_octet) {
366 printf("Guessing visiblestring:\n");
367 printf("'%s'\n", uif->u. octet_aligned->buf);
368 } else if (uif->which == Z_External_single) {
369 /* Peek at any private Init-diagnostic APDUs */
370 Odr_any *sat = uif->u.single_ASN1_type;
371 printf("### NAUGHTY: External is '%s'\n", sat->buf);
377 if (ODR_MASK_GET(res->options, Z_Options_search))
379 if (ODR_MASK_GET(res->options, Z_Options_present))
381 if (ODR_MASK_GET(res->options, Z_Options_delSet))
383 if (ODR_MASK_GET(res->options, Z_Options_resourceReport))
384 printf (" resourceReport");
385 if (ODR_MASK_GET(res->options, Z_Options_resourceCtrl))
386 printf (" resourceCtrl");
387 if (ODR_MASK_GET(res->options, Z_Options_accessCtrl))
388 printf (" accessCtrl");
389 if (ODR_MASK_GET(res->options, Z_Options_scan))
391 if (ODR_MASK_GET(res->options, Z_Options_sort))
393 if (ODR_MASK_GET(res->options, Z_Options_extendedServices))
394 printf (" extendedServices");
395 if (ODR_MASK_GET(res->options, Z_Options_level_1Segmentation))
396 printf (" level1Segmentation");
397 if (ODR_MASK_GET(res->options, Z_Options_level_2Segmentation))
398 printf (" level2Segmentation");
399 if (ODR_MASK_GET(res->options, Z_Options_concurrentOperations))
400 printf (" concurrentOperations");
401 if (ODR_MASK_GET(res->options, Z_Options_namedResultSets))
403 printf (" namedResultSets");
406 if (ODR_MASK_GET(res->options, Z_Options_encapsulation))
407 printf (" encapsulation");
408 if (ODR_MASK_GET(res->options, Z_Options_resultCount))
409 printf (" resultCount");
410 if (ODR_MASK_GET(res->options, Z_Options_negotiationModel))
411 printf (" negotiationModel");
412 if (ODR_MASK_GET(res->options, Z_Options_duplicateDetection))
413 printf (" duplicateDetection");
414 if (ODR_MASK_GET(res->options, Z_Options_queryType104))
415 printf (" queryType104");
418 if (ODR_MASK_GET(res->options, Z_Options_negotiationModel)) {
420 Z_CharSetandLanguageNegotiation *p =
421 yaz_get_charneg_record(res->otherInfo);
425 char *charset=NULL, *lang=NULL;
428 yaz_get_response_charneg(session_mem, p, &charset, &lang,
431 if (outputCharset && negotiationCharset) {
432 odr_set_charset (out, charset, outputCharset);
433 odr_set_charset (in, outputCharset, charset);
436 odr_set_charset (out, 0, 0);
437 odr_set_charset (in, 0, 0);
440 printf("Accepted character set : %s\n", charset);
441 printf("Accepted code language : %s\n", lang ? lang : "none");
442 printf("Accepted records in ...: %d\n", selected );
450 static void render_initUserInfo(Z_OtherInformation *ui1) {
452 printf("Init response contains %d otherInfo unit%s:\n",
453 ui1->num_elements, ui1->num_elements == 1 ? "" : "s");
455 for (i = 0; i < ui1->num_elements; i++) {
456 Z_OtherInformationUnit *unit = ui1->list[i];
457 printf(" %d: otherInfo unit contains ", i+1);
458 if (unit->which == Z_OtherInfo_externallyDefinedInfo &&
459 unit->information.externallyDefinedInfo->which ==
461 render_diag(unit->information.externallyDefinedInfo->u.diag1);
463 printf("unsupported otherInfo unit type %d\n", unit->which);
469 /* ### should this share code with display_diagrecs()? */
470 static void render_diag(Z_DiagnosticFormat *diag) {
473 printf("%d diagnostic%s:\n", diag->num, diag->num == 1 ? "" : "s");
474 for (i = 0; i < diag->num; i++) {
475 Z_DiagnosticFormat_s *ds = diag->elements[i];
476 printf(" %d: ", i+1);
478 case Z_DiagnosticFormat_s_defaultDiagRec: {
479 Z_DefaultDiagFormat *dd = ds->u.defaultDiagRec;
480 /* ### should check `dd->diagnosticSetId' */
481 printf("code=%d (%s)", *dd->condition,
482 diagbib1_str(*dd->condition));
483 /* Both types of addinfo are the same, so use type-pun */
484 if (dd->u.v2Addinfo != 0)
485 printf(",\n\taddinfo='%s'", dd->u.v2Addinfo);
488 case Z_DiagnosticFormat_s_explicitDiagnostic:
489 printf("Explicit diagnostic (not supported)");
492 printf("Unrecognised diagnostic type %d", ds->which);
496 if (ds->message != 0)
497 printf(", message='%s'", ds->message);
503 static int set_base(const char *arg)
508 for (i = 0; i<num_databaseNames; i++)
509 xfree (databaseNames[i]);
510 num_databaseNames = 0;
514 if (!(cp = strchr(arg, ' ')))
515 cp = arg + strlen(arg);
518 databaseNames[num_databaseNames] = (char *)xmalloc (1 + cp - arg);
519 memcpy (databaseNames[num_databaseNames], arg, cp - arg);
520 databaseNames[num_databaseNames][cp - arg] = '\0';
522 for (cp1 = databaseNames[num_databaseNames]; *cp1 ; cp1++)
531 if (num_databaseNames == 0)
533 num_databaseNames = 1;
534 databaseNames[0] = xstrdup("");
539 static int cmd_base(const char *arg)
543 printf("Usage: base <database> <database> ...\n");
546 return set_base(arg);
549 void cmd_open_remember_last_open_command(const char* arg, char* new_open_command)
551 if(last_open_command != arg)
553 if(last_open_command) xfree(last_open_command);
554 last_open_command = xstrdup(new_open_command);
558 int session_connect(const char *arg)
561 char type_and_host[101];
562 const char *basep = 0;
569 nmem_destroy (session_mem);
573 cs_get_host_args(arg, &basep);
575 strncpy(type_and_host, arg, sizeof(type_and_host)-1);
576 type_and_host[sizeof(type_and_host)-1] = '\0';
578 cmd_open_remember_last_open_command(arg,type_and_host);
581 conn = cs_create_host(yazProxy, 1, &add);
583 conn = cs_create_host(arg, 1, &add);
586 printf ("Couldn't create comstack\n");
591 if (conn->protocol == PROTO_HTTP)
593 printf ("SRW/HTTP not enabled in this YAZ\n");
599 protocol = conn->protocol;
600 if (conn->protocol == PROTO_HTTP)
604 printf("Connecting...");
606 if (cs_connect(conn, add) < 0)
608 printf ("error = %s\n", cs_strerror(conn));
609 if (conn->cerrno == CSYSERR)
612 yaz_strerror(msg, sizeof(msg));
613 printf ("%s\n", msg);
622 if (protocol == PROTO_Z3950)
624 send_initRequest(type_and_host);
630 int cmd_open(const char *arg)
632 static char cur_host[200];
635 strncpy (cur_host, arg, sizeof(cur_host)-1);
636 cur_host[sizeof(cur_host)-1] = 0;
638 return session_connect(cur_host);
645 if(!( auto_reconnect && last_open_command) ) return ;
647 open_command = (char *) xmalloc (strlen(last_open_command)+6);
648 strcpy (open_command, "open ");
650 strcat (open_command, last_open_command);
652 process_cmd_line(open_command);
657 int cmd_authentication(const char *arg)
659 static Z_IdAuthentication au;
660 static char user[40], group[40], pass[40];
661 static Z_IdPass idPass;
666 printf("Auth field set to null\n");
670 r = sscanf (arg, "%39s %39s %39s", user, group, pass);
673 printf("Authentication set to null\n");
679 if (!strcmp(user, "-")) {
680 au.which = Z_IdAuthentication_anonymous;
681 printf("Authentication set to Anonymous\n");
683 au.which = Z_IdAuthentication_open;
685 printf("Authentication set to Open (%s)\n", user);
691 au.which = Z_IdAuthentication_idPass;
692 au.u.idPass = &idPass;
693 idPass.groupId = NULL;
694 idPass.userId = user;
695 idPass.password = group;
696 printf("Authentication set to User (%s), Pass (%s)\n", user, group);
701 au.which = Z_IdAuthentication_idPass;
702 au.u.idPass = &idPass;
703 idPass.groupId = group;
704 idPass.userId = user;
705 idPass.password = pass;
706 printf("Authentication set to User (%s), Group (%s), Pass (%s)\n",
712 /* SEARCH SERVICE ------------------------------ */
713 static void display_record(Z_External *r);
715 static void print_record(const unsigned char *buf, size_t len)
718 print_stringn (buf, len);
719 /* add newline if not already added ... */
720 if (i <= 0 || buf[i-1] != '\n')
724 static void display_record(Z_External *r)
726 oident *ent = oid_getentbyoid(r->direct_reference);
730 * Tell the user what we got.
732 if (r->direct_reference)
734 printf("Record type: ");
736 printf("%s\n", ent->desc);
737 else if (!odr_oid(print, &r->direct_reference, 0, 0))
739 odr_perror(print, "print oid");
743 /* Check if this is a known, ASN.1 type tucked away in an octet string */
744 if (ent && r->which == Z_External_octet)
746 Z_ext_typeent *type = z_ext_getentbyref(ent->value);
752 * Call the given decoder to process the record.
754 odr_setbuf(in, (char*)r->u.octet_aligned->buf,
755 r->u.octet_aligned->len, 0);
756 if (!(*type->fun)(in, (char **)&rr, 0, 0))
758 odr_perror(in, "Decoding constructed record.");
759 fprintf(stdout, "[Near %d]\n", odr_offset(in));
760 fprintf(stdout, "Packet dump:\n---------\n");
761 odr_dumpBER(stdout, (char*)r->u.octet_aligned->buf,
762 r->u.octet_aligned->len);
763 fprintf(stdout, "---------\n");
765 /* note just ignores the error ant print the bytes form the octet_aligned later */
768 * Note: we throw away the original, BER-encoded record here.
769 * Do something else with it if you want to keep it.
771 r->u.sutrs = (Z_SUTRS *) rr; /* we don't actually check the type here. */
772 r->which = type->what;
776 if (ent && ent->oclass != CLASS_RECSYN)
778 if (ent && ent->value == VAL_SOIF)
779 print_record((const unsigned char *) r->u.octet_aligned->buf,
780 r->u.octet_aligned->len);
781 else if (r->which == Z_External_octet)
783 const char *octet_buf = (char*)r->u.octet_aligned->buf;
784 if (ent->value == VAL_TEXT_XML || ent->value == VAL_APPLICATION_XML ||
785 ent->value == VAL_HTML)
787 print_record((const unsigned char *) octet_buf,
788 r->u.octet_aligned->len);
790 else if (ent->value == VAL_POSTSCRIPT)
792 int size = r->u.octet_aligned->len;
795 print_record((const unsigned char *) octet_buf, size);
800 #if AVOID_MARC_DECODE
801 /* primitive check for a marc OID 5.1-29 except 16 */
802 ent->oidsuffix[0] == 5 && ent->oidsuffix[1] < 30 &&
803 ent->oidsuffix[1] != 16
812 yaz_marc_t mt = yaz_marc_create();
814 if (yaz_marc_decode_buf(mt, octet_buf,r->u.octet_aligned->len,
818 if (marcCharset && !strcmp(marcCharset, "auto"))
820 if (ent->value == VAL_USMARC)
822 if (octet_buf[9] == 'a')
830 else if (marcCharset)
832 if (outputCharset && from)
834 cd = yaz_iconv_open(outputCharset, from);
835 printf ("convert from %s to %s", from,
838 printf (" unsupported\n");
843 fwrite (result, 1, rlen, stdout);
847 size_t inbytesleft = rlen;
848 const char *inp = result;
852 size_t outbytesleft = sizeof(outbuf);
856 r = yaz_iconv (cd, (char**) &inp,
858 &outp, &outbytesleft);
859 if (r == (size_t) (-1))
861 int e = yaz_iconv_error(cd);
862 if (e != YAZ_ICONV_E2BIG)
865 fwrite (outbuf, outp - outbuf, 1, stdout);
871 printf ("bad MARC. Dumping as it is:\n");
872 print_record((const unsigned char*) octet_buf,
873 r->u.octet_aligned->len);
875 yaz_marc_destroy(mt);
881 print_record((const unsigned char*) octet_buf,
882 r->u.octet_aligned->len);
886 fwrite (octet_buf, 1, r->u.octet_aligned->len, marc_file);
888 else if (ent && ent->value == VAL_SUTRS)
890 if (r->which != Z_External_sutrs)
892 printf("Expecting single SUTRS type for SUTRS.\n");
895 print_record(r->u.sutrs->buf, r->u.sutrs->len);
897 else if (ent && ent->value == VAL_GRS1)
900 if (r->which != Z_External_grs1)
902 printf("Expecting single GRS type for GRS.\n");
906 yaz_display_grs1(w, r->u.grs1, 0);
910 else if ( /* OPAC display not complete yet .. */
911 ent && ent->value == VAL_OPAC)
914 if (r->u.opac->bibliographicRecord)
915 display_record(r->u.opac->bibliographicRecord);
916 for (i = 0; i<r->u.opac->num_holdingsData; i++)
918 Z_HoldingsRecord *h = r->u.opac->holdingsData[i];
919 if (h->which == Z_HoldingsRecord_marcHoldingsRecord)
921 printf ("MARC holdings %d\n", i);
922 display_record(h->u.marcHoldingsRecord);
924 else if (h->which == Z_HoldingsRecord_holdingsAndCirc)
928 Z_HoldingsAndCircData *data = h->u.holdingsAndCirc;
930 printf ("Data holdings %d\n", i);
931 if (data->typeOfRecord)
932 printf ("typeOfRecord: %s\n", data->typeOfRecord);
933 if (data->encodingLevel)
934 printf ("encodingLevel: %s\n", data->encodingLevel);
935 if (data->receiptAcqStatus)
936 printf ("receiptAcqStatus: %s\n", data->receiptAcqStatus);
937 if (data->generalRetention)
938 printf ("generalRetention: %s\n", data->generalRetention);
939 if (data->completeness)
940 printf ("completeness: %s\n", data->completeness);
941 if (data->dateOfReport)
942 printf ("dateOfReport: %s\n", data->dateOfReport);
944 printf ("nucCode: %s\n", data->nucCode);
945 if (data->localLocation)
946 printf ("localLocation: %s\n", data->localLocation);
947 if (data->shelvingLocation)
948 printf ("shelvingLocation: %s\n", data->shelvingLocation);
949 if (data->callNumber)
950 printf ("callNumber: %s\n", data->callNumber);
951 if (data->copyNumber)
952 printf ("copyNumber: %s\n", data->copyNumber);
953 if (data->publicNote)
954 printf ("publicNote: %s\n", data->publicNote);
955 if (data->reproductionNote)
956 printf ("reproductionNote: %s\n", data->reproductionNote);
957 if (data->termsUseRepro)
958 printf ("termsUseRepro: %s\n", data->termsUseRepro);
959 if (data->enumAndChron)
960 printf ("enumAndChron: %s\n", data->enumAndChron);
961 for (j = 0; j<data->num_volumes; j++)
963 printf ("volume %d\n", j);
964 if (data->volumes[j]->enumeration)
965 printf (" enumeration: %s\n",
966 data->volumes[j]->enumeration);
967 if (data->volumes[j]->chronology)
968 printf (" chronology: %s\n",
969 data->volumes[j]->chronology);
970 if (data->volumes[j]->enumAndChron)
971 printf (" enumAndChron: %s\n",
972 data->volumes[j]->enumAndChron);
974 for (j = 0; j<data->num_circulationData; j++)
976 printf ("circulation %d\n", j);
977 if (data->circulationData[j]->availableNow)
978 printf (" availableNow: %d\n",
979 *data->circulationData[j]->availableNow);
980 if (data->circulationData[j]->availablityDate)
981 printf (" availabiltyDate: %s\n",
982 data->circulationData[j]->availablityDate);
983 if (data->circulationData[j]->availableThru)
984 printf (" availableThru: %s\n",
985 data->circulationData[j]->availableThru);
986 if (data->circulationData[j]->restrictions)
987 printf (" restrictions: %s\n",
988 data->circulationData[j]->restrictions);
989 if (data->circulationData[j]->itemId)
990 printf (" itemId: %s\n",
991 data->circulationData[j]->itemId);
992 if (data->circulationData[j]->renewable)
993 printf (" renewable: %d\n",
994 *data->circulationData[j]->renewable);
995 if (data->circulationData[j]->onHold)
996 printf (" onHold: %d\n",
997 *data->circulationData[j]->onHold);
998 if (data->circulationData[j]->enumAndChron)
999 printf (" enumAndChron: %s\n",
1000 data->circulationData[j]->enumAndChron);
1001 if (data->circulationData[j]->midspine)
1002 printf (" midspine: %s\n",
1003 data->circulationData[j]->midspine);
1004 if (data->circulationData[j]->temporaryLocation)
1005 printf (" temporaryLocation: %s\n",
1006 data->circulationData[j]->temporaryLocation);
1013 printf("Unknown record representation.\n");
1014 if (!z_External(print, &r, 0, 0))
1016 odr_perror(print, "Printing external");
1022 static void display_diagrecs(Z_DiagRec **pp, int num)
1026 Z_DefaultDiagFormat *r;
1028 printf("Diagnostic message(s) from database:\n");
1029 for (i = 0; i<num; i++)
1031 Z_DiagRec *p = pp[i];
1032 if (p->which != Z_DiagRec_defaultFormat)
1034 printf("Diagnostic record not in default format.\n");
1038 r = p->u.defaultFormat;
1039 if (!(ent = oid_getentbyoid(r->diagnosticSetId)) ||
1040 ent->oclass != CLASS_DIAGSET || ent->value != VAL_BIB1)
1041 printf("Missing or unknown diagset\n");
1042 printf(" [%d] %s", *r->condition, diagbib1_str(*r->condition));
1045 case Z_DefaultDiagFormat_v2Addinfo:
1046 printf (" -- v2 addinfo '%s'\n", r->u.v2Addinfo);
1048 case Z_DefaultDiagFormat_v3Addinfo:
1049 printf (" -- v3 addinfo '%s'\n", r->u.v3Addinfo);
1056 static void display_nameplusrecord(Z_NamePlusRecord *p)
1058 if (p->databaseName)
1059 printf("[%s]", p->databaseName);
1060 if (p->which == Z_NamePlusRecord_surrogateDiagnostic)
1061 display_diagrecs(&p->u.surrogateDiagnostic, 1);
1062 else if (p->which == Z_NamePlusRecord_databaseRecord)
1063 display_record(p->u.databaseRecord);
1066 static void display_records(Z_Records *p)
1070 if (p->which == Z_Records_NSD)
1072 Z_DiagRec dr, *dr_p = &dr;
1073 dr.which = Z_DiagRec_defaultFormat;
1074 dr.u.defaultFormat = p->u.nonSurrogateDiagnostic;
1075 display_diagrecs (&dr_p, 1);
1077 else if (p->which == Z_Records_multipleNSD)
1078 display_diagrecs (p->u.multipleNonSurDiagnostics->diagRecs,
1079 p->u.multipleNonSurDiagnostics->num_diagRecs);
1082 printf("Records: %d\n", p->u.databaseOrSurDiagnostics->num_records);
1083 for (i = 0; i < p->u.databaseOrSurDiagnostics->num_records; i++)
1084 display_nameplusrecord(p->u.databaseOrSurDiagnostics->records[i]);
1088 static int send_deleteResultSetRequest(const char *arg)
1093 Z_APDU *apdu = zget_APDU(out, Z_APDU_deleteResultSetRequest);
1094 Z_DeleteResultSetRequest *req = apdu->u.deleteResultSetRequest;
1096 req->referenceId = set_refid (out);
1098 req->num_resultSetList =
1099 sscanf (arg, "%30s %30s %30s %30s %30s %30s %30s %30s",
1100 names[0], names[1], names[2], names[3],
1101 names[4], names[5], names[6], names[7]);
1103 req->deleteFunction = (int *)
1104 odr_malloc (out, sizeof(*req->deleteFunction));
1105 if (req->num_resultSetList > 0)
1107 *req->deleteFunction = Z_DeleteRequest_list;
1108 req->resultSetList = (char **)
1109 odr_malloc (out, sizeof(*req->resultSetList)*
1110 req->num_resultSetList);
1111 for (i = 0; i<req->num_resultSetList; i++)
1112 req->resultSetList[i] = names[i];
1116 *req->deleteFunction = Z_DeleteRequest_all;
1117 req->resultSetList = 0;
1121 printf("Sent deleteResultSetRequest.\n");
1126 static int send_srw(Z_SRW_PDU *sr)
1128 const char *charset = negotiationCharset;
1129 const char *host_port = 0;
1132 Z_SOAP_Handler h[2] = {
1133 {"http://www.loc.gov/zing/srw/v1.0/", 0, (Z_SOAP_fun) yaz_srw_codec},
1136 ODR o = odr_createmem(ODR_ENCODE);
1138 Z_SOAP *p = odr_malloc(o, sizeof(*p));
1141 path = odr_malloc(out, strlen(databaseNames[0])+2);
1143 strcpy(path+1, databaseNames[0]);
1145 gdu = z_get_HTTP_Request(out);
1146 gdu->u.HTTP_Request->path = odr_strdup(out, path);
1150 const char *cp0 = strstr(host_port, "://");
1151 const char *cp1 = 0;
1157 cp1 = strchr(cp0, '/');
1159 cp1 = cp0+strlen(cp0);
1163 char *h = odr_malloc(out, cp1 - cp0 + 1);
1164 memcpy (h, cp0, cp1 - cp0);
1166 z_HTTP_header_add(out, &gdu->u.HTTP_Request->headers,
1171 strcpy(ctype, "text/xml");
1172 if (charset && strlen(charset) < 20)
1174 strcat(ctype, "; charset=");
1175 strcat(ctype, charset);
1177 z_HTTP_header_add(out, &gdu->u.HTTP_Request->headers,
1178 "Content-Type", ctype);
1179 z_HTTP_header_add(out, &gdu->u.HTTP_Request->headers,
1180 "SOAPAction", "\"\"");
1181 p->which = Z_SOAP_generic;
1182 p->u.generic = odr_malloc(o, sizeof(*p->u.generic));
1183 p->u.generic->no = 0;
1184 p->u.generic->ns = 0;
1185 p->u.generic->p = sr;
1186 p->ns = "http://schemas.xmlsoap.org/soap/envelope/";
1188 ret = z_soap_codec_enc(o, &p,
1189 &gdu->u.HTTP_Request->content_buf,
1190 &gdu->u.HTTP_Request->content_len, h,
1193 if (z_GDU(out, &gdu, 0, 0))
1199 buf_out = odr_getbuf(out, &len_out, 0);
1201 /* we don't odr_reset(out), since we may need the buffer again */
1203 do_hex_dump(buf_out, len_out);
1205 r = cs_put(conn, buf_out, len_out);
1217 static int send_SRW_searchRequest(const char *arg)
1223 assert(srw_sr_odr_out == 0);
1224 srw_sr_odr_out = odr_createmem(ODR_ENCODE);
1226 odr_reset(srw_sr_odr_out);
1230 /* save this for later .. when fetching individual records */
1231 srw_sr = sr = yaz_srw_get(srw_sr_odr_out, Z_SRW_searchRetrieve_request);
1232 sr->u.request->query_type = Z_SRW_query_type_cql;
1233 sr->u.request->query.cql = odr_strdup(srw_sr_odr_out, arg);
1235 sr = yaz_srw_get(out, Z_SRW_searchRetrieve_request);
1236 sr->u.request->query_type = Z_SRW_query_type_cql;
1237 sr->u.request->query.cql = odr_strdup(out, arg);
1239 sr->u.request->recordSchema = schema;
1240 return send_srw(sr);
1244 static int send_searchRequest(const char *arg)
1246 Z_APDU *apdu = zget_APDU(out, Z_APDU_searchRequest);
1247 Z_SearchRequest *req = apdu->u.searchRequest;
1250 struct ccl_rpn_node *rpn = NULL;
1252 char setstring[100];
1253 Z_RPNQuery *RPNquery;
1255 YAZ_PQF_Parser pqf_parser;
1257 QueryType myQueryType = queryType;
1260 if (myQueryType == QueryType_CCL2RPN)
1262 rpn = ccl_find_str(bibset, arg, &error, &pos);
1265 printf("CCL ERROR: %s\n", ccl_err_msg(error));
1268 } else if (myQueryType == QueryType_CQL2RPN) {
1269 /* ### All this code should be wrapped in a utility function */
1271 struct cql_node *node;
1272 const char *addinfo;
1273 if (cqltrans == 0) {
1274 printf("Can't use CQL: no translation file. Try set_cqlfile\n");
1277 parser = cql_parser_create();
1278 if ((error = cql_parser_string(parser, arg)) != 0) {
1279 printf("Can't parse CQL: must be a syntax error\n");
1282 node = cql_parser_result(parser);
1283 if ((error = cql_transform_buf(cqltrans, node, pqfbuf,
1284 sizeof pqfbuf)) != 0) {
1285 error = cql_transform_error(cqltrans, &addinfo);
1286 printf ("Can't convert CQL to PQF: %s (addinfo=%s)\n",
1287 cql_strerror(error), addinfo);
1291 myQueryType = QueryType_Prefix;
1294 req->referenceId = set_refid (out);
1295 if (!strcmp(arg, "@big")) /* strictly for troublemaking */
1297 static unsigned char big[2100];
1298 static Odr_oct bigo;
1300 /* send a very big referenceid to test transport stack etc. */
1301 memset(big, 'A', 2100);
1302 bigo.len = bigo.size = 2100;
1304 req->referenceId = &bigo;
1309 sprintf(setstring, "%d", ++setnumber);
1310 req->resultSetName = setstring;
1312 *req->smallSetUpperBound = smallSetUpperBound;
1313 *req->largeSetLowerBound = largeSetLowerBound;
1314 *req->mediumSetPresentNumber = mediumSetPresentNumber;
1315 if (smallSetUpperBound > 0 || (largeSetLowerBound > 1 &&
1316 mediumSetPresentNumber > 0))
1320 prefsyn.proto = protocol;
1321 prefsyn.oclass = CLASS_RECSYN;
1322 prefsyn.value = recordsyntax;
1323 req->preferredRecordSyntax =
1324 odr_oiddup(out, oid_ent_to_oid(&prefsyn, oid));
1325 req->smallSetElementSetNames =
1326 req->mediumSetElementSetNames = elementSetNames;
1328 req->num_databaseNames = num_databaseNames;
1329 req->databaseNames = databaseNames;
1331 req->query = &query;
1333 switch (myQueryType)
1335 case QueryType_Prefix:
1336 query.which = Z_Query_type_1;
1337 pqf_parser = yaz_pqf_create ();
1338 RPNquery = yaz_pqf_parse (pqf_parser, out, arg);
1341 const char *pqf_msg;
1343 int code = yaz_pqf_error (pqf_parser, &pqf_msg, &off);
1344 printf("%*s^\n", off+4, "");
1345 printf("Prefix query error: %s (code %d)\n", pqf_msg, code);
1347 yaz_pqf_destroy (pqf_parser);
1350 yaz_pqf_destroy (pqf_parser);
1351 query.u.type_1 = RPNquery;
1354 query.which = Z_Query_type_2;
1355 query.u.type_2 = &ccl_query;
1356 ccl_query.buf = (unsigned char*) arg;
1357 ccl_query.len = strlen(arg);
1359 case QueryType_CCL2RPN:
1360 query.which = Z_Query_type_1;
1361 RPNquery = ccl_rpn_query(out, rpn);
1364 printf ("Couldn't convert from CCL to RPN\n");
1367 query.u.type_1 = RPNquery;
1368 ccl_rpn_delete (rpn);
1371 query.which = Z_Query_type_104;
1372 ext = (Z_External *) odr_malloc(out, sizeof(*ext));
1373 ext->direct_reference = odr_getoidbystr(out, "1.2.840.10003.16.2");
1374 ext->indirect_reference = 0;
1375 ext->descriptor = 0;
1376 ext->which = Z_External_CQL;
1377 ext->u.cql = odr_strdup(out, arg);
1378 query.u.type_104 = ext;
1381 printf ("Unsupported query type\n");
1384 if (send_apdu(apdu))
1385 printf("Sent searchRequest.\n");
1390 /* display Query Expression as part of searchResult-1 */
1391 static void display_queryExpression (Z_QueryExpression *qe)
1395 if (qe->which == Z_QueryExpression_term)
1397 if (qe->u.term->queryTerm)
1399 Z_Term *term = qe->u.term->queryTerm;
1400 switch (term->which)
1402 case Z_Term_general:
1403 printf (" %.*s", term->u.general->len, term->u.general->buf);
1405 case Z_Term_characterString:
1406 printf (" %s", term->u.characterString);
1408 case Z_Term_numeric:
1409 printf (" %d", *term->u.numeric);
1419 /* see if we can find USR:SearchResult-1 */
1420 static void display_searchResult (Z_OtherInformation *o)
1425 for (i = 0; i < o->num_elements; i++)
1427 if (o->list[i]->which == Z_OtherInfo_externallyDefinedInfo)
1429 Z_External *ext = o->list[i]->information.externallyDefinedInfo;
1431 if (ext->which == Z_External_searchResult1)
1434 Z_SearchInfoReport *sr = ext->u.searchResult1;
1435 printf ("SearchResult-1:");
1436 for (j = 0; j < sr->num; j++)
1438 if (!sr->elements[j]->subqueryExpression)
1440 display_queryExpression (
1441 sr->elements[j]->subqueryExpression);
1442 display_queryExpression (
1443 sr->elements[j]->subqueryInterpretation);
1444 display_queryExpression (
1445 sr->elements[j]->subqueryRecommendation);
1446 if (sr->elements[j]->subqueryCount)
1447 printf ("(%d)", *sr->elements[j]->subqueryCount);
1455 static int process_searchResponse(Z_SearchResponse *res)
1457 printf ("Received SearchResponse.\n");
1458 print_refid (res->referenceId);
1459 if (*res->searchStatus)
1460 printf("Search was a success.\n");
1462 printf("Search was a bloomin' failure.\n");
1463 printf("Number of hits: %d", *res->resultCount);
1465 printf (", setno %d", setnumber);
1467 display_searchResult (res->additionalSearchInfo);
1468 printf("records returned: %d\n",
1469 *res->numberOfRecordsReturned);
1470 setno += *res->numberOfRecordsReturned;
1472 display_records(res->records);
1476 static void print_level(int iLevel)
1479 for (i = 0; i < iLevel * 4; i++)
1483 static void print_int(int iLevel, const char *pTag, int *pInt)
1487 print_level(iLevel);
1488 printf("%s: %d\n", pTag, *pInt);
1492 static void print_string(int iLevel, const char *pTag, const char *pString)
1494 if (pString != NULL)
1496 print_level(iLevel);
1497 printf("%s: %s\n", pTag, pString);
1501 static void print_oid(int iLevel, const char *pTag, Odr_oid *pOid)
1507 print_level(iLevel);
1508 printf("%s:", pTag);
1509 for (; *pInt != -1; pInt++)
1510 printf(" %d", *pInt);
1515 static void print_referenceId(int iLevel, Z_ReferenceId *referenceId)
1517 if (referenceId != NULL)
1521 print_level(iLevel);
1522 printf("Ref Id (%d, %d): ", referenceId->len, referenceId->size);
1523 for (i = 0; i < referenceId->len; i++)
1524 printf("%c", referenceId->buf[i]);
1529 static void print_string_or_numeric(int iLevel, const char *pTag, Z_StringOrNumeric *pStringNumeric)
1531 if (pStringNumeric != NULL)
1533 switch (pStringNumeric->which)
1535 case Z_StringOrNumeric_string:
1536 print_string(iLevel, pTag, pStringNumeric->u.string);
1539 case Z_StringOrNumeric_numeric:
1540 print_int(iLevel, pTag, pStringNumeric->u.numeric);
1544 print_level(iLevel);
1545 printf("%s: valid type for Z_StringOrNumeric\n", pTag);
1551 static void print_universe_report_duplicate(
1553 Z_UniverseReportDuplicate *pUniverseReportDuplicate)
1555 if (pUniverseReportDuplicate != NULL)
1557 print_level(iLevel);
1558 printf("Universe Report Duplicate: \n");
1560 print_string_or_numeric(iLevel, "Hit No",
1561 pUniverseReportDuplicate->hitno);
1565 static void print_universe_report_hits(
1567 Z_UniverseReportHits *pUniverseReportHits)
1569 if (pUniverseReportHits != NULL)
1571 print_level(iLevel);
1572 printf("Universe Report Hits: \n");
1574 print_string_or_numeric(iLevel, "Database",
1575 pUniverseReportHits->database);
1576 print_string_or_numeric(iLevel, "Hits", pUniverseReportHits->hits);
1580 static void print_universe_report(int iLevel, Z_UniverseReport *pUniverseReport)
1582 if (pUniverseReport != NULL)
1584 print_level(iLevel);
1585 printf("Universe Report: \n");
1587 print_int(iLevel, "Total Hits", pUniverseReport->totalHits);
1588 switch (pUniverseReport->which)
1590 case Z_UniverseReport_databaseHits:
1591 print_universe_report_hits(iLevel,
1592 pUniverseReport->u.databaseHits);
1595 case Z_UniverseReport_duplicate:
1596 print_universe_report_duplicate(iLevel,
1597 pUniverseReport->u.duplicate);
1601 print_level(iLevel);
1602 printf("Type: %d\n", pUniverseReport->which);
1608 static void print_external(int iLevel, Z_External *pExternal)
1610 if (pExternal != NULL)
1612 print_level(iLevel);
1613 printf("External: \n");
1615 print_oid(iLevel, "Direct Reference", pExternal->direct_reference);
1616 print_int(iLevel, "InDirect Reference", pExternal->indirect_reference);
1617 print_string(iLevel, "Descriptor", pExternal->descriptor);
1618 switch (pExternal->which)
1620 case Z_External_universeReport:
1621 print_universe_report(iLevel, pExternal->u.universeReport);
1625 print_level(iLevel);
1626 printf("Type: %d\n", pExternal->which);
1632 static int process_resourceControlRequest (Z_ResourceControlRequest *req)
1634 printf ("Received ResourceControlRequest.\n");
1635 print_referenceId(1, req->referenceId);
1636 print_int(1, "Suspended Flag", req->suspendedFlag);
1637 print_int(1, "Partial Results Available", req->partialResultsAvailable);
1638 print_int(1, "Response Required", req->responseRequired);
1639 print_int(1, "Triggered Request Flag", req->triggeredRequestFlag);
1640 print_external(1, req->resourceReport);
1644 void process_ESResponse(Z_ExtendedServicesResponse *res)
1647 switch (*res->operationStatus)
1649 case Z_ExtendedServicesResponse_done:
1652 case Z_ExtendedServicesResponse_accepted:
1653 printf ("accepted\n");
1655 case Z_ExtendedServicesResponse_failure:
1656 printf ("failure\n");
1657 display_diagrecs(res->diagnostics, res->num_diagnostics);
1660 printf ("unknown\n");
1662 if ( (*res->operationStatus != Z_ExtendedServicesResponse_failure) &&
1663 (res->num_diagnostics != 0) ) {
1664 display_diagrecs(res->diagnostics, res->num_diagnostics);
1666 print_refid (res->referenceId);
1667 if (res->taskPackage &&
1668 res->taskPackage->which == Z_External_extendedService)
1670 Z_TaskPackage *taskPackage = res->taskPackage->u.extendedService;
1671 Odr_oct *id = taskPackage->targetReference;
1672 Z_External *ext = taskPackage->taskSpecificParameters;
1676 printf ("Target Reference: ");
1677 print_stringn (id->buf, id->len);
1680 if (ext->which == Z_External_update)
1682 Z_IUUpdateTaskPackage *utp = ext->u.update->u.taskPackage;
1683 if (utp && utp->targetPart)
1685 Z_IUTargetPart *targetPart = utp->targetPart;
1688 for (i = 0; i<targetPart->num_taskPackageRecords; i++)
1691 Z_IUTaskPackageRecordStructure *tpr =
1692 targetPart->taskPackageRecords[i];
1693 printf ("task package record %d\n", i+1);
1694 if (tpr->which == Z_IUTaskPackageRecordStructure_record)
1696 display_record (tpr->u.record);
1700 printf ("other type\n");
1708 const char *get_ill_element (void *clientData, const char *element)
1713 static Z_External *create_external_itemRequest()
1715 struct ill_get_ctl ctl;
1716 ILL_ItemRequest *req;
1718 int item_request_size = 0;
1719 char *item_request_buf = 0;
1723 ctl.f = get_ill_element;
1725 req = ill_get_ItemRequest(&ctl, "ill", 0);
1727 printf ("ill_get_ItemRequest failed\n");
1729 if (!ill_ItemRequest (out, &req, 0, 0))
1733 ill_ItemRequest(print, &req, 0, 0);
1736 item_request_buf = odr_getbuf (out, &item_request_size, 0);
1737 if (item_request_buf)
1738 odr_setbuf (out, item_request_buf, item_request_size, 1);
1739 printf ("Couldn't encode ItemRequest, size %d\n", item_request_size);
1746 item_request_buf = odr_getbuf (out, &item_request_size, 0);
1747 oid.proto = PROTO_GENERAL;
1748 oid.oclass = CLASS_GENERAL;
1749 oid.value = VAL_ISO_ILL_1;
1751 r = (Z_External *) odr_malloc (out, sizeof(*r));
1752 r->direct_reference = odr_oiddup(out,oid_getoidbyent(&oid));
1753 r->indirect_reference = 0;
1755 r->which = Z_External_single;
1757 r->u.single_ASN1_type = (Odr_oct *)
1758 odr_malloc (out, sizeof(*r->u.single_ASN1_type));
1759 r->u.single_ASN1_type->buf = (unsigned char *)
1760 odr_malloc (out, item_request_size);
1761 r->u.single_ASN1_type->len = item_request_size;
1762 r->u.single_ASN1_type->size = item_request_size;
1763 memcpy (r->u.single_ASN1_type->buf, item_request_buf,
1766 do_hex_dump(item_request_buf,item_request_size);
1771 static Z_External *create_external_ILL_APDU(int which)
1773 struct ill_get_ctl ctl;
1776 int ill_request_size = 0;
1777 char *ill_request_buf = 0;
1781 ctl.f = get_ill_element;
1783 ill_apdu = ill_get_APDU(&ctl, "ill", 0);
1785 if (!ill_APDU (out, &ill_apdu, 0, 0))
1789 printf ("-------------------\n");
1790 ill_APDU(print, &ill_apdu, 0, 0);
1792 printf ("-------------------\n");
1794 ill_request_buf = odr_getbuf (out, &ill_request_size, 0);
1795 if (ill_request_buf)
1796 odr_setbuf (out, ill_request_buf, ill_request_size, 1);
1797 printf ("Couldn't encode ILL-Request, size %d\n", ill_request_size);
1803 ill_request_buf = odr_getbuf (out, &ill_request_size, 0);
1805 oid.proto = PROTO_GENERAL;
1806 oid.oclass = CLASS_GENERAL;
1807 oid.value = VAL_ISO_ILL_1;
1809 r = (Z_External *) odr_malloc (out, sizeof(*r));
1810 r->direct_reference = odr_oiddup(out,oid_getoidbyent(&oid));
1811 r->indirect_reference = 0;
1813 r->which = Z_External_single;
1815 r->u.single_ASN1_type = (Odr_oct *)
1816 odr_malloc (out, sizeof(*r->u.single_ASN1_type));
1817 r->u.single_ASN1_type->buf = (unsigned char *)
1818 odr_malloc (out, ill_request_size);
1819 r->u.single_ASN1_type->len = ill_request_size;
1820 r->u.single_ASN1_type->size = ill_request_size;
1821 memcpy (r->u.single_ASN1_type->buf, ill_request_buf, ill_request_size);
1822 /* printf ("len = %d\n", ill_request_size); */
1823 /* do_hex_dump(ill_request_buf,ill_request_size); */
1824 /* printf("--- end of extenal\n"); */
1831 static Z_External *create_ItemOrderExternal(const char *type, int itemno)
1833 Z_External *r = (Z_External *) odr_malloc(out, sizeof(Z_External));
1834 oident ItemOrderRequest;
1836 ItemOrderRequest.proto = PROTO_Z3950;
1837 ItemOrderRequest.oclass = CLASS_EXTSERV;
1838 ItemOrderRequest.value = VAL_ITEMORDER;
1840 r->direct_reference = odr_oiddup(out,oid_getoidbyent(&ItemOrderRequest));
1841 r->indirect_reference = 0;
1844 r->which = Z_External_itemOrder;
1846 r->u.itemOrder = (Z_ItemOrder *) odr_malloc(out,sizeof(Z_ItemOrder));
1847 memset(r->u.itemOrder, 0, sizeof(Z_ItemOrder));
1848 r->u.itemOrder->which=Z_IOItemOrder_esRequest;
1850 r->u.itemOrder->u.esRequest = (Z_IORequest *)
1851 odr_malloc(out,sizeof(Z_IORequest));
1852 memset(r->u.itemOrder->u.esRequest, 0, sizeof(Z_IORequest));
1854 r->u.itemOrder->u.esRequest->toKeep = (Z_IOOriginPartToKeep *)
1855 odr_malloc(out,sizeof(Z_IOOriginPartToKeep));
1856 memset(r->u.itemOrder->u.esRequest->toKeep, 0, sizeof(Z_IOOriginPartToKeep));
1857 r->u.itemOrder->u.esRequest->notToKeep = (Z_IOOriginPartNotToKeep *)
1858 odr_malloc(out,sizeof(Z_IOOriginPartNotToKeep));
1859 memset(r->u.itemOrder->u.esRequest->notToKeep, 0, sizeof(Z_IOOriginPartNotToKeep));
1861 r->u.itemOrder->u.esRequest->toKeep->supplDescription = NULL;
1862 r->u.itemOrder->u.esRequest->toKeep->contact = NULL;
1863 r->u.itemOrder->u.esRequest->toKeep->addlBilling = NULL;
1865 r->u.itemOrder->u.esRequest->notToKeep->resultSetItem =
1866 (Z_IOResultSetItem *) odr_malloc(out, sizeof(Z_IOResultSetItem));
1867 memset(r->u.itemOrder->u.esRequest->notToKeep->resultSetItem, 0, sizeof(Z_IOResultSetItem));
1868 r->u.itemOrder->u.esRequest->notToKeep->resultSetItem->resultSetId = "1";
1870 r->u.itemOrder->u.esRequest->notToKeep->resultSetItem->item =
1871 (int *) odr_malloc(out, sizeof(int));
1872 *r->u.itemOrder->u.esRequest->notToKeep->resultSetItem->item = itemno;
1874 if (!strcmp (type, "item") || !strcmp(type, "2"))
1876 printf ("using item-request\n");
1877 r->u.itemOrder->u.esRequest->notToKeep->itemRequest =
1878 create_external_itemRequest();
1880 else if (!strcmp(type, "ill") || !strcmp(type, "1"))
1882 printf ("using ILL-request\n");
1883 r->u.itemOrder->u.esRequest->notToKeep->itemRequest =
1884 create_external_ILL_APDU(ILL_APDU_ILL_Request);
1886 else if (!strcmp(type, "xml") || !strcmp(type, "3"))
1888 const char *xml_buf =
1890 " <type>request</type>\n"
1891 " <libraryNo>000200</libraryNo>\n"
1892 " <borrowerTicketNo> 1212 </borrowerTicketNo>\n"
1894 r->u.itemOrder->u.esRequest->notToKeep->itemRequest =
1895 z_ext_record (out, VAL_TEXT_XML, xml_buf, strlen(xml_buf));
1898 r->u.itemOrder->u.esRequest->notToKeep->itemRequest = 0;
1903 static int send_itemorder(const char *type, int itemno)
1905 Z_APDU *apdu = zget_APDU(out, Z_APDU_extendedServicesRequest);
1906 Z_ExtendedServicesRequest *req = apdu->u.extendedServicesRequest;
1907 oident ItemOrderRequest;
1909 ItemOrderRequest.proto = PROTO_Z3950;
1910 ItemOrderRequest.oclass = CLASS_EXTSERV;
1911 ItemOrderRequest.value = VAL_ITEMORDER;
1912 req->packageType = odr_oiddup(out,oid_getoidbyent(&ItemOrderRequest));
1913 req->packageName = esPackageName;
1915 req->taskSpecificParameters = create_ItemOrderExternal(type, itemno);
1921 static int only_z3950()
1923 if (protocol == PROTO_HTTP)
1925 printf ("Not supported by SRW\n");
1931 static int cmd_update_common(const char *arg, int version);
1933 static int cmd_update(const char *arg)
1935 return cmd_update_common(arg, 1);
1938 static int cmd_update0(const char *arg)
1940 return cmd_update_common(arg, 0);
1943 static int cmd_update_common(const char *arg, int version)
1945 Z_APDU *apdu = zget_APDU(out, Z_APDU_extendedServicesRequest );
1946 Z_ExtendedServicesRequest *req = apdu->u.extendedServicesRequest;
1950 char action[20], recid[20], fname[80];
1952 Z_External *record_this = 0;
1959 sscanf (arg, "%19s %19s %79s", action, recid, fname);
1961 if (!strcmp (action, "insert"))
1962 action_no = Z_IUOriginPartToKeep_recordInsert;
1963 else if (!strcmp (action, "replace"))
1964 action_no = Z_IUOriginPartToKeep_recordReplace;
1965 else if (!strcmp (action, "delete"))
1966 action_no = Z_IUOriginPartToKeep_recordDelete;
1967 else if (!strcmp (action, "update"))
1968 action_no = Z_IUOriginPartToKeep_specialUpdate;
1971 printf ("Bad action: %s\n", action);
1972 printf ("Possible values: insert, replace, delete, update\n");
1980 stat (fname, &status);
1981 if (S_ISREG(status.st_mode) && (inf = fopen(fname, "r")))
1983 size_t len = status.st_size;
1984 char *buf = (char *) xmalloc (len);
1986 fread (buf, 1, len, inf);
1990 record_this = z_ext_record (out, VAL_TEXT_XML, buf, len);
1996 printf ("File %s doesn't exist\n", fname);
2004 printf ("No last record (update ignored)\n");
2007 record_this = record_last;
2010 update_oid.proto = PROTO_Z3950;
2011 update_oid.oclass = CLASS_EXTSERV;
2013 update_oid.value = VAL_DBUPDATE0;
2015 update_oid.value = VAL_DBUPDATE;
2016 oid_ent_to_oid (&update_oid, oid);
2017 req->packageType = odr_oiddup(out,oid);
2018 req->packageName = esPackageName;
2020 req->referenceId = set_refid (out);
2022 r = req->taskSpecificParameters = (Z_External *)
2023 odr_malloc (out, sizeof(*r));
2024 r->direct_reference = odr_oiddup(out,oid);
2025 r->indirect_reference = 0;
2029 Z_IU0OriginPartToKeep *toKeep;
2030 Z_IU0SuppliedRecords *notToKeep;
2032 r->which = Z_External_update0;
2033 r->u.update0 = (Z_IU0Update *) odr_malloc(out, sizeof(*r->u.update0));
2034 r->u.update0->which = Z_IUUpdate_esRequest;
2035 r->u.update0->u.esRequest = (Z_IU0UpdateEsRequest *)
2036 odr_malloc(out, sizeof(*r->u.update0->u.esRequest));
2037 toKeep = r->u.update0->u.esRequest->toKeep = (Z_IU0OriginPartToKeep *)
2038 odr_malloc(out, sizeof(*r->u.update0->u.esRequest->toKeep));
2040 toKeep->databaseName = databaseNames[0];
2042 toKeep->elementSetName = 0;
2044 toKeep->action = (int *) odr_malloc(out, sizeof(*toKeep->action));
2045 *toKeep->action = action_no;
2047 notToKeep = r->u.update0->u.esRequest->notToKeep = (Z_IU0SuppliedRecords *)
2048 odr_malloc(out, sizeof(*r->u.update0->u.esRequest->notToKeep));
2050 notToKeep->elements = (Z_IU0SuppliedRecords_elem **)
2051 odr_malloc(out, sizeof(*notToKeep->elements));
2052 notToKeep->elements[0] = (Z_IU0SuppliedRecords_elem *)
2053 odr_malloc(out, sizeof(**notToKeep->elements));
2054 notToKeep->elements[0]->which = Z_IUSuppliedRecords_elem_opaque;
2057 notToKeep->elements[0]->u.opaque = (Odr_oct *)
2058 odr_malloc (out, sizeof(Odr_oct));
2059 notToKeep->elements[0]->u.opaque->buf = (unsigned char *) recid;
2060 notToKeep->elements[0]->u.opaque->size = strlen(recid);
2061 notToKeep->elements[0]->u.opaque->len = strlen(recid);
2064 notToKeep->elements[0]->u.opaque = 0;
2065 notToKeep->elements[0]->supplementalId = 0;
2066 notToKeep->elements[0]->correlationInfo = 0;
2067 notToKeep->elements[0]->record = record_this;
2071 Z_IUOriginPartToKeep *toKeep;
2072 Z_IUSuppliedRecords *notToKeep;
2074 r->which = Z_External_update;
2075 r->u.update = (Z_IUUpdate *) odr_malloc(out, sizeof(*r->u.update));
2076 r->u.update->which = Z_IUUpdate_esRequest;
2077 r->u.update->u.esRequest = (Z_IUUpdateEsRequest *)
2078 odr_malloc(out, sizeof(*r->u.update->u.esRequest));
2079 toKeep = r->u.update->u.esRequest->toKeep = (Z_IUOriginPartToKeep *)
2080 odr_malloc(out, sizeof(*r->u.update->u.esRequest->toKeep));
2082 toKeep->databaseName = databaseNames[0];
2084 toKeep->elementSetName = 0;
2085 toKeep->actionQualifier = 0;
2086 toKeep->action = (int *) odr_malloc(out, sizeof(*toKeep->action));
2087 *toKeep->action = action_no;
2089 notToKeep = r->u.update->u.esRequest->notToKeep = (Z_IUSuppliedRecords *)
2090 odr_malloc(out, sizeof(*r->u.update->u.esRequest->notToKeep));
2092 notToKeep->elements = (Z_IUSuppliedRecords_elem **)
2093 odr_malloc(out, sizeof(*notToKeep->elements));
2094 notToKeep->elements[0] = (Z_IUSuppliedRecords_elem *)
2095 odr_malloc(out, sizeof(**notToKeep->elements));
2096 notToKeep->elements[0]->which = Z_IUSuppliedRecords_elem_opaque;
2099 notToKeep->elements[0]->u.opaque = (Odr_oct *)
2100 odr_malloc (out, sizeof(Odr_oct));
2101 notToKeep->elements[0]->u.opaque->buf = (unsigned char *) recid;
2102 notToKeep->elements[0]->u.opaque->size = strlen(recid);
2103 notToKeep->elements[0]->u.opaque->len = strlen(recid);
2106 notToKeep->elements[0]->u.opaque = 0;
2107 notToKeep->elements[0]->supplementalId = 0;
2108 notToKeep->elements[0]->correlationInfo = 0;
2109 notToKeep->elements[0]->record = record_this;
2117 static int cmd_itemorder(const char *arg)
2124 if (sscanf (arg, "%10s %d", type, &itemno) != 2)
2127 printf("Item order request\n");
2129 send_itemorder(type, itemno);
2133 static int cmd_find(const char *arg)
2137 printf("Find what?\n");
2140 if (protocol == PROTO_HTTP)
2145 if (!send_SRW_searchRequest(arg))
2158 printf("Not connected yet\n");
2162 if (!send_searchRequest(arg))
2168 static int cmd_delete(const char *arg)
2172 printf("Not connected yet\n");
2177 if (!send_deleteResultSetRequest(arg))
2182 static int cmd_ssub(const char *arg)
2184 if (!(smallSetUpperBound = atoi(arg)))
2189 static int cmd_lslb(const char *arg)
2193 if (!(largeSetLowerBound = atoi(arg)))
2198 static int cmd_mspn(const char *arg)
2202 if (!(mediumSetPresentNumber = atoi(arg)))
2207 static int cmd_status(const char *arg)
2209 printf("smallSetUpperBound: %d\n", smallSetUpperBound);
2210 printf("largeSetLowerBound: %d\n", largeSetLowerBound);
2211 printf("mediumSetPresentNumber: %d\n", mediumSetPresentNumber);
2215 static int cmd_setnames(const char *arg)
2217 if (*arg == '1') /* enable ? */
2219 else if (*arg == '0') /* disable ? */
2221 else if (setnumber < 0) /* no args, toggle .. */
2227 printf("Set numbering enabled.\n");
2229 printf("Set numbering disabled.\n");
2233 /* PRESENT SERVICE ----------------------------- */
2235 static void parse_show_args(const char *arg_c, char *setstring,
2236 int *start, int *number)
2241 strncpy(arg, arg_c, sizeof(arg)-1);
2242 arg[sizeof(arg)-1] = '\0';
2244 if ((p = strchr(arg, '+')))
2246 *number = atoi(p + 1);
2251 if (p && (p=strchr(p+1, '+')))
2252 strcpy (setstring, p+1);
2253 else if (setnumber >= 0)
2254 sprintf(setstring, "%d", setnumber);
2259 static int send_presentRequest(const char *arg)
2261 Z_APDU *apdu = zget_APDU(out, Z_APDU_presentRequest);
2262 Z_PresentRequest *req = apdu->u.presentRequest;
2263 Z_RecordComposition compo;
2267 char setstring[100];
2269 req->referenceId = set_refid (out);
2271 parse_show_args(arg, setstring, &setno, &nos);
2273 req->resultSetId = setstring;
2275 req->resultSetStartPoint = &setno;
2276 req->numberOfRecordsRequested = &nos;
2277 prefsyn.proto = protocol;
2278 prefsyn.oclass = CLASS_RECSYN;
2279 prefsyn.value = recordsyntax;
2280 req->preferredRecordSyntax =
2281 odr_oiddup (out, oid_ent_to_oid(&prefsyn, oid));
2287 prefschema.proto = protocol;
2288 prefschema.oclass = CLASS_SCHEMA;
2289 prefschema.value = oid_getvalbyname(schema);
2291 req->recordComposition = &compo;
2292 compo.which = Z_RecordComp_complex;
2293 compo.u.complex = (Z_CompSpec *)
2294 odr_malloc(out, sizeof(*compo.u.complex));
2295 compo.u.complex->selectAlternativeSyntax = (bool_t *)
2296 odr_malloc(out, sizeof(bool_t));
2297 *compo.u.complex->selectAlternativeSyntax = 0;
2299 compo.u.complex->generic = (Z_Specification *)
2300 odr_malloc(out, sizeof(*compo.u.complex->generic));
2301 compo.u.complex->generic->which = Z_Schema_oid;
2302 compo.u.complex->generic->schema.oid = (Odr_oid *)
2303 odr_oiddup(out, oid_ent_to_oid(&prefschema, oid));
2304 if (!compo.u.complex->generic->schema.oid)
2306 /* OID wasn't a schema! Try record syntax instead. */
2307 prefschema.oclass = CLASS_RECSYN;
2308 compo.u.complex->generic->schema.oid = (Odr_oid *)
2309 odr_oiddup(out, oid_ent_to_oid(&prefschema, oid));
2311 if (!elementSetNames)
2312 compo.u.complex->generic->elementSpec = 0;
2315 compo.u.complex->generic->elementSpec = (Z_ElementSpec *)
2316 odr_malloc(out, sizeof(Z_ElementSpec));
2317 compo.u.complex->generic->elementSpec->which =
2318 Z_ElementSpec_elementSetName;
2319 compo.u.complex->generic->elementSpec->u.elementSetName =
2320 elementSetNames->u.generic;
2322 compo.u.complex->num_dbSpecific = 0;
2323 compo.u.complex->dbSpecific = 0;
2324 compo.u.complex->num_recordSyntax = 0;
2325 compo.u.complex->recordSyntax = 0;
2327 else if (elementSetNames)
2329 req->recordComposition = &compo;
2330 compo.which = Z_RecordComp_simple;
2331 compo.u.simple = elementSetNames;
2334 printf("Sent presentRequest (%d+%d).\n", setno, nos);
2339 static int send_SRW_presentRequest(const char *arg)
2341 char setstring[100];
2343 Z_SRW_PDU *sr = srw_sr;
2347 parse_show_args(arg, setstring, &setno, &nos);
2348 sr->u.request->startRecord = odr_intdup(out, setno);
2349 sr->u.request->maximumRecords = odr_intdup(out, nos);
2351 sr->u.request->recordSchema = schema;
2352 return send_srw(sr);
2356 static void close_session (void)
2363 nmem_destroy (session_mem);
2372 void process_close(Z_Close *req)
2374 Z_APDU *apdu = zget_APDU(out, Z_APDU_close);
2375 Z_Close *res = apdu->u.close;
2377 static char *reasons[] =
2382 "cost limit reached",
2384 "security violation",
2391 printf("Reason: %s, message: %s\n", reasons[*req->closeReason],
2392 req->diagnosticInformation ? req->diagnosticInformation : "NULL");
2397 *res->closeReason = Z_Close_finished;
2399 printf("Sent response.\n");
2404 static int cmd_show(const char *arg)
2406 if (protocol == PROTO_HTTP)
2411 if (!send_SRW_presentRequest(arg))
2421 printf("Not connected yet\n");
2424 if (!send_presentRequest(arg))
2430 int cmd_quit(const char *arg)
2432 printf("See you later, alligator.\n");
2438 int cmd_cancel(const char *arg)
2440 Z_APDU *apdu = zget_APDU(out, Z_APDU_triggerResourceControlRequest);
2441 Z_TriggerResourceControlRequest *req =
2442 apdu->u.triggerResourceControlRequest;
2447 printf("Session not initialized yet\n");
2452 if (!ODR_MASK_GET(session->options, Z_Options_triggerResourceCtrl))
2454 printf("Target doesn't support cancel (trigger resource ctrl)\n");
2457 *req->requestedAction = Z_TriggerResourceCtrl_cancel;
2458 req->resultSetWanted = &rfalse;
2461 printf("Sent cancel request\n");
2465 int send_scanrequest(const char *query, int pp, int num, const char *term)
2467 Z_APDU *apdu = zget_APDU(out, Z_APDU_scanRequest);
2468 Z_ScanRequest *req = apdu->u.scanRequest;
2473 if (queryType == QueryType_CCL2RPN)
2477 struct ccl_rpn_node *rpn;
2479 rpn = ccl_find_str (bibset, query, &error, &pos);
2482 printf("CCL ERROR: %s\n", ccl_err_msg(error));
2485 bib1.proto = PROTO_Z3950;
2486 bib1.oclass = CLASS_ATTSET;
2487 bib1.value = VAL_BIB1;
2488 req->attributeSet = oid_ent_to_oid (&bib1, oid);
2489 if (!(req->termListAndStartPoint = ccl_scan_query (out, rpn)))
2491 printf("Couldn't convert CCL to Scan term\n");
2494 ccl_rpn_delete (rpn);
2498 YAZ_PQF_Parser pqf_parser = yaz_pqf_create ();
2500 if (!(req->termListAndStartPoint =
2501 yaz_pqf_scan(pqf_parser, out, &req->attributeSet, query)))
2503 const char *pqf_msg;
2505 int code = yaz_pqf_error (pqf_parser, &pqf_msg, &off);
2506 printf("%*s^\n", off+7, "");
2507 printf("Prefix query error: %s (code %d)\n", pqf_msg, code);
2508 yaz_pqf_destroy (pqf_parser);
2511 yaz_pqf_destroy (pqf_parser);
2515 if (req->termListAndStartPoint->term &&
2516 req->termListAndStartPoint->term->which == Z_Term_general &&
2517 req->termListAndStartPoint->term->u.general)
2519 req->termListAndStartPoint->term->u.general->buf =
2520 (unsigned char *) odr_strdup(out, term);
2521 req->termListAndStartPoint->term->u.general->len =
2522 req->termListAndStartPoint->term->u.general->size =
2526 req->referenceId = set_refid (out);
2527 req->num_databaseNames = num_databaseNames;
2528 req->databaseNames = databaseNames;
2529 req->numberOfTermsRequested = #
2530 req->preferredPositionInResponse = &pp;
2535 int send_sortrequest(const char *arg, int newset)
2537 Z_APDU *apdu = zget_APDU(out, Z_APDU_sortRequest);
2538 Z_SortRequest *req = apdu->u.sortRequest;
2539 Z_SortKeySpecList *sksl = (Z_SortKeySpecList *)
2540 odr_malloc (out, sizeof(*sksl));
2546 sprintf (setstring, "%d", setnumber);
2548 sprintf (setstring, "default");
2550 req->referenceId = set_refid (out);
2552 req->num_inputResultSetNames = 1;
2553 req->inputResultSetNames = (Z_InternationalString **)
2554 odr_malloc (out, sizeof(*req->inputResultSetNames));
2555 req->inputResultSetNames[0] = odr_strdup (out, setstring);
2557 if (newset && setnumber >= 0)
2558 sprintf (setstring, "%d", ++setnumber);
2560 req->sortedResultSetName = odr_strdup (out, setstring);
2562 req->sortSequence = yaz_sort_spec (out, arg);
2563 if (!req->sortSequence)
2565 printf ("Missing sort specifications\n");
2572 void display_term(Z_TermInfo *t)
2574 if (t->term->which == Z_Term_general)
2576 printf("%.*s", t->term->u.general->len, t->term->u.general->buf);
2577 sprintf(last_scan_line, "%.*s", t->term->u.general->len,
2578 t->term->u.general->buf);
2581 printf("Term (not general)");
2582 if (t->globalOccurrences)
2583 printf (" (%d)\n", *t->globalOccurrences);
2588 void process_scanResponse(Z_ScanResponse *res)
2591 Z_Entry **entries = NULL;
2592 int num_entries = 0;
2594 printf("Received ScanResponse\n");
2595 print_refid (res->referenceId);
2596 printf("%d entries", *res->numberOfEntriesReturned);
2597 if (res->positionOfTerm)
2598 printf (", position=%d", *res->positionOfTerm);
2600 if (*res->scanStatus != Z_Scan_success)
2601 printf("Scan returned code %d\n", *res->scanStatus);
2604 if ((entries = res->entries->entries))
2605 num_entries = res->entries->num_entries;
2606 for (i = 0; i < num_entries; i++)
2608 int pos_term = res->positionOfTerm ? *res->positionOfTerm : -1;
2609 if (entries[i]->which == Z_Entry_termInfo)
2611 printf("%c ", i + 1 == pos_term ? '*' : ' ');
2612 display_term(entries[i]->u.termInfo);
2615 display_diagrecs(&entries[i]->u.surrogateDiagnostic, 1);
2617 if (res->entries->nonsurrogateDiagnostics)
2618 display_diagrecs (res->entries->nonsurrogateDiagnostics,
2619 res->entries->num_nonsurrogateDiagnostics);
2622 void process_sortResponse(Z_SortResponse *res)
2624 printf("Received SortResponse: status=");
2625 switch (*res->sortStatus)
2627 case Z_SortStatus_success:
2628 printf ("success"); break;
2629 case Z_SortStatus_partial_1:
2630 printf ("partial"); break;
2631 case Z_SortStatus_failure:
2632 printf ("failure"); break;
2634 printf ("unknown (%d)", *res->sortStatus);
2637 print_refid (res->referenceId);
2638 if (res->diagnostics)
2639 display_diagrecs(res->diagnostics,
2640 res->num_diagnostics);
2643 void process_deleteResultSetResponse (Z_DeleteResultSetResponse *res)
2645 printf("Got deleteResultSetResponse status=%d\n",
2646 *res->deleteOperationStatus);
2647 if (res->deleteListStatuses)
2650 for (i = 0; i < res->deleteListStatuses->num; i++)
2652 printf ("%s status=%d\n", res->deleteListStatuses->elements[i]->id,
2653 *res->deleteListStatuses->elements[i]->status);
2658 int cmd_sort_generic(const char *arg, int newset)
2662 printf("Session not initialized yet\n");
2667 if (!ODR_MASK_GET(session->options, Z_Options_sort))
2669 printf("Target doesn't support sort\n");
2674 if (send_sortrequest(arg, newset) < 0)
2681 int cmd_sort(const char *arg)
2683 return cmd_sort_generic (arg, 0);
2686 int cmd_sort_newset (const char *arg)
2688 return cmd_sort_generic (arg, 1);
2691 int cmd_scan(const char *arg)
2700 printf("Session not initialized yet\n");
2704 if (!ODR_MASK_GET(session->options, Z_Options_scan))
2706 printf("Target doesn't support scan\n");
2711 strcpy (last_scan_query, arg);
2712 if (send_scanrequest(arg, 1, 20, 0) < 0)
2717 if (send_scanrequest(last_scan_query, 1, 20, last_scan_line) < 0)
2723 int cmd_schema(const char *arg)
2728 schema = xstrdup(arg);
2732 int cmd_format(const char *arg)
2737 printf("Usage: format <recordsyntax>\n");
2740 nsyntax = oid_getvalbyname (arg);
2741 if (strcmp(arg, "none") && nsyntax == VAL_NONE)
2743 printf ("unknown record syntax\n");
2746 recordsyntax = nsyntax;
2750 int cmd_elements(const char *arg)
2752 static Z_ElementSetNames esn;
2753 static char what[100];
2757 elementSetNames = 0;
2761 esn.which = Z_ElementSetNames_generic;
2762 esn.u.generic = what;
2763 elementSetNames = &esn;
2767 int cmd_attributeset(const char *arg)
2773 printf("Usage: attributeset <setname>\n");
2776 sscanf(arg, "%s", what);
2777 if (p_query_attset (what))
2779 printf("Unknown attribute set name\n");
2785 int cmd_querytype (const char *arg)
2787 if (!strcmp (arg, "ccl"))
2788 queryType = QueryType_CCL;
2789 else if (!strcmp (arg, "prefix") || !strcmp(arg, "rpn"))
2790 queryType = QueryType_Prefix;
2791 else if (!strcmp (arg, "ccl2rpn") || !strcmp (arg, "cclrpn"))
2792 queryType = QueryType_CCL2RPN;
2793 else if (!strcmp(arg, "cql"))
2794 queryType = QueryType_CQL;
2795 else if (!strcmp (arg, "cql2rpn") || !strcmp (arg, "cqlrpn"))
2796 queryType = QueryType_CQL2RPN;
2799 printf ("Querytype must be one of:\n");
2800 printf (" prefix - Prefix query\n");
2801 printf (" ccl - CCL query\n");
2802 printf (" ccl2rpn - CCL query converted to RPN\n");
2803 printf (" cql - CQL\n");
2804 printf (" cql2rpn - CQL query converted to RPN\n");
2810 int cmd_refid (const char *arg)
2816 refid = (char *) xmalloc (strlen(arg)+1);
2817 strcpy (refid, arg);
2822 int cmd_close(const char *arg)
2831 apdu = zget_APDU(out, Z_APDU_close);
2832 req = apdu->u.close;
2833 *req->closeReason = Z_Close_finished;
2835 printf("Sent close request.\n");
2840 int cmd_packagename(const char* arg)
2842 xfree (esPackageName);
2843 esPackageName = NULL;
2845 esPackageName = xstrdup(arg);
2849 int cmd_proxy(const char* arg)
2854 yazProxy = xstrdup (arg);
2858 int cmd_marccharset(const char *arg)
2863 if (sscanf(arg, "%29s", l1) < 1)
2865 xfree (marcCharset);
2867 if (strcmp(l1, "-"))
2868 marcCharset = xstrdup(l1);
2872 int cmd_charset(const char* arg)
2874 char l1[30], l2[30];
2877 if (sscanf(arg, "%29s %29s", l1, l2) < 1)
2879 printf("Current negotiation character set is `%s'\n",
2880 negotiationCharset ? negotiationCharset: "none");
2881 printf("Current output character set is `%s'\n",
2882 outputCharset ? outputCharset: "none");
2885 xfree (negotiationCharset);
2886 negotiationCharset = NULL;
2887 if (*l1 && strcmp(l1, "-"))
2889 negotiationCharset = xstrdup(l1);
2890 printf ("Character set negotiation : %s\n", negotiationCharset);
2893 printf ("Character set negotiation disabled\n");
2896 xfree (outputCharset);
2898 if (!strcmp(l2, "auto") && codeset)
2902 printf ("output charset: %s\n", codeset);
2903 outputCharset = xstrdup(codeset);
2908 printf ("No codeset found on this system\n");
2910 else if (strcmp(l2, "-"))
2911 outputCharset = xstrdup(l2);
2913 printf ("Output charset conversion disabled\n");
2919 int cmd_lang(const char* arg)
2922 printf("Current language is `%s'\n", (yazLang)?yazLang:NULL);
2929 yazLang = (char *) xmalloc (strlen(arg)+1);
2930 strcpy (yazLang, arg);
2935 int cmd_source(const char* arg)
2937 /* first should open the file and read one line at a time.. */
2939 char line[1024], *cp;
2942 fprintf(stderr,"Error in source command use a filename\n");
2946 includeFile = fopen (arg, "r");
2949 fprintf(stderr,"Unable to open file %s for reading\n",arg);
2953 while(!feof(includeFile)) {
2954 memset(line,0,sizeof(line));
2955 fgets(line,sizeof(line),includeFile);
2957 if(strlen(line) < 2) continue;
2958 if(line[0] == '#') continue;
2960 if ((cp = strrchr (line, '\n')))
2963 process_cmd_line(line);
2966 if(fclose(includeFile)<0) {
2967 perror("unable to close include file");
2973 int cmd_subshell(const char* args)
2978 system(getenv("SHELL"));
2984 int cmd_set_berfile(const char *arg)
2986 if (ber_file && ber_file != stdout && ber_file != stderr)
2988 if (!strcmp(arg, ""))
2990 else if (!strcmp(arg, "-"))
2993 ber_file = fopen(arg, "a");
2997 int cmd_set_apdufile(const char *arg)
2999 if(apdu_file && apdu_file != stderr && apdu_file != stderr)
3001 if (!strcmp(arg, ""))
3003 else if (!strcmp(arg, "-"))
3007 apdu_file = fopen(arg, "a");
3009 perror("unable to open apdu log file");
3012 odr_setprint(print, apdu_file);
3016 int cmd_set_cclfile(const char* arg)
3020 bibset = ccl_qual_mk ();
3021 inf = fopen (arg, "r");
3023 perror("unable to open CCL file");
3026 ccl_qual_file (bibset, inf);
3029 strcpy(ccl_fields,arg);
3033 int cmd_set_cqlfile(const char* arg)
3035 cql_transform_t newcqltrans;
3037 if ((newcqltrans = cql_transform_open_fname(arg)) == 0) {
3038 perror("unable to open CQL file");
3042 cql_transform_close(cqltrans);
3044 cqltrans = newcqltrans;
3045 strcpy(cql_fields, arg);
3049 int cmd_set_auto_reconnect(const char* arg)
3051 if(strlen(arg)==0) {
3052 auto_reconnect = ! auto_reconnect;
3053 } else if(strcmp(arg,"on")==0) {
3055 } else if(strcmp(arg,"off")==0) {
3058 printf("Error use on or off\n");
3063 printf("Set auto reconnect enabled.\n");
3065 printf("Set auto reconnect disabled.\n");
3070 int cmd_set_marcdump(const char* arg)
3072 if(marc_file && marc_file != stderr) { /* don't close stdout*/
3076 if (!strcmp(arg, ""))
3078 else if (!strcmp(arg, "-"))
3082 marc_file = fopen(arg, "a");
3084 perror("unable to open marc log file");
3090 this command takes 3 arge {name class oid}
3092 int cmd_register_oid(const char* args) {
3097 {"appctx",CLASS_APPCTX},
3098 {"absyn",CLASS_ABSYN},
3099 {"attset",CLASS_ATTSET},
3100 {"transyn",CLASS_TRANSYN},
3101 {"diagset",CLASS_DIAGSET},
3102 {"recsyn",CLASS_RECSYN},
3103 {"resform",CLASS_RESFORM},
3104 {"accform",CLASS_ACCFORM},
3105 {"extserv",CLASS_EXTSERV},
3106 {"userinfo",CLASS_USERINFO},
3107 {"elemspec",CLASS_ELEMSPEC},
3108 {"varset",CLASS_VARSET},
3109 {"schema",CLASS_SCHEMA},
3110 {"tagset",CLASS_TAGSET},
3111 {"general",CLASS_GENERAL},
3112 {0,(enum oid_class) 0}
3114 char oname_str[101], oclass_str[101], oid_str[101];
3117 oid_class oidclass = CLASS_GENERAL;
3118 int val = 0, oid[OID_SIZE];
3119 struct oident * new_oident=NULL;
3121 if (sscanf (args, "%100[^ ] %100[^ ] %100s",
3122 oname_str,oclass_str, oid_str) < 1) {
3123 printf("Error in regristrate command \n");
3127 for (i = 0; oid_classes[i].className; i++) {
3128 if (!strcmp(oid_classes[i].className, oclass_str))
3130 oidclass=oid_classes[i].oclass;
3135 if(!(oid_classes[i].className)) {
3136 printf("Unknonwn oid class %s\n",oclass_str);
3144 while (isdigit (*name))
3146 val = val*10 + (*name - '0');
3159 new_oident=oid_addent (oid,PROTO_GENERAL,oidclass,oname_str,VAL_DYNAMIC);
3160 if(strcmp(new_oident->desc,oname_str)) {
3161 fprintf(stderr,"oid is already named as %s, regristration faild\n",
3167 int cmd_push_command(const char* arg)
3169 #if HAVE_READLINE_HISTORY_H
3173 fprintf(stderr,"Not compiled with the readline/history module\n");
3178 void source_rcfile()
3180 /* Look for a $HOME/.yazclientrc and source it if it exists */
3181 struct stat statbuf;
3183 char* homedir=getenv("HOME");
3185 if(!homedir) return;
3187 sprintf(buffer,"%s/.yazclientrc",homedir);
3189 if(stat(buffer,&statbuf)==0) {
3193 if(stat(".yazclientrc",&statbuf)==0) {
3194 cmd_source(".yazclientrc");
3199 static void initialize(void)
3204 if (!(out = odr_createmem(ODR_ENCODE)) ||
3205 !(in = odr_createmem(ODR_DECODE)) ||
3206 !(print = odr_createmem(ODR_PRINT)))
3208 fprintf(stderr, "failed to allocate ODR streams\n");
3213 setvbuf(stdout, 0, _IONBF, 0);
3215 odr_setprint(print, apdu_file);
3217 bibset = ccl_qual_mk ();
3218 inf = fopen (ccl_fields, "r");
3221 ccl_qual_file (bibset, inf);
3225 cqltrans = cql_transform_open_fname(cql_fields);
3226 /* If this fails, no problem: we detect cqltrans == 0 later */
3228 #if HAVE_READLINE_READLINE_H
3229 rl_attempted_completion_function = (CPPFunction*)readline_completer;
3233 for(i=0; i<maxOtherInfosSupported; ++i) {
3234 extraOtherInfos[i].oidval = -1;
3241 #if HAVE_GETTIMEOFDAY
3242 struct timeval tv_start, tv_end;
3246 static void handle_srw_response(Z_SRW_searchRetrieveResponse *res)
3250 printf ("Received SRW SearchRetrieve Response\n");
3252 for (i = 0; i<res->num_diagnostics; i++)
3254 printf ("SRW diagnostic %d %s\n",
3255 *res->diagnostics[i].code,
3256 yaz_diag_srw_str(*res->diagnostics[i].code));
3258 if (res->diagnostics[i].details)
3259 printf ("Details: %s\n", res->diagnostics[i].details);
3261 if (res->numberOfRecords)
3262 printf ("Number of hits: %d\n", *res->numberOfRecords);
3263 for (i = 0; i<res->num_records; i++)
3265 Z_SRW_record *rec = res->records + i;
3267 if (rec->recordPosition)
3269 printf ("pos=%d", *rec->recordPosition);
3270 setno = *rec->recordPosition + 1;
3272 if (rec->recordSchema)
3273 printf (" schema=%s", rec->recordSchema);
3275 if (rec->recordData_buf && rec->recordData_len)
3277 fwrite(rec->recordData_buf, 1, rec->recordData_len, stdout);
3283 static void http_response(Z_HTTP_Response *hres)
3286 const char *content_type = z_HTTP_header_lookup(hres->headers,
3288 const char *connection_head = z_HTTP_header_lookup(hres->headers,
3290 if (content_type && !yaz_strcmp_del("text/xml", content_type, "; "))
3292 Z_SOAP *soap_package = 0;
3293 ODR o = odr_createmem(ODR_DECODE);
3294 Z_SOAP_Handler soap_handlers[2] = {
3295 {"http://www.loc.gov/zing/srw/v1.0/", 0,
3296 (Z_SOAP_fun) yaz_srw_codec},
3299 ret = z_soap_codec(o, &soap_package,
3300 &hres->content_buf, &hres->content_len,
3302 if (!ret && soap_package->which == Z_SOAP_generic &&
3303 soap_package->u.generic->no == 0)
3305 Z_SRW_PDU *sr = soap_package->u.generic->p;
3306 if (sr->which == Z_SRW_searchRetrieve_response)
3307 handle_srw_response(sr->u.response);
3311 else if (!ret && (soap_package->which == Z_SOAP_fault
3312 || soap_package->which == Z_SOAP_error))
3314 printf ("HTTP Error Status=%d\n", hres->code);
3315 printf ("SOAP Fault code %s\n",
3316 soap_package->u.fault->fault_code);
3317 printf ("SOAP Fault string %s\n",
3318 soap_package->u.fault->fault_string);
3326 if (hres->code != 200)
3328 printf ("HTTP Error Status=%d\n", hres->code);
3332 printf ("Decoding of SRW package failed\n");
3336 if (!strcmp(hres->version, "1.0"))
3338 /* HTTP 1.0: only if Keep-Alive we stay alive.. */
3339 if (!connection_head || strcmp(connection_head, "Keep-Alive"))
3344 /* HTTP 1.1: only if no close we stay alive .. */
3345 if (connection_head && !strcmp(connection_head, "close"))
3351 void wait_and_handle_response()
3353 int reconnect_ok = 1;
3356 int netbufferlen = 0;
3361 res = cs_get(conn, &netbuffer, &netbufferlen);
3362 if (reconnect_ok && res <= 0 && protocol == PROTO_HTTP)
3373 buf_out = odr_getbuf(out, &len_out, 0);
3375 do_hex_dump(buf_out, len_out);
3377 cs_put(conn, buf_out, len_out);
3385 printf("Target closed connection\n");
3390 odr_reset(in); /* release APDU from last round */
3392 do_hex_dump(netbuffer, res);
3393 odr_setbuf(in, netbuffer, res, 0);
3395 if (!z_GDU(in, &gdu, 0, 0))
3397 FILE *f = ber_file ? ber_file : stdout;
3398 odr_perror(in, "Decoding incoming APDU");
3399 fprintf(f, "[Near %d]\n", odr_offset(in));
3400 fprintf(f, "Packet dump:\n---------\n");
3401 odr_dumpBER(f, netbuffer, res);
3402 fprintf(f, "---------\n");
3404 z_GDU(print, &gdu, 0, 0);
3405 if (conn && cs_more(conn))
3410 odr_dumpBER(ber_file, netbuffer, res);
3411 if (apdu_file && !z_GDU(print, &gdu, 0, 0))
3413 odr_perror(print, "Failed to print incoming APDU");
3417 if (gdu->which == Z_GDU_Z3950)
3419 Z_APDU *apdu = gdu->u.z3950;
3422 case Z_APDU_initResponse:
3423 process_initResponse(apdu->u.initResponse);
3425 case Z_APDU_searchResponse:
3426 process_searchResponse(apdu->u.searchResponse);
3428 case Z_APDU_scanResponse:
3429 process_scanResponse(apdu->u.scanResponse);
3431 case Z_APDU_presentResponse:
3432 print_refid (apdu->u.presentResponse->referenceId);
3434 *apdu->u.presentResponse->numberOfRecordsReturned;
3435 if (apdu->u.presentResponse->records)
3436 display_records(apdu->u.presentResponse->records);
3438 printf("No records.\n");
3439 printf ("nextResultSetPosition = %d\n",
3440 *apdu->u.presentResponse->nextResultSetPosition);
3442 case Z_APDU_sortResponse:
3443 process_sortResponse(apdu->u.sortResponse);
3445 case Z_APDU_extendedServicesResponse:
3446 printf("Got extended services response\n");
3447 process_ESResponse(apdu->u.extendedServicesResponse);
3450 printf("Target has closed the association.\n");
3451 process_close(apdu->u.close);
3453 case Z_APDU_resourceControlRequest:
3454 process_resourceControlRequest
3455 (apdu->u.resourceControlRequest);
3457 case Z_APDU_deleteResultSetResponse:
3458 process_deleteResultSetResponse(apdu->u.
3459 deleteResultSetResponse);
3462 printf("Received unknown APDU type (%d).\n",
3468 else if (gdu->which == Z_GDU_HTTP_Response)
3470 http_response(gdu->u.HTTP_Response);
3473 if (conn && !cs_more(conn))
3478 #if HAVE_GETTIMEOFDAY
3479 gettimeofday (&tv_end, 0);
3481 printf ("S/U S/U=%ld/%ld %ld/%ld",
3482 (long) tv_start.tv_sec,
3483 (long) tv_start.tv_usec,
3484 (long) tv_end.tv_sec,
3485 (long) tv_end.tv_usec);
3487 printf ("Elapsed: %.6f\n",
3488 (double) tv_end.tv_usec / 1e6 + tv_end.tv_sec -
3489 ((double) tv_start.tv_usec / 1e6 + tv_start.tv_sec));
3496 int cmd_cclparse(const char* arg)
3499 struct ccl_rpn_node *rpn=NULL;
3502 rpn = ccl_find_str (bibset, arg, &error, &pos);
3505 printf ("%*s^ - ", 3+strlen(last_cmd)+1+pos, " ");
3506 printf ("%s\n", ccl_err_msg (error));
3512 ccl_pr_tree(rpn, stdout);
3516 ccl_rpn_delete(rpn);
3524 int cmd_set_otherinfo(const char* args)
3526 char oid[101], otherinfoString[101];
3531 sscan_res = sscanf (args, "%d %100[^ ] %100s", &otherinfoNo, oid, otherinfoString);
3533 /* reset this otherinfo */
3534 if(otherinfoNo>=maxOtherInfosSupported) {
3535 printf("Error otherinfo index to large (%d>%d)\n",otherinfoNo,maxOtherInfosSupported);
3537 extraOtherInfos[otherinfoNo].oidval = -1;
3538 if(extraOtherInfos[otherinfoNo].value) free(extraOtherInfos[otherinfoNo].value);
3542 printf("Error in set_otherinfo command \n");
3546 if(otherinfoNo>=maxOtherInfosSupported) {
3547 printf("Error otherinfo index to large (%d>%d)\n",otherinfoNo,maxOtherInfosSupported);
3551 oidval = oid_getvalbyname (oid);
3553 printf("Error in set_otherinfo command unknown oid %s \n",oid);
3556 extraOtherInfos[otherinfoNo].oidval = oidval;
3557 if(extraOtherInfos[otherinfoNo].value) free(extraOtherInfos[otherinfoNo].value);
3558 extraOtherInfos[otherinfoNo].value = strdup(otherinfoString);
3563 int cmd_list_otherinfo(const char* args)
3567 if(strlen(args)>0) {
3569 if( i >= maxOtherInfosSupported ) {
3570 printf("Error otherinfo index to large (%d>%d)\n",i,maxOtherInfosSupported);
3574 if(extraOtherInfos[i].oidval != -1)
3575 printf(" otherinfo %d %s %s\n",
3577 yaz_z3950_oid_value_to_str(
3578 (enum oid_value) extraOtherInfos[i].oidval,
3580 extraOtherInfos[i].value);
3583 for(i=0; i<maxOtherInfosSupported; ++i) {
3584 if(extraOtherInfos[i].oidval != -1)
3585 printf(" otherinfo %d %s %s\n",
3587 yaz_z3950_oid_value_to_str(
3588 (enum oid_value) extraOtherInfos[i].oidval,
3590 extraOtherInfos[i].value);
3598 int cmd_list_all(const char* args) {
3601 /* connection options */
3603 printf("Connected to : %s\n",last_open_command);
3605 if(last_open_command)
3606 printf("Not connected to : %s\n",last_open_command);
3608 printf("Not connected : \n");
3611 if(yazProxy) printf("using proxy : %s\n",yazProxy);
3613 printf("auto_reconnect : %s\n",auto_reconnect?"on":"off");
3616 printf("Authentication : none\n");
3618 switch(auth->which) {
3619 case Z_IdAuthentication_idPass:
3620 printf("Authentication : IdPass\n");
3621 printf(" Login User : %s\n",auth->u.idPass->userId?auth->u.idPass->userId:"");
3622 printf(" Login Group : %s\n",auth->u.idPass->groupId?auth->u.idPass->groupId:"");
3623 printf(" Password : %s\n",auth->u.idPass->password?auth->u.idPass->password:"");
3625 case Z_IdAuthentication_open:
3626 printf("Authentication : psOpen\n");
3627 printf(" Open string : %s\n",auth->u.open);
3630 printf("Authentication : Unknown\n");
3633 if (negotiationCharset)
3634 printf("Neg. Character set : `%s'\n", negotiationCharset);
3638 for (i = 0; i<num_databaseNames; i++) printf("%s ",databaseNames[i]);
3642 printf("CCL file : %s\n",ccl_fields);
3643 printf("CQL file : %s\n",cql_fields);
3644 printf("Query type : %s\n",query_type_as_string(queryType));
3646 printf("Named Result Sets : %s\n",setnumber==-1?"off":"on");
3648 /* piggy back options */
3649 printf("ssub/lslb/mspn : %d/%d/%d\n",smallSetUpperBound,largeSetLowerBound,mediumSetPresentNumber);
3651 /* print present related options */
3652 printf("Format : %s\n",yaz_z3950_oid_value_to_str(recordsyntax,CLASS_RECSYN));
3653 printf("Schema : %s\n",schema);
3654 printf("Elements : %s\n",elementSetNames?elementSetNames->u.generic:"");
3656 /* loging options */
3657 printf("APDU log : %s\n",apdu_file?"on":"off");
3658 printf("Record log : %s\n",marc_file?"on":"off");
3661 printf("Other Info: \n");
3662 cmd_list_otherinfo("");
3667 int cmd_clear_otherinfo(const char* args)
3669 if(strlen(args)>0) {
3671 otherinfoNo = atoi(args);
3672 if( otherinfoNo >= maxOtherInfosSupported ) {
3673 printf("Error otherinfo index to large (%d>%d)\n",otherinfoNo,maxOtherInfosSupported);
3677 if(extraOtherInfos[otherinfoNo].oidval != -1) {
3678 /* only clear if set. */
3679 extraOtherInfos[otherinfoNo].oidval=-1;
3680 free(extraOtherInfos[otherinfoNo].value);
3685 for(i=0; i<maxOtherInfosSupported; ++i) {
3686 if (extraOtherInfos[i].oidval!=-1 ) {
3687 extraOtherInfos[i].oidval=-1;
3688 free(extraOtherInfos[i].value);
3695 static int cmd_help (const char *line);
3697 typedef char *(*completerFunctionType)(const char *text, int state);
3701 int (*fun)(const char *arg);
3703 completerFunctionType rl_completerfunction;
3704 int complete_filenames;
3705 char **local_tabcompletes;
3707 {"open", cmd_open, "('tcp'|'ssl')':<host>[':'<port>][/<db>]",NULL,0,NULL},
3708 {"quit", cmd_quit, "",NULL,0,NULL},
3709 {"find", cmd_find, "<query>",NULL,0,NULL},
3710 {"delete", cmd_delete, "<setname>",NULL,0,NULL},
3711 {"base", cmd_base, "<base-name>",NULL,0,NULL},
3712 {"show", cmd_show, "<rec#>['+'<#recs>['+'<setname>]]",NULL,0,NULL},
3713 {"scan", cmd_scan, "<term>",NULL,0,NULL},
3714 {"sort", cmd_sort, "<sortkey> <flag> <sortkey> <flag> ...",NULL,0,NULL},
3715 {"sort+", cmd_sort_newset, "<sortkey> <flag> <sortkey> <flag> ...",NULL,0,NULL},
3716 {"authentication", cmd_authentication, "<acctstring>",NULL,0,NULL},
3717 {"lslb", cmd_lslb, "<largeSetLowerBound>",NULL,0,NULL},
3718 {"ssub", cmd_ssub, "<smallSetUpperBound>",NULL,0,NULL},
3719 {"mspn", cmd_mspn, "<mediumSetPresentNumber>",NULL,0,NULL},
3720 {"status", cmd_status, "",NULL,0,NULL},
3721 {"setnames", cmd_setnames, "",NULL,0,NULL},
3722 {"cancel", cmd_cancel, "",NULL,0,NULL},
3723 {"format", cmd_format, "<recordsyntax>",complete_format,0,NULL},
3724 {"schema", cmd_schema, "<schema>",complete_schema,0,NULL},
3725 {"elements", cmd_elements, "<elementSetName>",NULL,0,NULL},
3726 {"close", cmd_close, "",NULL,0,NULL},
3727 {"attributeset", cmd_attributeset, "<attrset>",complete_attributeset,0,NULL},
3728 {"querytype", cmd_querytype, "<type>",complete_querytype,0,NULL},
3729 {"refid", cmd_refid, "<id>",NULL,0,NULL},
3730 {"itemorder", cmd_itemorder, "ill|item <itemno>",NULL,0,NULL},
3731 {"update", cmd_update, "<action> <recid> [<file>]",NULL,0,NULL},
3732 {"update0", cmd_update0, "<action> <recid> [<file>]",NULL,0,NULL},
3733 {"packagename", cmd_packagename, "<packagename>",NULL,0,NULL},
3734 {"proxy", cmd_proxy, "[('tcp'|'ssl')]<host>[':'<port>]",NULL,0,NULL},
3735 {"charset", cmd_charset, "<nego_charset> <output_charset>",NULL,0,NULL},
3736 {"marccharset", cmd_marccharset, "<charset_name>",NULL,0,NULL},
3737 {"lang", cmd_lang, "<language_code>",NULL,0,NULL},
3738 {".", cmd_source, "<filename>",NULL,1,NULL},
3739 {"!", cmd_subshell, "Subshell command",NULL,1,NULL},
3740 {"set_apdufile", cmd_set_apdufile, "<filename>",NULL,1,NULL},
3741 {"set_berfile", cmd_set_berfile, "<filename>",NULL,1,NULL},
3742 {"set_marcdump", cmd_set_marcdump," <filename>",NULL,1,NULL},
3743 {"set_cclfile", cmd_set_cclfile," <filename>",NULL,1,NULL},
3744 {"set_cqlfile", cmd_set_cqlfile," <filename>",NULL,1,NULL},
3745 {"set_auto_reconnect", cmd_set_auto_reconnect," on|off",complete_auto_reconnect,1,NULL},
3746 {"set_otherinfo", cmd_set_otherinfo,"<otherinfoinddex> <oid> <string>",NULL,0,NULL},
3747 {"register_oid", cmd_register_oid,"<name> <class> <oid>",NULL,0,NULL},
3748 {"push_command", cmd_push_command,"<command>",command_generator,0,NULL},
3749 {"register_tab", cmd_register_tab,"<commandname> <tab>",command_generator,0,NULL},
3750 {"cclparse", cmd_cclparse,"<ccl find command>",NULL,0,NULL},
3751 {"list_otherinfo",cmd_list_otherinfo,"[otherinfoinddex]",NULL,0,NULL},
3752 {"list_all",cmd_list_all,"",NULL,0,NULL},
3753 {"clear_otherinfo",cmd_clear_otherinfo,"",NULL,0,NULL},
3754 /* Server Admin Functions */
3755 {"adm-reindex", cmd_adm_reindex, "<database-name>",NULL,0,NULL},
3756 {"adm-truncate", cmd_adm_truncate, "('database'|'index')<object-name>",NULL,0,NULL},
3757 {"adm-create", cmd_adm_create, "",NULL,0,NULL},
3758 {"adm-drop", cmd_adm_drop, "('database'|'index')<object-name>",NULL,0,NULL},
3759 {"adm-import", cmd_adm_import, "<record-type> <dir> <pattern>",NULL,0,NULL},
3760 {"adm-refresh", cmd_adm_refresh, "",NULL,0,NULL},
3761 {"adm-commit", cmd_adm_commit, "",NULL,0,NULL},
3762 {"adm-shutdown", cmd_adm_shutdown, "",NULL,0,NULL},
3763 {"adm-startup", cmd_adm_startup, "",NULL,0,NULL},
3764 {"help", cmd_help, "", NULL,0,NULL},
3768 static int cmd_help (const char *line)
3774 sscanf (line, "%20s", topic);
3777 printf("Commands:\n");
3778 for (i = 0; cmd_array[i].cmd; i++)
3779 if (*topic == 0 || strcmp (topic, cmd_array[i].cmd) == 0)
3780 printf(" %s %s\n", cmd_array[i].cmd, cmd_array[i].ad);
3781 if (strcmp (topic, "find") == 0)
3784 printf (" \"term\" Simple Term\n");
3785 printf (" @attr [attset] type=value op Attribute\n");
3786 printf (" @and opl opr And\n");
3787 printf (" @or opl opr Or\n");
3788 printf (" @not opl opr And-Not\n");
3789 printf (" @set set Result set\n");
3791 printf ("Bib-1 attribute types\n");
3793 printf ("4=Title 7=ISBN 8=ISSN 30=Date 62=Abstract 1003=Author 1016=Any\n");
3794 printf ("2=Relation: ");
3795 printf ("1< 2<= 3= 4>= 5> 6!= 102=Relevance\n");
3796 printf ("3=Position: ");
3797 printf ("1=First in Field 2=First in subfield 3=Any position\n");
3798 printf ("4=Structure: ");
3799 printf ("1=Phrase 2=Word 3=Key 4=Year 5=Date 6=WordList\n");
3800 printf ("5=Truncation: ");
3801 printf ("1=Right 2=Left 3=L&R 100=No 101=# 102=Re-1 103=Re-2\n");
3802 printf ("6=Completeness:");
3803 printf ("1=Incomplete subfield 2=Complete subfield 3=Complete field\n");
3808 int cmd_register_tab(const char* arg) {
3810 char command[101], tabargument[101];
3815 if (sscanf (arg, "%100s %100s", command, tabargument) < 1) {
3819 /* locate the amdn in the list */
3820 for (i = 0; cmd_array[i].cmd; i++) {
3821 if (!strncmp(cmd_array[i].cmd, command, strlen(command))) {
3826 if(!cmd_array[i].cmd) {
3827 fprintf(stderr,"Unknown command %s\n",command);
3832 if(!cmd_array[i].local_tabcompletes)
3833 cmd_array[i].local_tabcompletes = (char **) calloc(1,sizeof(char**));
3837 tabslist = cmd_array[i].local_tabcompletes;
3838 for(;tabslist && *tabslist;tabslist++) {
3842 cmd_array[i].local_tabcompletes = (char **)
3843 realloc(cmd_array[i].local_tabcompletes,(num_of_tabs+2)*sizeof(char**));
3844 tabslist=cmd_array[i].local_tabcompletes;
3845 tabslist[num_of_tabs]=strdup(tabargument);
3846 tabslist[num_of_tabs+1]=NULL;
3851 void process_cmd_line(char* line)
3854 char word[32], arg[1024];
3856 #if HAVE_GETTIMEOFDAY
3857 gettimeofday (&tv_start, 0);
3860 if ((res = sscanf(line, "%31s %1023[^;]", word, arg)) <= 0)
3862 strcpy(word, last_cmd);
3867 strcpy(last_cmd, word);
3869 /* removed tailing spaces from the arg command */
3872 char* lastnonspace=NULL;
3880 *(++lastnonspace) = 0;
3883 for (i = 0; cmd_array[i].cmd; i++)
3884 if (!strncmp(cmd_array[i].cmd, word, strlen(word)))
3886 res = (*cmd_array[i].fun)(arg);
3890 if (!cmd_array[i].cmd) /* dump our help-screen */
3892 printf("Unknown command: %s.\n", word);
3893 printf("use help for list of commands\n");
3894 /* cmd_help (""); */
3898 if(apdu_file) fflush(apdu_file);
3901 wait_and_handle_response();
3910 char *command_generator(const char *text, int state)
3916 for( ; cmd_array[idx].cmd; ++idx) {
3917 if (!strncmp(cmd_array[idx].cmd,text,strlen(text))) {
3918 ++idx; /* skip this entry on the next run */
3919 return strdup(cmd_array[idx-1].cmd);
3927 This function only known how to complete on the first word
3929 char ** readline_completer(char *text, int start, int end) {
3930 #if HAVE_READLINE_READLINE_H
3932 completerFunctionType completerToUse;
3935 #if HAVE_READLINE_RL_COMPLETION_MATCHES
3936 char** res=rl_completion_matches(text,
3939 char** res=completion_matches(text,
3940 (CPFunction*)command_generator);
3942 rl_attempted_completion_over = 1;
3945 char arg[1024],word[32];
3947 if ((res = sscanf(rl_line_buffer, "%31s %1023[^;]", word, arg)) <= 0) {
3948 rl_attempted_completion_over = 1;
3952 for (i = 0; cmd_array[i].cmd; i++) {
3953 if (!strncmp(cmd_array[i].cmd, word, strlen(word))) {
3958 if(!cmd_array[i].cmd) return NULL;
3960 curret_global_list = cmd_array[i].local_tabcompletes;
3962 completerToUse = cmd_array[i].rl_completerfunction;
3963 if(completerToUse==NULL) /* if no pr. command completer is defined use the default completer */
3964 completerToUse = default_completer;
3966 if(completerToUse) {
3967 #ifdef HAVE_READLINE_RL_COMPLETION_MATCHES
3969 rl_completion_matches(text,
3973 completion_matches(text,
3974 (CPFunction*)completerToUse);
3976 if(!cmd_array[i].complete_filenames)
3977 rl_attempted_completion_over = 1;
3980 if(!cmd_array[i].complete_filenames)
3981 rl_attempted_completion_over = 1;
3991 static void client(void)
3997 #if HAVE_GETTIMEOFDAY
3998 gettimeofday (&tv_start, 0);
4003 char *line_in = NULL;
4004 #if HAVE_READLINE_READLINE_H
4007 line_in=readline(C_PROMPT);
4010 #if HAVE_READLINE_HISTORY_H
4012 add_history(line_in);
4014 strncpy(line, line_in, 1023);
4023 if (!fgets(line, 1023, stdin))
4025 if ((end_p = strchr (line, '\n')))
4028 process_cmd_line(line);
4032 static void show_version(void)
4036 yaz_version(vstr, 0);
4037 printf ("YAZ version: %s\n", YAZ_VERSION);
4038 if (strcmp(vstr, YAZ_VERSION))
4039 printf ("YAZ DLL/SO: %s\n", vstr);
4043 int main(int argc, char **argv)
4046 char *open_command = 0;
4047 char *auth_command = 0;
4052 if (!setlocale(LC_CTYPE, ""))
4053 fprintf (stderr, "setlocale failed\n");
4057 codeset = nl_langinfo(CODESET);
4061 outputCharset = xstrdup(codeset);
4063 while ((ret = options("k:c:q:a:b:m:v:p:u:t:Vxd:", argv, argc, &arg)) != -2)
4070 open_command = (char *) xmalloc (strlen(arg)+6);
4071 strcpy (open_command, "open ");
4072 strcat (open_command, arg);
4076 dump_file_prefix = arg;
4079 kilobytes = atoi(arg);
4082 if (!(marc_file = fopen (arg, "a")))
4089 outputCharset = xstrdup(arg);
4092 strncpy (ccl_fields, arg, sizeof(ccl_fields)-1);
4093 ccl_fields[sizeof(ccl_fields)-1] = '\0';
4096 strncpy (cql_fields, arg, sizeof(cql_fields)-1);
4097 cql_fields[sizeof(cql_fields)-1] = '\0';
4100 if (!strcmp(arg, "-"))
4103 ber_file=fopen(arg, "a");
4106 if (!strcmp(arg, "-"))
4109 apdu_file=fopen(arg, "a");
4115 yazProxy=strdup(arg);
4120 auth_command = (char *) xmalloc (strlen(arg)+6);
4121 strcpy (auth_command, "auth ");
4122 strcat (auth_command, arg);
4126 yaz_log_init(yaz_log_mask_str(arg), "", 0);
4132 fprintf (stderr, "Usage: %s [-m <marclog>] [ -a <apdulog>] "
4133 "[-b berdump] [-c cclfields] \n"
4134 "[-q cqlfields] [-p <proxy-addr>] [-u <auth>] "
4135 "[-k size] [-d dump] [-V] [<server-addr>]\n",
4143 #ifdef HAVE_GETTIMEOFDAY
4144 gettimeofday (&tv_start, 0);
4146 process_cmd_line (auth_command);
4147 #if HAVE_READLINE_HISTORY_H
4148 add_history(auth_command);
4150 xfree(auth_command);
4154 #ifdef HAVE_GETTIMEOFDAY
4155 gettimeofday (&tv_start, 0);
4157 process_cmd_line (open_command);
4158 #if HAVE_READLINE_HISTORY_H
4159 add_history(open_command);
4161 xfree(open_command);
4172 * vim600: sw=4 ts=8 fdm=marker
4173 * vim<600: sw=4 ts=8