2 * Copyright (c) 1995-2003, Index Data
3 * See the file LICENSE for details.
5 * $Id: client.c,v 1.210 2003-10-21 12:35:50 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", *dd->condition);
482 /* Both types of addinfo are the same, so use type-pun */
483 if (dd->u.v2Addinfo != 0)
484 printf(", addinfo='%s'", dd->u.v2Addinfo);
487 case Z_DiagnosticFormat_s_explicitDiagnostic:
488 printf("Explicit diagnostic (not supported)");
491 printf("Unrecognised diagnostic type %d", ds->which);
495 if (ds->message != 0)
496 printf(", message='%s'", ds->message);
502 static int set_base(const char *arg)
507 for (i = 0; i<num_databaseNames; i++)
508 xfree (databaseNames[i]);
509 num_databaseNames = 0;
513 if (!(cp = strchr(arg, ' ')))
514 cp = arg + strlen(arg);
517 databaseNames[num_databaseNames] = (char *)xmalloc (1 + cp - arg);
518 memcpy (databaseNames[num_databaseNames], arg, cp - arg);
519 databaseNames[num_databaseNames][cp - arg] = '\0';
521 for (cp1 = databaseNames[num_databaseNames]; *cp1 ; cp1++)
530 if (num_databaseNames == 0)
532 num_databaseNames = 1;
533 databaseNames[0] = xstrdup("");
538 static int cmd_base(const char *arg)
542 printf("Usage: base <database> <database> ...\n");
545 return set_base(arg);
548 void cmd_open_remember_last_open_command(const char* arg, char* new_open_command)
550 if(last_open_command != arg)
552 if(last_open_command) xfree(last_open_command);
553 last_open_command = xstrdup(new_open_command);
557 int session_connect(const char *arg)
560 char type_and_host[101];
561 const char *basep = 0;
568 nmem_destroy (session_mem);
572 cs_get_host_args(arg, &basep);
574 strncpy(type_and_host, arg, sizeof(type_and_host)-1);
575 type_and_host[sizeof(type_and_host)-1] = '\0';
577 cmd_open_remember_last_open_command(arg,type_and_host);
580 conn = cs_create_host(yazProxy, 1, &add);
582 conn = cs_create_host(arg, 1, &add);
585 printf ("Couldn't create comstack\n");
590 if (conn->protocol == PROTO_HTTP)
592 printf ("SRW/HTTP not enabled in this YAZ\n");
598 protocol = conn->protocol;
599 if (conn->protocol == PROTO_HTTP)
603 printf("Connecting...");
605 if (cs_connect(conn, add) < 0)
607 printf ("error = %s\n", cs_strerror(conn));
608 if (conn->cerrno == CSYSERR)
611 yaz_strerror(msg, sizeof(msg));
612 printf ("%s\n", msg);
621 if (protocol == PROTO_Z3950)
623 send_initRequest(type_and_host);
629 int cmd_open(const char *arg)
631 static char cur_host[200];
634 strncpy (cur_host, arg, sizeof(cur_host)-1);
635 cur_host[sizeof(cur_host)-1] = 0;
637 return session_connect(cur_host);
644 if(!( auto_reconnect && last_open_command) ) return ;
646 open_command = (char *) xmalloc (strlen(last_open_command)+6);
647 strcpy (open_command, "open ");
649 strcat (open_command, last_open_command);
651 process_cmd_line(open_command);
656 int cmd_authentication(const char *arg)
658 static Z_IdAuthentication au;
659 static char user[40], group[40], pass[40];
660 static Z_IdPass idPass;
665 printf("Auth field set to null\n");
669 r = sscanf (arg, "%39s %39s %39s", user, group, pass);
672 printf("Authentication set to null\n");
678 if (!strcmp(user, "-")) {
679 au.which = Z_IdAuthentication_anonymous;
680 printf("Authentication set to Anonymous\n");
682 au.which = Z_IdAuthentication_open;
684 printf("Authentication set to Open (%s)\n", user);
690 au.which = Z_IdAuthentication_idPass;
691 au.u.idPass = &idPass;
692 idPass.groupId = NULL;
693 idPass.userId = user;
694 idPass.password = group;
695 printf("Authentication set to User (%s), Pass (%s)\n", user, group);
700 au.which = Z_IdAuthentication_idPass;
701 au.u.idPass = &idPass;
702 idPass.groupId = group;
703 idPass.userId = user;
704 idPass.password = pass;
705 printf("Authentication set to User (%s), Group (%s), Pass (%s)\n",
711 /* SEARCH SERVICE ------------------------------ */
712 static void display_record(Z_External *r);
714 static void print_record(const unsigned char *buf, size_t len)
717 print_stringn (buf, len);
718 /* add newline if not already added ... */
719 if (i <= 0 || buf[i-1] != '\n')
723 static void display_record(Z_External *r)
725 oident *ent = oid_getentbyoid(r->direct_reference);
729 * Tell the user what we got.
731 if (r->direct_reference)
733 printf("Record type: ");
735 printf("%s\n", ent->desc);
736 else if (!odr_oid(print, &r->direct_reference, 0, 0))
738 odr_perror(print, "print oid");
742 /* Check if this is a known, ASN.1 type tucked away in an octet string */
743 if (ent && r->which == Z_External_octet)
745 Z_ext_typeent *type = z_ext_getentbyref(ent->value);
751 * Call the given decoder to process the record.
753 odr_setbuf(in, (char*)r->u.octet_aligned->buf,
754 r->u.octet_aligned->len, 0);
755 if (!(*type->fun)(in, (char **)&rr, 0, 0))
757 odr_perror(in, "Decoding constructed record.");
758 fprintf(stdout, "[Near %d]\n", odr_offset(in));
759 fprintf(stdout, "Packet dump:\n---------\n");
760 odr_dumpBER(stdout, (char*)r->u.octet_aligned->buf,
761 r->u.octet_aligned->len);
762 fprintf(stdout, "---------\n");
764 /* note just ignores the error ant print the bytes form the octet_aligned later */
767 * Note: we throw away the original, BER-encoded record here.
768 * Do something else with it if you want to keep it.
770 r->u.sutrs = (Z_SUTRS *) rr; /* we don't actually check the type here. */
771 r->which = type->what;
775 if (ent && ent->oclass != CLASS_RECSYN)
777 if (ent && ent->value == VAL_SOIF)
778 print_record((const unsigned char *) r->u.octet_aligned->buf,
779 r->u.octet_aligned->len);
780 else if (r->which == Z_External_octet)
782 const char *octet_buf = (char*)r->u.octet_aligned->buf;
783 if (ent->value == VAL_TEXT_XML || ent->value == VAL_APPLICATION_XML ||
784 ent->value == VAL_HTML)
786 print_record((const unsigned char *) octet_buf,
787 r->u.octet_aligned->len);
789 else if (ent->value == VAL_POSTSCRIPT)
791 int size = r->u.octet_aligned->len;
794 print_record((const unsigned char *) octet_buf, size);
799 #if AVOID_MARC_DECODE
800 /* primitive check for a marc OID 5.1-29 except 16 */
801 ent->oidsuffix[0] == 5 && ent->oidsuffix[1] < 30 &&
802 ent->oidsuffix[1] != 16
811 yaz_marc_t mt = yaz_marc_create();
813 if (yaz_marc_decode_buf(mt, octet_buf,r->u.octet_aligned->len,
817 if (marcCharset && !strcmp(marcCharset, "auto"))
819 if (ent->value == VAL_USMARC)
821 if (octet_buf[9] == 'a')
829 else if (marcCharset)
831 if (outputCharset && from)
833 cd = yaz_iconv_open(outputCharset, from);
834 printf ("convert from %s to %s", from,
837 printf (" unsupported\n");
842 fwrite (result, 1, rlen, stdout);
846 size_t inbytesleft = rlen;
847 const char *inp = result;
851 size_t outbytesleft = sizeof(outbuf);
855 r = yaz_iconv (cd, (char**) &inp,
857 &outp, &outbytesleft);
858 if (r == (size_t) (-1))
860 int e = yaz_iconv_error(cd);
861 if (e != YAZ_ICONV_E2BIG)
864 fwrite (outbuf, outp - outbuf, 1, stdout);
870 printf ("bad MARC. Dumping as it is:\n");
871 print_record((const unsigned char*) octet_buf,
872 r->u.octet_aligned->len);
874 yaz_marc_destroy(mt);
880 print_record((const unsigned char*) octet_buf,
881 r->u.octet_aligned->len);
885 fwrite (octet_buf, 1, r->u.octet_aligned->len, marc_file);
887 else if (ent && ent->value == VAL_SUTRS)
889 if (r->which != Z_External_sutrs)
891 printf("Expecting single SUTRS type for SUTRS.\n");
894 print_record(r->u.sutrs->buf, r->u.sutrs->len);
896 else if (ent && ent->value == VAL_GRS1)
899 if (r->which != Z_External_grs1)
901 printf("Expecting single GRS type for GRS.\n");
905 yaz_display_grs1(w, r->u.grs1, 0);
909 else if ( /* OPAC display not complete yet .. */
910 ent && ent->value == VAL_OPAC)
913 if (r->u.opac->bibliographicRecord)
914 display_record(r->u.opac->bibliographicRecord);
915 for (i = 0; i<r->u.opac->num_holdingsData; i++)
917 Z_HoldingsRecord *h = r->u.opac->holdingsData[i];
918 if (h->which == Z_HoldingsRecord_marcHoldingsRecord)
920 printf ("MARC holdings %d\n", i);
921 display_record(h->u.marcHoldingsRecord);
923 else if (h->which == Z_HoldingsRecord_holdingsAndCirc)
927 Z_HoldingsAndCircData *data = h->u.holdingsAndCirc;
929 printf ("Data holdings %d\n", i);
930 if (data->typeOfRecord)
931 printf ("typeOfRecord: %s\n", data->typeOfRecord);
932 if (data->encodingLevel)
933 printf ("encodingLevel: %s\n", data->encodingLevel);
934 if (data->receiptAcqStatus)
935 printf ("receiptAcqStatus: %s\n", data->receiptAcqStatus);
936 if (data->generalRetention)
937 printf ("generalRetention: %s\n", data->generalRetention);
938 if (data->completeness)
939 printf ("completeness: %s\n", data->completeness);
940 if (data->dateOfReport)
941 printf ("dateOfReport: %s\n", data->dateOfReport);
943 printf ("nucCode: %s\n", data->nucCode);
944 if (data->localLocation)
945 printf ("localLocation: %s\n", data->localLocation);
946 if (data->shelvingLocation)
947 printf ("shelvingLocation: %s\n", data->shelvingLocation);
948 if (data->callNumber)
949 printf ("callNumber: %s\n", data->callNumber);
950 if (data->copyNumber)
951 printf ("copyNumber: %s\n", data->copyNumber);
952 if (data->publicNote)
953 printf ("publicNote: %s\n", data->publicNote);
954 if (data->reproductionNote)
955 printf ("reproductionNote: %s\n", data->reproductionNote);
956 if (data->termsUseRepro)
957 printf ("termsUseRepro: %s\n", data->termsUseRepro);
958 if (data->enumAndChron)
959 printf ("enumAndChron: %s\n", data->enumAndChron);
960 for (j = 0; j<data->num_volumes; j++)
962 printf ("volume %d\n", j);
963 if (data->volumes[j]->enumeration)
964 printf (" enumeration: %s\n",
965 data->volumes[j]->enumeration);
966 if (data->volumes[j]->chronology)
967 printf (" chronology: %s\n",
968 data->volumes[j]->chronology);
969 if (data->volumes[j]->enumAndChron)
970 printf (" enumAndChron: %s\n",
971 data->volumes[j]->enumAndChron);
973 for (j = 0; j<data->num_circulationData; j++)
975 printf ("circulation %d\n", j);
976 if (data->circulationData[j]->availableNow)
977 printf (" availableNow: %d\n",
978 *data->circulationData[j]->availableNow);
979 if (data->circulationData[j]->availablityDate)
980 printf (" availabiltyDate: %s\n",
981 data->circulationData[j]->availablityDate);
982 if (data->circulationData[j]->availableThru)
983 printf (" availableThru: %s\n",
984 data->circulationData[j]->availableThru);
985 if (data->circulationData[j]->restrictions)
986 printf (" restrictions: %s\n",
987 data->circulationData[j]->restrictions);
988 if (data->circulationData[j]->itemId)
989 printf (" itemId: %s\n",
990 data->circulationData[j]->itemId);
991 if (data->circulationData[j]->renewable)
992 printf (" renewable: %d\n",
993 *data->circulationData[j]->renewable);
994 if (data->circulationData[j]->onHold)
995 printf (" onHold: %d\n",
996 *data->circulationData[j]->onHold);
997 if (data->circulationData[j]->enumAndChron)
998 printf (" enumAndChron: %s\n",
999 data->circulationData[j]->enumAndChron);
1000 if (data->circulationData[j]->midspine)
1001 printf (" midspine: %s\n",
1002 data->circulationData[j]->midspine);
1003 if (data->circulationData[j]->temporaryLocation)
1004 printf (" temporaryLocation: %s\n",
1005 data->circulationData[j]->temporaryLocation);
1012 printf("Unknown record representation.\n");
1013 if (!z_External(print, &r, 0, 0))
1015 odr_perror(print, "Printing external");
1021 static void display_diagrecs(Z_DiagRec **pp, int num)
1025 Z_DefaultDiagFormat *r;
1027 printf("Diagnostic message(s) from database:\n");
1028 for (i = 0; i<num; i++)
1030 Z_DiagRec *p = pp[i];
1031 if (p->which != Z_DiagRec_defaultFormat)
1033 printf("Diagnostic record not in default format.\n");
1037 r = p->u.defaultFormat;
1038 if (!(ent = oid_getentbyoid(r->diagnosticSetId)) ||
1039 ent->oclass != CLASS_DIAGSET || ent->value != VAL_BIB1)
1040 printf("Missing or unknown diagset\n");
1041 printf(" [%d] %s", *r->condition, diagbib1_str(*r->condition));
1044 case Z_DefaultDiagFormat_v2Addinfo:
1045 printf (" -- v2 addinfo '%s'\n", r->u.v2Addinfo);
1047 case Z_DefaultDiagFormat_v3Addinfo:
1048 printf (" -- v3 addinfo '%s'\n", r->u.v3Addinfo);
1055 static void display_nameplusrecord(Z_NamePlusRecord *p)
1057 if (p->databaseName)
1058 printf("[%s]", p->databaseName);
1059 if (p->which == Z_NamePlusRecord_surrogateDiagnostic)
1060 display_diagrecs(&p->u.surrogateDiagnostic, 1);
1061 else if (p->which == Z_NamePlusRecord_databaseRecord)
1062 display_record(p->u.databaseRecord);
1065 static void display_records(Z_Records *p)
1069 if (p->which == Z_Records_NSD)
1071 Z_DiagRec dr, *dr_p = &dr;
1072 dr.which = Z_DiagRec_defaultFormat;
1073 dr.u.defaultFormat = p->u.nonSurrogateDiagnostic;
1074 display_diagrecs (&dr_p, 1);
1076 else if (p->which == Z_Records_multipleNSD)
1077 display_diagrecs (p->u.multipleNonSurDiagnostics->diagRecs,
1078 p->u.multipleNonSurDiagnostics->num_diagRecs);
1081 printf("Records: %d\n", p->u.databaseOrSurDiagnostics->num_records);
1082 for (i = 0; i < p->u.databaseOrSurDiagnostics->num_records; i++)
1083 display_nameplusrecord(p->u.databaseOrSurDiagnostics->records[i]);
1087 static int send_deleteResultSetRequest(const char *arg)
1092 Z_APDU *apdu = zget_APDU(out, Z_APDU_deleteResultSetRequest);
1093 Z_DeleteResultSetRequest *req = apdu->u.deleteResultSetRequest;
1095 req->referenceId = set_refid (out);
1097 req->num_resultSetList =
1098 sscanf (arg, "%30s %30s %30s %30s %30s %30s %30s %30s",
1099 names[0], names[1], names[2], names[3],
1100 names[4], names[5], names[6], names[7]);
1102 req->deleteFunction = (int *)
1103 odr_malloc (out, sizeof(*req->deleteFunction));
1104 if (req->num_resultSetList > 0)
1106 *req->deleteFunction = Z_DeleteRequest_list;
1107 req->resultSetList = (char **)
1108 odr_malloc (out, sizeof(*req->resultSetList)*
1109 req->num_resultSetList);
1110 for (i = 0; i<req->num_resultSetList; i++)
1111 req->resultSetList[i] = names[i];
1115 *req->deleteFunction = Z_DeleteRequest_all;
1116 req->resultSetList = 0;
1120 printf("Sent deleteResultSetRequest.\n");
1125 static int send_srw(Z_SRW_PDU *sr)
1127 const char *charset = negotiationCharset;
1128 const char *host_port = 0;
1131 Z_SOAP_Handler h[2] = {
1132 {"http://www.loc.gov/zing/srw/v1.0/", 0, (Z_SOAP_fun) yaz_srw_codec},
1135 ODR o = odr_createmem(ODR_ENCODE);
1137 Z_SOAP *p = odr_malloc(o, sizeof(*p));
1140 path = odr_malloc(out, strlen(databaseNames[0])+2);
1142 strcpy(path+1, databaseNames[0]);
1144 gdu = z_get_HTTP_Request(out);
1145 gdu->u.HTTP_Request->path = odr_strdup(out, path);
1149 const char *cp0 = strstr(host_port, "://");
1150 const char *cp1 = 0;
1156 cp1 = strchr(cp0, '/');
1158 cp1 = cp0+strlen(cp0);
1162 char *h = odr_malloc(out, cp1 - cp0 + 1);
1163 memcpy (h, cp0, cp1 - cp0);
1165 z_HTTP_header_add(out, &gdu->u.HTTP_Request->headers,
1170 strcpy(ctype, "text/xml");
1171 if (charset && strlen(charset) < 20)
1173 strcat(ctype, "; charset=");
1174 strcat(ctype, charset);
1176 z_HTTP_header_add(out, &gdu->u.HTTP_Request->headers,
1177 "Content-Type", ctype);
1178 z_HTTP_header_add(out, &gdu->u.HTTP_Request->headers,
1179 "SOAPAction", "\"\"");
1180 p->which = Z_SOAP_generic;
1181 p->u.generic = odr_malloc(o, sizeof(*p->u.generic));
1182 p->u.generic->no = 0;
1183 p->u.generic->ns = 0;
1184 p->u.generic->p = sr;
1185 p->ns = "http://schemas.xmlsoap.org/soap/envelope/";
1187 ret = z_soap_codec_enc(o, &p,
1188 &gdu->u.HTTP_Request->content_buf,
1189 &gdu->u.HTTP_Request->content_len, h,
1192 if (z_GDU(out, &gdu, 0, 0))
1198 buf_out = odr_getbuf(out, &len_out, 0);
1200 /* we don't odr_reset(out), since we may need the buffer again */
1202 do_hex_dump(buf_out, len_out);
1204 r = cs_put(conn, buf_out, len_out);
1216 static int send_SRW_searchRequest(const char *arg)
1222 assert(srw_sr_odr_out == 0);
1223 srw_sr_odr_out = odr_createmem(ODR_ENCODE);
1225 odr_reset(srw_sr_odr_out);
1229 /* save this for later .. when fetching individual records */
1230 srw_sr = sr = yaz_srw_get(srw_sr_odr_out, Z_SRW_searchRetrieve_request);
1231 sr->u.request->query_type = Z_SRW_query_type_cql;
1232 sr->u.request->query.cql = odr_strdup(srw_sr_odr_out, arg);
1234 sr = yaz_srw_get(out, Z_SRW_searchRetrieve_request);
1235 sr->u.request->query_type = Z_SRW_query_type_cql;
1236 sr->u.request->query.cql = odr_strdup(out, arg);
1238 sr->u.request->recordSchema = schema;
1239 return send_srw(sr);
1243 static int send_searchRequest(const char *arg)
1245 Z_APDU *apdu = zget_APDU(out, Z_APDU_searchRequest);
1246 Z_SearchRequest *req = apdu->u.searchRequest;
1249 struct ccl_rpn_node *rpn = NULL;
1251 char setstring[100];
1252 Z_RPNQuery *RPNquery;
1254 YAZ_PQF_Parser pqf_parser;
1256 QueryType myQueryType = queryType;
1259 if (myQueryType == QueryType_CCL2RPN)
1261 rpn = ccl_find_str(bibset, arg, &error, &pos);
1264 printf("CCL ERROR: %s\n", ccl_err_msg(error));
1267 } else if (myQueryType == QueryType_CQL2RPN) {
1268 /* ### All this code should be wrapped in a utility function */
1270 struct cql_node *node;
1271 const char *addinfo;
1272 if (cqltrans == 0) {
1273 printf("Can't use CQL: no translation file. Try set_cqlfile\n");
1276 parser = cql_parser_create();
1277 if ((error = cql_parser_string(parser, arg)) != 0) {
1278 printf("Can't parse CQL: must be a syntax error\n");
1281 node = cql_parser_result(parser);
1282 if ((error = cql_transform_buf(cqltrans, node, pqfbuf,
1283 sizeof pqfbuf)) != 0) {
1284 error = cql_transform_error(cqltrans, &addinfo);
1285 printf ("Can't convert CQL to PQF: %s (addinfo=%s)\n",
1286 cql_strerror(error), addinfo);
1290 myQueryType = QueryType_Prefix;
1293 req->referenceId = set_refid (out);
1294 if (!strcmp(arg, "@big")) /* strictly for troublemaking */
1296 static unsigned char big[2100];
1297 static Odr_oct bigo;
1299 /* send a very big referenceid to test transport stack etc. */
1300 memset(big, 'A', 2100);
1301 bigo.len = bigo.size = 2100;
1303 req->referenceId = &bigo;
1308 sprintf(setstring, "%d", ++setnumber);
1309 req->resultSetName = setstring;
1311 *req->smallSetUpperBound = smallSetUpperBound;
1312 *req->largeSetLowerBound = largeSetLowerBound;
1313 *req->mediumSetPresentNumber = mediumSetPresentNumber;
1314 if (smallSetUpperBound > 0 || (largeSetLowerBound > 1 &&
1315 mediumSetPresentNumber > 0))
1319 prefsyn.proto = protocol;
1320 prefsyn.oclass = CLASS_RECSYN;
1321 prefsyn.value = recordsyntax;
1322 req->preferredRecordSyntax =
1323 odr_oiddup(out, oid_ent_to_oid(&prefsyn, oid));
1324 req->smallSetElementSetNames =
1325 req->mediumSetElementSetNames = elementSetNames;
1327 req->num_databaseNames = num_databaseNames;
1328 req->databaseNames = databaseNames;
1330 req->query = &query;
1332 switch (myQueryType)
1334 case QueryType_Prefix:
1335 query.which = Z_Query_type_1;
1336 pqf_parser = yaz_pqf_create ();
1337 RPNquery = yaz_pqf_parse (pqf_parser, out, arg);
1340 const char *pqf_msg;
1342 int code = yaz_pqf_error (pqf_parser, &pqf_msg, &off);
1343 printf("%*s^\n", off+4, "");
1344 printf("Prefix query error: %s (code %d)\n", pqf_msg, code);
1346 yaz_pqf_destroy (pqf_parser);
1349 yaz_pqf_destroy (pqf_parser);
1350 query.u.type_1 = RPNquery;
1353 query.which = Z_Query_type_2;
1354 query.u.type_2 = &ccl_query;
1355 ccl_query.buf = (unsigned char*) arg;
1356 ccl_query.len = strlen(arg);
1358 case QueryType_CCL2RPN:
1359 query.which = Z_Query_type_1;
1360 RPNquery = ccl_rpn_query(out, rpn);
1363 printf ("Couldn't convert from CCL to RPN\n");
1366 query.u.type_1 = RPNquery;
1367 ccl_rpn_delete (rpn);
1370 query.which = Z_Query_type_104;
1371 ext = (Z_External *) odr_malloc(out, sizeof(*ext));
1372 ext->direct_reference = odr_getoidbystr(out, "1.2.840.10003.16.2");
1373 ext->indirect_reference = 0;
1374 ext->descriptor = 0;
1375 ext->which = Z_External_CQL;
1376 ext->u.cql = odr_strdup(out, arg);
1377 query.u.type_104 = ext;
1380 printf ("Unsupported query type\n");
1383 if (send_apdu(apdu))
1384 printf("Sent searchRequest.\n");
1389 /* display Query Expression as part of searchResult-1 */
1390 static void display_queryExpression (Z_QueryExpression *qe)
1394 if (qe->which == Z_QueryExpression_term)
1396 if (qe->u.term->queryTerm)
1398 Z_Term *term = qe->u.term->queryTerm;
1399 switch (term->which)
1401 case Z_Term_general:
1402 printf (" %.*s", term->u.general->len, term->u.general->buf);
1404 case Z_Term_characterString:
1405 printf (" %s", term->u.characterString);
1407 case Z_Term_numeric:
1408 printf (" %d", *term->u.numeric);
1418 /* see if we can find USR:SearchResult-1 */
1419 static void display_searchResult (Z_OtherInformation *o)
1424 for (i = 0; i < o->num_elements; i++)
1426 if (o->list[i]->which == Z_OtherInfo_externallyDefinedInfo)
1428 Z_External *ext = o->list[i]->information.externallyDefinedInfo;
1430 if (ext->which == Z_External_searchResult1)
1433 Z_SearchInfoReport *sr = ext->u.searchResult1;
1434 printf ("SearchResult-1:");
1435 for (j = 0; j < sr->num; j++)
1437 if (!sr->elements[j]->subqueryExpression)
1439 display_queryExpression (
1440 sr->elements[j]->subqueryExpression);
1441 display_queryExpression (
1442 sr->elements[j]->subqueryInterpretation);
1443 display_queryExpression (
1444 sr->elements[j]->subqueryRecommendation);
1445 if (sr->elements[j]->subqueryCount)
1446 printf ("(%d)", *sr->elements[j]->subqueryCount);
1454 static int process_searchResponse(Z_SearchResponse *res)
1456 printf ("Received SearchResponse.\n");
1457 print_refid (res->referenceId);
1458 if (*res->searchStatus)
1459 printf("Search was a success.\n");
1461 printf("Search was a bloomin' failure.\n");
1462 printf("Number of hits: %d", *res->resultCount);
1464 printf (", setno %d", setnumber);
1466 display_searchResult (res->additionalSearchInfo);
1467 printf("records returned: %d\n",
1468 *res->numberOfRecordsReturned);
1469 setno += *res->numberOfRecordsReturned;
1471 display_records(res->records);
1475 static void print_level(int iLevel)
1478 for (i = 0; i < iLevel * 4; i++)
1482 static void print_int(int iLevel, const char *pTag, int *pInt)
1486 print_level(iLevel);
1487 printf("%s: %d\n", pTag, *pInt);
1491 static void print_string(int iLevel, const char *pTag, const char *pString)
1493 if (pString != NULL)
1495 print_level(iLevel);
1496 printf("%s: %s\n", pTag, pString);
1500 static void print_oid(int iLevel, const char *pTag, Odr_oid *pOid)
1506 print_level(iLevel);
1507 printf("%s:", pTag);
1508 for (; *pInt != -1; pInt++)
1509 printf(" %d", *pInt);
1514 static void print_referenceId(int iLevel, Z_ReferenceId *referenceId)
1516 if (referenceId != NULL)
1520 print_level(iLevel);
1521 printf("Ref Id (%d, %d): ", referenceId->len, referenceId->size);
1522 for (i = 0; i < referenceId->len; i++)
1523 printf("%c", referenceId->buf[i]);
1528 static void print_string_or_numeric(int iLevel, const char *pTag, Z_StringOrNumeric *pStringNumeric)
1530 if (pStringNumeric != NULL)
1532 switch (pStringNumeric->which)
1534 case Z_StringOrNumeric_string:
1535 print_string(iLevel, pTag, pStringNumeric->u.string);
1538 case Z_StringOrNumeric_numeric:
1539 print_int(iLevel, pTag, pStringNumeric->u.numeric);
1543 print_level(iLevel);
1544 printf("%s: valid type for Z_StringOrNumeric\n", pTag);
1550 static void print_universe_report_duplicate(
1552 Z_UniverseReportDuplicate *pUniverseReportDuplicate)
1554 if (pUniverseReportDuplicate != NULL)
1556 print_level(iLevel);
1557 printf("Universe Report Duplicate: \n");
1559 print_string_or_numeric(iLevel, "Hit No",
1560 pUniverseReportDuplicate->hitno);
1564 static void print_universe_report_hits(
1566 Z_UniverseReportHits *pUniverseReportHits)
1568 if (pUniverseReportHits != NULL)
1570 print_level(iLevel);
1571 printf("Universe Report Hits: \n");
1573 print_string_or_numeric(iLevel, "Database",
1574 pUniverseReportHits->database);
1575 print_string_or_numeric(iLevel, "Hits", pUniverseReportHits->hits);
1579 static void print_universe_report(int iLevel, Z_UniverseReport *pUniverseReport)
1581 if (pUniverseReport != NULL)
1583 print_level(iLevel);
1584 printf("Universe Report: \n");
1586 print_int(iLevel, "Total Hits", pUniverseReport->totalHits);
1587 switch (pUniverseReport->which)
1589 case Z_UniverseReport_databaseHits:
1590 print_universe_report_hits(iLevel,
1591 pUniverseReport->u.databaseHits);
1594 case Z_UniverseReport_duplicate:
1595 print_universe_report_duplicate(iLevel,
1596 pUniverseReport->u.duplicate);
1600 print_level(iLevel);
1601 printf("Type: %d\n", pUniverseReport->which);
1607 static void print_external(int iLevel, Z_External *pExternal)
1609 if (pExternal != NULL)
1611 print_level(iLevel);
1612 printf("External: \n");
1614 print_oid(iLevel, "Direct Reference", pExternal->direct_reference);
1615 print_int(iLevel, "InDirect Reference", pExternal->indirect_reference);
1616 print_string(iLevel, "Descriptor", pExternal->descriptor);
1617 switch (pExternal->which)
1619 case Z_External_universeReport:
1620 print_universe_report(iLevel, pExternal->u.universeReport);
1624 print_level(iLevel);
1625 printf("Type: %d\n", pExternal->which);
1631 static int process_resourceControlRequest (Z_ResourceControlRequest *req)
1633 printf ("Received ResourceControlRequest.\n");
1634 print_referenceId(1, req->referenceId);
1635 print_int(1, "Suspended Flag", req->suspendedFlag);
1636 print_int(1, "Partial Results Available", req->partialResultsAvailable);
1637 print_int(1, "Response Required", req->responseRequired);
1638 print_int(1, "Triggered Request Flag", req->triggeredRequestFlag);
1639 print_external(1, req->resourceReport);
1643 void process_ESResponse(Z_ExtendedServicesResponse *res)
1646 switch (*res->operationStatus)
1648 case Z_ExtendedServicesResponse_done:
1651 case Z_ExtendedServicesResponse_accepted:
1652 printf ("accepted\n");
1654 case Z_ExtendedServicesResponse_failure:
1655 printf ("failure\n");
1656 display_diagrecs(res->diagnostics, res->num_diagnostics);
1659 printf ("unknown\n");
1661 if ( (*res->operationStatus != Z_ExtendedServicesResponse_failure) &&
1662 (res->num_diagnostics != 0) ) {
1663 display_diagrecs(res->diagnostics, res->num_diagnostics);
1665 print_refid (res->referenceId);
1666 if (res->taskPackage &&
1667 res->taskPackage->which == Z_External_extendedService)
1669 Z_TaskPackage *taskPackage = res->taskPackage->u.extendedService;
1670 Odr_oct *id = taskPackage->targetReference;
1671 Z_External *ext = taskPackage->taskSpecificParameters;
1675 printf ("Target Reference: ");
1676 print_stringn (id->buf, id->len);
1679 if (ext->which == Z_External_update)
1681 Z_IUUpdateTaskPackage *utp = ext->u.update->u.taskPackage;
1682 if (utp && utp->targetPart)
1684 Z_IUTargetPart *targetPart = utp->targetPart;
1687 for (i = 0; i<targetPart->num_taskPackageRecords; i++)
1690 Z_IUTaskPackageRecordStructure *tpr =
1691 targetPart->taskPackageRecords[i];
1692 printf ("task package record %d\n", i+1);
1693 if (tpr->which == Z_IUTaskPackageRecordStructure_record)
1695 display_record (tpr->u.record);
1699 printf ("other type\n");
1707 const char *get_ill_element (void *clientData, const char *element)
1712 static Z_External *create_external_itemRequest()
1714 struct ill_get_ctl ctl;
1715 ILL_ItemRequest *req;
1717 int item_request_size = 0;
1718 char *item_request_buf = 0;
1722 ctl.f = get_ill_element;
1724 req = ill_get_ItemRequest(&ctl, "ill", 0);
1726 printf ("ill_get_ItemRequest failed\n");
1728 if (!ill_ItemRequest (out, &req, 0, 0))
1732 ill_ItemRequest(print, &req, 0, 0);
1735 item_request_buf = odr_getbuf (out, &item_request_size, 0);
1736 if (item_request_buf)
1737 odr_setbuf (out, item_request_buf, item_request_size, 1);
1738 printf ("Couldn't encode ItemRequest, size %d\n", item_request_size);
1745 item_request_buf = odr_getbuf (out, &item_request_size, 0);
1746 oid.proto = PROTO_GENERAL;
1747 oid.oclass = CLASS_GENERAL;
1748 oid.value = VAL_ISO_ILL_1;
1750 r = (Z_External *) odr_malloc (out, sizeof(*r));
1751 r->direct_reference = odr_oiddup(out,oid_getoidbyent(&oid));
1752 r->indirect_reference = 0;
1754 r->which = Z_External_single;
1756 r->u.single_ASN1_type = (Odr_oct *)
1757 odr_malloc (out, sizeof(*r->u.single_ASN1_type));
1758 r->u.single_ASN1_type->buf = (unsigned char *)
1759 odr_malloc (out, item_request_size);
1760 r->u.single_ASN1_type->len = item_request_size;
1761 r->u.single_ASN1_type->size = item_request_size;
1762 memcpy (r->u.single_ASN1_type->buf, item_request_buf,
1765 do_hex_dump(item_request_buf,item_request_size);
1770 static Z_External *create_external_ILL_APDU(int which)
1772 struct ill_get_ctl ctl;
1775 int ill_request_size = 0;
1776 char *ill_request_buf = 0;
1780 ctl.f = get_ill_element;
1782 ill_apdu = ill_get_APDU(&ctl, "ill", 0);
1784 if (!ill_APDU (out, &ill_apdu, 0, 0))
1788 printf ("-------------------\n");
1789 ill_APDU(print, &ill_apdu, 0, 0);
1791 printf ("-------------------\n");
1793 ill_request_buf = odr_getbuf (out, &ill_request_size, 0);
1794 if (ill_request_buf)
1795 odr_setbuf (out, ill_request_buf, ill_request_size, 1);
1796 printf ("Couldn't encode ILL-Request, size %d\n", ill_request_size);
1802 ill_request_buf = odr_getbuf (out, &ill_request_size, 0);
1804 oid.proto = PROTO_GENERAL;
1805 oid.oclass = CLASS_GENERAL;
1806 oid.value = VAL_ISO_ILL_1;
1808 r = (Z_External *) odr_malloc (out, sizeof(*r));
1809 r->direct_reference = odr_oiddup(out,oid_getoidbyent(&oid));
1810 r->indirect_reference = 0;
1812 r->which = Z_External_single;
1814 r->u.single_ASN1_type = (Odr_oct *)
1815 odr_malloc (out, sizeof(*r->u.single_ASN1_type));
1816 r->u.single_ASN1_type->buf = (unsigned char *)
1817 odr_malloc (out, ill_request_size);
1818 r->u.single_ASN1_type->len = ill_request_size;
1819 r->u.single_ASN1_type->size = ill_request_size;
1820 memcpy (r->u.single_ASN1_type->buf, ill_request_buf, ill_request_size);
1821 /* printf ("len = %d\n", ill_request_size); */
1822 /* do_hex_dump(ill_request_buf,ill_request_size); */
1823 /* printf("--- end of extenal\n"); */
1830 static Z_External *create_ItemOrderExternal(const char *type, int itemno)
1832 Z_External *r = (Z_External *) odr_malloc(out, sizeof(Z_External));
1833 oident ItemOrderRequest;
1835 ItemOrderRequest.proto = PROTO_Z3950;
1836 ItemOrderRequest.oclass = CLASS_EXTSERV;
1837 ItemOrderRequest.value = VAL_ITEMORDER;
1839 r->direct_reference = odr_oiddup(out,oid_getoidbyent(&ItemOrderRequest));
1840 r->indirect_reference = 0;
1843 r->which = Z_External_itemOrder;
1845 r->u.itemOrder = (Z_ItemOrder *) odr_malloc(out,sizeof(Z_ItemOrder));
1846 memset(r->u.itemOrder, 0, sizeof(Z_ItemOrder));
1847 r->u.itemOrder->which=Z_IOItemOrder_esRequest;
1849 r->u.itemOrder->u.esRequest = (Z_IORequest *)
1850 odr_malloc(out,sizeof(Z_IORequest));
1851 memset(r->u.itemOrder->u.esRequest, 0, sizeof(Z_IORequest));
1853 r->u.itemOrder->u.esRequest->toKeep = (Z_IOOriginPartToKeep *)
1854 odr_malloc(out,sizeof(Z_IOOriginPartToKeep));
1855 memset(r->u.itemOrder->u.esRequest->toKeep, 0, sizeof(Z_IOOriginPartToKeep));
1856 r->u.itemOrder->u.esRequest->notToKeep = (Z_IOOriginPartNotToKeep *)
1857 odr_malloc(out,sizeof(Z_IOOriginPartNotToKeep));
1858 memset(r->u.itemOrder->u.esRequest->notToKeep, 0, sizeof(Z_IOOriginPartNotToKeep));
1860 r->u.itemOrder->u.esRequest->toKeep->supplDescription = NULL;
1861 r->u.itemOrder->u.esRequest->toKeep->contact = NULL;
1862 r->u.itemOrder->u.esRequest->toKeep->addlBilling = NULL;
1864 r->u.itemOrder->u.esRequest->notToKeep->resultSetItem =
1865 (Z_IOResultSetItem *) odr_malloc(out, sizeof(Z_IOResultSetItem));
1866 memset(r->u.itemOrder->u.esRequest->notToKeep->resultSetItem, 0, sizeof(Z_IOResultSetItem));
1867 r->u.itemOrder->u.esRequest->notToKeep->resultSetItem->resultSetId = "1";
1869 r->u.itemOrder->u.esRequest->notToKeep->resultSetItem->item =
1870 (int *) odr_malloc(out, sizeof(int));
1871 *r->u.itemOrder->u.esRequest->notToKeep->resultSetItem->item = itemno;
1873 if (!strcmp (type, "item") || !strcmp(type, "2"))
1875 printf ("using item-request\n");
1876 r->u.itemOrder->u.esRequest->notToKeep->itemRequest =
1877 create_external_itemRequest();
1879 else if (!strcmp(type, "ill") || !strcmp(type, "1"))
1881 printf ("using ILL-request\n");
1882 r->u.itemOrder->u.esRequest->notToKeep->itemRequest =
1883 create_external_ILL_APDU(ILL_APDU_ILL_Request);
1885 else if (!strcmp(type, "xml") || !strcmp(type, "3"))
1887 const char *xml_buf =
1889 " <type>request</type>\n"
1890 " <libraryNo>000200</libraryNo>\n"
1891 " <borrowerTicketNo> 1212 </borrowerTicketNo>\n"
1893 r->u.itemOrder->u.esRequest->notToKeep->itemRequest =
1894 z_ext_record (out, VAL_TEXT_XML, xml_buf, strlen(xml_buf));
1897 r->u.itemOrder->u.esRequest->notToKeep->itemRequest = 0;
1902 static int send_itemorder(const char *type, int itemno)
1904 Z_APDU *apdu = zget_APDU(out, Z_APDU_extendedServicesRequest);
1905 Z_ExtendedServicesRequest *req = apdu->u.extendedServicesRequest;
1906 oident ItemOrderRequest;
1908 ItemOrderRequest.proto = PROTO_Z3950;
1909 ItemOrderRequest.oclass = CLASS_EXTSERV;
1910 ItemOrderRequest.value = VAL_ITEMORDER;
1911 req->packageType = odr_oiddup(out,oid_getoidbyent(&ItemOrderRequest));
1912 req->packageName = esPackageName;
1914 req->taskSpecificParameters = create_ItemOrderExternal(type, itemno);
1920 static int only_z3950()
1922 if (protocol == PROTO_HTTP)
1924 printf ("Not supported by SRW\n");
1930 static int cmd_update_common(const char *arg, int version);
1932 static int cmd_update(const char *arg)
1934 return cmd_update_common(arg, 1);
1937 static int cmd_update0(const char *arg)
1939 return cmd_update_common(arg, 0);
1942 static int cmd_update_common(const char *arg, int version)
1944 Z_APDU *apdu = zget_APDU(out, Z_APDU_extendedServicesRequest );
1945 Z_ExtendedServicesRequest *req = apdu->u.extendedServicesRequest;
1949 char action[20], recid[20], fname[80];
1951 Z_External *record_this = 0;
1958 sscanf (arg, "%19s %19s %79s", action, recid, fname);
1960 if (!strcmp (action, "insert"))
1961 action_no = Z_IUOriginPartToKeep_recordInsert;
1962 else if (!strcmp (action, "replace"))
1963 action_no = Z_IUOriginPartToKeep_recordReplace;
1964 else if (!strcmp (action, "delete"))
1965 action_no = Z_IUOriginPartToKeep_recordDelete;
1966 else if (!strcmp (action, "update"))
1967 action_no = Z_IUOriginPartToKeep_specialUpdate;
1970 printf ("Bad action: %s\n", action);
1971 printf ("Possible values: insert, replace, delete, update\n");
1979 stat (fname, &status);
1980 if (S_ISREG(status.st_mode) && (inf = fopen(fname, "r")))
1982 size_t len = status.st_size;
1983 char *buf = (char *) xmalloc (len);
1985 fread (buf, 1, len, inf);
1989 record_this = z_ext_record (out, VAL_TEXT_XML, buf, len);
1995 printf ("File %s doesn't exist\n", fname);
2003 printf ("No last record (update ignored)\n");
2006 record_this = record_last;
2009 update_oid.proto = PROTO_Z3950;
2010 update_oid.oclass = CLASS_EXTSERV;
2012 update_oid.value = VAL_DBUPDATE0;
2014 update_oid.value = VAL_DBUPDATE;
2015 oid_ent_to_oid (&update_oid, oid);
2016 req->packageType = odr_oiddup(out,oid);
2017 req->packageName = esPackageName;
2019 req->referenceId = set_refid (out);
2021 r = req->taskSpecificParameters = (Z_External *)
2022 odr_malloc (out, sizeof(*r));
2023 r->direct_reference = odr_oiddup(out,oid);
2024 r->indirect_reference = 0;
2028 Z_IU0OriginPartToKeep *toKeep;
2029 Z_IU0SuppliedRecords *notToKeep;
2031 r->which = Z_External_update0;
2032 r->u.update0 = (Z_IU0Update *) odr_malloc(out, sizeof(*r->u.update0));
2033 r->u.update0->which = Z_IUUpdate_esRequest;
2034 r->u.update0->u.esRequest = (Z_IU0UpdateEsRequest *)
2035 odr_malloc(out, sizeof(*r->u.update0->u.esRequest));
2036 toKeep = r->u.update0->u.esRequest->toKeep = (Z_IU0OriginPartToKeep *)
2037 odr_malloc(out, sizeof(*r->u.update0->u.esRequest->toKeep));
2039 toKeep->databaseName = databaseNames[0];
2041 toKeep->elementSetName = 0;
2043 toKeep->action = (int *) odr_malloc(out, sizeof(*toKeep->action));
2044 *toKeep->action = action_no;
2046 notToKeep = r->u.update0->u.esRequest->notToKeep = (Z_IU0SuppliedRecords *)
2047 odr_malloc(out, sizeof(*r->u.update0->u.esRequest->notToKeep));
2049 notToKeep->elements = (Z_IU0SuppliedRecords_elem **)
2050 odr_malloc(out, sizeof(*notToKeep->elements));
2051 notToKeep->elements[0] = (Z_IU0SuppliedRecords_elem *)
2052 odr_malloc(out, sizeof(**notToKeep->elements));
2053 notToKeep->elements[0]->which = Z_IUSuppliedRecords_elem_opaque;
2056 notToKeep->elements[0]->u.opaque = (Odr_oct *)
2057 odr_malloc (out, sizeof(Odr_oct));
2058 notToKeep->elements[0]->u.opaque->buf = (unsigned char *) recid;
2059 notToKeep->elements[0]->u.opaque->size = strlen(recid);
2060 notToKeep->elements[0]->u.opaque->len = strlen(recid);
2063 notToKeep->elements[0]->u.opaque = 0;
2064 notToKeep->elements[0]->supplementalId = 0;
2065 notToKeep->elements[0]->correlationInfo = 0;
2066 notToKeep->elements[0]->record = record_this;
2070 Z_IUOriginPartToKeep *toKeep;
2071 Z_IUSuppliedRecords *notToKeep;
2073 r->which = Z_External_update;
2074 r->u.update = (Z_IUUpdate *) odr_malloc(out, sizeof(*r->u.update));
2075 r->u.update->which = Z_IUUpdate_esRequest;
2076 r->u.update->u.esRequest = (Z_IUUpdateEsRequest *)
2077 odr_malloc(out, sizeof(*r->u.update->u.esRequest));
2078 toKeep = r->u.update->u.esRequest->toKeep = (Z_IUOriginPartToKeep *)
2079 odr_malloc(out, sizeof(*r->u.update->u.esRequest->toKeep));
2081 toKeep->databaseName = databaseNames[0];
2083 toKeep->elementSetName = 0;
2084 toKeep->actionQualifier = 0;
2085 toKeep->action = (int *) odr_malloc(out, sizeof(*toKeep->action));
2086 *toKeep->action = action_no;
2088 notToKeep = r->u.update->u.esRequest->notToKeep = (Z_IUSuppliedRecords *)
2089 odr_malloc(out, sizeof(*r->u.update->u.esRequest->notToKeep));
2091 notToKeep->elements = (Z_IUSuppliedRecords_elem **)
2092 odr_malloc(out, sizeof(*notToKeep->elements));
2093 notToKeep->elements[0] = (Z_IUSuppliedRecords_elem *)
2094 odr_malloc(out, sizeof(**notToKeep->elements));
2095 notToKeep->elements[0]->which = Z_IUSuppliedRecords_elem_opaque;
2098 notToKeep->elements[0]->u.opaque = (Odr_oct *)
2099 odr_malloc (out, sizeof(Odr_oct));
2100 notToKeep->elements[0]->u.opaque->buf = (unsigned char *) recid;
2101 notToKeep->elements[0]->u.opaque->size = strlen(recid);
2102 notToKeep->elements[0]->u.opaque->len = strlen(recid);
2105 notToKeep->elements[0]->u.opaque = 0;
2106 notToKeep->elements[0]->supplementalId = 0;
2107 notToKeep->elements[0]->correlationInfo = 0;
2108 notToKeep->elements[0]->record = record_this;
2116 static int cmd_itemorder(const char *arg)
2123 if (sscanf (arg, "%10s %d", type, &itemno) != 2)
2126 printf("Item order request\n");
2128 send_itemorder(type, itemno);
2132 static int cmd_find(const char *arg)
2136 printf("Find what?\n");
2139 if (protocol == PROTO_HTTP)
2144 if (!send_SRW_searchRequest(arg))
2157 printf("Not connected yet\n");
2161 if (!send_searchRequest(arg))
2167 static int cmd_delete(const char *arg)
2171 printf("Not connected yet\n");
2176 if (!send_deleteResultSetRequest(arg))
2181 static int cmd_ssub(const char *arg)
2183 if (!(smallSetUpperBound = atoi(arg)))
2188 static int cmd_lslb(const char *arg)
2192 if (!(largeSetLowerBound = atoi(arg)))
2197 static int cmd_mspn(const char *arg)
2201 if (!(mediumSetPresentNumber = atoi(arg)))
2206 static int cmd_status(const char *arg)
2208 printf("smallSetUpperBound: %d\n", smallSetUpperBound);
2209 printf("largeSetLowerBound: %d\n", largeSetLowerBound);
2210 printf("mediumSetPresentNumber: %d\n", mediumSetPresentNumber);
2214 static int cmd_setnames(const char *arg)
2216 if (*arg == '1') /* enable ? */
2218 else if (*arg == '0') /* disable ? */
2220 else if (setnumber < 0) /* no args, toggle .. */
2226 printf("Set numbering enabled.\n");
2228 printf("Set numbering disabled.\n");
2232 /* PRESENT SERVICE ----------------------------- */
2234 static void parse_show_args(const char *arg_c, char *setstring,
2235 int *start, int *number)
2240 strncpy(arg, arg_c, sizeof(arg)-1);
2241 arg[sizeof(arg)-1] = '\0';
2243 if ((p = strchr(arg, '+')))
2245 *number = atoi(p + 1);
2250 if (p && (p=strchr(p+1, '+')))
2251 strcpy (setstring, p+1);
2252 else if (setnumber >= 0)
2253 sprintf(setstring, "%d", setnumber);
2258 static int send_presentRequest(const char *arg)
2260 Z_APDU *apdu = zget_APDU(out, Z_APDU_presentRequest);
2261 Z_PresentRequest *req = apdu->u.presentRequest;
2262 Z_RecordComposition compo;
2266 char setstring[100];
2268 req->referenceId = set_refid (out);
2270 parse_show_args(arg, setstring, &setno, &nos);
2272 req->resultSetId = setstring;
2274 req->resultSetStartPoint = &setno;
2275 req->numberOfRecordsRequested = &nos;
2276 prefsyn.proto = protocol;
2277 prefsyn.oclass = CLASS_RECSYN;
2278 prefsyn.value = recordsyntax;
2279 req->preferredRecordSyntax =
2280 odr_oiddup (out, oid_ent_to_oid(&prefsyn, oid));
2286 prefschema.proto = protocol;
2287 prefschema.oclass = CLASS_SCHEMA;
2288 prefschema.value = oid_getvalbyname(schema);
2290 req->recordComposition = &compo;
2291 compo.which = Z_RecordComp_complex;
2292 compo.u.complex = (Z_CompSpec *)
2293 odr_malloc(out, sizeof(*compo.u.complex));
2294 compo.u.complex->selectAlternativeSyntax = (bool_t *)
2295 odr_malloc(out, sizeof(bool_t));
2296 *compo.u.complex->selectAlternativeSyntax = 0;
2298 compo.u.complex->generic = (Z_Specification *)
2299 odr_malloc(out, sizeof(*compo.u.complex->generic));
2300 compo.u.complex->generic->which = Z_Schema_oid;
2301 compo.u.complex->generic->schema.oid = (Odr_oid *)
2302 odr_oiddup(out, oid_ent_to_oid(&prefschema, oid));
2303 if (!compo.u.complex->generic->schema.oid)
2305 /* OID wasn't a schema! Try record syntax instead. */
2306 prefschema.oclass = CLASS_RECSYN;
2307 compo.u.complex->generic->schema.oid = (Odr_oid *)
2308 odr_oiddup(out, oid_ent_to_oid(&prefschema, oid));
2310 if (!elementSetNames)
2311 compo.u.complex->generic->elementSpec = 0;
2314 compo.u.complex->generic->elementSpec = (Z_ElementSpec *)
2315 odr_malloc(out, sizeof(Z_ElementSpec));
2316 compo.u.complex->generic->elementSpec->which =
2317 Z_ElementSpec_elementSetName;
2318 compo.u.complex->generic->elementSpec->u.elementSetName =
2319 elementSetNames->u.generic;
2321 compo.u.complex->num_dbSpecific = 0;
2322 compo.u.complex->dbSpecific = 0;
2323 compo.u.complex->num_recordSyntax = 0;
2324 compo.u.complex->recordSyntax = 0;
2326 else if (elementSetNames)
2328 req->recordComposition = &compo;
2329 compo.which = Z_RecordComp_simple;
2330 compo.u.simple = elementSetNames;
2333 printf("Sent presentRequest (%d+%d).\n", setno, nos);
2338 static int send_SRW_presentRequest(const char *arg)
2340 char setstring[100];
2342 Z_SRW_PDU *sr = srw_sr;
2346 parse_show_args(arg, setstring, &setno, &nos);
2347 sr->u.request->startRecord = odr_intdup(out, setno);
2348 sr->u.request->maximumRecords = odr_intdup(out, nos);
2350 sr->u.request->recordSchema = schema;
2351 return send_srw(sr);
2355 static void close_session (void)
2362 nmem_destroy (session_mem);
2371 void process_close(Z_Close *req)
2373 Z_APDU *apdu = zget_APDU(out, Z_APDU_close);
2374 Z_Close *res = apdu->u.close;
2376 static char *reasons[] =
2381 "cost limit reached",
2383 "security violation",
2390 printf("Reason: %s, message: %s\n", reasons[*req->closeReason],
2391 req->diagnosticInformation ? req->diagnosticInformation : "NULL");
2396 *res->closeReason = Z_Close_finished;
2398 printf("Sent response.\n");
2403 static int cmd_show(const char *arg)
2405 if (protocol == PROTO_HTTP)
2410 if (!send_SRW_presentRequest(arg))
2420 printf("Not connected yet\n");
2423 if (!send_presentRequest(arg))
2429 int cmd_quit(const char *arg)
2431 printf("See you later, alligator.\n");
2437 int cmd_cancel(const char *arg)
2439 Z_APDU *apdu = zget_APDU(out, Z_APDU_triggerResourceControlRequest);
2440 Z_TriggerResourceControlRequest *req =
2441 apdu->u.triggerResourceControlRequest;
2446 printf("Session not initialized yet\n");
2451 if (!ODR_MASK_GET(session->options, Z_Options_triggerResourceCtrl))
2453 printf("Target doesn't support cancel (trigger resource ctrl)\n");
2456 *req->requestedAction = Z_TriggerResourceCtrl_cancel;
2457 req->resultSetWanted = &rfalse;
2460 printf("Sent cancel request\n");
2464 int send_scanrequest(const char *query, int pp, int num, const char *term)
2466 Z_APDU *apdu = zget_APDU(out, Z_APDU_scanRequest);
2467 Z_ScanRequest *req = apdu->u.scanRequest;
2472 if (queryType == QueryType_CCL2RPN)
2476 struct ccl_rpn_node *rpn;
2478 rpn = ccl_find_str (bibset, query, &error, &pos);
2481 printf("CCL ERROR: %s\n", ccl_err_msg(error));
2484 bib1.proto = PROTO_Z3950;
2485 bib1.oclass = CLASS_ATTSET;
2486 bib1.value = VAL_BIB1;
2487 req->attributeSet = oid_ent_to_oid (&bib1, oid);
2488 if (!(req->termListAndStartPoint = ccl_scan_query (out, rpn)))
2490 printf("Couldn't convert CCL to Scan term\n");
2493 ccl_rpn_delete (rpn);
2497 YAZ_PQF_Parser pqf_parser = yaz_pqf_create ();
2499 if (!(req->termListAndStartPoint =
2500 yaz_pqf_scan(pqf_parser, out, &req->attributeSet, query)))
2502 const char *pqf_msg;
2504 int code = yaz_pqf_error (pqf_parser, &pqf_msg, &off);
2505 printf("%*s^\n", off+7, "");
2506 printf("Prefix query error: %s (code %d)\n", pqf_msg, code);
2507 yaz_pqf_destroy (pqf_parser);
2510 yaz_pqf_destroy (pqf_parser);
2514 if (req->termListAndStartPoint->term &&
2515 req->termListAndStartPoint->term->which == Z_Term_general &&
2516 req->termListAndStartPoint->term->u.general)
2518 req->termListAndStartPoint->term->u.general->buf =
2519 (unsigned char *) odr_strdup(out, term);
2520 req->termListAndStartPoint->term->u.general->len =
2521 req->termListAndStartPoint->term->u.general->size =
2525 req->referenceId = set_refid (out);
2526 req->num_databaseNames = num_databaseNames;
2527 req->databaseNames = databaseNames;
2528 req->numberOfTermsRequested = #
2529 req->preferredPositionInResponse = &pp;
2534 int send_sortrequest(const char *arg, int newset)
2536 Z_APDU *apdu = zget_APDU(out, Z_APDU_sortRequest);
2537 Z_SortRequest *req = apdu->u.sortRequest;
2538 Z_SortKeySpecList *sksl = (Z_SortKeySpecList *)
2539 odr_malloc (out, sizeof(*sksl));
2545 sprintf (setstring, "%d", setnumber);
2547 sprintf (setstring, "default");
2549 req->referenceId = set_refid (out);
2551 req->num_inputResultSetNames = 1;
2552 req->inputResultSetNames = (Z_InternationalString **)
2553 odr_malloc (out, sizeof(*req->inputResultSetNames));
2554 req->inputResultSetNames[0] = odr_strdup (out, setstring);
2556 if (newset && setnumber >= 0)
2557 sprintf (setstring, "%d", ++setnumber);
2559 req->sortedResultSetName = odr_strdup (out, setstring);
2561 req->sortSequence = yaz_sort_spec (out, arg);
2562 if (!req->sortSequence)
2564 printf ("Missing sort specifications\n");
2571 void display_term(Z_TermInfo *t)
2573 if (t->term->which == Z_Term_general)
2575 printf("%.*s", t->term->u.general->len, t->term->u.general->buf);
2576 sprintf(last_scan_line, "%.*s", t->term->u.general->len,
2577 t->term->u.general->buf);
2580 printf("Term (not general)");
2581 if (t->globalOccurrences)
2582 printf (" (%d)\n", *t->globalOccurrences);
2587 void process_scanResponse(Z_ScanResponse *res)
2590 Z_Entry **entries = NULL;
2591 int num_entries = 0;
2593 printf("Received ScanResponse\n");
2594 print_refid (res->referenceId);
2595 printf("%d entries", *res->numberOfEntriesReturned);
2596 if (res->positionOfTerm)
2597 printf (", position=%d", *res->positionOfTerm);
2599 if (*res->scanStatus != Z_Scan_success)
2600 printf("Scan returned code %d\n", *res->scanStatus);
2603 if ((entries = res->entries->entries))
2604 num_entries = res->entries->num_entries;
2605 for (i = 0; i < num_entries; i++)
2607 int pos_term = res->positionOfTerm ? *res->positionOfTerm : -1;
2608 if (entries[i]->which == Z_Entry_termInfo)
2610 printf("%c ", i + 1 == pos_term ? '*' : ' ');
2611 display_term(entries[i]->u.termInfo);
2614 display_diagrecs(&entries[i]->u.surrogateDiagnostic, 1);
2616 if (res->entries->nonsurrogateDiagnostics)
2617 display_diagrecs (res->entries->nonsurrogateDiagnostics,
2618 res->entries->num_nonsurrogateDiagnostics);
2621 void process_sortResponse(Z_SortResponse *res)
2623 printf("Received SortResponse: status=");
2624 switch (*res->sortStatus)
2626 case Z_SortStatus_success:
2627 printf ("success"); break;
2628 case Z_SortStatus_partial_1:
2629 printf ("partial"); break;
2630 case Z_SortStatus_failure:
2631 printf ("failure"); break;
2633 printf ("unknown (%d)", *res->sortStatus);
2636 print_refid (res->referenceId);
2637 if (res->diagnostics)
2638 display_diagrecs(res->diagnostics,
2639 res->num_diagnostics);
2642 void process_deleteResultSetResponse (Z_DeleteResultSetResponse *res)
2644 printf("Got deleteResultSetResponse status=%d\n",
2645 *res->deleteOperationStatus);
2646 if (res->deleteListStatuses)
2649 for (i = 0; i < res->deleteListStatuses->num; i++)
2651 printf ("%s status=%d\n", res->deleteListStatuses->elements[i]->id,
2652 *res->deleteListStatuses->elements[i]->status);
2657 int cmd_sort_generic(const char *arg, int newset)
2661 printf("Session not initialized yet\n");
2666 if (!ODR_MASK_GET(session->options, Z_Options_sort))
2668 printf("Target doesn't support sort\n");
2673 if (send_sortrequest(arg, newset) < 0)
2680 int cmd_sort(const char *arg)
2682 return cmd_sort_generic (arg, 0);
2685 int cmd_sort_newset (const char *arg)
2687 return cmd_sort_generic (arg, 1);
2690 int cmd_scan(const char *arg)
2699 printf("Session not initialized yet\n");
2703 if (!ODR_MASK_GET(session->options, Z_Options_scan))
2705 printf("Target doesn't support scan\n");
2710 strcpy (last_scan_query, arg);
2711 if (send_scanrequest(arg, 1, 20, 0) < 0)
2716 if (send_scanrequest(last_scan_query, 1, 20, last_scan_line) < 0)
2722 int cmd_schema(const char *arg)
2727 schema = xstrdup(arg);
2731 int cmd_format(const char *arg)
2736 printf("Usage: format <recordsyntax>\n");
2739 nsyntax = oid_getvalbyname (arg);
2740 if (strcmp(arg, "none") && nsyntax == VAL_NONE)
2742 printf ("unknown record syntax\n");
2745 recordsyntax = nsyntax;
2749 int cmd_elements(const char *arg)
2751 static Z_ElementSetNames esn;
2752 static char what[100];
2756 elementSetNames = 0;
2760 esn.which = Z_ElementSetNames_generic;
2761 esn.u.generic = what;
2762 elementSetNames = &esn;
2766 int cmd_attributeset(const char *arg)
2772 printf("Usage: attributeset <setname>\n");
2775 sscanf(arg, "%s", what);
2776 if (p_query_attset (what))
2778 printf("Unknown attribute set name\n");
2784 int cmd_querytype (const char *arg)
2786 if (!strcmp (arg, "ccl"))
2787 queryType = QueryType_CCL;
2788 else if (!strcmp (arg, "prefix") || !strcmp(arg, "rpn"))
2789 queryType = QueryType_Prefix;
2790 else if (!strcmp (arg, "ccl2rpn") || !strcmp (arg, "cclrpn"))
2791 queryType = QueryType_CCL2RPN;
2792 else if (!strcmp(arg, "cql"))
2793 queryType = QueryType_CQL;
2794 else if (!strcmp (arg, "cql2rpn") || !strcmp (arg, "cqlrpn"))
2795 queryType = QueryType_CQL2RPN;
2798 printf ("Querytype must be one of:\n");
2799 printf (" prefix - Prefix query\n");
2800 printf (" ccl - CCL query\n");
2801 printf (" ccl2rpn - CCL query converted to RPN\n");
2802 printf (" cql - CQL\n");
2803 printf (" cql2rpn - CQL query converted to RPN\n");
2809 int cmd_refid (const char *arg)
2815 refid = (char *) xmalloc (strlen(arg)+1);
2816 strcpy (refid, arg);
2821 int cmd_close(const char *arg)
2830 apdu = zget_APDU(out, Z_APDU_close);
2831 req = apdu->u.close;
2832 *req->closeReason = Z_Close_finished;
2834 printf("Sent close request.\n");
2839 int cmd_packagename(const char* arg)
2841 xfree (esPackageName);
2842 esPackageName = NULL;
2844 esPackageName = xstrdup(arg);
2848 int cmd_proxy(const char* arg)
2853 yazProxy = xstrdup (arg);
2857 int cmd_marccharset(const char *arg)
2862 if (sscanf(arg, "%29s", l1) < 1)
2864 xfree (marcCharset);
2866 if (strcmp(l1, "-"))
2867 marcCharset = xstrdup(l1);
2871 int cmd_charset(const char* arg)
2873 char l1[30], l2[30];
2876 if (sscanf(arg, "%29s %29s", l1, l2) < 1)
2878 printf("Current negotiation character set is `%s'\n",
2879 negotiationCharset ? negotiationCharset: "none");
2880 printf("Current output character set is `%s'\n",
2881 outputCharset ? outputCharset: "none");
2884 xfree (negotiationCharset);
2885 negotiationCharset = NULL;
2886 if (*l1 && strcmp(l1, "-"))
2888 negotiationCharset = xstrdup(l1);
2889 printf ("Character set negotiation : %s\n", negotiationCharset);
2892 printf ("Character set negotiation disabled\n");
2895 xfree (outputCharset);
2897 if (!strcmp(l2, "auto") && codeset)
2901 printf ("output charset: %s\n", codeset);
2902 outputCharset = xstrdup(codeset);
2907 printf ("No codeset found on this system\n");
2909 else if (strcmp(l2, "-"))
2910 outputCharset = xstrdup(l2);
2912 printf ("Output charset conversion disabled\n");
2918 int cmd_lang(const char* arg)
2921 printf("Current language is `%s'\n", (yazLang)?yazLang:NULL);
2928 yazLang = (char *) xmalloc (strlen(arg)+1);
2929 strcpy (yazLang, arg);
2934 int cmd_source(const char* arg)
2936 /* first should open the file and read one line at a time.. */
2938 char line[1024], *cp;
2941 fprintf(stderr,"Error in source command use a filename\n");
2945 includeFile = fopen (arg, "r");
2948 fprintf(stderr,"Unable to open file %s for reading\n",arg);
2952 while(!feof(includeFile)) {
2953 memset(line,0,sizeof(line));
2954 fgets(line,sizeof(line),includeFile);
2956 if(strlen(line) < 2) continue;
2957 if(line[0] == '#') continue;
2959 if ((cp = strrchr (line, '\n')))
2962 process_cmd_line(line);
2965 if(fclose(includeFile)<0) {
2966 perror("unable to close include file");
2972 int cmd_subshell(const char* args)
2977 system(getenv("SHELL"));
2983 int cmd_set_berfile(const char *arg)
2985 if (ber_file && ber_file != stdout && ber_file != stderr)
2987 if (!strcmp(arg, ""))
2989 else if (!strcmp(arg, "-"))
2992 ber_file = fopen(arg, "a");
2996 int cmd_set_apdufile(const char *arg)
2998 if(apdu_file && apdu_file != stderr && apdu_file != stderr)
3000 if (!strcmp(arg, ""))
3002 else if (!strcmp(arg, "-"))
3006 apdu_file = fopen(arg, "a");
3008 perror("unable to open apdu log file");
3011 odr_setprint(print, apdu_file);
3015 int cmd_set_cclfile(const char* arg)
3019 bibset = ccl_qual_mk ();
3020 inf = fopen (arg, "r");
3022 perror("unable to open CCL file");
3025 ccl_qual_file (bibset, inf);
3028 strcpy(ccl_fields,arg);
3032 int cmd_set_cqlfile(const char* arg)
3034 cql_transform_t newcqltrans;
3036 if ((newcqltrans = cql_transform_open_fname(arg)) == 0) {
3037 perror("unable to open CQL file");
3041 cql_transform_close(cqltrans);
3043 cqltrans = newcqltrans;
3044 strcpy(cql_fields, arg);
3048 int cmd_set_auto_reconnect(const char* arg)
3050 if(strlen(arg)==0) {
3051 auto_reconnect = ! auto_reconnect;
3052 } else if(strcmp(arg,"on")==0) {
3054 } else if(strcmp(arg,"off")==0) {
3057 printf("Error use on or off\n");
3062 printf("Set auto reconnect enabled.\n");
3064 printf("Set auto reconnect disabled.\n");
3069 int cmd_set_marcdump(const char* arg)
3071 if(marc_file && marc_file != stderr) { /* don't close stdout*/
3075 if (!strcmp(arg, ""))
3077 else if (!strcmp(arg, "-"))
3081 marc_file = fopen(arg, "a");
3083 perror("unable to open marc log file");
3089 this command takes 3 arge {name class oid}
3091 int cmd_register_oid(const char* args) {
3096 {"appctx",CLASS_APPCTX},
3097 {"absyn",CLASS_ABSYN},
3098 {"attset",CLASS_ATTSET},
3099 {"transyn",CLASS_TRANSYN},
3100 {"diagset",CLASS_DIAGSET},
3101 {"recsyn",CLASS_RECSYN},
3102 {"resform",CLASS_RESFORM},
3103 {"accform",CLASS_ACCFORM},
3104 {"extserv",CLASS_EXTSERV},
3105 {"userinfo",CLASS_USERINFO},
3106 {"elemspec",CLASS_ELEMSPEC},
3107 {"varset",CLASS_VARSET},
3108 {"schema",CLASS_SCHEMA},
3109 {"tagset",CLASS_TAGSET},
3110 {"general",CLASS_GENERAL},
3111 {0,(enum oid_class) 0}
3113 char oname_str[101], oclass_str[101], oid_str[101];
3116 oid_class oidclass = CLASS_GENERAL;
3117 int val = 0, oid[OID_SIZE];
3118 struct oident * new_oident=NULL;
3120 if (sscanf (args, "%100[^ ] %100[^ ] %100s",
3121 oname_str,oclass_str, oid_str) < 1) {
3122 printf("Error in regristrate command \n");
3126 for (i = 0; oid_classes[i].className; i++) {
3127 if (!strcmp(oid_classes[i].className, oclass_str))
3129 oidclass=oid_classes[i].oclass;
3134 if(!(oid_classes[i].className)) {
3135 printf("Unknonwn oid class %s\n",oclass_str);
3143 while (isdigit (*name))
3145 val = val*10 + (*name - '0');
3158 new_oident=oid_addent (oid,PROTO_GENERAL,oidclass,oname_str,VAL_DYNAMIC);
3159 if(strcmp(new_oident->desc,oname_str)) {
3160 fprintf(stderr,"oid is already named as %s, regristration faild\n",
3166 int cmd_push_command(const char* arg)
3168 #if HAVE_READLINE_HISTORY_H
3172 fprintf(stderr,"Not compiled with the readline/history module\n");
3177 void source_rcfile()
3179 /* Look for a $HOME/.yazclientrc and source it if it exists */
3180 struct stat statbuf;
3182 char* homedir=getenv("HOME");
3184 if(!homedir) return;
3186 sprintf(buffer,"%s/.yazclientrc",homedir);
3188 if(stat(buffer,&statbuf)==0) {
3192 if(stat(".yazclientrc",&statbuf)==0) {
3193 cmd_source(".yazclientrc");
3198 static void initialize(void)
3203 if (!(out = odr_createmem(ODR_ENCODE)) ||
3204 !(in = odr_createmem(ODR_DECODE)) ||
3205 !(print = odr_createmem(ODR_PRINT)))
3207 fprintf(stderr, "failed to allocate ODR streams\n");
3212 setvbuf(stdout, 0, _IONBF, 0);
3214 odr_setprint(print, apdu_file);
3216 bibset = ccl_qual_mk ();
3217 inf = fopen (ccl_fields, "r");
3220 ccl_qual_file (bibset, inf);
3224 cqltrans = cql_transform_open_fname(cql_fields);
3225 /* If this fails, no problem: we detect cqltrans == 0 later */
3227 #if HAVE_READLINE_READLINE_H
3228 rl_attempted_completion_function = (CPPFunction*)readline_completer;
3232 for(i=0; i<maxOtherInfosSupported; ++i) {
3233 extraOtherInfos[i].oidval = -1;
3240 #if HAVE_GETTIMEOFDAY
3241 struct timeval tv_start, tv_end;
3245 static void handle_srw_response(Z_SRW_searchRetrieveResponse *res)
3249 printf ("Received SRW SearchRetrieve Response\n");
3251 for (i = 0; i<res->num_diagnostics; i++)
3253 printf ("SRW diagnostic %d %s\n",
3254 *res->diagnostics[i].code,
3255 yaz_diag_srw_str(*res->diagnostics[i].code));
3257 if (res->diagnostics[i].details)
3258 printf ("Details: %s\n", res->diagnostics[i].details);
3260 if (res->numberOfRecords)
3261 printf ("Number of hits: %d\n", *res->numberOfRecords);
3262 for (i = 0; i<res->num_records; i++)
3264 Z_SRW_record *rec = res->records + i;
3266 if (rec->recordPosition)
3268 printf ("pos=%d", *rec->recordPosition);
3269 setno = *rec->recordPosition + 1;
3271 if (rec->recordSchema)
3272 printf (" schema=%s", rec->recordSchema);
3274 if (rec->recordData_buf && rec->recordData_len)
3276 fwrite(rec->recordData_buf, 1, rec->recordData_len, stdout);
3282 static void http_response(Z_HTTP_Response *hres)
3285 const char *content_type = z_HTTP_header_lookup(hres->headers,
3287 const char *connection_head = z_HTTP_header_lookup(hres->headers,
3289 if (content_type && !yaz_strcmp_del("text/xml", content_type, "; "))
3291 Z_SOAP *soap_package = 0;
3292 ODR o = odr_createmem(ODR_DECODE);
3293 Z_SOAP_Handler soap_handlers[2] = {
3294 {"http://www.loc.gov/zing/srw/v1.0/", 0,
3295 (Z_SOAP_fun) yaz_srw_codec},
3298 ret = z_soap_codec(o, &soap_package,
3299 &hres->content_buf, &hres->content_len,
3301 if (!ret && soap_package->which == Z_SOAP_generic &&
3302 soap_package->u.generic->no == 0)
3304 Z_SRW_PDU *sr = soap_package->u.generic->p;
3305 if (sr->which == Z_SRW_searchRetrieve_response)
3306 handle_srw_response(sr->u.response);
3310 else if (!ret && (soap_package->which == Z_SOAP_fault
3311 || soap_package->which == Z_SOAP_error))
3313 printf ("HTTP Error Status=%d\n", hres->code);
3314 printf ("SOAP Fault code %s\n",
3315 soap_package->u.fault->fault_code);
3316 printf ("SOAP Fault string %s\n",
3317 soap_package->u.fault->fault_string);
3325 if (hres->code != 200)
3327 printf ("HTTP Error Status=%d\n", hres->code);
3331 printf ("Decoding of SRW package failed\n");
3335 if (!strcmp(hres->version, "1.0"))
3337 /* HTTP 1.0: only if Keep-Alive we stay alive.. */
3338 if (!connection_head || strcmp(connection_head, "Keep-Alive"))
3343 /* HTTP 1.1: only if no close we stay alive .. */
3344 if (connection_head && !strcmp(connection_head, "close"))
3350 void wait_and_handle_response()
3352 int reconnect_ok = 1;
3355 int netbufferlen = 0;
3360 res = cs_get(conn, &netbuffer, &netbufferlen);
3361 if (reconnect_ok && res <= 0 && protocol == PROTO_HTTP)
3372 buf_out = odr_getbuf(out, &len_out, 0);
3374 do_hex_dump(buf_out, len_out);
3376 cs_put(conn, buf_out, len_out);
3384 printf("Target closed connection\n");
3389 odr_reset(in); /* release APDU from last round */
3391 do_hex_dump(netbuffer, res);
3392 odr_setbuf(in, netbuffer, res, 0);
3394 if (!z_GDU(in, &gdu, 0, 0))
3396 FILE *f = ber_file ? ber_file : stdout;
3397 odr_perror(in, "Decoding incoming APDU");
3398 fprintf(f, "[Near %d]\n", odr_offset(in));
3399 fprintf(f, "Packet dump:\n---------\n");
3400 odr_dumpBER(f, netbuffer, res);
3401 fprintf(f, "---------\n");
3403 z_GDU(print, &gdu, 0, 0);
3404 if (conn && cs_more(conn))
3409 odr_dumpBER(ber_file, netbuffer, res);
3410 if (apdu_file && !z_GDU(print, &gdu, 0, 0))
3412 odr_perror(print, "Failed to print incoming APDU");
3416 if (gdu->which == Z_GDU_Z3950)
3418 Z_APDU *apdu = gdu->u.z3950;
3421 case Z_APDU_initResponse:
3422 process_initResponse(apdu->u.initResponse);
3424 case Z_APDU_searchResponse:
3425 process_searchResponse(apdu->u.searchResponse);
3427 case Z_APDU_scanResponse:
3428 process_scanResponse(apdu->u.scanResponse);
3430 case Z_APDU_presentResponse:
3431 print_refid (apdu->u.presentResponse->referenceId);
3433 *apdu->u.presentResponse->numberOfRecordsReturned;
3434 if (apdu->u.presentResponse->records)
3435 display_records(apdu->u.presentResponse->records);
3437 printf("No records.\n");
3438 printf ("nextResultSetPosition = %d\n",
3439 *apdu->u.presentResponse->nextResultSetPosition);
3441 case Z_APDU_sortResponse:
3442 process_sortResponse(apdu->u.sortResponse);
3444 case Z_APDU_extendedServicesResponse:
3445 printf("Got extended services response\n");
3446 process_ESResponse(apdu->u.extendedServicesResponse);
3449 printf("Target has closed the association.\n");
3450 process_close(apdu->u.close);
3452 case Z_APDU_resourceControlRequest:
3453 process_resourceControlRequest
3454 (apdu->u.resourceControlRequest);
3456 case Z_APDU_deleteResultSetResponse:
3457 process_deleteResultSetResponse(apdu->u.
3458 deleteResultSetResponse);
3461 printf("Received unknown APDU type (%d).\n",
3467 else if (gdu->which == Z_GDU_HTTP_Response)
3469 http_response(gdu->u.HTTP_Response);
3472 if (conn && !cs_more(conn))
3477 #if HAVE_GETTIMEOFDAY
3478 gettimeofday (&tv_end, 0);
3480 printf ("S/U S/U=%ld/%ld %ld/%ld",
3481 (long) tv_start.tv_sec,
3482 (long) tv_start.tv_usec,
3483 (long) tv_end.tv_sec,
3484 (long) tv_end.tv_usec);
3486 printf ("Elapsed: %.6f\n",
3487 (double) tv_end.tv_usec / 1e6 + tv_end.tv_sec -
3488 ((double) tv_start.tv_usec / 1e6 + tv_start.tv_sec));
3495 int cmd_cclparse(const char* arg)
3498 struct ccl_rpn_node *rpn=NULL;
3501 rpn = ccl_find_str (bibset, arg, &error, &pos);
3504 printf ("%*s^ - ", 3+strlen(last_cmd)+1+pos, " ");
3505 printf ("%s\n", ccl_err_msg (error));
3511 ccl_pr_tree(rpn, stdout);
3515 ccl_rpn_delete(rpn);
3523 int cmd_set_otherinfo(const char* args)
3525 char oid[101], otherinfoString[101];
3530 sscan_res = sscanf (args, "%d %100[^ ] %100s", &otherinfoNo, oid, otherinfoString);
3532 /* reset this otherinfo */
3533 if(otherinfoNo>=maxOtherInfosSupported) {
3534 printf("Error otherinfo index to large (%d>%d)\n",otherinfoNo,maxOtherInfosSupported);
3536 extraOtherInfos[otherinfoNo].oidval = -1;
3537 if(extraOtherInfos[otherinfoNo].value) free(extraOtherInfos[otherinfoNo].value);
3541 printf("Error in set_otherinfo command \n");
3545 if(otherinfoNo>=maxOtherInfosSupported) {
3546 printf("Error otherinfo index to large (%d>%d)\n",otherinfoNo,maxOtherInfosSupported);
3550 oidval = oid_getvalbyname (oid);
3552 printf("Error in set_otherinfo command unknown oid %s \n",oid);
3555 extraOtherInfos[otherinfoNo].oidval = oidval;
3556 if(extraOtherInfos[otherinfoNo].value) free(extraOtherInfos[otherinfoNo].value);
3557 extraOtherInfos[otherinfoNo].value = strdup(otherinfoString);
3562 int cmd_list_otherinfo(const char* args)
3566 if(strlen(args)>0) {
3568 if( i >= maxOtherInfosSupported ) {
3569 printf("Error otherinfo index to large (%d>%d)\n",i,maxOtherInfosSupported);
3573 if(extraOtherInfos[i].oidval != -1)
3574 printf(" otherinfo %d %s %s\n",
3576 yaz_z3950_oid_value_to_str(
3577 (enum oid_value) extraOtherInfos[i].oidval,
3579 extraOtherInfos[i].value);
3582 for(i=0; i<maxOtherInfosSupported; ++i) {
3583 if(extraOtherInfos[i].oidval != -1)
3584 printf(" otherinfo %d %s %s\n",
3586 yaz_z3950_oid_value_to_str(
3587 (enum oid_value) extraOtherInfos[i].oidval,
3589 extraOtherInfos[i].value);
3597 int cmd_list_all(const char* args) {
3600 /* connection options */
3602 printf("Connected to : %s\n",last_open_command);
3604 if(last_open_command)
3605 printf("Not connected to : %s\n",last_open_command);
3607 printf("Not connected : \n");
3610 if(yazProxy) printf("using proxy : %s\n",yazProxy);
3612 printf("auto_reconnect : %s\n",auto_reconnect?"on":"off");
3615 printf("Authentication : none\n");
3617 switch(auth->which) {
3618 case Z_IdAuthentication_idPass:
3619 printf("Authentication : IdPass\n");
3620 printf(" Login User : %s\n",auth->u.idPass->userId?auth->u.idPass->userId:"");
3621 printf(" Login Group : %s\n",auth->u.idPass->groupId?auth->u.idPass->groupId:"");
3622 printf(" Password : %s\n",auth->u.idPass->password?auth->u.idPass->password:"");
3624 case Z_IdAuthentication_open:
3625 printf("Authentication : psOpen\n");
3626 printf(" Open string : %s\n",auth->u.open);
3629 printf("Authentication : Unknown\n");
3632 if (negotiationCharset)
3633 printf("Neg. Character set : `%s'\n", negotiationCharset);
3637 for (i = 0; i<num_databaseNames; i++) printf("%s ",databaseNames[i]);
3641 printf("CCL file : %s\n",ccl_fields);
3642 printf("CQL file : %s\n",cql_fields);
3643 printf("Query type : %s\n",query_type_as_string(queryType));
3645 printf("Named Result Sets : %s\n",setnumber==-1?"off":"on");
3647 /* piggy back options */
3648 printf("ssub/lslb/mspn : %d/%d/%d\n",smallSetUpperBound,largeSetLowerBound,mediumSetPresentNumber);
3650 /* print present related options */
3651 printf("Format : %s\n",yaz_z3950_oid_value_to_str(recordsyntax,CLASS_RECSYN));
3652 printf("Schema : %s\n",schema);
3653 printf("Elements : %s\n",elementSetNames?elementSetNames->u.generic:"");
3655 /* loging options */
3656 printf("APDU log : %s\n",apdu_file?"on":"off");
3657 printf("Record log : %s\n",marc_file?"on":"off");
3660 printf("Other Info: \n");
3661 cmd_list_otherinfo("");
3666 int cmd_clear_otherinfo(const char* args)
3668 if(strlen(args)>0) {
3670 otherinfoNo = atoi(args);
3671 if( otherinfoNo >= maxOtherInfosSupported ) {
3672 printf("Error otherinfo index to large (%d>%d)\n",otherinfoNo,maxOtherInfosSupported);
3676 if(extraOtherInfos[otherinfoNo].oidval != -1) {
3677 /* only clear if set. */
3678 extraOtherInfos[otherinfoNo].oidval=-1;
3679 free(extraOtherInfos[otherinfoNo].value);
3684 for(i=0; i<maxOtherInfosSupported; ++i) {
3685 if (extraOtherInfos[i].oidval!=-1 ) {
3686 extraOtherInfos[i].oidval=-1;
3687 free(extraOtherInfos[i].value);
3694 static int cmd_help (const char *line);
3696 typedef char *(*completerFunctionType)(const char *text, int state);
3700 int (*fun)(const char *arg);
3702 completerFunctionType rl_completerfunction;
3703 int complete_filenames;
3704 char **local_tabcompletes;
3706 {"open", cmd_open, "('tcp'|'ssl')':<host>[':'<port>][/<db>]",NULL,0,NULL},
3707 {"quit", cmd_quit, "",NULL,0,NULL},
3708 {"find", cmd_find, "<query>",NULL,0,NULL},
3709 {"delete", cmd_delete, "<setname>",NULL,0,NULL},
3710 {"base", cmd_base, "<base-name>",NULL,0,NULL},
3711 {"show", cmd_show, "<rec#>['+'<#recs>['+'<setname>]]",NULL,0,NULL},
3712 {"scan", cmd_scan, "<term>",NULL,0,NULL},
3713 {"sort", cmd_sort, "<sortkey> <flag> <sortkey> <flag> ...",NULL,0,NULL},
3714 {"sort+", cmd_sort_newset, "<sortkey> <flag> <sortkey> <flag> ...",NULL,0,NULL},
3715 {"authentication", cmd_authentication, "<acctstring>",NULL,0,NULL},
3716 {"lslb", cmd_lslb, "<largeSetLowerBound>",NULL,0,NULL},
3717 {"ssub", cmd_ssub, "<smallSetUpperBound>",NULL,0,NULL},
3718 {"mspn", cmd_mspn, "<mediumSetPresentNumber>",NULL,0,NULL},
3719 {"status", cmd_status, "",NULL,0,NULL},
3720 {"setnames", cmd_setnames, "",NULL,0,NULL},
3721 {"cancel", cmd_cancel, "",NULL,0,NULL},
3722 {"format", cmd_format, "<recordsyntax>",complete_format,0,NULL},
3723 {"schema", cmd_schema, "<schema>",complete_schema,0,NULL},
3724 {"elements", cmd_elements, "<elementSetName>",NULL,0,NULL},
3725 {"close", cmd_close, "",NULL,0,NULL},
3726 {"attributeset", cmd_attributeset, "<attrset>",complete_attributeset,0,NULL},
3727 {"querytype", cmd_querytype, "<type>",complete_querytype,0,NULL},
3728 {"refid", cmd_refid, "<id>",NULL,0,NULL},
3729 {"itemorder", cmd_itemorder, "ill|item <itemno>",NULL,0,NULL},
3730 {"update", cmd_update, "<action> <recid> [<file>]",NULL,0,NULL},
3731 {"update0", cmd_update0, "<action> <recid> [<file>]",NULL,0,NULL},
3732 {"packagename", cmd_packagename, "<packagename>",NULL,0,NULL},
3733 {"proxy", cmd_proxy, "[('tcp'|'ssl')]<host>[':'<port>]",NULL,0,NULL},
3734 {"charset", cmd_charset, "<nego_charset> <output_charset>",NULL,0,NULL},
3735 {"marccharset", cmd_marccharset, "<charset_name>",NULL,0,NULL},
3736 {"lang", cmd_lang, "<language_code>",NULL,0,NULL},
3737 {".", cmd_source, "<filename>",NULL,1,NULL},
3738 {"!", cmd_subshell, "Subshell command",NULL,1,NULL},
3739 {"set_apdufile", cmd_set_apdufile, "<filename>",NULL,1,NULL},
3740 {"set_berfile", cmd_set_berfile, "<filename>",NULL,1,NULL},
3741 {"set_marcdump", cmd_set_marcdump," <filename>",NULL,1,NULL},
3742 {"set_cclfile", cmd_set_cclfile," <filename>",NULL,1,NULL},
3743 {"set_cqlfile", cmd_set_cqlfile," <filename>",NULL,1,NULL},
3744 {"set_auto_reconnect", cmd_set_auto_reconnect," on|off",complete_auto_reconnect,1,NULL},
3745 {"set_otherinfo", cmd_set_otherinfo,"<otherinfoinddex> <oid> <string>",NULL,0,NULL},
3746 {"register_oid", cmd_register_oid,"<name> <class> <oid>",NULL,0,NULL},
3747 {"push_command", cmd_push_command,"<command>",command_generator,0,NULL},
3748 {"register_tab", cmd_register_tab,"<commandname> <tab>",command_generator,0,NULL},
3749 {"cclparse", cmd_cclparse,"<ccl find command>",NULL,0,NULL},
3750 {"list_otherinfo",cmd_list_otherinfo,"[otherinfoinddex]",NULL,0,NULL},
3751 {"list_all",cmd_list_all,"",NULL,0,NULL},
3752 {"clear_otherinfo",cmd_clear_otherinfo,"",NULL,0,NULL},
3753 /* Server Admin Functions */
3754 {"adm-reindex", cmd_adm_reindex, "<database-name>",NULL,0,NULL},
3755 {"adm-truncate", cmd_adm_truncate, "('database'|'index')<object-name>",NULL,0,NULL},
3756 {"adm-create", cmd_adm_create, "",NULL,0,NULL},
3757 {"adm-drop", cmd_adm_drop, "('database'|'index')<object-name>",NULL,0,NULL},
3758 {"adm-import", cmd_adm_import, "<record-type> <dir> <pattern>",NULL,0,NULL},
3759 {"adm-refresh", cmd_adm_refresh, "",NULL,0,NULL},
3760 {"adm-commit", cmd_adm_commit, "",NULL,0,NULL},
3761 {"adm-shutdown", cmd_adm_shutdown, "",NULL,0,NULL},
3762 {"adm-startup", cmd_adm_startup, "",NULL,0,NULL},
3763 {"help", cmd_help, "", NULL,0,NULL},
3767 static int cmd_help (const char *line)
3773 sscanf (line, "%20s", topic);
3776 printf("Commands:\n");
3777 for (i = 0; cmd_array[i].cmd; i++)
3778 if (*topic == 0 || strcmp (topic, cmd_array[i].cmd) == 0)
3779 printf(" %s %s\n", cmd_array[i].cmd, cmd_array[i].ad);
3780 if (strcmp (topic, "find") == 0)
3783 printf (" \"term\" Simple Term\n");
3784 printf (" @attr [attset] type=value op Attribute\n");
3785 printf (" @and opl opr And\n");
3786 printf (" @or opl opr Or\n");
3787 printf (" @not opl opr And-Not\n");
3788 printf (" @set set Result set\n");
3790 printf ("Bib-1 attribute types\n");
3792 printf ("4=Title 7=ISBN 8=ISSN 30=Date 62=Abstract 1003=Author 1016=Any\n");
3793 printf ("2=Relation: ");
3794 printf ("1< 2<= 3= 4>= 5> 6!= 102=Relevance\n");
3795 printf ("3=Position: ");
3796 printf ("1=First in Field 2=First in subfield 3=Any position\n");
3797 printf ("4=Structure: ");
3798 printf ("1=Phrase 2=Word 3=Key 4=Year 5=Date 6=WordList\n");
3799 printf ("5=Truncation: ");
3800 printf ("1=Right 2=Left 3=L&R 100=No 101=# 102=Re-1 103=Re-2\n");
3801 printf ("6=Completeness:");
3802 printf ("1=Incomplete subfield 2=Complete subfield 3=Complete field\n");
3807 int cmd_register_tab(const char* arg) {
3809 char command[101], tabargument[101];
3814 if (sscanf (arg, "%100s %100s", command, tabargument) < 1) {
3818 /* locate the amdn in the list */
3819 for (i = 0; cmd_array[i].cmd; i++) {
3820 if (!strncmp(cmd_array[i].cmd, command, strlen(command))) {
3825 if(!cmd_array[i].cmd) {
3826 fprintf(stderr,"Unknown command %s\n",command);
3831 if(!cmd_array[i].local_tabcompletes)
3832 cmd_array[i].local_tabcompletes = (char **) calloc(1,sizeof(char**));
3836 tabslist = cmd_array[i].local_tabcompletes;
3837 for(;tabslist && *tabslist;tabslist++) {
3841 cmd_array[i].local_tabcompletes = (char **)
3842 realloc(cmd_array[i].local_tabcompletes,(num_of_tabs+2)*sizeof(char**));
3843 tabslist=cmd_array[i].local_tabcompletes;
3844 tabslist[num_of_tabs]=strdup(tabargument);
3845 tabslist[num_of_tabs+1]=NULL;
3850 void process_cmd_line(char* line)
3853 char word[32], arg[1024];
3855 #if HAVE_GETTIMEOFDAY
3856 gettimeofday (&tv_start, 0);
3859 if ((res = sscanf(line, "%31s %1023[^;]", word, arg)) <= 0)
3861 strcpy(word, last_cmd);
3866 strcpy(last_cmd, word);
3868 /* removed tailing spaces from the arg command */
3871 char* lastnonspace=NULL;
3879 *(++lastnonspace) = 0;
3882 for (i = 0; cmd_array[i].cmd; i++)
3883 if (!strncmp(cmd_array[i].cmd, word, strlen(word)))
3885 res = (*cmd_array[i].fun)(arg);
3889 if (!cmd_array[i].cmd) /* dump our help-screen */
3891 printf("Unknown command: %s.\n", word);
3892 printf("use help for list of commands\n");
3893 /* cmd_help (""); */
3897 if(apdu_file) fflush(apdu_file);
3900 wait_and_handle_response();
3909 char *command_generator(const char *text, int state)
3915 for( ; cmd_array[idx].cmd; ++idx) {
3916 if (!strncmp(cmd_array[idx].cmd,text,strlen(text))) {
3917 ++idx; /* skip this entry on the next run */
3918 return strdup(cmd_array[idx-1].cmd);
3926 This function only known how to complete on the first word
3928 char ** readline_completer(char *text, int start, int end) {
3929 #if HAVE_READLINE_READLINE_H
3931 completerFunctionType completerToUse;
3934 #if HAVE_READLINE_RL_COMPLETION_MATCHES
3935 char** res=rl_completion_matches(text,
3938 char** res=completion_matches(text,
3939 (CPFunction*)command_generator);
3941 rl_attempted_completion_over = 1;
3944 char arg[1024],word[32];
3946 if ((res = sscanf(rl_line_buffer, "%31s %1023[^;]", word, arg)) <= 0) {
3947 rl_attempted_completion_over = 1;
3951 for (i = 0; cmd_array[i].cmd; i++) {
3952 if (!strncmp(cmd_array[i].cmd, word, strlen(word))) {
3957 if(!cmd_array[i].cmd) return NULL;
3959 curret_global_list = cmd_array[i].local_tabcompletes;
3961 completerToUse = cmd_array[i].rl_completerfunction;
3962 if(completerToUse==NULL) /* if no pr. command completer is defined use the default completer */
3963 completerToUse = default_completer;
3965 if(completerToUse) {
3966 #ifdef HAVE_READLINE_RL_COMPLETION_MATCHES
3968 rl_completion_matches(text,
3972 completion_matches(text,
3973 (CPFunction*)completerToUse);
3975 if(!cmd_array[i].complete_filenames)
3976 rl_attempted_completion_over = 1;
3979 if(!cmd_array[i].complete_filenames)
3980 rl_attempted_completion_over = 1;
3990 static void client(void)
3996 #if HAVE_GETTIMEOFDAY
3997 gettimeofday (&tv_start, 0);
4002 char *line_in = NULL;
4003 #if HAVE_READLINE_READLINE_H
4006 line_in=readline(C_PROMPT);
4009 #if HAVE_READLINE_HISTORY_H
4011 add_history(line_in);
4013 strncpy(line, line_in, 1023);
4022 if (!fgets(line, 1023, stdin))
4024 if ((end_p = strchr (line, '\n')))
4027 process_cmd_line(line);
4031 static void show_version(void)
4035 yaz_version(vstr, 0);
4036 printf ("YAZ version: %s\n", YAZ_VERSION);
4037 if (strcmp(vstr, YAZ_VERSION))
4038 printf ("YAZ DLL/SO: %s\n", vstr);
4042 int main(int argc, char **argv)
4045 char *open_command = 0;
4046 char *auth_command = 0;
4051 if (!setlocale(LC_CTYPE, ""))
4052 fprintf (stderr, "setlocale failed\n");
4056 codeset = nl_langinfo(CODESET);
4060 outputCharset = xstrdup(codeset);
4062 while ((ret = options("k:c:q:a:b:m:v:p:u:t:Vxd:", argv, argc, &arg)) != -2)
4069 open_command = (char *) xmalloc (strlen(arg)+6);
4070 strcpy (open_command, "open ");
4071 strcat (open_command, arg);
4075 dump_file_prefix = arg;
4078 kilobytes = atoi(arg);
4081 if (!(marc_file = fopen (arg, "a")))
4088 outputCharset = xstrdup(arg);
4091 strncpy (ccl_fields, arg, sizeof(ccl_fields)-1);
4092 ccl_fields[sizeof(ccl_fields)-1] = '\0';
4095 strncpy (cql_fields, arg, sizeof(cql_fields)-1);
4096 cql_fields[sizeof(cql_fields)-1] = '\0';
4099 if (!strcmp(arg, "-"))
4102 ber_file=fopen(arg, "a");
4105 if (!strcmp(arg, "-"))
4108 apdu_file=fopen(arg, "a");
4114 yazProxy=strdup(arg);
4119 auth_command = (char *) xmalloc (strlen(arg)+6);
4120 strcpy (auth_command, "auth ");
4121 strcat (auth_command, arg);
4125 yaz_log_init(yaz_log_mask_str(arg), "", 0);
4131 fprintf (stderr, "Usage: %s [-m <marclog>] [ -a <apdulog>] "
4132 "[-b berdump] [-c cclfields] \n"
4133 "[-q cqlfields] [-p <proxy-addr>] [-u <auth>] "
4134 "[-k size] [-d dump] [-V] [<server-addr>]\n",
4142 #ifdef HAVE_GETTIMEOFDAY
4143 gettimeofday (&tv_start, 0);
4145 process_cmd_line (auth_command);
4146 #if HAVE_READLINE_HISTORY_H
4147 add_history(auth_command);
4149 xfree(auth_command);
4153 #ifdef HAVE_GETTIMEOFDAY
4154 gettimeofday (&tv_start, 0);
4156 process_cmd_line (open_command);
4157 #if HAVE_READLINE_HISTORY_H
4158 add_history(open_command);
4160 xfree(open_command);
4171 * vim600: sw=4 ts=8 fdm=marker
4172 * vim<600: sw=4 ts=8