2 * Copyright (c) 1995-2004, Index Data
3 * See the file LICENSE for details.
5 * $Id: client.c,v 1.238 2004-04-07 13:51:50 adam Exp $
24 #define S_ISREG(x) (x & _S_IFREG)
25 #define S_ISDIR(x) (x & _S_IFDIR)
28 #include <yaz/yaz-util.h>
30 #include <yaz/comstack.h>
32 #include <yaz/proto.h>
33 #include <yaz/marcdisp.h>
34 #include <yaz/diagbib1.h>
35 #include <yaz/otherinfo.h>
36 #include <yaz/charneg.h>
38 #include <yaz/pquery.h>
39 #include <yaz/sortspec.h>
43 #include <yaz/yaz-ccl.h>
46 #if HAVE_READLINE_READLINE_H
47 #include <readline/readline.h>
50 #if HAVE_READLINE_HISTORY_H
51 #include <readline/history.h>
57 #include "tabcomplete.h"
59 #define C_PROMPT "Z> "
61 static char *codeset = 0; /* character set for output */
62 static int hex_dump = 0;
63 static char *dump_file_prefix = 0;
64 static ODR out, in, print; /* encoding and decoding streams */
66 static ODR srw_sr_odr_out = 0;
67 static Z_SRW_PDU *srw_sr = 0;
69 static FILE *apdu_file = 0;
70 static FILE *ber_file = 0;
71 static COMSTACK conn = 0; /* our z-association */
72 static Z_IdAuthentication *auth = 0; /* our current auth definition */
73 char *databaseNames[128];
74 int num_databaseNames = 0;
75 static Z_External *record_last = 0;
76 static int setnumber = -1; /* current result set number */
77 static int smallSetUpperBound = 0;
78 static int largeSetLowerBound = 1;
79 static int mediumSetPresentNumber = 0;
80 static Z_ElementSetNames *elementSetNames = 0;
81 static int setno = 1; /* current set offset */
82 static enum oid_proto protocol = PROTO_Z3950; /* current app protocol */
83 static enum oid_value recordsyntax = VAL_USMARC;
84 static char *record_schema = 0;
85 static int sent_close = 0;
86 static NMEM session_mem = NULL; /* memory handle for init-response */
87 static Z_InitResponse *session = 0; /* session parameters */
88 static char last_scan_line[512] = "0";
89 static char last_scan_query[512] = "0";
90 static char ccl_fields[512] = "default.bib";
91 /* ### How can I set this path to use wherever YAZ is installed? */
92 static char cql_fields[512] = "/usr/local/share/yaz/etc/pqf.properties";
93 static char *esPackageName = 0;
94 static char *yazProxy = 0;
95 static int kilobytes = 1024;
96 static char *negotiationCharset = 0;
97 static char *outputCharset = 0;
98 static char *marcCharset = 0;
99 static char* yazLang = 0;
100 static char* http_version = "1.1";
102 static char last_cmd[32] = "?";
103 static FILE *marc_file = 0;
104 static char *refid = NULL;
105 static char *last_open_command = NULL;
106 static int auto_reconnect = 0;
107 static Odr_bitmask z3950_options;
108 static int z3950_version = 3;
110 static char cur_host[200];
120 static QueryType queryType = QueryType_Prefix;
122 static CCL_bibset bibset; /* CCL bibset handle */
123 static cql_transform_t cqltrans; /* CQL context-set handle */
125 #if HAVE_READLINE_COMPLETION_OVER
128 /* readline doesn't have this var. Define it ourselves. */
129 int rl_attempted_completion_over = 0;
132 /* set this one to 1, to avoid decode of unknown MARCs */
133 #define AVOID_MARC_DECODE 1
135 #define maxOtherInfosSupported 10
139 } extraOtherInfos[maxOtherInfosSupported];
142 void process_cmd_line(char* line);
143 char ** readline_completer(char *text, int start, int end);
144 char *command_generator(const char *text, int state);
145 char** curret_global_list=NULL;
146 int cmd_register_tab(const char* arg);
148 static void close_session (void);
150 ODR getODROutputStream()
155 const char* query_type_as_string(QueryType q)
158 case QueryType_Prefix: return "prefix (RPN sent to server)";
159 case QueryType_CCL: return "CCL (CCL sent to server) ";
160 case QueryType_CCL2RPN: return "CCL -> RPN (RPN sent to server)";
161 case QueryType_CQL: return "CQL (CQL sent to server)";
162 case QueryType_CQL2RPN: return "CQL -> RPN (RPN sent to server)";
164 return "unknown Query type internal yaz-client error";
168 static void do_hex_dump(const char* buf, int len)
173 for( i=0; i<len ; i=i+16 )
176 for(x=0 ; i+x<len && x<16; ++x)
178 printf("%2.2X ",(unsigned int)((unsigned char)buf[i+x]));
183 if (dump_file_prefix)
186 if (++no < 1000 && strlen(dump_file_prefix) < 500)
190 sprintf (fname, "%s.%03d.raw", dump_file_prefix, no);
191 of = fopen(fname, "wb");
193 fwrite (buf, 1, len, of);
200 void add_otherInfos(Z_APDU *a)
202 Z_OtherInformation **oi;
206 for(i=0; i<maxOtherInfosSupported; ++i)
208 if(extraOtherInfos[i].oidval != -1)
209 yaz_oi_set_string_oidval(oi, out, extraOtherInfos[i].oidval,
210 1, extraOtherInfos[i].value);
214 int send_apdu(Z_APDU *a)
223 z_APDU(print, &a, 0, 0);
226 if (!z_APDU(out, &a, 0, 0))
228 odr_perror(out, "Encoding APDU");
232 buf = odr_getbuf(out, &len, 0);
234 odr_dumpBER(ber_file, buf, len);
235 /* printf ("sending APDU of size %d\n", len); */
236 do_hex_dump(buf, len);
237 if (cs_put(conn, buf, len) < 0)
239 fprintf(stderr, "cs_put: %s", cs_errmsg(cs_errno(conn)));
243 odr_reset(out); /* release the APDU structure */
247 static void print_stringn(const unsigned char *buf, size_t len)
250 for (i = 0; i<len; i++)
251 if ((buf[i] <= 126 && buf[i] >= 32) || strchr ("\n\r\t\f", buf[i]))
252 printf ("%c", buf[i]);
254 printf ("\\X%02X", buf[i]);
257 static void print_refid (Z_ReferenceId *id)
261 printf ("Reference Id: ");
262 print_stringn (id->buf, id->len);
267 static Z_ReferenceId *set_refid (ODR out)
272 id = (Z_ReferenceId *) odr_malloc (out, sizeof(*id));
273 id->size = id->len = strlen(refid);
274 id->buf = (unsigned char *) odr_malloc (out, id->len);
275 memcpy (id->buf, refid, id->len);
279 /* INIT SERVICE ------------------------------- */
281 static void send_initRequest(const char* type_and_host)
283 Z_APDU *apdu = zget_APDU(out, Z_APDU_initRequest);
284 Z_InitRequest *req = apdu->u.initRequest;
287 req->options = &z3950_options;
289 ODR_MASK_ZERO(req->protocolVersion);
290 for (i = 0; i<z3950_version; i++)
291 ODR_MASK_SET(req->protocolVersion, i);
293 *req->maximumRecordSize = 1024*kilobytes;
294 *req->preferredMessageSize = 1024*kilobytes;
296 req->idAuthentication = auth;
298 req->referenceId = set_refid (out);
300 if (yazProxy && type_and_host)
301 yaz_oi_set_string_oidval(&req->otherInfo, out, VAL_PROXY,
304 if (negotiationCharset || yazLang) {
305 Z_OtherInformation **p;
306 Z_OtherInformationUnit *p0;
308 yaz_oi_APDU(apdu, &p);
310 if ((p0=yaz_oi_update(p, out, NULL, 0, 0))) {
311 ODR_MASK_SET(req->options, Z_Options_negotiationModel);
313 p0->which = Z_OtherInfo_externallyDefinedInfo;
314 p0->information.externallyDefinedInfo =
315 yaz_set_proposal_charneg(
317 (const char**)&negotiationCharset,
318 negotiationCharset ? 1 : 0,
319 (const char**)&yazLang, yazLang ? 1 : 0, 1);
324 printf("Sent initrequest.\n");
328 /* These two are used only from process_initResponse() */
329 static void render_initUserInfo(Z_OtherInformation *ui1);
330 static void render_diag(Z_DiagnosticFormat *diag);
332 static void pr_opt(const char *opt, void *clientData)
337 static int process_initResponse(Z_InitResponse *res)
340 /* save session parameters for later use */
341 session_mem = odr_extract_mem(in);
344 for (ver = 0; ver < 8; ver++)
345 if (!ODR_MASK_GET(res->protocolVersion, ver))
349 printf("Connection rejected by v%d target.\n", ver);
351 printf("Connection accepted by v%d target.\n", ver);
352 if (res->implementationId)
353 printf("ID : %s\n", res->implementationId);
354 if (res->implementationName)
355 printf("Name : %s\n", res->implementationName);
356 if (res->implementationVersion)
357 printf("Version: %s\n", res->implementationVersion);
358 if (res->userInformationField)
360 Z_External *uif = res->userInformationField;
361 if (uif->which == Z_External_userInfo1) {
362 render_initUserInfo(uif->u.userInfo1);
364 printf("UserInformationfield:\n");
365 if (!z_External(print, (Z_External**)&uif, 0, 0)) {
366 odr_perror(print, "Printing userinfo\n");
369 if (uif->which == Z_External_octet) {
370 printf("Guessing visiblestring:\n");
371 printf("'%s'\n", uif->u. octet_aligned->buf);
372 } else if (uif->which == Z_External_single) {
373 /* Peek at any private Init-diagnostic APDUs */
374 Odr_any *sat = uif->u.single_ASN1_type;
375 printf("### NAUGHTY: External is '%s'\n", sat->buf);
381 yaz_init_opt_decode(res->options, pr_opt, 0);
384 if (ODR_MASK_GET(res->options, Z_Options_namedResultSets))
387 if (ODR_MASK_GET(res->options, Z_Options_negotiationModel)) {
389 Z_CharSetandLanguageNegotiation *p =
390 yaz_get_charneg_record(res->otherInfo);
394 char *charset=NULL, *lang=NULL;
397 yaz_get_response_charneg(session_mem, p, &charset, &lang,
400 if (outputCharset && negotiationCharset) {
401 odr_set_charset (out, charset, outputCharset);
402 odr_set_charset (in, outputCharset, charset);
405 odr_set_charset (out, 0, 0);
406 odr_set_charset (in, 0, 0);
409 printf("Accepted character set : %s\n", charset);
410 printf("Accepted code language : %s\n", lang ? lang : "none");
411 printf("Accepted records in ...: %d\n", selected );
419 static void render_initUserInfo(Z_OtherInformation *ui1) {
421 printf("Init response contains %d otherInfo unit%s:\n",
422 ui1->num_elements, ui1->num_elements == 1 ? "" : "s");
424 for (i = 0; i < ui1->num_elements; i++) {
425 Z_OtherInformationUnit *unit = ui1->list[i];
426 printf(" %d: otherInfo unit contains ", i+1);
427 if (unit->which == Z_OtherInfo_externallyDefinedInfo &&
428 unit->information.externallyDefinedInfo->which ==
430 render_diag(unit->information.externallyDefinedInfo->u.diag1);
432 printf("unsupported otherInfo unit type %d\n", unit->which);
438 /* ### should this share code with display_diagrecs()? */
439 static void render_diag(Z_DiagnosticFormat *diag) {
442 printf("%d diagnostic%s:\n", diag->num, diag->num == 1 ? "" : "s");
443 for (i = 0; i < diag->num; i++) {
444 Z_DiagnosticFormat_s *ds = diag->elements[i];
445 printf(" %d: ", i+1);
447 case Z_DiagnosticFormat_s_defaultDiagRec: {
448 Z_DefaultDiagFormat *dd = ds->u.defaultDiagRec;
449 /* ### should check `dd->diagnosticSetId' */
450 printf("code=%d (%s)", *dd->condition,
451 diagbib1_str(*dd->condition));
452 /* Both types of addinfo are the same, so use type-pun */
453 if (dd->u.v2Addinfo != 0)
454 printf(",\n\taddinfo='%s'", dd->u.v2Addinfo);
457 case Z_DiagnosticFormat_s_explicitDiagnostic:
458 printf("Explicit diagnostic (not supported)");
461 printf("Unrecognised diagnostic type %d", ds->which);
465 if (ds->message != 0)
466 printf(", message='%s'", ds->message);
472 static int set_base(const char *arg)
477 for (i = 0; i<num_databaseNames; i++)
478 xfree (databaseNames[i]);
479 num_databaseNames = 0;
483 if (!(cp = strchr(arg, ' ')))
484 cp = arg + strlen(arg);
487 databaseNames[num_databaseNames] = (char *)xmalloc (1 + cp - arg);
488 memcpy (databaseNames[num_databaseNames], arg, cp - arg);
489 databaseNames[num_databaseNames][cp - arg] = '\0';
491 for (cp1 = databaseNames[num_databaseNames]; *cp1 ; cp1++)
500 if (num_databaseNames == 0)
502 num_databaseNames = 1;
503 databaseNames[0] = xstrdup("");
508 static int cmd_base(const char *arg)
512 printf("Usage: base <database> <database> ...\n");
515 return set_base(arg);
518 void cmd_open_remember_last_open_command(const char* arg, char* new_open_command)
520 if(last_open_command != arg)
522 if(last_open_command) xfree(last_open_command);
523 last_open_command = xstrdup(new_open_command);
527 int session_connect(const char *arg)
530 char type_and_host[101];
531 const char *basep = 0;
538 nmem_destroy (session_mem);
542 cs_get_host_args(arg, &basep);
544 strncpy(type_and_host, arg, sizeof(type_and_host)-1);
545 type_and_host[sizeof(type_and_host)-1] = '\0';
547 cmd_open_remember_last_open_command(arg,type_and_host);
550 conn = cs_create_host(yazProxy, 1, &add);
552 conn = cs_create_host(arg, 1, &add);
555 printf ("Couldn't create comstack\n");
560 if (conn->protocol == PROTO_HTTP)
562 printf ("SRW/HTTP not enabled in this YAZ\n");
568 protocol = conn->protocol;
569 if (conn->protocol == PROTO_HTTP)
573 printf("Connecting...");
575 if (cs_connect(conn, add) < 0)
577 printf ("error = %s\n", cs_strerror(conn));
578 if (conn->cerrno == CSYSERR)
581 yaz_strerror(msg, sizeof(msg));
582 printf ("%s\n", msg);
591 if (protocol == PROTO_Z3950)
593 send_initRequest(type_and_host);
599 int cmd_open(const char *arg)
603 strncpy (cur_host, arg, sizeof(cur_host)-1);
604 cur_host[sizeof(cur_host)-1] = 0;
606 return session_connect(cur_host);
613 if(!( auto_reconnect && last_open_command) ) return ;
615 open_command = (char *) xmalloc (strlen(last_open_command)+6);
616 strcpy (open_command, "open ");
618 strcat (open_command, last_open_command);
620 process_cmd_line(open_command);
625 int cmd_authentication(const char *arg)
627 static Z_IdAuthentication au;
628 static char user[40], group[40], pass[40];
629 static Z_IdPass idPass;
634 printf("Auth field set to null\n");
638 r = sscanf (arg, "%39s %39s %39s", user, group, pass);
641 printf("Authentication set to null\n");
647 if (!strcmp(user, "-")) {
648 au.which = Z_IdAuthentication_anonymous;
649 printf("Authentication set to Anonymous\n");
651 au.which = Z_IdAuthentication_open;
653 printf("Authentication set to Open (%s)\n", user);
659 au.which = Z_IdAuthentication_idPass;
660 au.u.idPass = &idPass;
661 idPass.groupId = NULL;
662 idPass.userId = user;
663 idPass.password = group;
664 printf("Authentication set to User (%s), Pass (%s)\n", user, group);
669 au.which = Z_IdAuthentication_idPass;
670 au.u.idPass = &idPass;
671 idPass.groupId = group;
672 idPass.userId = user;
673 idPass.password = pass;
674 printf("Authentication set to User (%s), Group (%s), Pass (%s)\n",
680 /* SEARCH SERVICE ------------------------------ */
681 static void display_record(Z_External *r);
683 static void print_record(const unsigned char *buf, size_t len)
686 print_stringn (buf, len);
687 /* add newline if not already added ... */
688 if (i <= 0 || buf[i-1] != '\n')
692 static void display_record(Z_External *r)
694 oident *ent = oid_getentbyoid(r->direct_reference);
698 * Tell the user what we got.
700 if (r->direct_reference)
702 printf("Record type: ");
704 printf("%s\n", ent->desc);
705 else if (!odr_oid(print, &r->direct_reference, 0, 0))
707 odr_perror(print, "print oid");
711 /* Check if this is a known, ASN.1 type tucked away in an octet string */
712 if (ent && r->which == Z_External_octet)
714 Z_ext_typeent *type = z_ext_getentbyref(ent->value);
720 * Call the given decoder to process the record.
722 odr_setbuf(in, (char*)r->u.octet_aligned->buf,
723 r->u.octet_aligned->len, 0);
724 if (!(*type->fun)(in, &rr, 0, 0))
726 odr_perror(in, "Decoding constructed record.");
727 fprintf(stdout, "[Near %d]\n", odr_offset(in));
728 fprintf(stdout, "Packet dump:\n---------\n");
729 odr_dumpBER(stdout, (char*)r->u.octet_aligned->buf,
730 r->u.octet_aligned->len);
731 fprintf(stdout, "---------\n");
733 /* note just ignores the error ant print the bytes form the octet_aligned later */
736 * Note: we throw away the original, BER-encoded record here.
737 * Do something else with it if you want to keep it.
739 r->u.sutrs = (Z_SUTRS *) rr; /* we don't actually check the type here. */
740 r->which = type->what;
744 if (ent && ent->value == VAL_SOIF)
745 print_record((const unsigned char *) r->u.octet_aligned->buf,
746 r->u.octet_aligned->len);
747 else if (r->which == Z_External_octet)
749 const char *octet_buf = (char*)r->u.octet_aligned->buf;
750 if (ent->oclass == CLASS_RECSYN &&
751 (ent->value == VAL_TEXT_XML ||
752 ent->value == VAL_APPLICATION_XML ||
753 ent->value == VAL_HTML))
755 print_record((const unsigned char *) octet_buf,
756 r->u.octet_aligned->len);
758 else if (ent->value == VAL_POSTSCRIPT)
760 int size = r->u.octet_aligned->len;
763 print_record((const unsigned char *) octet_buf, size);
768 #if AVOID_MARC_DECODE
769 /* primitive check for a marc OID 5.1-29 except 16 */
770 ent->oidsuffix[0] == 5 && ent->oidsuffix[1] < 30 &&
771 ent->oidsuffix[1] != 16
780 yaz_marc_t mt = yaz_marc_create();
782 if (yaz_marc_decode_buf(mt, octet_buf,r->u.octet_aligned->len,
786 if (marcCharset && !strcmp(marcCharset, "auto"))
788 if (ent->value == VAL_USMARC)
790 if (octet_buf[9] == 'a')
798 else if (marcCharset)
800 if (outputCharset && from)
802 cd = yaz_iconv_open(outputCharset, from);
803 printf ("convert from %s to %s", from,
806 printf (" unsupported\n");
811 fwrite (result, 1, rlen, stdout);
815 size_t inbytesleft = rlen;
816 const char *inp = result;
820 size_t outbytesleft = sizeof(outbuf);
824 r = yaz_iconv (cd, (char**) &inp,
826 &outp, &outbytesleft);
827 if (r == (size_t) (-1))
829 int e = yaz_iconv_error(cd);
830 if (e != YAZ_ICONV_E2BIG)
833 fwrite (outbuf, outp - outbuf, 1, stdout);
839 printf ("bad MARC. Dumping as it is:\n");
840 print_record((const unsigned char*) octet_buf,
841 r->u.octet_aligned->len);
843 yaz_marc_destroy(mt);
849 print_record((const unsigned char*) octet_buf,
850 r->u.octet_aligned->len);
854 fwrite (octet_buf, 1, r->u.octet_aligned->len, marc_file);
856 else if (ent && ent->value == VAL_SUTRS)
858 if (r->which != Z_External_sutrs)
860 printf("Expecting single SUTRS type for SUTRS.\n");
863 print_record(r->u.sutrs->buf, r->u.sutrs->len);
865 else if (ent && ent->value == VAL_GRS1)
868 if (r->which != Z_External_grs1)
870 printf("Expecting single GRS type for GRS.\n");
874 yaz_display_grs1(w, r->u.grs1, 0);
878 else if ( /* OPAC display not complete yet .. */
879 ent && ent->value == VAL_OPAC)
882 if (r->u.opac->bibliographicRecord)
883 display_record(r->u.opac->bibliographicRecord);
884 for (i = 0; i<r->u.opac->num_holdingsData; i++)
886 Z_HoldingsRecord *h = r->u.opac->holdingsData[i];
887 if (h->which == Z_HoldingsRecord_marcHoldingsRecord)
889 printf ("MARC holdings %d\n", i);
890 display_record(h->u.marcHoldingsRecord);
892 else if (h->which == Z_HoldingsRecord_holdingsAndCirc)
896 Z_HoldingsAndCircData *data = h->u.holdingsAndCirc;
898 printf ("Data holdings %d\n", i);
899 if (data->typeOfRecord)
900 printf ("typeOfRecord: %s\n", data->typeOfRecord);
901 if (data->encodingLevel)
902 printf ("encodingLevel: %s\n", data->encodingLevel);
903 if (data->receiptAcqStatus)
904 printf ("receiptAcqStatus: %s\n", data->receiptAcqStatus);
905 if (data->generalRetention)
906 printf ("generalRetention: %s\n", data->generalRetention);
907 if (data->completeness)
908 printf ("completeness: %s\n", data->completeness);
909 if (data->dateOfReport)
910 printf ("dateOfReport: %s\n", data->dateOfReport);
912 printf ("nucCode: %s\n", data->nucCode);
913 if (data->localLocation)
914 printf ("localLocation: %s\n", data->localLocation);
915 if (data->shelvingLocation)
916 printf ("shelvingLocation: %s\n", data->shelvingLocation);
917 if (data->callNumber)
918 printf ("callNumber: %s\n", data->callNumber);
919 if (data->shelvingData)
920 printf ("shelvingData: %s\n", data->shelvingData);
921 if (data->copyNumber)
922 printf ("copyNumber: %s\n", data->copyNumber);
923 if (data->publicNote)
924 printf ("publicNote: %s\n", data->publicNote);
925 if (data->reproductionNote)
926 printf ("reproductionNote: %s\n", data->reproductionNote);
927 if (data->termsUseRepro)
928 printf ("termsUseRepro: %s\n", data->termsUseRepro);
929 if (data->enumAndChron)
930 printf ("enumAndChron: %s\n", data->enumAndChron);
931 for (j = 0; j<data->num_volumes; j++)
933 printf ("volume %d\n", j);
934 if (data->volumes[j]->enumeration)
935 printf (" enumeration: %s\n",
936 data->volumes[j]->enumeration);
937 if (data->volumes[j]->chronology)
938 printf (" chronology: %s\n",
939 data->volumes[j]->chronology);
940 if (data->volumes[j]->enumAndChron)
941 printf (" enumAndChron: %s\n",
942 data->volumes[j]->enumAndChron);
944 for (j = 0; j<data->num_circulationData; j++)
946 printf ("circulation %d\n", j);
947 if (data->circulationData[j]->availableNow)
948 printf (" availableNow: %d\n",
949 *data->circulationData[j]->availableNow);
950 if (data->circulationData[j]->availablityDate)
951 printf (" availabiltyDate: %s\n",
952 data->circulationData[j]->availablityDate);
953 if (data->circulationData[j]->availableThru)
954 printf (" availableThru: %s\n",
955 data->circulationData[j]->availableThru);
956 if (data->circulationData[j]->restrictions)
957 printf (" restrictions: %s\n",
958 data->circulationData[j]->restrictions);
959 if (data->circulationData[j]->itemId)
960 printf (" itemId: %s\n",
961 data->circulationData[j]->itemId);
962 if (data->circulationData[j]->renewable)
963 printf (" renewable: %d\n",
964 *data->circulationData[j]->renewable);
965 if (data->circulationData[j]->onHold)
966 printf (" onHold: %d\n",
967 *data->circulationData[j]->onHold);
968 if (data->circulationData[j]->enumAndChron)
969 printf (" enumAndChron: %s\n",
970 data->circulationData[j]->enumAndChron);
971 if (data->circulationData[j]->midspine)
972 printf (" midspine: %s\n",
973 data->circulationData[j]->midspine);
974 if (data->circulationData[j]->temporaryLocation)
975 printf (" temporaryLocation: %s\n",
976 data->circulationData[j]->temporaryLocation);
983 printf("Unknown record representation.\n");
984 if (!z_External(print, &r, 0, 0))
986 odr_perror(print, "Printing external");
992 static void display_diagrecs(Z_DiagRec **pp, int num)
996 Z_DefaultDiagFormat *r;
998 printf("Diagnostic message(s) from database:\n");
999 for (i = 0; i<num; i++)
1001 Z_DiagRec *p = pp[i];
1002 if (p->which != Z_DiagRec_defaultFormat)
1004 printf("Diagnostic record not in default format.\n");
1008 r = p->u.defaultFormat;
1009 if (!(ent = oid_getentbyoid(r->diagnosticSetId)) ||
1010 ent->oclass != CLASS_DIAGSET || ent->value != VAL_BIB1)
1011 printf("Missing or unknown diagset\n");
1012 printf(" [%d] %s", *r->condition, diagbib1_str(*r->condition));
1015 case Z_DefaultDiagFormat_v2Addinfo:
1016 printf (" -- v2 addinfo '%s'\n", r->u.v2Addinfo);
1018 case Z_DefaultDiagFormat_v3Addinfo:
1019 printf (" -- v3 addinfo '%s'\n", r->u.v3Addinfo);
1026 static void display_nameplusrecord(Z_NamePlusRecord *p)
1028 if (p->databaseName)
1029 printf("[%s]", p->databaseName);
1030 if (p->which == Z_NamePlusRecord_surrogateDiagnostic)
1031 display_diagrecs(&p->u.surrogateDiagnostic, 1);
1032 else if (p->which == Z_NamePlusRecord_databaseRecord)
1033 display_record(p->u.databaseRecord);
1036 static void display_records(Z_Records *p)
1040 if (p->which == Z_Records_NSD)
1042 Z_DiagRec dr, *dr_p = &dr;
1043 dr.which = Z_DiagRec_defaultFormat;
1044 dr.u.defaultFormat = p->u.nonSurrogateDiagnostic;
1045 display_diagrecs (&dr_p, 1);
1047 else if (p->which == Z_Records_multipleNSD)
1048 display_diagrecs (p->u.multipleNonSurDiagnostics->diagRecs,
1049 p->u.multipleNonSurDiagnostics->num_diagRecs);
1052 printf("Records: %d\n", p->u.databaseOrSurDiagnostics->num_records);
1053 for (i = 0; i < p->u.databaseOrSurDiagnostics->num_records; i++)
1054 display_nameplusrecord(p->u.databaseOrSurDiagnostics->records[i]);
1058 static int send_deleteResultSetRequest(const char *arg)
1063 Z_APDU *apdu = zget_APDU(out, Z_APDU_deleteResultSetRequest);
1064 Z_DeleteResultSetRequest *req = apdu->u.deleteResultSetRequest;
1066 req->referenceId = set_refid (out);
1068 req->num_resultSetList =
1069 sscanf (arg, "%30s %30s %30s %30s %30s %30s %30s %30s",
1070 names[0], names[1], names[2], names[3],
1071 names[4], names[5], names[6], names[7]);
1073 req->deleteFunction = (int *)
1074 odr_malloc (out, sizeof(*req->deleteFunction));
1075 if (req->num_resultSetList > 0)
1077 *req->deleteFunction = Z_DeleteRequest_list;
1078 req->resultSetList = (char **)
1079 odr_malloc (out, sizeof(*req->resultSetList)*
1080 req->num_resultSetList);
1081 for (i = 0; i<req->num_resultSetList; i++)
1082 req->resultSetList[i] = names[i];
1086 *req->deleteFunction = Z_DeleteRequest_all;
1087 req->resultSetList = 0;
1091 printf("Sent deleteResultSetRequest.\n");
1096 static int send_srw(Z_SRW_PDU *sr)
1098 const char *charset = negotiationCharset;
1099 const char *host_port = cur_host;
1102 Z_SOAP_Handler h[2] = {
1103 {"http://www.loc.gov/zing/srw/", 0, (Z_SOAP_fun) yaz_srw_codec},
1106 ODR o = odr_createmem(ODR_ENCODE);
1108 Z_SOAP *p = odr_malloc(o, sizeof(*p));
1111 path = odr_malloc(out, strlen(databaseNames[0])+2);
1113 strcpy(path+1, databaseNames[0]);
1115 gdu = z_get_HTTP_Request(out);
1116 gdu->u.HTTP_Request->version = http_version;
1117 gdu->u.HTTP_Request->path = odr_strdup(out, path);
1121 const char *cp0 = strstr(host_port, "://");
1122 const char *cp1 = 0;
1128 cp1 = strchr(cp0, '/');
1130 cp1 = cp0+strlen(cp0);
1134 char *h = odr_malloc(out, cp1 - cp0 + 1);
1135 memcpy (h, cp0, cp1 - cp0);
1137 z_HTTP_header_add(out, &gdu->u.HTTP_Request->headers,
1142 strcpy(ctype, "text/xml");
1143 if (charset && strlen(charset) < 20)
1145 strcat(ctype, "; charset=");
1146 strcat(ctype, charset);
1148 z_HTTP_header_add(out, &gdu->u.HTTP_Request->headers,
1149 "Content-Type", ctype);
1150 z_HTTP_header_add(out, &gdu->u.HTTP_Request->headers,
1151 "SOAPAction", "\"\"");
1152 p->which = Z_SOAP_generic;
1153 p->u.generic = odr_malloc(o, sizeof(*p->u.generic));
1154 p->u.generic->no = 0;
1155 p->u.generic->ns = 0;
1156 p->u.generic->p = sr;
1157 p->ns = "http://schemas.xmlsoap.org/soap/envelope/";
1159 ret = z_soap_codec_enc(o, &p,
1160 &gdu->u.HTTP_Request->content_buf,
1161 &gdu->u.HTTP_Request->content_len, h,
1164 if (z_GDU(out, &gdu, 0, 0))
1172 if (!z_GDU(print, &gdu, 0, 0))
1173 printf ("Failed to print outgoing APDU\n");
1176 buf_out = odr_getbuf(out, &len_out, 0);
1178 /* we don't odr_reset(out), since we may need the buffer again */
1180 do_hex_dump(buf_out, len_out);
1182 r = cs_put(conn, buf_out, len_out);
1194 static int send_SRW_searchRequest(const char *arg)
1200 assert(srw_sr_odr_out == 0);
1201 srw_sr_odr_out = odr_createmem(ODR_ENCODE);
1203 odr_reset(srw_sr_odr_out);
1207 /* save this for later .. when fetching individual records */
1208 srw_sr = sr = yaz_srw_get(srw_sr_odr_out, Z_SRW_searchRetrieve_request);
1209 sr->u.request->query_type = Z_SRW_query_type_cql;
1210 sr->u.request->query.cql = odr_strdup(srw_sr_odr_out, arg);
1212 sr = yaz_srw_get(out, Z_SRW_searchRetrieve_request);
1213 sr->u.request->query_type = Z_SRW_query_type_cql;
1214 sr->u.request->query.cql = odr_strdup(out, arg);
1216 sr->u.request->maximumRecords = odr_intdup(out, 0);
1219 sr->u.request->recordSchema = record_schema;
1220 if (recordsyntax == VAL_TEXT_XML)
1221 sr->u.explain_request->recordPacking = "xml";
1222 return send_srw(sr);
1226 static int send_searchRequest(const char *arg)
1228 Z_APDU *apdu = zget_APDU(out, Z_APDU_searchRequest);
1229 Z_SearchRequest *req = apdu->u.searchRequest;
1232 struct ccl_rpn_node *rpn = NULL;
1234 char setstring[100];
1235 Z_RPNQuery *RPNquery;
1237 YAZ_PQF_Parser pqf_parser;
1239 QueryType myQueryType = queryType;
1242 if (myQueryType == QueryType_CCL2RPN)
1244 rpn = ccl_find_str(bibset, arg, &error, &pos);
1247 printf("CCL ERROR: %s\n", ccl_err_msg(error));
1250 } else if (myQueryType == QueryType_CQL2RPN) {
1251 /* ### All this code should be wrapped in a utility function */
1253 struct cql_node *node;
1254 const char *addinfo;
1255 if (cqltrans == 0) {
1256 printf("Can't use CQL: no translation file. Try set_cqlfile\n");
1259 parser = cql_parser_create();
1260 if ((error = cql_parser_string(parser, arg)) != 0) {
1261 printf("Can't parse CQL: must be a syntax error\n");
1264 node = cql_parser_result(parser);
1265 if ((error = cql_transform_buf(cqltrans, node, pqfbuf,
1266 sizeof pqfbuf)) != 0) {
1267 error = cql_transform_error(cqltrans, &addinfo);
1268 printf ("Can't convert CQL to PQF: %s (addinfo=%s)\n",
1269 cql_strerror(error), addinfo);
1273 myQueryType = QueryType_Prefix;
1276 req->referenceId = set_refid (out);
1277 if (!strcmp(arg, "@big")) /* strictly for troublemaking */
1279 static unsigned char big[2100];
1280 static Odr_oct bigo;
1282 /* send a very big referenceid to test transport stack etc. */
1283 memset(big, 'A', 2100);
1284 bigo.len = bigo.size = 2100;
1286 req->referenceId = &bigo;
1291 sprintf(setstring, "%d", ++setnumber);
1292 req->resultSetName = setstring;
1294 *req->smallSetUpperBound = smallSetUpperBound;
1295 *req->largeSetLowerBound = largeSetLowerBound;
1296 *req->mediumSetPresentNumber = mediumSetPresentNumber;
1297 if (smallSetUpperBound > 0 || (largeSetLowerBound > 1 &&
1298 mediumSetPresentNumber > 0))
1302 prefsyn.proto = protocol;
1303 prefsyn.oclass = CLASS_RECSYN;
1304 prefsyn.value = recordsyntax;
1305 req->preferredRecordSyntax =
1306 odr_oiddup(out, oid_ent_to_oid(&prefsyn, oid));
1307 req->smallSetElementSetNames =
1308 req->mediumSetElementSetNames = elementSetNames;
1310 req->num_databaseNames = num_databaseNames;
1311 req->databaseNames = databaseNames;
1313 req->query = &query;
1315 switch (myQueryType)
1317 case QueryType_Prefix:
1318 query.which = Z_Query_type_1;
1319 pqf_parser = yaz_pqf_create ();
1320 RPNquery = yaz_pqf_parse (pqf_parser, out, arg);
1323 const char *pqf_msg;
1325 int code = yaz_pqf_error (pqf_parser, &pqf_msg, &off);
1326 printf("%*s^\n", off+4, "");
1327 printf("Prefix query error: %s (code %d)\n", pqf_msg, code);
1329 yaz_pqf_destroy (pqf_parser);
1332 yaz_pqf_destroy (pqf_parser);
1333 query.u.type_1 = RPNquery;
1336 query.which = Z_Query_type_2;
1337 query.u.type_2 = &ccl_query;
1338 ccl_query.buf = (unsigned char*) arg;
1339 ccl_query.len = strlen(arg);
1341 case QueryType_CCL2RPN:
1342 query.which = Z_Query_type_1;
1343 RPNquery = ccl_rpn_query(out, rpn);
1346 printf ("Couldn't convert from CCL to RPN\n");
1349 query.u.type_1 = RPNquery;
1350 ccl_rpn_delete (rpn);
1353 query.which = Z_Query_type_104;
1354 ext = (Z_External *) odr_malloc(out, sizeof(*ext));
1355 ext->direct_reference = odr_getoidbystr(out, "1.2.840.10003.16.2");
1356 ext->indirect_reference = 0;
1357 ext->descriptor = 0;
1358 ext->which = Z_External_CQL;
1359 ext->u.cql = odr_strdup(out, arg);
1360 query.u.type_104 = ext;
1363 printf ("Unsupported query type\n");
1366 if (send_apdu(apdu))
1367 printf("Sent searchRequest.\n");
1372 /* display Query Expression as part of searchResult-1 */
1373 static void display_queryExpression (Z_QueryExpression *qe)
1377 if (qe->which == Z_QueryExpression_term)
1379 if (qe->u.term->queryTerm)
1381 Z_Term *term = qe->u.term->queryTerm;
1382 switch (term->which)
1384 case Z_Term_general:
1385 printf (" %.*s", term->u.general->len, term->u.general->buf);
1387 case Z_Term_characterString:
1388 printf (" %s", term->u.characterString);
1390 case Z_Term_numeric:
1391 printf (" %d", *term->u.numeric);
1401 /* see if we can find USR:SearchResult-1 */
1402 static void display_searchResult (Z_OtherInformation *o)
1407 for (i = 0; i < o->num_elements; i++)
1409 if (o->list[i]->which == Z_OtherInfo_externallyDefinedInfo)
1411 Z_External *ext = o->list[i]->information.externallyDefinedInfo;
1413 if (ext->which == Z_External_searchResult1)
1416 Z_SearchInfoReport *sr = ext->u.searchResult1;
1417 printf ("SearchResult-1:");
1418 for (j = 0; j < sr->num; j++)
1420 if (!sr->elements[j]->subqueryExpression)
1422 display_queryExpression (
1423 sr->elements[j]->subqueryExpression);
1424 display_queryExpression (
1425 sr->elements[j]->subqueryInterpretation);
1426 display_queryExpression (
1427 sr->elements[j]->subqueryRecommendation);
1428 if (sr->elements[j]->subqueryCount)
1429 printf ("(%d)", *sr->elements[j]->subqueryCount);
1437 static int process_searchResponse(Z_SearchResponse *res)
1439 printf ("Received SearchResponse.\n");
1440 print_refid (res->referenceId);
1441 if (*res->searchStatus)
1442 printf("Search was a success.\n");
1444 printf("Search was a bloomin' failure.\n");
1445 printf("Number of hits: %d", *res->resultCount);
1447 printf (", setno %d", setnumber);
1449 display_searchResult (res->additionalSearchInfo);
1450 printf("records returned: %d\n",
1451 *res->numberOfRecordsReturned);
1452 setno += *res->numberOfRecordsReturned;
1454 display_records(res->records);
1458 static void print_level(int iLevel)
1461 for (i = 0; i < iLevel * 4; i++)
1465 static void print_int(int iLevel, const char *pTag, int *pInt)
1469 print_level(iLevel);
1470 printf("%s: %d\n", pTag, *pInt);
1474 static void print_string(int iLevel, const char *pTag, const char *pString)
1476 if (pString != NULL)
1478 print_level(iLevel);
1479 printf("%s: %s\n", pTag, pString);
1483 static void print_oid(int iLevel, const char *pTag, Odr_oid *pOid)
1489 print_level(iLevel);
1490 printf("%s:", pTag);
1491 for (; *pInt != -1; pInt++)
1492 printf(" %d", *pInt);
1497 static void print_referenceId(int iLevel, Z_ReferenceId *referenceId)
1499 if (referenceId != NULL)
1503 print_level(iLevel);
1504 printf("Ref Id (%d, %d): ", referenceId->len, referenceId->size);
1505 for (i = 0; i < referenceId->len; i++)
1506 printf("%c", referenceId->buf[i]);
1511 static void print_string_or_numeric(int iLevel, const char *pTag, Z_StringOrNumeric *pStringNumeric)
1513 if (pStringNumeric != NULL)
1515 switch (pStringNumeric->which)
1517 case Z_StringOrNumeric_string:
1518 print_string(iLevel, pTag, pStringNumeric->u.string);
1521 case Z_StringOrNumeric_numeric:
1522 print_int(iLevel, pTag, pStringNumeric->u.numeric);
1526 print_level(iLevel);
1527 printf("%s: valid type for Z_StringOrNumeric\n", pTag);
1533 static void print_universe_report_duplicate(
1535 Z_UniverseReportDuplicate *pUniverseReportDuplicate)
1537 if (pUniverseReportDuplicate != NULL)
1539 print_level(iLevel);
1540 printf("Universe Report Duplicate: \n");
1542 print_string_or_numeric(iLevel, "Hit No",
1543 pUniverseReportDuplicate->hitno);
1547 static void print_universe_report_hits(
1549 Z_UniverseReportHits *pUniverseReportHits)
1551 if (pUniverseReportHits != NULL)
1553 print_level(iLevel);
1554 printf("Universe Report Hits: \n");
1556 print_string_or_numeric(iLevel, "Database",
1557 pUniverseReportHits->database);
1558 print_string_or_numeric(iLevel, "Hits", pUniverseReportHits->hits);
1562 static void print_universe_report(int iLevel, Z_UniverseReport *pUniverseReport)
1564 if (pUniverseReport != NULL)
1566 print_level(iLevel);
1567 printf("Universe Report: \n");
1569 print_int(iLevel, "Total Hits", pUniverseReport->totalHits);
1570 switch (pUniverseReport->which)
1572 case Z_UniverseReport_databaseHits:
1573 print_universe_report_hits(iLevel,
1574 pUniverseReport->u.databaseHits);
1577 case Z_UniverseReport_duplicate:
1578 print_universe_report_duplicate(iLevel,
1579 pUniverseReport->u.duplicate);
1583 print_level(iLevel);
1584 printf("Type: %d\n", pUniverseReport->which);
1590 static void print_external(int iLevel, Z_External *pExternal)
1592 if (pExternal != NULL)
1594 print_level(iLevel);
1595 printf("External: \n");
1597 print_oid(iLevel, "Direct Reference", pExternal->direct_reference);
1598 print_int(iLevel, "InDirect Reference", pExternal->indirect_reference);
1599 print_string(iLevel, "Descriptor", pExternal->descriptor);
1600 switch (pExternal->which)
1602 case Z_External_universeReport:
1603 print_universe_report(iLevel, pExternal->u.universeReport);
1607 print_level(iLevel);
1608 printf("Type: %d\n", pExternal->which);
1614 static int process_resourceControlRequest (Z_ResourceControlRequest *req)
1616 printf ("Received ResourceControlRequest.\n");
1617 print_referenceId(1, req->referenceId);
1618 print_int(1, "Suspended Flag", req->suspendedFlag);
1619 print_int(1, "Partial Results Available", req->partialResultsAvailable);
1620 print_int(1, "Response Required", req->responseRequired);
1621 print_int(1, "Triggered Request Flag", req->triggeredRequestFlag);
1622 print_external(1, req->resourceReport);
1626 void process_ESResponse(Z_ExtendedServicesResponse *res)
1629 switch (*res->operationStatus)
1631 case Z_ExtendedServicesResponse_done:
1634 case Z_ExtendedServicesResponse_accepted:
1635 printf ("accepted\n");
1637 case Z_ExtendedServicesResponse_failure:
1638 printf ("failure\n");
1639 display_diagrecs(res->diagnostics, res->num_diagnostics);
1642 printf ("unknown\n");
1644 if ( (*res->operationStatus != Z_ExtendedServicesResponse_failure) &&
1645 (res->num_diagnostics != 0) ) {
1646 display_diagrecs(res->diagnostics, res->num_diagnostics);
1648 print_refid (res->referenceId);
1649 if (res->taskPackage &&
1650 res->taskPackage->which == Z_External_extendedService)
1652 Z_TaskPackage *taskPackage = res->taskPackage->u.extendedService;
1653 Odr_oct *id = taskPackage->targetReference;
1654 Z_External *ext = taskPackage->taskSpecificParameters;
1658 printf ("Target Reference: ");
1659 print_stringn (id->buf, id->len);
1662 if (ext->which == Z_External_update)
1664 Z_IUUpdateTaskPackage *utp = ext->u.update->u.taskPackage;
1665 if (utp && utp->targetPart)
1667 Z_IUTargetPart *targetPart = utp->targetPart;
1670 for (i = 0; i<targetPart->num_taskPackageRecords; i++)
1673 Z_IUTaskPackageRecordStructure *tpr =
1674 targetPart->taskPackageRecords[i];
1675 printf ("task package record %d\n", i+1);
1676 if (tpr->which == Z_IUTaskPackageRecordStructure_record)
1678 display_record (tpr->u.record);
1682 printf ("other type\n");
1690 const char *get_ill_element (void *clientData, const char *element)
1695 static Z_External *create_external_itemRequest()
1697 struct ill_get_ctl ctl;
1698 ILL_ItemRequest *req;
1700 int item_request_size = 0;
1701 char *item_request_buf = 0;
1705 ctl.f = get_ill_element;
1707 req = ill_get_ItemRequest(&ctl, "ill", 0);
1709 printf ("ill_get_ItemRequest failed\n");
1711 if (!ill_ItemRequest (out, &req, 0, 0))
1715 ill_ItemRequest(print, &req, 0, 0);
1718 item_request_buf = odr_getbuf (out, &item_request_size, 0);
1719 if (item_request_buf)
1720 odr_setbuf (out, item_request_buf, item_request_size, 1);
1721 printf ("Couldn't encode ItemRequest, size %d\n", item_request_size);
1728 item_request_buf = odr_getbuf (out, &item_request_size, 0);
1729 oid.proto = PROTO_GENERAL;
1730 oid.oclass = CLASS_GENERAL;
1731 oid.value = VAL_ISO_ILL_1;
1733 r = (Z_External *) odr_malloc (out, sizeof(*r));
1734 r->direct_reference = odr_oiddup(out,oid_getoidbyent(&oid));
1735 r->indirect_reference = 0;
1737 r->which = Z_External_single;
1739 r->u.single_ASN1_type = (Odr_oct *)
1740 odr_malloc (out, sizeof(*r->u.single_ASN1_type));
1741 r->u.single_ASN1_type->buf = (unsigned char *)
1742 odr_malloc (out, item_request_size);
1743 r->u.single_ASN1_type->len = item_request_size;
1744 r->u.single_ASN1_type->size = item_request_size;
1745 memcpy (r->u.single_ASN1_type->buf, item_request_buf,
1748 do_hex_dump(item_request_buf,item_request_size);
1753 static Z_External *create_external_ILL_APDU(int which)
1755 struct ill_get_ctl ctl;
1758 int ill_request_size = 0;
1759 char *ill_request_buf = 0;
1763 ctl.f = get_ill_element;
1765 ill_apdu = ill_get_APDU(&ctl, "ill", 0);
1767 if (!ill_APDU (out, &ill_apdu, 0, 0))
1771 printf ("-------------------\n");
1772 ill_APDU(print, &ill_apdu, 0, 0);
1774 printf ("-------------------\n");
1776 ill_request_buf = odr_getbuf (out, &ill_request_size, 0);
1777 if (ill_request_buf)
1778 odr_setbuf (out, ill_request_buf, ill_request_size, 1);
1779 printf ("Couldn't encode ILL-Request, size %d\n", ill_request_size);
1785 ill_request_buf = odr_getbuf (out, &ill_request_size, 0);
1787 oid.proto = PROTO_GENERAL;
1788 oid.oclass = CLASS_GENERAL;
1789 oid.value = VAL_ISO_ILL_1;
1791 r = (Z_External *) odr_malloc (out, sizeof(*r));
1792 r->direct_reference = odr_oiddup(out,oid_getoidbyent(&oid));
1793 r->indirect_reference = 0;
1795 r->which = Z_External_single;
1797 r->u.single_ASN1_type = (Odr_oct *)
1798 odr_malloc (out, sizeof(*r->u.single_ASN1_type));
1799 r->u.single_ASN1_type->buf = (unsigned char *)
1800 odr_malloc (out, ill_request_size);
1801 r->u.single_ASN1_type->len = ill_request_size;
1802 r->u.single_ASN1_type->size = ill_request_size;
1803 memcpy (r->u.single_ASN1_type->buf, ill_request_buf, ill_request_size);
1804 /* printf ("len = %d\n", ill_request_size); */
1805 /* do_hex_dump(ill_request_buf,ill_request_size); */
1806 /* printf("--- end of extenal\n"); */
1813 static Z_External *create_ItemOrderExternal(const char *type, int itemno)
1815 Z_External *r = (Z_External *) odr_malloc(out, sizeof(Z_External));
1816 oident ItemOrderRequest;
1818 ItemOrderRequest.proto = PROTO_Z3950;
1819 ItemOrderRequest.oclass = CLASS_EXTSERV;
1820 ItemOrderRequest.value = VAL_ITEMORDER;
1822 r->direct_reference = odr_oiddup(out,oid_getoidbyent(&ItemOrderRequest));
1823 r->indirect_reference = 0;
1826 r->which = Z_External_itemOrder;
1828 r->u.itemOrder = (Z_ItemOrder *) odr_malloc(out,sizeof(Z_ItemOrder));
1829 memset(r->u.itemOrder, 0, sizeof(Z_ItemOrder));
1830 r->u.itemOrder->which=Z_IOItemOrder_esRequest;
1832 r->u.itemOrder->u.esRequest = (Z_IORequest *)
1833 odr_malloc(out,sizeof(Z_IORequest));
1834 memset(r->u.itemOrder->u.esRequest, 0, sizeof(Z_IORequest));
1836 r->u.itemOrder->u.esRequest->toKeep = (Z_IOOriginPartToKeep *)
1837 odr_malloc(out,sizeof(Z_IOOriginPartToKeep));
1838 memset(r->u.itemOrder->u.esRequest->toKeep, 0, sizeof(Z_IOOriginPartToKeep));
1839 r->u.itemOrder->u.esRequest->notToKeep = (Z_IOOriginPartNotToKeep *)
1840 odr_malloc(out,sizeof(Z_IOOriginPartNotToKeep));
1841 memset(r->u.itemOrder->u.esRequest->notToKeep, 0, sizeof(Z_IOOriginPartNotToKeep));
1843 r->u.itemOrder->u.esRequest->toKeep->supplDescription = NULL;
1844 r->u.itemOrder->u.esRequest->toKeep->contact = NULL;
1845 r->u.itemOrder->u.esRequest->toKeep->addlBilling = NULL;
1847 r->u.itemOrder->u.esRequest->notToKeep->resultSetItem =
1848 (Z_IOResultSetItem *) odr_malloc(out, sizeof(Z_IOResultSetItem));
1849 memset(r->u.itemOrder->u.esRequest->notToKeep->resultSetItem, 0, sizeof(Z_IOResultSetItem));
1850 r->u.itemOrder->u.esRequest->notToKeep->resultSetItem->resultSetId = "1";
1852 r->u.itemOrder->u.esRequest->notToKeep->resultSetItem->item =
1853 (int *) odr_malloc(out, sizeof(int));
1854 *r->u.itemOrder->u.esRequest->notToKeep->resultSetItem->item = itemno;
1856 if (!strcmp (type, "item") || !strcmp(type, "2"))
1858 printf ("using item-request\n");
1859 r->u.itemOrder->u.esRequest->notToKeep->itemRequest =
1860 create_external_itemRequest();
1862 else if (!strcmp(type, "ill") || !strcmp(type, "1"))
1864 printf ("using ILL-request\n");
1865 r->u.itemOrder->u.esRequest->notToKeep->itemRequest =
1866 create_external_ILL_APDU(ILL_APDU_ILL_Request);
1868 else if (!strcmp(type, "xml") || !strcmp(type, "3"))
1870 const char *xml_buf =
1872 " <type>request</type>\n"
1873 " <libraryNo>000200</libraryNo>\n"
1874 " <borrowerTicketNo> 1212 </borrowerTicketNo>\n"
1876 r->u.itemOrder->u.esRequest->notToKeep->itemRequest =
1877 z_ext_record (out, VAL_TEXT_XML, xml_buf, strlen(xml_buf));
1880 r->u.itemOrder->u.esRequest->notToKeep->itemRequest = 0;
1885 static int send_itemorder(const char *type, int itemno)
1887 Z_APDU *apdu = zget_APDU(out, Z_APDU_extendedServicesRequest);
1888 Z_ExtendedServicesRequest *req = apdu->u.extendedServicesRequest;
1889 oident ItemOrderRequest;
1891 ItemOrderRequest.proto = PROTO_Z3950;
1892 ItemOrderRequest.oclass = CLASS_EXTSERV;
1893 ItemOrderRequest.value = VAL_ITEMORDER;
1894 req->packageType = odr_oiddup(out,oid_getoidbyent(&ItemOrderRequest));
1895 req->packageName = esPackageName;
1897 req->taskSpecificParameters = create_ItemOrderExternal(type, itemno);
1903 static int only_z3950()
1905 if (protocol == PROTO_HTTP)
1907 printf ("Not supported by SRW\n");
1913 static int cmd_update_common(const char *arg, int version);
1915 static int cmd_update(const char *arg)
1917 return cmd_update_common(arg, 1);
1920 static int cmd_update0(const char *arg)
1922 return cmd_update_common(arg, 0);
1925 static int cmd_update_common(const char *arg, int version)
1927 Z_APDU *apdu = zget_APDU(out, Z_APDU_extendedServicesRequest );
1928 Z_ExtendedServicesRequest *req = apdu->u.extendedServicesRequest;
1932 char action[20], recid[20], fname[80];
1934 Z_External *record_this = 0;
1941 sscanf (arg, "%19s %19s %79s", action, recid, fname);
1943 if (!strcmp (action, "insert"))
1944 action_no = Z_IUOriginPartToKeep_recordInsert;
1945 else if (!strcmp (action, "replace"))
1946 action_no = Z_IUOriginPartToKeep_recordReplace;
1947 else if (!strcmp (action, "delete"))
1948 action_no = Z_IUOriginPartToKeep_recordDelete;
1949 else if (!strcmp (action, "update"))
1950 action_no = Z_IUOriginPartToKeep_specialUpdate;
1953 printf ("Bad action: %s\n", action);
1954 printf ("Possible values: insert, replace, delete, update\n");
1962 stat (fname, &status);
1963 if (S_ISREG(status.st_mode) && (inf = fopen(fname, "r")))
1965 size_t len = status.st_size;
1966 char *buf = (char *) xmalloc (len);
1968 fread (buf, 1, len, inf);
1972 record_this = z_ext_record (out, VAL_TEXT_XML, buf, len);
1978 printf ("File %s doesn't exist\n", fname);
1986 printf ("No last record (update ignored)\n");
1989 record_this = record_last;
1992 update_oid.proto = PROTO_Z3950;
1993 update_oid.oclass = CLASS_EXTSERV;
1995 update_oid.value = VAL_DBUPDATE0;
1997 update_oid.value = VAL_DBUPDATE;
1998 oid_ent_to_oid (&update_oid, oid);
1999 req->packageType = odr_oiddup(out,oid);
2000 req->packageName = esPackageName;
2002 req->referenceId = set_refid (out);
2004 r = req->taskSpecificParameters = (Z_External *)
2005 odr_malloc (out, sizeof(*r));
2006 r->direct_reference = odr_oiddup(out,oid);
2007 r->indirect_reference = 0;
2011 Z_IU0OriginPartToKeep *toKeep;
2012 Z_IU0SuppliedRecords *notToKeep;
2014 r->which = Z_External_update0;
2015 r->u.update0 = (Z_IU0Update *) odr_malloc(out, sizeof(*r->u.update0));
2016 r->u.update0->which = Z_IUUpdate_esRequest;
2017 r->u.update0->u.esRequest = (Z_IU0UpdateEsRequest *)
2018 odr_malloc(out, sizeof(*r->u.update0->u.esRequest));
2019 toKeep = r->u.update0->u.esRequest->toKeep = (Z_IU0OriginPartToKeep *)
2020 odr_malloc(out, sizeof(*r->u.update0->u.esRequest->toKeep));
2022 toKeep->databaseName = databaseNames[0];
2024 toKeep->elementSetName = 0;
2026 toKeep->action = (int *) odr_malloc(out, sizeof(*toKeep->action));
2027 *toKeep->action = action_no;
2029 notToKeep = r->u.update0->u.esRequest->notToKeep = (Z_IU0SuppliedRecords *)
2030 odr_malloc(out, sizeof(*r->u.update0->u.esRequest->notToKeep));
2032 notToKeep->elements = (Z_IU0SuppliedRecords_elem **)
2033 odr_malloc(out, sizeof(*notToKeep->elements));
2034 notToKeep->elements[0] = (Z_IU0SuppliedRecords_elem *)
2035 odr_malloc(out, sizeof(**notToKeep->elements));
2036 notToKeep->elements[0]->which = Z_IUSuppliedRecords_elem_opaque;
2039 notToKeep->elements[0]->u.opaque = (Odr_oct *)
2040 odr_malloc (out, sizeof(Odr_oct));
2041 notToKeep->elements[0]->u.opaque->buf = (unsigned char *) recid;
2042 notToKeep->elements[0]->u.opaque->size = strlen(recid);
2043 notToKeep->elements[0]->u.opaque->len = strlen(recid);
2046 notToKeep->elements[0]->u.opaque = 0;
2047 notToKeep->elements[0]->supplementalId = 0;
2048 notToKeep->elements[0]->correlationInfo = 0;
2049 notToKeep->elements[0]->record = record_this;
2053 Z_IUOriginPartToKeep *toKeep;
2054 Z_IUSuppliedRecords *notToKeep;
2056 r->which = Z_External_update;
2057 r->u.update = (Z_IUUpdate *) odr_malloc(out, sizeof(*r->u.update));
2058 r->u.update->which = Z_IUUpdate_esRequest;
2059 r->u.update->u.esRequest = (Z_IUUpdateEsRequest *)
2060 odr_malloc(out, sizeof(*r->u.update->u.esRequest));
2061 toKeep = r->u.update->u.esRequest->toKeep = (Z_IUOriginPartToKeep *)
2062 odr_malloc(out, sizeof(*r->u.update->u.esRequest->toKeep));
2064 toKeep->databaseName = databaseNames[0];
2066 toKeep->elementSetName = 0;
2067 toKeep->actionQualifier = 0;
2068 toKeep->action = (int *) odr_malloc(out, sizeof(*toKeep->action));
2069 *toKeep->action = action_no;
2071 notToKeep = r->u.update->u.esRequest->notToKeep = (Z_IUSuppliedRecords *)
2072 odr_malloc(out, sizeof(*r->u.update->u.esRequest->notToKeep));
2074 notToKeep->elements = (Z_IUSuppliedRecords_elem **)
2075 odr_malloc(out, sizeof(*notToKeep->elements));
2076 notToKeep->elements[0] = (Z_IUSuppliedRecords_elem *)
2077 odr_malloc(out, sizeof(**notToKeep->elements));
2078 notToKeep->elements[0]->which = Z_IUSuppliedRecords_elem_opaque;
2081 notToKeep->elements[0]->u.opaque = (Odr_oct *)
2082 odr_malloc (out, sizeof(Odr_oct));
2083 notToKeep->elements[0]->u.opaque->buf = (unsigned char *) recid;
2084 notToKeep->elements[0]->u.opaque->size = strlen(recid);
2085 notToKeep->elements[0]->u.opaque->len = strlen(recid);
2088 notToKeep->elements[0]->u.opaque = 0;
2089 notToKeep->elements[0]->supplementalId = 0;
2090 notToKeep->elements[0]->correlationInfo = 0;
2091 notToKeep->elements[0]->record = record_this;
2099 static int cmd_itemorder(const char *arg)
2106 if (sscanf (arg, "%10s %d", type, &itemno) != 2)
2109 printf("Item order request\n");
2111 send_itemorder(type, itemno);
2115 static void show_opt(const char *arg, void *clientData)
2117 printf ("%s ", arg);
2120 static int cmd_zversion(const char *arg)
2123 z3950_version = atoi(arg);
2125 printf ("version is %d\n", z3950_version);
2129 static int cmd_options(const char *arg)
2135 r = yaz_init_opt_encode(&z3950_options, arg, &pos);
2139 yaz_init_opt_decode(&z3950_options, show_opt, 0);
2145 static int cmd_explain(const char *arg)
2147 if (protocol != PROTO_HTTP)
2158 /* save this for later .. when fetching individual records */
2159 sr = yaz_srw_get(out, Z_SRW_explain_request);
2160 if (recordsyntax == VAL_TEXT_XML)
2161 sr->u.explain_request->recordPacking = "xml";
2169 static int cmd_init(const char *arg)
2171 if (!conn || protocol != PROTO_Z3950)
2173 send_initRequest(0);
2177 static int cmd_find(const char *arg)
2181 printf("Find what?\n");
2184 if (protocol == PROTO_HTTP)
2191 if (!send_SRW_searchRequest(arg))
2204 printf("Not connected yet\n");
2208 if (!send_searchRequest(arg))
2214 static int cmd_delete(const char *arg)
2218 printf("Not connected yet\n");
2223 if (!send_deleteResultSetRequest(arg))
2228 static int cmd_ssub(const char *arg)
2230 if (!(smallSetUpperBound = atoi(arg)))
2235 static int cmd_lslb(const char *arg)
2239 if (!(largeSetLowerBound = atoi(arg)))
2244 static int cmd_mspn(const char *arg)
2248 if (!(mediumSetPresentNumber = atoi(arg)))
2253 static int cmd_status(const char *arg)
2255 printf("smallSetUpperBound: %d\n", smallSetUpperBound);
2256 printf("largeSetLowerBound: %d\n", largeSetLowerBound);
2257 printf("mediumSetPresentNumber: %d\n", mediumSetPresentNumber);
2261 static int cmd_setnames(const char *arg)
2263 if (*arg == '1') /* enable ? */
2265 else if (*arg == '0') /* disable ? */
2267 else if (setnumber < 0) /* no args, toggle .. */
2273 printf("Set numbering enabled.\n");
2275 printf("Set numbering disabled.\n");
2279 /* PRESENT SERVICE ----------------------------- */
2281 static void parse_show_args(const char *arg_c, char *setstring,
2282 int *start, int *number)
2287 strncpy(arg, arg_c, sizeof(arg)-1);
2288 arg[sizeof(arg)-1] = '\0';
2290 if ((p = strchr(arg, '+')))
2292 *number = atoi(p + 1);
2297 if (p && (p=strchr(p+1, '+')))
2298 strcpy (setstring, p+1);
2299 else if (setnumber >= 0)
2300 sprintf(setstring, "%d", setnumber);
2305 static int send_presentRequest(const char *arg)
2307 Z_APDU *apdu = zget_APDU(out, Z_APDU_presentRequest);
2308 Z_PresentRequest *req = apdu->u.presentRequest;
2309 Z_RecordComposition compo;
2313 char setstring[100];
2315 req->referenceId = set_refid (out);
2317 parse_show_args(arg, setstring, &setno, &nos);
2319 req->resultSetId = setstring;
2321 req->resultSetStartPoint = &setno;
2322 req->numberOfRecordsRequested = &nos;
2323 prefsyn.proto = protocol;
2324 prefsyn.oclass = CLASS_RECSYN;
2325 prefsyn.value = recordsyntax;
2326 req->preferredRecordSyntax =
2327 odr_oiddup (out, oid_ent_to_oid(&prefsyn, oid));
2333 prefschema.proto = protocol;
2334 prefschema.oclass = CLASS_SCHEMA;
2335 prefschema.value = oid_getvalbyname(record_schema);
2337 req->recordComposition = &compo;
2338 compo.which = Z_RecordComp_complex;
2339 compo.u.complex = (Z_CompSpec *)
2340 odr_malloc(out, sizeof(*compo.u.complex));
2341 compo.u.complex->selectAlternativeSyntax = (bool_t *)
2342 odr_malloc(out, sizeof(bool_t));
2343 *compo.u.complex->selectAlternativeSyntax = 0;
2345 compo.u.complex->generic = (Z_Specification *)
2346 odr_malloc(out, sizeof(*compo.u.complex->generic));
2347 compo.u.complex->generic->which = Z_Schema_oid;
2348 compo.u.complex->generic->schema.oid = (Odr_oid *)
2349 odr_oiddup(out, oid_ent_to_oid(&prefschema, oid));
2350 if (!compo.u.complex->generic->schema.oid)
2352 /* OID wasn't a schema! Try record syntax instead. */
2353 prefschema.oclass = CLASS_RECSYN;
2354 compo.u.complex->generic->schema.oid = (Odr_oid *)
2355 odr_oiddup(out, oid_ent_to_oid(&prefschema, oid));
2357 if (!elementSetNames)
2358 compo.u.complex->generic->elementSpec = 0;
2361 compo.u.complex->generic->elementSpec = (Z_ElementSpec *)
2362 odr_malloc(out, sizeof(Z_ElementSpec));
2363 compo.u.complex->generic->elementSpec->which =
2364 Z_ElementSpec_elementSetName;
2365 compo.u.complex->generic->elementSpec->u.elementSetName =
2366 elementSetNames->u.generic;
2368 compo.u.complex->num_dbSpecific = 0;
2369 compo.u.complex->dbSpecific = 0;
2370 compo.u.complex->num_recordSyntax = 0;
2371 compo.u.complex->recordSyntax = 0;
2373 else if (elementSetNames)
2375 req->recordComposition = &compo;
2376 compo.which = Z_RecordComp_simple;
2377 compo.u.simple = elementSetNames;
2380 printf("Sent presentRequest (%d+%d).\n", setno, nos);
2385 static int send_SRW_presentRequest(const char *arg)
2387 char setstring[100];
2389 Z_SRW_PDU *sr = srw_sr;
2393 parse_show_args(arg, setstring, &setno, &nos);
2394 sr->u.request->startRecord = odr_intdup(out, setno);
2395 sr->u.request->maximumRecords = odr_intdup(out, nos);
2397 sr->u.request->recordSchema = record_schema;
2398 if (recordsyntax == VAL_TEXT_XML)
2399 sr->u.request->recordPacking = "xml";
2400 return send_srw(sr);
2404 static void close_session (void)
2411 nmem_destroy (session_mem);
2420 void process_close(Z_Close *req)
2422 Z_APDU *apdu = zget_APDU(out, Z_APDU_close);
2423 Z_Close *res = apdu->u.close;
2425 static char *reasons[] =
2430 "cost limit reached",
2432 "security violation",
2439 printf("Reason: %s, message: %s\n", reasons[*req->closeReason],
2440 req->diagnosticInformation ? req->diagnosticInformation : "NULL");
2445 *res->closeReason = Z_Close_finished;
2447 printf("Sent response.\n");
2452 static int cmd_show(const char *arg)
2454 if (protocol == PROTO_HTTP)
2461 if (!send_SRW_presentRequest(arg))
2471 printf("Not connected yet\n");
2474 if (!send_presentRequest(arg))
2480 int cmd_quit(const char *arg)
2482 printf("See you later, alligator.\n");
2488 int cmd_cancel(const char *arg)
2490 Z_APDU *apdu = zget_APDU(out, Z_APDU_triggerResourceControlRequest);
2491 Z_TriggerResourceControlRequest *req =
2492 apdu->u.triggerResourceControlRequest;
2497 printf("Session not initialized yet\n");
2502 if (!ODR_MASK_GET(session->options, Z_Options_triggerResourceCtrl))
2504 printf("Target doesn't support cancel (trigger resource ctrl)\n");
2507 *req->requestedAction = Z_TriggerResourceCtrl_cancel;
2508 req->resultSetWanted = &rfalse;
2511 printf("Sent cancel request\n");
2515 int send_scanrequest(const char *query, int pp, int num, const char *term)
2517 Z_APDU *apdu = zget_APDU(out, Z_APDU_scanRequest);
2518 Z_ScanRequest *req = apdu->u.scanRequest;
2523 if (queryType == QueryType_CCL2RPN)
2527 struct ccl_rpn_node *rpn;
2529 rpn = ccl_find_str (bibset, query, &error, &pos);
2532 printf("CCL ERROR: %s\n", ccl_err_msg(error));
2535 bib1.proto = PROTO_Z3950;
2536 bib1.oclass = CLASS_ATTSET;
2537 bib1.value = VAL_BIB1;
2538 req->attributeSet = oid_ent_to_oid (&bib1, oid);
2539 if (!(req->termListAndStartPoint = ccl_scan_query (out, rpn)))
2541 printf("Couldn't convert CCL to Scan term\n");
2544 ccl_rpn_delete (rpn);
2548 YAZ_PQF_Parser pqf_parser = yaz_pqf_create ();
2550 if (!(req->termListAndStartPoint =
2551 yaz_pqf_scan(pqf_parser, out, &req->attributeSet, query)))
2553 const char *pqf_msg;
2555 int code = yaz_pqf_error (pqf_parser, &pqf_msg, &off);
2556 printf("%*s^\n", off+7, "");
2557 printf("Prefix query error: %s (code %d)\n", pqf_msg, code);
2558 yaz_pqf_destroy (pqf_parser);
2561 yaz_pqf_destroy (pqf_parser);
2565 if (req->termListAndStartPoint->term &&
2566 req->termListAndStartPoint->term->which == Z_Term_general &&
2567 req->termListAndStartPoint->term->u.general)
2569 req->termListAndStartPoint->term->u.general->buf =
2570 (unsigned char *) odr_strdup(out, term);
2571 req->termListAndStartPoint->term->u.general->len =
2572 req->termListAndStartPoint->term->u.general->size =
2576 req->referenceId = set_refid (out);
2577 req->num_databaseNames = num_databaseNames;
2578 req->databaseNames = databaseNames;
2579 req->numberOfTermsRequested = #
2580 req->preferredPositionInResponse = &pp;
2585 int send_sortrequest(const char *arg, int newset)
2587 Z_APDU *apdu = zget_APDU(out, Z_APDU_sortRequest);
2588 Z_SortRequest *req = apdu->u.sortRequest;
2589 Z_SortKeySpecList *sksl = (Z_SortKeySpecList *)
2590 odr_malloc (out, sizeof(*sksl));
2596 sprintf (setstring, "%d", setnumber);
2598 sprintf (setstring, "default");
2600 req->referenceId = set_refid (out);
2602 req->num_inputResultSetNames = 1;
2603 req->inputResultSetNames = (Z_InternationalString **)
2604 odr_malloc (out, sizeof(*req->inputResultSetNames));
2605 req->inputResultSetNames[0] = odr_strdup (out, setstring);
2607 if (newset && setnumber >= 0)
2608 sprintf (setstring, "%d", ++setnumber);
2610 req->sortedResultSetName = odr_strdup (out, setstring);
2612 req->sortSequence = yaz_sort_spec (out, arg);
2613 if (!req->sortSequence)
2615 printf ("Missing sort specifications\n");
2622 void display_term(Z_TermInfo *t)
2625 printf("%s", t->displayTerm);
2626 else if (t->term->which == Z_Term_general)
2628 printf("%.*s", t->term->u.general->len, t->term->u.general->buf);
2629 sprintf(last_scan_line, "%.*s", t->term->u.general->len,
2630 t->term->u.general->buf);
2633 printf("Term (not general)");
2634 if (t->globalOccurrences)
2635 printf (" (%d)\n", *t->globalOccurrences);
2640 void process_scanResponse(Z_ScanResponse *res)
2643 Z_Entry **entries = NULL;
2644 int num_entries = 0;
2646 printf("Received ScanResponse\n");
2647 print_refid (res->referenceId);
2648 printf("%d entries", *res->numberOfEntriesReturned);
2649 if (res->positionOfTerm)
2650 printf (", position=%d", *res->positionOfTerm);
2652 if (*res->scanStatus != Z_Scan_success)
2653 printf("Scan returned code %d\n", *res->scanStatus);
2656 if ((entries = res->entries->entries))
2657 num_entries = res->entries->num_entries;
2658 for (i = 0; i < num_entries; i++)
2660 int pos_term = res->positionOfTerm ? *res->positionOfTerm : -1;
2661 if (entries[i]->which == Z_Entry_termInfo)
2663 printf("%c ", i + 1 == pos_term ? '*' : ' ');
2664 display_term(entries[i]->u.termInfo);
2667 display_diagrecs(&entries[i]->u.surrogateDiagnostic, 1);
2669 if (res->entries->nonsurrogateDiagnostics)
2670 display_diagrecs (res->entries->nonsurrogateDiagnostics,
2671 res->entries->num_nonsurrogateDiagnostics);
2674 void process_sortResponse(Z_SortResponse *res)
2676 printf("Received SortResponse: status=");
2677 switch (*res->sortStatus)
2679 case Z_SortStatus_success:
2680 printf ("success"); break;
2681 case Z_SortStatus_partial_1:
2682 printf ("partial"); break;
2683 case Z_SortStatus_failure:
2684 printf ("failure"); break;
2686 printf ("unknown (%d)", *res->sortStatus);
2689 print_refid (res->referenceId);
2690 if (res->diagnostics)
2691 display_diagrecs(res->diagnostics,
2692 res->num_diagnostics);
2695 void process_deleteResultSetResponse (Z_DeleteResultSetResponse *res)
2697 printf("Got deleteResultSetResponse status=%d\n",
2698 *res->deleteOperationStatus);
2699 if (res->deleteListStatuses)
2702 for (i = 0; i < res->deleteListStatuses->num; i++)
2704 printf ("%s status=%d\n", res->deleteListStatuses->elements[i]->id,
2705 *res->deleteListStatuses->elements[i]->status);
2710 int cmd_sort_generic(const char *arg, int newset)
2714 printf("Session not initialized yet\n");
2719 if (!ODR_MASK_GET(session->options, Z_Options_sort))
2721 printf("Target doesn't support sort\n");
2726 if (send_sortrequest(arg, newset) < 0)
2733 int cmd_sort(const char *arg)
2735 return cmd_sort_generic (arg, 0);
2738 int cmd_sort_newset (const char *arg)
2740 return cmd_sort_generic (arg, 1);
2743 int cmd_scan(const char *arg)
2752 printf("Session not initialized yet\n");
2756 if (!ODR_MASK_GET(session->options, Z_Options_scan))
2758 printf("Target doesn't support scan\n");
2763 strcpy (last_scan_query, arg);
2764 if (send_scanrequest(arg, 1, 20, 0) < 0)
2769 if (send_scanrequest(last_scan_query, 1, 20, last_scan_line) < 0)
2775 int cmd_schema(const char *arg)
2777 xfree(record_schema);
2780 record_schema = xstrdup(arg);
2784 int cmd_format(const char *arg)
2789 printf("Usage: format <recordsyntax>\n");
2792 nsyntax = oid_getvalbyname (arg);
2793 if (strcmp(arg, "none") && nsyntax == VAL_NONE)
2795 printf ("unknown record syntax\n");
2798 recordsyntax = nsyntax;
2802 int cmd_elements(const char *arg)
2804 static Z_ElementSetNames esn;
2805 static char what[100];
2809 elementSetNames = 0;
2813 esn.which = Z_ElementSetNames_generic;
2814 esn.u.generic = what;
2815 elementSetNames = &esn;
2819 int cmd_attributeset(const char *arg)
2825 printf("Usage: attributeset <setname>\n");
2828 sscanf(arg, "%s", what);
2829 if (p_query_attset (what))
2831 printf("Unknown attribute set name\n");
2837 int cmd_querytype (const char *arg)
2839 if (!strcmp (arg, "ccl"))
2840 queryType = QueryType_CCL;
2841 else if (!strcmp (arg, "prefix") || !strcmp(arg, "rpn"))
2842 queryType = QueryType_Prefix;
2843 else if (!strcmp (arg, "ccl2rpn") || !strcmp (arg, "cclrpn"))
2844 queryType = QueryType_CCL2RPN;
2845 else if (!strcmp(arg, "cql"))
2846 queryType = QueryType_CQL;
2847 else if (!strcmp (arg, "cql2rpn") || !strcmp (arg, "cqlrpn"))
2848 queryType = QueryType_CQL2RPN;
2851 printf ("Querytype must be one of:\n");
2852 printf (" prefix - Prefix query\n");
2853 printf (" ccl - CCL query\n");
2854 printf (" ccl2rpn - CCL query converted to RPN\n");
2855 printf (" cql - CQL\n");
2856 printf (" cql2rpn - CQL query converted to RPN\n");
2862 int cmd_refid (const char *arg)
2868 refid = (char *) xmalloc (strlen(arg)+1);
2869 strcpy (refid, arg);
2874 int cmd_close(const char *arg)
2883 apdu = zget_APDU(out, Z_APDU_close);
2884 req = apdu->u.close;
2885 *req->closeReason = Z_Close_finished;
2887 printf("Sent close request.\n");
2892 int cmd_packagename(const char* arg)
2894 xfree (esPackageName);
2895 esPackageName = NULL;
2897 esPackageName = xstrdup(arg);
2901 int cmd_proxy(const char* arg)
2906 yazProxy = xstrdup (arg);
2910 int cmd_marccharset(const char *arg)
2915 if (sscanf(arg, "%29s", l1) < 1)
2917 xfree (marcCharset);
2919 if (strcmp(l1, "-"))
2920 marcCharset = xstrdup(l1);
2924 int cmd_charset(const char* arg)
2926 char l1[30], l2[30];
2929 if (sscanf(arg, "%29s %29s", l1, l2) < 1)
2931 printf("Current negotiation character set is `%s'\n",
2932 negotiationCharset ? negotiationCharset: "none");
2933 printf("Current output character set is `%s'\n",
2934 outputCharset ? outputCharset: "none");
2937 xfree (negotiationCharset);
2938 negotiationCharset = NULL;
2939 if (*l1 && strcmp(l1, "-"))
2941 negotiationCharset = xstrdup(l1);
2942 printf ("Character set negotiation : %s\n", negotiationCharset);
2945 printf ("Character set negotiation disabled\n");
2948 xfree (outputCharset);
2950 if (!strcmp(l2, "auto") && codeset)
2954 printf ("output charset: %s\n", codeset);
2955 outputCharset = xstrdup(codeset);
2960 printf ("No codeset found on this system\n");
2962 else if (strcmp(l2, "-"))
2963 outputCharset = xstrdup(l2);
2965 printf ("Output charset conversion disabled\n");
2971 int cmd_lang(const char* arg)
2974 printf("Current language is `%s'\n", (yazLang)?yazLang:NULL);
2981 yazLang = (char *) xmalloc (strlen(arg)+1);
2982 strcpy (yazLang, arg);
2987 int cmd_source(const char* arg)
2989 /* first should open the file and read one line at a time.. */
2991 char line[1024], *cp;
2994 fprintf(stderr,"Error in source command use a filename\n");
2998 includeFile = fopen (arg, "r");
3001 fprintf(stderr,"Unable to open file %s for reading\n",arg);
3005 while(!feof(includeFile)) {
3006 memset(line,0,sizeof(line));
3007 fgets(line,sizeof(line),includeFile);
3009 if(strlen(line) < 2) continue;
3010 if(line[0] == '#') continue;
3012 if ((cp = strrchr (line, '\n')))
3015 process_cmd_line(line);
3018 if(fclose(includeFile)<0) {
3019 perror("unable to close include file");
3025 int cmd_subshell(const char* args)
3030 system(getenv("SHELL"));
3036 int cmd_set_berfile(const char *arg)
3038 if (ber_file && ber_file != stdout && ber_file != stderr)
3040 if (!strcmp(arg, ""))
3042 else if (!strcmp(arg, "-"))
3045 ber_file = fopen(arg, "a");
3049 int cmd_set_apdufile(const char *arg)
3051 if(apdu_file && apdu_file != stderr && apdu_file != stderr)
3053 if (!strcmp(arg, ""))
3055 else if (!strcmp(arg, "-"))
3059 apdu_file = fopen(arg, "a");
3061 perror("unable to open apdu log file");
3064 odr_setprint(print, apdu_file);
3068 int cmd_set_cclfile(const char* arg)
3072 bibset = ccl_qual_mk ();
3073 inf = fopen (arg, "r");
3075 perror("unable to open CCL file");
3078 ccl_qual_file (bibset, inf);
3081 strcpy(ccl_fields,arg);
3085 int cmd_set_cqlfile(const char* arg)
3087 cql_transform_t newcqltrans;
3089 if ((newcqltrans = cql_transform_open_fname(arg)) == 0) {
3090 perror("unable to open CQL file");
3094 cql_transform_close(cqltrans);
3096 cqltrans = newcqltrans;
3097 strcpy(cql_fields, arg);
3101 int cmd_set_auto_reconnect(const char* arg)
3103 if(strlen(arg)==0) {
3104 auto_reconnect = ! auto_reconnect;
3105 } else if(strcmp(arg,"on")==0) {
3107 } else if(strcmp(arg,"off")==0) {
3110 printf("Error use on or off\n");
3115 printf("Set auto reconnect enabled.\n");
3117 printf("Set auto reconnect disabled.\n");
3122 int cmd_set_marcdump(const char* arg)
3124 if(marc_file && marc_file != stderr) { /* don't close stdout*/
3128 if (!strcmp(arg, ""))
3130 else if (!strcmp(arg, "-"))
3134 marc_file = fopen(arg, "a");
3136 perror("unable to open marc log file");
3142 this command takes 3 arge {name class oid}
3144 int cmd_register_oid(const char* args) {
3149 {"appctx",CLASS_APPCTX},
3150 {"absyn",CLASS_ABSYN},
3151 {"attset",CLASS_ATTSET},
3152 {"transyn",CLASS_TRANSYN},
3153 {"diagset",CLASS_DIAGSET},
3154 {"recsyn",CLASS_RECSYN},
3155 {"resform",CLASS_RESFORM},
3156 {"accform",CLASS_ACCFORM},
3157 {"extserv",CLASS_EXTSERV},
3158 {"userinfo",CLASS_USERINFO},
3159 {"elemspec",CLASS_ELEMSPEC},
3160 {"varset",CLASS_VARSET},
3161 {"schema",CLASS_SCHEMA},
3162 {"tagset",CLASS_TAGSET},
3163 {"general",CLASS_GENERAL},
3164 {0,(enum oid_class) 0}
3166 char oname_str[101], oclass_str[101], oid_str[101];
3169 oid_class oidclass = CLASS_GENERAL;
3170 int val = 0, oid[OID_SIZE];
3171 struct oident * new_oident=NULL;
3173 if (sscanf (args, "%100[^ ] %100[^ ] %100s",
3174 oname_str,oclass_str, oid_str) < 1) {
3175 printf("Error in regristrate command \n");
3179 for (i = 0; oid_classes[i].className; i++) {
3180 if (!strcmp(oid_classes[i].className, oclass_str))
3182 oidclass=oid_classes[i].oclass;
3187 if(!(oid_classes[i].className)) {
3188 printf("Unknonwn oid class %s\n",oclass_str);
3196 while (isdigit (*name))
3198 val = val*10 + (*name - '0');
3211 new_oident=oid_addent (oid,PROTO_GENERAL,oidclass,oname_str,VAL_DYNAMIC);
3212 if(strcmp(new_oident->desc,oname_str)) {
3213 fprintf(stderr,"oid is already named as %s, regristration faild\n",
3219 int cmd_push_command(const char* arg)
3221 #if HAVE_READLINE_HISTORY_H
3225 fprintf(stderr,"Not compiled with the readline/history module\n");
3230 void source_rcfile()
3232 /* Look for a $HOME/.yazclientrc and source it if it exists */
3233 struct stat statbuf;
3235 char* homedir=getenv("HOME");
3237 if(!homedir) return;
3239 sprintf(buffer,"%s/.yazclientrc",homedir);
3241 if(stat(buffer,&statbuf)==0) {
3245 if(stat(".yazclientrc",&statbuf)==0) {
3246 cmd_source(".yazclientrc");
3251 static void initialize(void)
3256 if (!(out = odr_createmem(ODR_ENCODE)) ||
3257 !(in = odr_createmem(ODR_DECODE)) ||
3258 !(print = odr_createmem(ODR_PRINT)))
3260 fprintf(stderr, "failed to allocate ODR streams\n");
3265 setvbuf(stdout, 0, _IONBF, 0);
3267 odr_setprint(print, apdu_file);
3269 bibset = ccl_qual_mk ();
3270 inf = fopen (ccl_fields, "r");
3273 ccl_qual_file (bibset, inf);
3277 cqltrans = cql_transform_open_fname(cql_fields);
3278 /* If this fails, no problem: we detect cqltrans == 0 later */
3280 #if HAVE_READLINE_READLINE_H
3281 rl_attempted_completion_function = (CPPFunction*)readline_completer;
3285 for(i=0; i<maxOtherInfosSupported; ++i) {
3286 extraOtherInfos[i].oidval = -1;
3293 #if HAVE_GETTIMEOFDAY
3294 struct timeval tv_start, tv_end;
3298 static void handle_srw_record(Z_SRW_record *rec)
3300 if (rec->recordPosition)
3302 printf ("pos=%d", *rec->recordPosition);
3303 setno = *rec->recordPosition + 1;
3305 if (rec->recordSchema)
3306 printf (" schema=%s", rec->recordSchema);
3308 if (rec->recordData_buf && rec->recordData_len)
3309 fwrite(rec->recordData_buf, 1, rec->recordData_len, stdout);
3311 printf ("No data!");
3315 static void handle_srw_explain_response(Z_SRW_explainResponse *res)
3317 handle_srw_record(&res->record);
3320 static void handle_srw_response(Z_SRW_searchRetrieveResponse *res)
3324 printf ("Received SRW SearchRetrieve Response\n");
3326 for (i = 0; i<res->num_diagnostics; i++)
3328 if (res->diagnostics[i].uri)
3329 printf ("SRW diagnostic %s\n",
3330 res->diagnostics[i].uri);
3332 printf ("SRW diagnostic missing or could not be decoded\n");
3333 if (res->diagnostics[i].message)
3334 printf ("Message: %s\n", res->diagnostics[i].message);
3335 if (res->diagnostics[i].details)
3336 printf ("Details: %s\n", res->diagnostics[i].details);
3338 if (res->numberOfRecords)
3339 printf ("Number of hits: %d\n", *res->numberOfRecords);
3340 for (i = 0; i<res->num_records; i++)
3341 handle_srw_record(res->records + i);
3344 static void http_response(Z_HTTP_Response *hres)
3347 const char *content_type = z_HTTP_header_lookup(hres->headers,
3349 const char *connection_head = z_HTTP_header_lookup(hres->headers,
3351 if (content_type && !yaz_strcmp_del("text/xml", content_type, "; "))
3353 Z_SOAP *soap_package = 0;
3354 ODR o = odr_createmem(ODR_DECODE);
3355 Z_SOAP_Handler soap_handlers[2] = {
3356 {"http://www.loc.gov/zing/srw/", 0,
3357 (Z_SOAP_fun) yaz_srw_codec},
3360 ret = z_soap_codec(o, &soap_package,
3361 &hres->content_buf, &hres->content_len,
3363 if (!ret && soap_package->which == Z_SOAP_generic &&
3364 soap_package->u.generic->no == 0)
3366 Z_SRW_PDU *sr = soap_package->u.generic->p;
3367 if (sr->which == Z_SRW_searchRetrieve_response)
3368 handle_srw_response(sr->u.response);
3369 else if (sr->which == Z_SRW_explain_response)
3370 handle_srw_explain_response(sr->u.explain_response);
3374 else if (soap_package && (soap_package->which == Z_SOAP_fault
3375 || soap_package->which == Z_SOAP_error))
3377 printf ("HTTP Error Status=%d\n", hres->code);
3378 printf ("SOAP Fault code %s\n",
3379 soap_package->u.fault->fault_code);
3380 printf ("SOAP Fault string %s\n",
3381 soap_package->u.fault->fault_string);
3382 if (soap_package->u.fault->details)
3383 printf ("SOAP Details %s\n",
3384 soap_package->u.fault->details);
3392 if (hres->code != 200)
3394 printf ("HTTP Error Status=%d\n", hres->code);
3398 printf ("Decoding of SRW package failed\n");
3404 if (!strcmp(hres->version, "1.0"))
3406 /* HTTP 1.0: only if Keep-Alive we stay alive.. */
3407 if (!connection_head || strcmp(connection_head, "Keep-Alive"))
3412 /* HTTP 1.1: only if no close we stay alive .. */
3413 if (connection_head && !strcmp(connection_head, "close"))
3420 void wait_and_handle_response()
3422 int reconnect_ok = 1;
3425 int netbufferlen = 0;
3430 res = cs_get(conn, &netbuffer, &netbufferlen);
3431 if (reconnect_ok && res <= 0 && protocol == PROTO_HTTP)
3442 buf_out = odr_getbuf(out, &len_out, 0);
3444 do_hex_dump(buf_out, len_out);
3446 cs_put(conn, buf_out, len_out);
3454 printf("Target closed connection\n");
3459 odr_reset(in); /* release APDU from last round */
3461 do_hex_dump(netbuffer, res);
3462 odr_setbuf(in, netbuffer, res, 0);
3464 if (!z_GDU(in, &gdu, 0, 0))
3466 FILE *f = ber_file ? ber_file : stdout;
3467 odr_perror(in, "Decoding incoming APDU");
3468 fprintf(f, "[Near %d]\n", odr_offset(in));
3469 fprintf(f, "Packet dump:\n---------\n");
3470 odr_dumpBER(f, netbuffer, res);
3471 fprintf(f, "---------\n");
3474 z_GDU(print, &gdu, 0, 0);
3477 if (conn && cs_more(conn))
3482 odr_dumpBER(ber_file, netbuffer, res);
3483 if (apdu_file && !z_GDU(print, &gdu, 0, 0))
3485 odr_perror(print, "Failed to print incoming APDU");
3489 if (gdu->which == Z_GDU_Z3950)
3491 Z_APDU *apdu = gdu->u.z3950;
3494 case Z_APDU_initResponse:
3495 process_initResponse(apdu->u.initResponse);
3497 case Z_APDU_searchResponse:
3498 process_searchResponse(apdu->u.searchResponse);
3500 case Z_APDU_scanResponse:
3501 process_scanResponse(apdu->u.scanResponse);
3503 case Z_APDU_presentResponse:
3504 print_refid (apdu->u.presentResponse->referenceId);
3506 *apdu->u.presentResponse->numberOfRecordsReturned;
3507 if (apdu->u.presentResponse->records)
3508 display_records(apdu->u.presentResponse->records);
3510 printf("No records.\n");
3511 printf ("nextResultSetPosition = %d\n",
3512 *apdu->u.presentResponse->nextResultSetPosition);
3514 case Z_APDU_sortResponse:
3515 process_sortResponse(apdu->u.sortResponse);
3517 case Z_APDU_extendedServicesResponse:
3518 printf("Got extended services response\n");
3519 process_ESResponse(apdu->u.extendedServicesResponse);
3522 printf("Target has closed the association.\n");
3523 process_close(apdu->u.close);
3525 case Z_APDU_resourceControlRequest:
3526 process_resourceControlRequest
3527 (apdu->u.resourceControlRequest);
3529 case Z_APDU_deleteResultSetResponse:
3530 process_deleteResultSetResponse(apdu->u.
3531 deleteResultSetResponse);
3534 printf("Received unknown APDU type (%d).\n",
3540 else if (gdu->which == Z_GDU_HTTP_Response)
3542 http_response(gdu->u.HTTP_Response);
3545 if (conn && !cs_more(conn))
3550 #if HAVE_GETTIMEOFDAY
3551 gettimeofday (&tv_end, 0);
3553 printf ("S/U S/U=%ld/%ld %ld/%ld",
3554 (long) tv_start.tv_sec,
3555 (long) tv_start.tv_usec,
3556 (long) tv_end.tv_sec,
3557 (long) tv_end.tv_usec);
3559 printf ("Elapsed: %.6f\n",
3560 (double) tv_end.tv_usec / 1e6 + tv_end.tv_sec -
3561 ((double) tv_start.tv_usec / 1e6 + tv_start.tv_sec));
3568 int cmd_cclparse(const char* arg)
3571 struct ccl_rpn_node *rpn=NULL;
3574 rpn = ccl_find_str (bibset, arg, &error, &pos);
3577 printf ("%*s^ - ", 3+strlen(last_cmd)+1+pos, " ");
3578 printf ("%s\n", ccl_err_msg (error));
3584 ccl_pr_tree(rpn, stdout);
3588 ccl_rpn_delete(rpn);
3596 int cmd_set_otherinfo(const char* args)
3598 char oid[101], otherinfoString[101];
3603 sscan_res = sscanf (args, "%d %100[^ ] %100s", &otherinfoNo, oid, otherinfoString);
3605 /* reset this otherinfo */
3606 if(otherinfoNo>=maxOtherInfosSupported) {
3607 printf("Error otherinfo index to large (%d>%d)\n",otherinfoNo,maxOtherInfosSupported);
3609 extraOtherInfos[otherinfoNo].oidval = -1;
3610 if(extraOtherInfos[otherinfoNo].value) free(extraOtherInfos[otherinfoNo].value);
3614 printf("Error in set_otherinfo command \n");
3618 if(otherinfoNo>=maxOtherInfosSupported) {
3619 printf("Error otherinfo index to large (%d>%d)\n",otherinfoNo,maxOtherInfosSupported);
3622 oidval = oid_getvalbyname (oid);
3624 printf("Error in set_otherinfo command unknown oid %s \n",oid);
3627 extraOtherInfos[otherinfoNo].oidval = oidval;
3628 if(extraOtherInfos[otherinfoNo].value) free(extraOtherInfos[otherinfoNo].value);
3629 extraOtherInfos[otherinfoNo].value = strdup(otherinfoString);
3634 int cmd_list_otherinfo(const char* args)
3638 if(strlen(args)>0) {
3640 if( i >= maxOtherInfosSupported ) {
3641 printf("Error otherinfo index to large (%d>%d)\n",i,maxOtherInfosSupported);
3645 if(extraOtherInfos[i].oidval != -1)
3646 printf(" otherinfo %d %s %s\n",
3648 yaz_z3950_oid_value_to_str(
3649 (enum oid_value) extraOtherInfos[i].oidval,
3651 extraOtherInfos[i].value);
3654 for(i=0; i<maxOtherInfosSupported; ++i) {
3655 if(extraOtherInfos[i].oidval != -1)
3656 printf(" otherinfo %d %s %s\n",
3658 yaz_z3950_oid_value_to_str(
3659 (enum oid_value) extraOtherInfos[i].oidval,
3661 extraOtherInfos[i].value);
3669 int cmd_list_all(const char* args) {
3672 /* connection options */
3674 printf("Connected to : %s\n",last_open_command);
3676 if(last_open_command)
3677 printf("Not connected to : %s\n",last_open_command);
3679 printf("Not connected : \n");
3682 if(yazProxy) printf("using proxy : %s\n",yazProxy);
3684 printf("auto_reconnect : %s\n",auto_reconnect?"on":"off");
3687 printf("Authentication : none\n");
3689 switch(auth->which) {
3690 case Z_IdAuthentication_idPass:
3691 printf("Authentication : IdPass\n");
3692 printf(" Login User : %s\n",auth->u.idPass->userId?auth->u.idPass->userId:"");
3693 printf(" Login Group : %s\n",auth->u.idPass->groupId?auth->u.idPass->groupId:"");
3694 printf(" Password : %s\n",auth->u.idPass->password?auth->u.idPass->password:"");
3696 case Z_IdAuthentication_open:
3697 printf("Authentication : psOpen\n");
3698 printf(" Open string : %s\n",auth->u.open);
3701 printf("Authentication : Unknown\n");
3704 if (negotiationCharset)
3705 printf("Neg. Character set : `%s'\n", negotiationCharset);
3709 for (i = 0; i<num_databaseNames; i++) printf("%s ",databaseNames[i]);
3713 printf("CCL file : %s\n",ccl_fields);
3714 printf("CQL file : %s\n",cql_fields);
3715 printf("Query type : %s\n",query_type_as_string(queryType));
3717 printf("Named Result Sets : %s\n",setnumber==-1?"off":"on");
3719 /* piggy back options */
3720 printf("ssub/lslb/mspn : %d/%d/%d\n",smallSetUpperBound,largeSetLowerBound,mediumSetPresentNumber);
3722 /* print present related options */
3723 printf("Format : %s\n",yaz_z3950_oid_value_to_str(recordsyntax,CLASS_RECSYN));
3724 printf("Schema : %s\n",record_schema ? record_schema : "not set");
3725 printf("Elements : %s\n",elementSetNames?elementSetNames->u.generic:"");
3727 /* loging options */
3728 printf("APDU log : %s\n",apdu_file?"on":"off");
3729 printf("Record log : %s\n",marc_file?"on":"off");
3732 printf("Other Info: \n");
3733 cmd_list_otherinfo("");
3738 int cmd_clear_otherinfo(const char* args)
3740 if(strlen(args)>0) {
3742 otherinfoNo = atoi(args);
3743 if( otherinfoNo >= maxOtherInfosSupported ) {
3744 printf("Error otherinfo index to large (%d>%d)\n",otherinfoNo,maxOtherInfosSupported);
3748 if(extraOtherInfos[otherinfoNo].oidval != -1) {
3749 /* only clear if set. */
3750 extraOtherInfos[otherinfoNo].oidval=-1;
3751 free(extraOtherInfos[otherinfoNo].value);
3756 for(i=0; i<maxOtherInfosSupported; ++i) {
3757 if (extraOtherInfos[i].oidval!=-1 ) {
3758 extraOtherInfos[i].oidval=-1;
3759 free(extraOtherInfos[i].value);
3766 static int cmd_help (const char *line);
3768 typedef char *(*completerFunctionType)(const char *text, int state);
3772 int (*fun)(const char *arg);
3774 completerFunctionType rl_completerfunction;
3775 int complete_filenames;
3776 char **local_tabcompletes;
3778 {"open", cmd_open, "('tcp'|'ssl')':<host>[':'<port>][/<db>]",NULL,0,NULL},
3779 {"quit", cmd_quit, "",NULL,0,NULL},
3780 {"find", cmd_find, "<query>",NULL,0,NULL},
3781 {"delete", cmd_delete, "<setname>",NULL,0,NULL},
3782 {"base", cmd_base, "<base-name>",NULL,0,NULL},
3783 {"show", cmd_show, "<rec#>['+'<#recs>['+'<setname>]]",NULL,0,NULL},
3784 {"scan", cmd_scan, "<term>",NULL,0,NULL},
3785 {"sort", cmd_sort, "<sortkey> <flag> <sortkey> <flag> ...",NULL,0,NULL},
3786 {"sort+", cmd_sort_newset, "<sortkey> <flag> <sortkey> <flag> ...",NULL,0,NULL},
3787 {"authentication", cmd_authentication, "<acctstring>",NULL,0,NULL},
3788 {"lslb", cmd_lslb, "<largeSetLowerBound>",NULL,0,NULL},
3789 {"ssub", cmd_ssub, "<smallSetUpperBound>",NULL,0,NULL},
3790 {"mspn", cmd_mspn, "<mediumSetPresentNumber>",NULL,0,NULL},
3791 {"status", cmd_status, "",NULL,0,NULL},
3792 {"setnames", cmd_setnames, "",NULL,0,NULL},
3793 {"cancel", cmd_cancel, "",NULL,0,NULL},
3794 {"format", cmd_format, "<recordsyntax>",complete_format,0,NULL},
3795 {"schema", cmd_schema, "<schema>",complete_schema,0,NULL},
3796 {"elements", cmd_elements, "<elementSetName>",NULL,0,NULL},
3797 {"close", cmd_close, "",NULL,0,NULL},
3798 {"attributeset", cmd_attributeset, "<attrset>",complete_attributeset,0,NULL},
3799 {"querytype", cmd_querytype, "<type>",complete_querytype,0,NULL},
3800 {"refid", cmd_refid, "<id>",NULL,0,NULL},
3801 {"itemorder", cmd_itemorder, "ill|item <itemno>",NULL,0,NULL},
3802 {"update", cmd_update, "<action> <recid> [<file>]",NULL,0,NULL},
3803 {"update0", cmd_update0, "<action> <recid> [<file>]",NULL,0,NULL},
3804 {"packagename", cmd_packagename, "<packagename>",NULL,0,NULL},
3805 {"proxy", cmd_proxy, "[('tcp'|'ssl')]<host>[':'<port>]",NULL,0,NULL},
3806 {"charset", cmd_charset, "<nego_charset> <output_charset>",NULL,0,NULL},
3807 {"marccharset", cmd_marccharset, "<charset_name>",NULL,0,NULL},
3808 {"lang", cmd_lang, "<language_code>",NULL,0,NULL},
3809 {".", cmd_source, "<filename>",NULL,1,NULL},
3810 {"!", cmd_subshell, "Subshell command",NULL,1,NULL},
3811 {"set_apdufile", cmd_set_apdufile, "<filename>",NULL,1,NULL},
3812 {"set_berfile", cmd_set_berfile, "<filename>",NULL,1,NULL},
3813 {"set_marcdump", cmd_set_marcdump," <filename>",NULL,1,NULL},
3814 {"set_cclfile", cmd_set_cclfile," <filename>",NULL,1,NULL},
3815 {"set_cqlfile", cmd_set_cqlfile," <filename>",NULL,1,NULL},
3816 {"set_auto_reconnect", cmd_set_auto_reconnect," on|off",complete_auto_reconnect,1,NULL},
3817 {"set_otherinfo", cmd_set_otherinfo,"<otherinfoinddex> <oid> <string>",NULL,0,NULL},
3818 {"register_oid", cmd_register_oid,"<name> <class> <oid>",NULL,0,NULL},
3819 {"push_command", cmd_push_command,"<command>",command_generator,0,NULL},
3820 {"register_tab", cmd_register_tab,"<commandname> <tab>",command_generator,0,NULL},
3821 {"cclparse", cmd_cclparse,"<ccl find command>",NULL,0,NULL},
3822 {"list_otherinfo",cmd_list_otherinfo,"[otherinfoinddex]",NULL,0,NULL},
3823 {"list_all",cmd_list_all,"",NULL,0,NULL},
3824 {"clear_otherinfo",cmd_clear_otherinfo,"",NULL,0,NULL},
3825 /* Server Admin Functions */
3826 {"adm-reindex", cmd_adm_reindex, "<database-name>",NULL,0,NULL},
3827 {"adm-truncate", cmd_adm_truncate, "('database'|'index')<object-name>",NULL,0,NULL},
3828 {"adm-create", cmd_adm_create, "",NULL,0,NULL},
3829 {"adm-drop", cmd_adm_drop, "('database'|'index')<object-name>",NULL,0,NULL},
3830 {"adm-import", cmd_adm_import, "<record-type> <dir> <pattern>",NULL,0,NULL},
3831 {"adm-refresh", cmd_adm_refresh, "",NULL,0,NULL},
3832 {"adm-commit", cmd_adm_commit, "",NULL,0,NULL},
3833 {"adm-shutdown", cmd_adm_shutdown, "",NULL,0,NULL},
3834 {"adm-startup", cmd_adm_startup, "",NULL,0,NULL},
3835 {"explain", cmd_explain, "", NULL, 0, NULL},
3836 {"options", cmd_options, "", NULL, 0, NULL},
3837 {"zversion", cmd_zversion, "", NULL, 0, NULL},
3838 {"help", cmd_help, "", NULL,0,NULL},
3839 {"init", cmd_init, "", NULL,0,NULL},
3843 static int cmd_help (const char *line)
3849 sscanf (line, "%20s", topic);
3852 printf("Commands:\n");
3853 for (i = 0; cmd_array[i].cmd; i++)
3854 if (*topic == 0 || strcmp (topic, cmd_array[i].cmd) == 0)
3855 printf(" %s %s\n", cmd_array[i].cmd, cmd_array[i].ad);
3856 if (strcmp (topic, "find") == 0)
3859 printf (" \"term\" Simple Term\n");
3860 printf (" @attr [attset] type=value op Attribute\n");
3861 printf (" @and opl opr And\n");
3862 printf (" @or opl opr Or\n");
3863 printf (" @not opl opr And-Not\n");
3864 printf (" @set set Result set\n");
3866 printf ("Bib-1 attribute types\n");
3868 printf ("4=Title 7=ISBN 8=ISSN 30=Date 62=Abstract 1003=Author 1016=Any\n");
3869 printf ("2=Relation: ");
3870 printf ("1< 2<= 3= 4>= 5> 6!= 102=Relevance\n");
3871 printf ("3=Position: ");
3872 printf ("1=First in Field 2=First in subfield 3=Any position\n");
3873 printf ("4=Structure: ");
3874 printf ("1=Phrase 2=Word 3=Key 4=Year 5=Date 6=WordList\n");
3875 printf ("5=Truncation: ");
3876 printf ("1=Right 2=Left 3=L&R 100=No 101=# 102=Re-1 103=Re-2\n");
3877 printf ("6=Completeness:");
3878 printf ("1=Incomplete subfield 2=Complete subfield 3=Complete field\n");
3883 int cmd_register_tab(const char* arg) {
3885 char command[101], tabargument[101];
3890 if (sscanf (arg, "%100s %100s", command, tabargument) < 1) {
3894 /* locate the amdn in the list */
3895 for (i = 0; cmd_array[i].cmd; i++) {
3896 if (!strncmp(cmd_array[i].cmd, command, strlen(command))) {
3901 if(!cmd_array[i].cmd) {
3902 fprintf(stderr,"Unknown command %s\n",command);
3907 if(!cmd_array[i].local_tabcompletes)
3908 cmd_array[i].local_tabcompletes = (char **) calloc(1,sizeof(char**));
3912 tabslist = cmd_array[i].local_tabcompletes;
3913 for(;tabslist && *tabslist;tabslist++) {
3917 cmd_array[i].local_tabcompletes = (char **)
3918 realloc(cmd_array[i].local_tabcompletes,(num_of_tabs+2)*sizeof(char**));
3919 tabslist=cmd_array[i].local_tabcompletes;
3920 tabslist[num_of_tabs]=strdup(tabargument);
3921 tabslist[num_of_tabs+1]=NULL;
3926 void process_cmd_line(char* line)
3929 char word[32], arg[1024];
3931 #if HAVE_GETTIMEOFDAY
3932 gettimeofday (&tv_start, 0);
3935 if ((res = sscanf(line, "%31s %1023[^;]", word, arg)) <= 0)
3937 strcpy(word, last_cmd);
3942 strcpy(last_cmd, word);
3944 /* removed tailing spaces from the arg command */
3947 char* lastnonspace=NULL;
3955 *(++lastnonspace) = 0;
3958 for (i = 0; cmd_array[i].cmd; i++)
3959 if (!strncmp(cmd_array[i].cmd, word, strlen(word)))
3961 res = (*cmd_array[i].fun)(arg);
3965 if (!cmd_array[i].cmd) /* dump our help-screen */
3967 printf("Unknown command: %s.\n", word);
3968 printf("use help for list of commands\n");
3969 /* cmd_help (""); */
3973 if(apdu_file) fflush(apdu_file);
3976 wait_and_handle_response();
3985 char *command_generator(const char *text, int state)
3991 for( ; cmd_array[idx].cmd; ++idx) {
3992 if (!strncmp(cmd_array[idx].cmd,text,strlen(text))) {
3993 ++idx; /* skip this entry on the next run */
3994 return strdup(cmd_array[idx-1].cmd);
4002 This function only known how to complete on the first word
4004 char ** readline_completer(char *text, int start, int end) {
4005 #if HAVE_READLINE_READLINE_H
4007 completerFunctionType completerToUse;
4010 #if HAVE_READLINE_RL_COMPLETION_MATCHES
4011 char** res=rl_completion_matches(text,
4014 char** res=completion_matches(text,
4015 (CPFunction*)command_generator);
4017 rl_attempted_completion_over = 1;
4020 char arg[1024],word[32];
4022 if ((res = sscanf(rl_line_buffer, "%31s %1023[^;]", word, arg)) <= 0) {
4023 rl_attempted_completion_over = 1;
4027 for (i = 0; cmd_array[i].cmd; i++) {
4028 if (!strncmp(cmd_array[i].cmd, word, strlen(word))) {
4033 if(!cmd_array[i].cmd) return NULL;
4035 curret_global_list = cmd_array[i].local_tabcompletes;
4037 completerToUse = cmd_array[i].rl_completerfunction;
4038 if(completerToUse==NULL) /* if no pr. command completer is defined use the default completer */
4039 completerToUse = default_completer;
4041 if(completerToUse) {
4042 #ifdef HAVE_READLINE_RL_COMPLETION_MATCHES
4044 rl_completion_matches(text,
4048 completion_matches(text,
4049 (CPFunction*)completerToUse);
4051 if(!cmd_array[i].complete_filenames)
4052 rl_attempted_completion_over = 1;
4055 if(!cmd_array[i].complete_filenames)
4056 rl_attempted_completion_over = 1;
4066 static void client(void)
4072 #if HAVE_GETTIMEOFDAY
4073 gettimeofday (&tv_start, 0);
4078 char *line_in = NULL;
4079 #if HAVE_READLINE_READLINE_H
4082 line_in=readline(C_PROMPT);
4085 #if HAVE_READLINE_HISTORY_H
4087 add_history(line_in);
4089 strncpy(line, line_in, 1023);
4098 if (!fgets(line, 1023, stdin))
4100 if ((end_p = strchr (line, '\n')))
4103 process_cmd_line(line);
4107 static void show_version(void)
4111 yaz_version(vstr, 0);
4112 printf ("YAZ version: %s\n", YAZ_VERSION);
4113 if (strcmp(vstr, YAZ_VERSION))
4114 printf ("YAZ DLL/SO: %s\n", vstr);
4118 int main(int argc, char **argv)
4121 char *open_command = 0;
4122 char *auth_command = 0;
4127 if (!setlocale(LC_CTYPE, ""))
4128 fprintf (stderr, "setlocale failed\n");
4132 codeset = nl_langinfo(CODESET);
4136 outputCharset = xstrdup(codeset);
4138 ODR_MASK_SET(&z3950_options, Z_Options_search);
4139 ODR_MASK_SET(&z3950_options, Z_Options_present);
4140 ODR_MASK_SET(&z3950_options, Z_Options_namedResultSets);
4141 ODR_MASK_SET(&z3950_options, Z_Options_triggerResourceCtrl);
4142 ODR_MASK_SET(&z3950_options, Z_Options_scan);
4143 ODR_MASK_SET(&z3950_options, Z_Options_sort);
4144 ODR_MASK_SET(&z3950_options, Z_Options_extendedServices);
4145 ODR_MASK_SET(&z3950_options, Z_Options_delSet);
4147 while ((ret = options("k:c:q:a:b:m:v:p:u:t:Vxd:", argv, argc, &arg)) != -2)
4154 open_command = (char *) xmalloc (strlen(arg)+6);
4155 strcpy (open_command, "open ");
4156 strcat (open_command, arg);
4160 dump_file_prefix = arg;
4163 kilobytes = atoi(arg);
4166 if (!(marc_file = fopen (arg, "a")))
4173 outputCharset = xstrdup(arg);
4176 strncpy (ccl_fields, arg, sizeof(ccl_fields)-1);
4177 ccl_fields[sizeof(ccl_fields)-1] = '\0';
4180 strncpy (cql_fields, arg, sizeof(cql_fields)-1);
4181 cql_fields[sizeof(cql_fields)-1] = '\0';
4184 if (!strcmp(arg, "-"))
4187 ber_file=fopen(arg, "a");
4190 if (!strcmp(arg, "-"))
4193 apdu_file=fopen(arg, "a");
4199 yazProxy=strdup(arg);
4204 auth_command = (char *) xmalloc (strlen(arg)+6);
4205 strcpy (auth_command, "auth ");
4206 strcat (auth_command, arg);
4210 yaz_log_init(yaz_log_mask_str(arg), "", 0);
4216 fprintf (stderr, "Usage: %s [-m <marclog>] [ -a <apdulog>] "
4217 "[-b berdump] [-c cclfields] \n"
4218 "[-q cqlfields] [-p <proxy-addr>] [-u <auth>] "
4219 "[-k size] [-d dump] [-V] [<server-addr>]\n",
4227 #ifdef HAVE_GETTIMEOFDAY
4228 gettimeofday (&tv_start, 0);
4230 process_cmd_line (auth_command);
4231 #if HAVE_READLINE_HISTORY_H
4232 add_history(auth_command);
4234 xfree(auth_command);
4238 #ifdef HAVE_GETTIMEOFDAY
4239 gettimeofday (&tv_start, 0);
4241 process_cmd_line (open_command);
4242 #if HAVE_READLINE_HISTORY_H
4243 add_history(open_command);
4245 xfree(open_command);
4256 * vim600: sw=4 ts=8 fdm=marker
4257 * vim<600: sw=4 ts=8