2 * Copyright (c) 1995-2004, Index Data
3 * See the file LICENSE for details.
5 * $Id: client.c,v 1.232 2004-02-19 23:37:36 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.0";
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->oclass != CLASS_RECSYN)
746 if (ent && ent->value == VAL_SOIF)
747 print_record((const unsigned char *) r->u.octet_aligned->buf,
748 r->u.octet_aligned->len);
749 else if (r->which == Z_External_octet)
751 const char *octet_buf = (char*)r->u.octet_aligned->buf;
752 if (ent->value == VAL_TEXT_XML || 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->copyNumber)
920 printf ("copyNumber: %s\n", data->copyNumber);
921 if (data->publicNote)
922 printf ("publicNote: %s\n", data->publicNote);
923 if (data->reproductionNote)
924 printf ("reproductionNote: %s\n", data->reproductionNote);
925 if (data->termsUseRepro)
926 printf ("termsUseRepro: %s\n", data->termsUseRepro);
927 if (data->enumAndChron)
928 printf ("enumAndChron: %s\n", data->enumAndChron);
929 for (j = 0; j<data->num_volumes; j++)
931 printf ("volume %d\n", j);
932 if (data->volumes[j]->enumeration)
933 printf (" enumeration: %s\n",
934 data->volumes[j]->enumeration);
935 if (data->volumes[j]->chronology)
936 printf (" chronology: %s\n",
937 data->volumes[j]->chronology);
938 if (data->volumes[j]->enumAndChron)
939 printf (" enumAndChron: %s\n",
940 data->volumes[j]->enumAndChron);
942 for (j = 0; j<data->num_circulationData; j++)
944 printf ("circulation %d\n", j);
945 if (data->circulationData[j]->availableNow)
946 printf (" availableNow: %d\n",
947 *data->circulationData[j]->availableNow);
948 if (data->circulationData[j]->availablityDate)
949 printf (" availabiltyDate: %s\n",
950 data->circulationData[j]->availablityDate);
951 if (data->circulationData[j]->availableThru)
952 printf (" availableThru: %s\n",
953 data->circulationData[j]->availableThru);
954 if (data->circulationData[j]->restrictions)
955 printf (" restrictions: %s\n",
956 data->circulationData[j]->restrictions);
957 if (data->circulationData[j]->itemId)
958 printf (" itemId: %s\n",
959 data->circulationData[j]->itemId);
960 if (data->circulationData[j]->renewable)
961 printf (" renewable: %d\n",
962 *data->circulationData[j]->renewable);
963 if (data->circulationData[j]->onHold)
964 printf (" onHold: %d\n",
965 *data->circulationData[j]->onHold);
966 if (data->circulationData[j]->enumAndChron)
967 printf (" enumAndChron: %s\n",
968 data->circulationData[j]->enumAndChron);
969 if (data->circulationData[j]->midspine)
970 printf (" midspine: %s\n",
971 data->circulationData[j]->midspine);
972 if (data->circulationData[j]->temporaryLocation)
973 printf (" temporaryLocation: %s\n",
974 data->circulationData[j]->temporaryLocation);
981 printf("Unknown record representation.\n");
982 if (!z_External(print, &r, 0, 0))
984 odr_perror(print, "Printing external");
990 static void display_diagrecs(Z_DiagRec **pp, int num)
994 Z_DefaultDiagFormat *r;
996 printf("Diagnostic message(s) from database:\n");
997 for (i = 0; i<num; i++)
999 Z_DiagRec *p = pp[i];
1000 if (p->which != Z_DiagRec_defaultFormat)
1002 printf("Diagnostic record not in default format.\n");
1006 r = p->u.defaultFormat;
1007 if (!(ent = oid_getentbyoid(r->diagnosticSetId)) ||
1008 ent->oclass != CLASS_DIAGSET || ent->value != VAL_BIB1)
1009 printf("Missing or unknown diagset\n");
1010 printf(" [%d] %s", *r->condition, diagbib1_str(*r->condition));
1013 case Z_DefaultDiagFormat_v2Addinfo:
1014 printf (" -- v2 addinfo '%s'\n", r->u.v2Addinfo);
1016 case Z_DefaultDiagFormat_v3Addinfo:
1017 printf (" -- v3 addinfo '%s'\n", r->u.v3Addinfo);
1024 static void display_nameplusrecord(Z_NamePlusRecord *p)
1026 if (p->databaseName)
1027 printf("[%s]", p->databaseName);
1028 if (p->which == Z_NamePlusRecord_surrogateDiagnostic)
1029 display_diagrecs(&p->u.surrogateDiagnostic, 1);
1030 else if (p->which == Z_NamePlusRecord_databaseRecord)
1031 display_record(p->u.databaseRecord);
1034 static void display_records(Z_Records *p)
1038 if (p->which == Z_Records_NSD)
1040 Z_DiagRec dr, *dr_p = &dr;
1041 dr.which = Z_DiagRec_defaultFormat;
1042 dr.u.defaultFormat = p->u.nonSurrogateDiagnostic;
1043 display_diagrecs (&dr_p, 1);
1045 else if (p->which == Z_Records_multipleNSD)
1046 display_diagrecs (p->u.multipleNonSurDiagnostics->diagRecs,
1047 p->u.multipleNonSurDiagnostics->num_diagRecs);
1050 printf("Records: %d\n", p->u.databaseOrSurDiagnostics->num_records);
1051 for (i = 0; i < p->u.databaseOrSurDiagnostics->num_records; i++)
1052 display_nameplusrecord(p->u.databaseOrSurDiagnostics->records[i]);
1056 static int send_deleteResultSetRequest(const char *arg)
1061 Z_APDU *apdu = zget_APDU(out, Z_APDU_deleteResultSetRequest);
1062 Z_DeleteResultSetRequest *req = apdu->u.deleteResultSetRequest;
1064 req->referenceId = set_refid (out);
1066 req->num_resultSetList =
1067 sscanf (arg, "%30s %30s %30s %30s %30s %30s %30s %30s",
1068 names[0], names[1], names[2], names[3],
1069 names[4], names[5], names[6], names[7]);
1071 req->deleteFunction = (int *)
1072 odr_malloc (out, sizeof(*req->deleteFunction));
1073 if (req->num_resultSetList > 0)
1075 *req->deleteFunction = Z_DeleteRequest_list;
1076 req->resultSetList = (char **)
1077 odr_malloc (out, sizeof(*req->resultSetList)*
1078 req->num_resultSetList);
1079 for (i = 0; i<req->num_resultSetList; i++)
1080 req->resultSetList[i] = names[i];
1084 *req->deleteFunction = Z_DeleteRequest_all;
1085 req->resultSetList = 0;
1089 printf("Sent deleteResultSetRequest.\n");
1094 static int send_srw(Z_SRW_PDU *sr)
1096 const char *charset = negotiationCharset;
1097 const char *host_port = cur_host;
1100 Z_SOAP_Handler h[2] = {
1101 {"http://www.loc.gov/zing/srw/", 0, (Z_SOAP_fun) yaz_srw_codec},
1104 ODR o = odr_createmem(ODR_ENCODE);
1106 Z_SOAP *p = odr_malloc(o, sizeof(*p));
1109 path = odr_malloc(out, strlen(databaseNames[0])+2);
1111 strcpy(path+1, databaseNames[0]);
1113 gdu = z_get_HTTP_Request(out);
1114 gdu->u.HTTP_Request->version = http_version;
1115 gdu->u.HTTP_Request->path = odr_strdup(out, path);
1119 const char *cp0 = strstr(host_port, "://");
1120 const char *cp1 = 0;
1126 cp1 = strchr(cp0, '/');
1128 cp1 = cp0+strlen(cp0);
1132 char *h = odr_malloc(out, cp1 - cp0 + 1);
1133 memcpy (h, cp0, cp1 - cp0);
1135 z_HTTP_header_add(out, &gdu->u.HTTP_Request->headers,
1140 strcpy(ctype, "text/xml");
1141 if (charset && strlen(charset) < 20)
1143 strcat(ctype, "; charset=");
1144 strcat(ctype, charset);
1146 z_HTTP_header_add(out, &gdu->u.HTTP_Request->headers,
1147 "Content-Type", ctype);
1148 z_HTTP_header_add(out, &gdu->u.HTTP_Request->headers,
1149 "SOAPAction", "\"\"");
1150 p->which = Z_SOAP_generic;
1151 p->u.generic = odr_malloc(o, sizeof(*p->u.generic));
1152 p->u.generic->no = 0;
1153 p->u.generic->ns = 0;
1154 p->u.generic->p = sr;
1155 p->ns = "http://schemas.xmlsoap.org/soap/envelope/";
1157 ret = z_soap_codec_enc(o, &p,
1158 &gdu->u.HTTP_Request->content_buf,
1159 &gdu->u.HTTP_Request->content_len, h,
1162 if (z_GDU(out, &gdu, 0, 0))
1170 if (!z_GDU(print, &gdu, 0, 0))
1171 printf ("Failed to print outgoing APDU\n");
1174 buf_out = odr_getbuf(out, &len_out, 0);
1176 /* we don't odr_reset(out), since we may need the buffer again */
1178 do_hex_dump(buf_out, len_out);
1180 r = cs_put(conn, buf_out, len_out);
1192 static int send_SRW_searchRequest(const char *arg)
1198 assert(srw_sr_odr_out == 0);
1199 srw_sr_odr_out = odr_createmem(ODR_ENCODE);
1201 odr_reset(srw_sr_odr_out);
1205 /* save this for later .. when fetching individual records */
1206 srw_sr = sr = yaz_srw_get(srw_sr_odr_out, Z_SRW_searchRetrieve_request);
1207 sr->u.request->query_type = Z_SRW_query_type_cql;
1208 sr->u.request->query.cql = odr_strdup(srw_sr_odr_out, arg);
1210 sr = yaz_srw_get(out, Z_SRW_searchRetrieve_request);
1211 sr->u.request->query_type = Z_SRW_query_type_cql;
1212 sr->u.request->query.cql = odr_strdup(out, arg);
1214 sr->u.request->maximumRecords = odr_intdup(out, 0);
1217 sr->u.request->recordSchema = record_schema;
1218 return send_srw(sr);
1222 static int send_searchRequest(const char *arg)
1224 Z_APDU *apdu = zget_APDU(out, Z_APDU_searchRequest);
1225 Z_SearchRequest *req = apdu->u.searchRequest;
1228 struct ccl_rpn_node *rpn = NULL;
1230 char setstring[100];
1231 Z_RPNQuery *RPNquery;
1233 YAZ_PQF_Parser pqf_parser;
1235 QueryType myQueryType = queryType;
1238 if (myQueryType == QueryType_CCL2RPN)
1240 rpn = ccl_find_str(bibset, arg, &error, &pos);
1243 printf("CCL ERROR: %s\n", ccl_err_msg(error));
1246 } else if (myQueryType == QueryType_CQL2RPN) {
1247 /* ### All this code should be wrapped in a utility function */
1249 struct cql_node *node;
1250 const char *addinfo;
1251 if (cqltrans == 0) {
1252 printf("Can't use CQL: no translation file. Try set_cqlfile\n");
1255 parser = cql_parser_create();
1256 if ((error = cql_parser_string(parser, arg)) != 0) {
1257 printf("Can't parse CQL: must be a syntax error\n");
1260 node = cql_parser_result(parser);
1261 if ((error = cql_transform_buf(cqltrans, node, pqfbuf,
1262 sizeof pqfbuf)) != 0) {
1263 error = cql_transform_error(cqltrans, &addinfo);
1264 printf ("Can't convert CQL to PQF: %s (addinfo=%s)\n",
1265 cql_strerror(error), addinfo);
1269 myQueryType = QueryType_Prefix;
1272 req->referenceId = set_refid (out);
1273 if (!strcmp(arg, "@big")) /* strictly for troublemaking */
1275 static unsigned char big[2100];
1276 static Odr_oct bigo;
1278 /* send a very big referenceid to test transport stack etc. */
1279 memset(big, 'A', 2100);
1280 bigo.len = bigo.size = 2100;
1282 req->referenceId = &bigo;
1287 sprintf(setstring, "%d", ++setnumber);
1288 req->resultSetName = setstring;
1290 *req->smallSetUpperBound = smallSetUpperBound;
1291 *req->largeSetLowerBound = largeSetLowerBound;
1292 *req->mediumSetPresentNumber = mediumSetPresentNumber;
1293 if (smallSetUpperBound > 0 || (largeSetLowerBound > 1 &&
1294 mediumSetPresentNumber > 0))
1298 prefsyn.proto = protocol;
1299 prefsyn.oclass = CLASS_RECSYN;
1300 prefsyn.value = recordsyntax;
1301 req->preferredRecordSyntax =
1302 odr_oiddup(out, oid_ent_to_oid(&prefsyn, oid));
1303 req->smallSetElementSetNames =
1304 req->mediumSetElementSetNames = elementSetNames;
1306 req->num_databaseNames = num_databaseNames;
1307 req->databaseNames = databaseNames;
1309 req->query = &query;
1311 switch (myQueryType)
1313 case QueryType_Prefix:
1314 query.which = Z_Query_type_1;
1315 pqf_parser = yaz_pqf_create ();
1316 RPNquery = yaz_pqf_parse (pqf_parser, out, arg);
1319 const char *pqf_msg;
1321 int code = yaz_pqf_error (pqf_parser, &pqf_msg, &off);
1322 printf("%*s^\n", off+4, "");
1323 printf("Prefix query error: %s (code %d)\n", pqf_msg, code);
1325 yaz_pqf_destroy (pqf_parser);
1328 yaz_pqf_destroy (pqf_parser);
1329 query.u.type_1 = RPNquery;
1332 query.which = Z_Query_type_2;
1333 query.u.type_2 = &ccl_query;
1334 ccl_query.buf = (unsigned char*) arg;
1335 ccl_query.len = strlen(arg);
1337 case QueryType_CCL2RPN:
1338 query.which = Z_Query_type_1;
1339 RPNquery = ccl_rpn_query(out, rpn);
1342 printf ("Couldn't convert from CCL to RPN\n");
1345 query.u.type_1 = RPNquery;
1346 ccl_rpn_delete (rpn);
1349 query.which = Z_Query_type_104;
1350 ext = (Z_External *) odr_malloc(out, sizeof(*ext));
1351 ext->direct_reference = odr_getoidbystr(out, "1.2.840.10003.16.2");
1352 ext->indirect_reference = 0;
1353 ext->descriptor = 0;
1354 ext->which = Z_External_CQL;
1355 ext->u.cql = odr_strdup(out, arg);
1356 query.u.type_104 = ext;
1359 printf ("Unsupported query type\n");
1362 if (send_apdu(apdu))
1363 printf("Sent searchRequest.\n");
1368 /* display Query Expression as part of searchResult-1 */
1369 static void display_queryExpression (Z_QueryExpression *qe)
1373 if (qe->which == Z_QueryExpression_term)
1375 if (qe->u.term->queryTerm)
1377 Z_Term *term = qe->u.term->queryTerm;
1378 switch (term->which)
1380 case Z_Term_general:
1381 printf (" %.*s", term->u.general->len, term->u.general->buf);
1383 case Z_Term_characterString:
1384 printf (" %s", term->u.characterString);
1386 case Z_Term_numeric:
1387 printf (" %d", *term->u.numeric);
1397 /* see if we can find USR:SearchResult-1 */
1398 static void display_searchResult (Z_OtherInformation *o)
1403 for (i = 0; i < o->num_elements; i++)
1405 if (o->list[i]->which == Z_OtherInfo_externallyDefinedInfo)
1407 Z_External *ext = o->list[i]->information.externallyDefinedInfo;
1409 if (ext->which == Z_External_searchResult1)
1412 Z_SearchInfoReport *sr = ext->u.searchResult1;
1413 printf ("SearchResult-1:");
1414 for (j = 0; j < sr->num; j++)
1416 if (!sr->elements[j]->subqueryExpression)
1418 display_queryExpression (
1419 sr->elements[j]->subqueryExpression);
1420 display_queryExpression (
1421 sr->elements[j]->subqueryInterpretation);
1422 display_queryExpression (
1423 sr->elements[j]->subqueryRecommendation);
1424 if (sr->elements[j]->subqueryCount)
1425 printf ("(%d)", *sr->elements[j]->subqueryCount);
1433 static int process_searchResponse(Z_SearchResponse *res)
1435 printf ("Received SearchResponse.\n");
1436 print_refid (res->referenceId);
1437 if (*res->searchStatus)
1438 printf("Search was a success.\n");
1440 printf("Search was a bloomin' failure.\n");
1441 printf("Number of hits: %d", *res->resultCount);
1443 printf (", setno %d", setnumber);
1445 display_searchResult (res->additionalSearchInfo);
1446 printf("records returned: %d\n",
1447 *res->numberOfRecordsReturned);
1448 setno += *res->numberOfRecordsReturned;
1450 display_records(res->records);
1454 static void print_level(int iLevel)
1457 for (i = 0; i < iLevel * 4; i++)
1461 static void print_int(int iLevel, const char *pTag, int *pInt)
1465 print_level(iLevel);
1466 printf("%s: %d\n", pTag, *pInt);
1470 static void print_string(int iLevel, const char *pTag, const char *pString)
1472 if (pString != NULL)
1474 print_level(iLevel);
1475 printf("%s: %s\n", pTag, pString);
1479 static void print_oid(int iLevel, const char *pTag, Odr_oid *pOid)
1485 print_level(iLevel);
1486 printf("%s:", pTag);
1487 for (; *pInt != -1; pInt++)
1488 printf(" %d", *pInt);
1493 static void print_referenceId(int iLevel, Z_ReferenceId *referenceId)
1495 if (referenceId != NULL)
1499 print_level(iLevel);
1500 printf("Ref Id (%d, %d): ", referenceId->len, referenceId->size);
1501 for (i = 0; i < referenceId->len; i++)
1502 printf("%c", referenceId->buf[i]);
1507 static void print_string_or_numeric(int iLevel, const char *pTag, Z_StringOrNumeric *pStringNumeric)
1509 if (pStringNumeric != NULL)
1511 switch (pStringNumeric->which)
1513 case Z_StringOrNumeric_string:
1514 print_string(iLevel, pTag, pStringNumeric->u.string);
1517 case Z_StringOrNumeric_numeric:
1518 print_int(iLevel, pTag, pStringNumeric->u.numeric);
1522 print_level(iLevel);
1523 printf("%s: valid type for Z_StringOrNumeric\n", pTag);
1529 static void print_universe_report_duplicate(
1531 Z_UniverseReportDuplicate *pUniverseReportDuplicate)
1533 if (pUniverseReportDuplicate != NULL)
1535 print_level(iLevel);
1536 printf("Universe Report Duplicate: \n");
1538 print_string_or_numeric(iLevel, "Hit No",
1539 pUniverseReportDuplicate->hitno);
1543 static void print_universe_report_hits(
1545 Z_UniverseReportHits *pUniverseReportHits)
1547 if (pUniverseReportHits != NULL)
1549 print_level(iLevel);
1550 printf("Universe Report Hits: \n");
1552 print_string_or_numeric(iLevel, "Database",
1553 pUniverseReportHits->database);
1554 print_string_or_numeric(iLevel, "Hits", pUniverseReportHits->hits);
1558 static void print_universe_report(int iLevel, Z_UniverseReport *pUniverseReport)
1560 if (pUniverseReport != NULL)
1562 print_level(iLevel);
1563 printf("Universe Report: \n");
1565 print_int(iLevel, "Total Hits", pUniverseReport->totalHits);
1566 switch (pUniverseReport->which)
1568 case Z_UniverseReport_databaseHits:
1569 print_universe_report_hits(iLevel,
1570 pUniverseReport->u.databaseHits);
1573 case Z_UniverseReport_duplicate:
1574 print_universe_report_duplicate(iLevel,
1575 pUniverseReport->u.duplicate);
1579 print_level(iLevel);
1580 printf("Type: %d\n", pUniverseReport->which);
1586 static void print_external(int iLevel, Z_External *pExternal)
1588 if (pExternal != NULL)
1590 print_level(iLevel);
1591 printf("External: \n");
1593 print_oid(iLevel, "Direct Reference", pExternal->direct_reference);
1594 print_int(iLevel, "InDirect Reference", pExternal->indirect_reference);
1595 print_string(iLevel, "Descriptor", pExternal->descriptor);
1596 switch (pExternal->which)
1598 case Z_External_universeReport:
1599 print_universe_report(iLevel, pExternal->u.universeReport);
1603 print_level(iLevel);
1604 printf("Type: %d\n", pExternal->which);
1610 static int process_resourceControlRequest (Z_ResourceControlRequest *req)
1612 printf ("Received ResourceControlRequest.\n");
1613 print_referenceId(1, req->referenceId);
1614 print_int(1, "Suspended Flag", req->suspendedFlag);
1615 print_int(1, "Partial Results Available", req->partialResultsAvailable);
1616 print_int(1, "Response Required", req->responseRequired);
1617 print_int(1, "Triggered Request Flag", req->triggeredRequestFlag);
1618 print_external(1, req->resourceReport);
1622 void process_ESResponse(Z_ExtendedServicesResponse *res)
1625 switch (*res->operationStatus)
1627 case Z_ExtendedServicesResponse_done:
1630 case Z_ExtendedServicesResponse_accepted:
1631 printf ("accepted\n");
1633 case Z_ExtendedServicesResponse_failure:
1634 printf ("failure\n");
1635 display_diagrecs(res->diagnostics, res->num_diagnostics);
1638 printf ("unknown\n");
1640 if ( (*res->operationStatus != Z_ExtendedServicesResponse_failure) &&
1641 (res->num_diagnostics != 0) ) {
1642 display_diagrecs(res->diagnostics, res->num_diagnostics);
1644 print_refid (res->referenceId);
1645 if (res->taskPackage &&
1646 res->taskPackage->which == Z_External_extendedService)
1648 Z_TaskPackage *taskPackage = res->taskPackage->u.extendedService;
1649 Odr_oct *id = taskPackage->targetReference;
1650 Z_External *ext = taskPackage->taskSpecificParameters;
1654 printf ("Target Reference: ");
1655 print_stringn (id->buf, id->len);
1658 if (ext->which == Z_External_update)
1660 Z_IUUpdateTaskPackage *utp = ext->u.update->u.taskPackage;
1661 if (utp && utp->targetPart)
1663 Z_IUTargetPart *targetPart = utp->targetPart;
1666 for (i = 0; i<targetPart->num_taskPackageRecords; i++)
1669 Z_IUTaskPackageRecordStructure *tpr =
1670 targetPart->taskPackageRecords[i];
1671 printf ("task package record %d\n", i+1);
1672 if (tpr->which == Z_IUTaskPackageRecordStructure_record)
1674 display_record (tpr->u.record);
1678 printf ("other type\n");
1686 const char *get_ill_element (void *clientData, const char *element)
1691 static Z_External *create_external_itemRequest()
1693 struct ill_get_ctl ctl;
1694 ILL_ItemRequest *req;
1696 int item_request_size = 0;
1697 char *item_request_buf = 0;
1701 ctl.f = get_ill_element;
1703 req = ill_get_ItemRequest(&ctl, "ill", 0);
1705 printf ("ill_get_ItemRequest failed\n");
1707 if (!ill_ItemRequest (out, &req, 0, 0))
1711 ill_ItemRequest(print, &req, 0, 0);
1714 item_request_buf = odr_getbuf (out, &item_request_size, 0);
1715 if (item_request_buf)
1716 odr_setbuf (out, item_request_buf, item_request_size, 1);
1717 printf ("Couldn't encode ItemRequest, size %d\n", item_request_size);
1724 item_request_buf = odr_getbuf (out, &item_request_size, 0);
1725 oid.proto = PROTO_GENERAL;
1726 oid.oclass = CLASS_GENERAL;
1727 oid.value = VAL_ISO_ILL_1;
1729 r = (Z_External *) odr_malloc (out, sizeof(*r));
1730 r->direct_reference = odr_oiddup(out,oid_getoidbyent(&oid));
1731 r->indirect_reference = 0;
1733 r->which = Z_External_single;
1735 r->u.single_ASN1_type = (Odr_oct *)
1736 odr_malloc (out, sizeof(*r->u.single_ASN1_type));
1737 r->u.single_ASN1_type->buf = (unsigned char *)
1738 odr_malloc (out, item_request_size);
1739 r->u.single_ASN1_type->len = item_request_size;
1740 r->u.single_ASN1_type->size = item_request_size;
1741 memcpy (r->u.single_ASN1_type->buf, item_request_buf,
1744 do_hex_dump(item_request_buf,item_request_size);
1749 static Z_External *create_external_ILL_APDU(int which)
1751 struct ill_get_ctl ctl;
1754 int ill_request_size = 0;
1755 char *ill_request_buf = 0;
1759 ctl.f = get_ill_element;
1761 ill_apdu = ill_get_APDU(&ctl, "ill", 0);
1763 if (!ill_APDU (out, &ill_apdu, 0, 0))
1767 printf ("-------------------\n");
1768 ill_APDU(print, &ill_apdu, 0, 0);
1770 printf ("-------------------\n");
1772 ill_request_buf = odr_getbuf (out, &ill_request_size, 0);
1773 if (ill_request_buf)
1774 odr_setbuf (out, ill_request_buf, ill_request_size, 1);
1775 printf ("Couldn't encode ILL-Request, size %d\n", ill_request_size);
1781 ill_request_buf = odr_getbuf (out, &ill_request_size, 0);
1783 oid.proto = PROTO_GENERAL;
1784 oid.oclass = CLASS_GENERAL;
1785 oid.value = VAL_ISO_ILL_1;
1787 r = (Z_External *) odr_malloc (out, sizeof(*r));
1788 r->direct_reference = odr_oiddup(out,oid_getoidbyent(&oid));
1789 r->indirect_reference = 0;
1791 r->which = Z_External_single;
1793 r->u.single_ASN1_type = (Odr_oct *)
1794 odr_malloc (out, sizeof(*r->u.single_ASN1_type));
1795 r->u.single_ASN1_type->buf = (unsigned char *)
1796 odr_malloc (out, ill_request_size);
1797 r->u.single_ASN1_type->len = ill_request_size;
1798 r->u.single_ASN1_type->size = ill_request_size;
1799 memcpy (r->u.single_ASN1_type->buf, ill_request_buf, ill_request_size);
1800 /* printf ("len = %d\n", ill_request_size); */
1801 /* do_hex_dump(ill_request_buf,ill_request_size); */
1802 /* printf("--- end of extenal\n"); */
1809 static Z_External *create_ItemOrderExternal(const char *type, int itemno)
1811 Z_External *r = (Z_External *) odr_malloc(out, sizeof(Z_External));
1812 oident ItemOrderRequest;
1814 ItemOrderRequest.proto = PROTO_Z3950;
1815 ItemOrderRequest.oclass = CLASS_EXTSERV;
1816 ItemOrderRequest.value = VAL_ITEMORDER;
1818 r->direct_reference = odr_oiddup(out,oid_getoidbyent(&ItemOrderRequest));
1819 r->indirect_reference = 0;
1822 r->which = Z_External_itemOrder;
1824 r->u.itemOrder = (Z_ItemOrder *) odr_malloc(out,sizeof(Z_ItemOrder));
1825 memset(r->u.itemOrder, 0, sizeof(Z_ItemOrder));
1826 r->u.itemOrder->which=Z_IOItemOrder_esRequest;
1828 r->u.itemOrder->u.esRequest = (Z_IORequest *)
1829 odr_malloc(out,sizeof(Z_IORequest));
1830 memset(r->u.itemOrder->u.esRequest, 0, sizeof(Z_IORequest));
1832 r->u.itemOrder->u.esRequest->toKeep = (Z_IOOriginPartToKeep *)
1833 odr_malloc(out,sizeof(Z_IOOriginPartToKeep));
1834 memset(r->u.itemOrder->u.esRequest->toKeep, 0, sizeof(Z_IOOriginPartToKeep));
1835 r->u.itemOrder->u.esRequest->notToKeep = (Z_IOOriginPartNotToKeep *)
1836 odr_malloc(out,sizeof(Z_IOOriginPartNotToKeep));
1837 memset(r->u.itemOrder->u.esRequest->notToKeep, 0, sizeof(Z_IOOriginPartNotToKeep));
1839 r->u.itemOrder->u.esRequest->toKeep->supplDescription = NULL;
1840 r->u.itemOrder->u.esRequest->toKeep->contact = NULL;
1841 r->u.itemOrder->u.esRequest->toKeep->addlBilling = NULL;
1843 r->u.itemOrder->u.esRequest->notToKeep->resultSetItem =
1844 (Z_IOResultSetItem *) odr_malloc(out, sizeof(Z_IOResultSetItem));
1845 memset(r->u.itemOrder->u.esRequest->notToKeep->resultSetItem, 0, sizeof(Z_IOResultSetItem));
1846 r->u.itemOrder->u.esRequest->notToKeep->resultSetItem->resultSetId = "1";
1848 r->u.itemOrder->u.esRequest->notToKeep->resultSetItem->item =
1849 (int *) odr_malloc(out, sizeof(int));
1850 *r->u.itemOrder->u.esRequest->notToKeep->resultSetItem->item = itemno;
1852 if (!strcmp (type, "item") || !strcmp(type, "2"))
1854 printf ("using item-request\n");
1855 r->u.itemOrder->u.esRequest->notToKeep->itemRequest =
1856 create_external_itemRequest();
1858 else if (!strcmp(type, "ill") || !strcmp(type, "1"))
1860 printf ("using ILL-request\n");
1861 r->u.itemOrder->u.esRequest->notToKeep->itemRequest =
1862 create_external_ILL_APDU(ILL_APDU_ILL_Request);
1864 else if (!strcmp(type, "xml") || !strcmp(type, "3"))
1866 const char *xml_buf =
1868 " <type>request</type>\n"
1869 " <libraryNo>000200</libraryNo>\n"
1870 " <borrowerTicketNo> 1212 </borrowerTicketNo>\n"
1872 r->u.itemOrder->u.esRequest->notToKeep->itemRequest =
1873 z_ext_record (out, VAL_TEXT_XML, xml_buf, strlen(xml_buf));
1876 r->u.itemOrder->u.esRequest->notToKeep->itemRequest = 0;
1881 static int send_itemorder(const char *type, int itemno)
1883 Z_APDU *apdu = zget_APDU(out, Z_APDU_extendedServicesRequest);
1884 Z_ExtendedServicesRequest *req = apdu->u.extendedServicesRequest;
1885 oident ItemOrderRequest;
1887 ItemOrderRequest.proto = PROTO_Z3950;
1888 ItemOrderRequest.oclass = CLASS_EXTSERV;
1889 ItemOrderRequest.value = VAL_ITEMORDER;
1890 req->packageType = odr_oiddup(out,oid_getoidbyent(&ItemOrderRequest));
1891 req->packageName = esPackageName;
1893 req->taskSpecificParameters = create_ItemOrderExternal(type, itemno);
1899 static int only_z3950()
1901 if (protocol == PROTO_HTTP)
1903 printf ("Not supported by SRW\n");
1909 static int cmd_update_common(const char *arg, int version);
1911 static int cmd_update(const char *arg)
1913 return cmd_update_common(arg, 1);
1916 static int cmd_update0(const char *arg)
1918 return cmd_update_common(arg, 0);
1921 static int cmd_update_common(const char *arg, int version)
1923 Z_APDU *apdu = zget_APDU(out, Z_APDU_extendedServicesRequest );
1924 Z_ExtendedServicesRequest *req = apdu->u.extendedServicesRequest;
1928 char action[20], recid[20], fname[80];
1930 Z_External *record_this = 0;
1937 sscanf (arg, "%19s %19s %79s", action, recid, fname);
1939 if (!strcmp (action, "insert"))
1940 action_no = Z_IUOriginPartToKeep_recordInsert;
1941 else if (!strcmp (action, "replace"))
1942 action_no = Z_IUOriginPartToKeep_recordReplace;
1943 else if (!strcmp (action, "delete"))
1944 action_no = Z_IUOriginPartToKeep_recordDelete;
1945 else if (!strcmp (action, "update"))
1946 action_no = Z_IUOriginPartToKeep_specialUpdate;
1949 printf ("Bad action: %s\n", action);
1950 printf ("Possible values: insert, replace, delete, update\n");
1958 stat (fname, &status);
1959 if (S_ISREG(status.st_mode) && (inf = fopen(fname, "r")))
1961 size_t len = status.st_size;
1962 char *buf = (char *) xmalloc (len);
1964 fread (buf, 1, len, inf);
1968 record_this = z_ext_record (out, VAL_TEXT_XML, buf, len);
1974 printf ("File %s doesn't exist\n", fname);
1982 printf ("No last record (update ignored)\n");
1985 record_this = record_last;
1988 update_oid.proto = PROTO_Z3950;
1989 update_oid.oclass = CLASS_EXTSERV;
1991 update_oid.value = VAL_DBUPDATE0;
1993 update_oid.value = VAL_DBUPDATE;
1994 oid_ent_to_oid (&update_oid, oid);
1995 req->packageType = odr_oiddup(out,oid);
1996 req->packageName = esPackageName;
1998 req->referenceId = set_refid (out);
2000 r = req->taskSpecificParameters = (Z_External *)
2001 odr_malloc (out, sizeof(*r));
2002 r->direct_reference = odr_oiddup(out,oid);
2003 r->indirect_reference = 0;
2007 Z_IU0OriginPartToKeep *toKeep;
2008 Z_IU0SuppliedRecords *notToKeep;
2010 r->which = Z_External_update0;
2011 r->u.update0 = (Z_IU0Update *) odr_malloc(out, sizeof(*r->u.update0));
2012 r->u.update0->which = Z_IUUpdate_esRequest;
2013 r->u.update0->u.esRequest = (Z_IU0UpdateEsRequest *)
2014 odr_malloc(out, sizeof(*r->u.update0->u.esRequest));
2015 toKeep = r->u.update0->u.esRequest->toKeep = (Z_IU0OriginPartToKeep *)
2016 odr_malloc(out, sizeof(*r->u.update0->u.esRequest->toKeep));
2018 toKeep->databaseName = databaseNames[0];
2020 toKeep->elementSetName = 0;
2022 toKeep->action = (int *) odr_malloc(out, sizeof(*toKeep->action));
2023 *toKeep->action = action_no;
2025 notToKeep = r->u.update0->u.esRequest->notToKeep = (Z_IU0SuppliedRecords *)
2026 odr_malloc(out, sizeof(*r->u.update0->u.esRequest->notToKeep));
2028 notToKeep->elements = (Z_IU0SuppliedRecords_elem **)
2029 odr_malloc(out, sizeof(*notToKeep->elements));
2030 notToKeep->elements[0] = (Z_IU0SuppliedRecords_elem *)
2031 odr_malloc(out, sizeof(**notToKeep->elements));
2032 notToKeep->elements[0]->which = Z_IUSuppliedRecords_elem_opaque;
2035 notToKeep->elements[0]->u.opaque = (Odr_oct *)
2036 odr_malloc (out, sizeof(Odr_oct));
2037 notToKeep->elements[0]->u.opaque->buf = (unsigned char *) recid;
2038 notToKeep->elements[0]->u.opaque->size = strlen(recid);
2039 notToKeep->elements[0]->u.opaque->len = strlen(recid);
2042 notToKeep->elements[0]->u.opaque = 0;
2043 notToKeep->elements[0]->supplementalId = 0;
2044 notToKeep->elements[0]->correlationInfo = 0;
2045 notToKeep->elements[0]->record = record_this;
2049 Z_IUOriginPartToKeep *toKeep;
2050 Z_IUSuppliedRecords *notToKeep;
2052 r->which = Z_External_update;
2053 r->u.update = (Z_IUUpdate *) odr_malloc(out, sizeof(*r->u.update));
2054 r->u.update->which = Z_IUUpdate_esRequest;
2055 r->u.update->u.esRequest = (Z_IUUpdateEsRequest *)
2056 odr_malloc(out, sizeof(*r->u.update->u.esRequest));
2057 toKeep = r->u.update->u.esRequest->toKeep = (Z_IUOriginPartToKeep *)
2058 odr_malloc(out, sizeof(*r->u.update->u.esRequest->toKeep));
2060 toKeep->databaseName = databaseNames[0];
2062 toKeep->elementSetName = 0;
2063 toKeep->actionQualifier = 0;
2064 toKeep->action = (int *) odr_malloc(out, sizeof(*toKeep->action));
2065 *toKeep->action = action_no;
2067 notToKeep = r->u.update->u.esRequest->notToKeep = (Z_IUSuppliedRecords *)
2068 odr_malloc(out, sizeof(*r->u.update->u.esRequest->notToKeep));
2070 notToKeep->elements = (Z_IUSuppliedRecords_elem **)
2071 odr_malloc(out, sizeof(*notToKeep->elements));
2072 notToKeep->elements[0] = (Z_IUSuppliedRecords_elem *)
2073 odr_malloc(out, sizeof(**notToKeep->elements));
2074 notToKeep->elements[0]->which = Z_IUSuppliedRecords_elem_opaque;
2077 notToKeep->elements[0]->u.opaque = (Odr_oct *)
2078 odr_malloc (out, sizeof(Odr_oct));
2079 notToKeep->elements[0]->u.opaque->buf = (unsigned char *) recid;
2080 notToKeep->elements[0]->u.opaque->size = strlen(recid);
2081 notToKeep->elements[0]->u.opaque->len = strlen(recid);
2084 notToKeep->elements[0]->u.opaque = 0;
2085 notToKeep->elements[0]->supplementalId = 0;
2086 notToKeep->elements[0]->correlationInfo = 0;
2087 notToKeep->elements[0]->record = record_this;
2095 static int cmd_itemorder(const char *arg)
2102 if (sscanf (arg, "%10s %d", type, &itemno) != 2)
2105 printf("Item order request\n");
2107 send_itemorder(type, itemno);
2111 static void show_opt(const char *arg, void *clientData)
2113 printf ("%s ", arg);
2116 static int cmd_zversion(const char *arg)
2119 z3950_version = atoi(arg);
2121 printf ("version is %d\n", z3950_version);
2125 static int cmd_options(const char *arg)
2131 r = yaz_init_opt_encode(&z3950_options, arg, &pos);
2135 yaz_init_opt_decode(&z3950_options, show_opt, 0);
2141 static int cmd_explain(const char *arg)
2143 if (protocol != PROTO_HTTP)
2154 /* save this for later .. when fetching individual records */
2155 sr = yaz_srw_get(out, Z_SRW_explain_request);
2163 static int cmd_init(const char *arg)
2165 if (!conn || protocol != PROTO_Z3950)
2167 send_initRequest(0);
2171 static int cmd_find(const char *arg)
2175 printf("Find what?\n");
2178 if (protocol == PROTO_HTTP)
2185 if (!send_SRW_searchRequest(arg))
2198 printf("Not connected yet\n");
2202 if (!send_searchRequest(arg))
2208 static int cmd_delete(const char *arg)
2212 printf("Not connected yet\n");
2217 if (!send_deleteResultSetRequest(arg))
2222 static int cmd_ssub(const char *arg)
2224 if (!(smallSetUpperBound = atoi(arg)))
2229 static int cmd_lslb(const char *arg)
2233 if (!(largeSetLowerBound = atoi(arg)))
2238 static int cmd_mspn(const char *arg)
2242 if (!(mediumSetPresentNumber = atoi(arg)))
2247 static int cmd_status(const char *arg)
2249 printf("smallSetUpperBound: %d\n", smallSetUpperBound);
2250 printf("largeSetLowerBound: %d\n", largeSetLowerBound);
2251 printf("mediumSetPresentNumber: %d\n", mediumSetPresentNumber);
2255 static int cmd_setnames(const char *arg)
2257 if (*arg == '1') /* enable ? */
2259 else if (*arg == '0') /* disable ? */
2261 else if (setnumber < 0) /* no args, toggle .. */
2267 printf("Set numbering enabled.\n");
2269 printf("Set numbering disabled.\n");
2273 /* PRESENT SERVICE ----------------------------- */
2275 static void parse_show_args(const char *arg_c, char *setstring,
2276 int *start, int *number)
2281 strncpy(arg, arg_c, sizeof(arg)-1);
2282 arg[sizeof(arg)-1] = '\0';
2284 if ((p = strchr(arg, '+')))
2286 *number = atoi(p + 1);
2291 if (p && (p=strchr(p+1, '+')))
2292 strcpy (setstring, p+1);
2293 else if (setnumber >= 0)
2294 sprintf(setstring, "%d", setnumber);
2299 static int send_presentRequest(const char *arg)
2301 Z_APDU *apdu = zget_APDU(out, Z_APDU_presentRequest);
2302 Z_PresentRequest *req = apdu->u.presentRequest;
2303 Z_RecordComposition compo;
2307 char setstring[100];
2309 req->referenceId = set_refid (out);
2311 parse_show_args(arg, setstring, &setno, &nos);
2313 req->resultSetId = setstring;
2315 req->resultSetStartPoint = &setno;
2316 req->numberOfRecordsRequested = &nos;
2317 prefsyn.proto = protocol;
2318 prefsyn.oclass = CLASS_RECSYN;
2319 prefsyn.value = recordsyntax;
2320 req->preferredRecordSyntax =
2321 odr_oiddup (out, oid_ent_to_oid(&prefsyn, oid));
2327 prefschema.proto = protocol;
2328 prefschema.oclass = CLASS_SCHEMA;
2329 prefschema.value = oid_getvalbyname(record_schema);
2331 req->recordComposition = &compo;
2332 compo.which = Z_RecordComp_complex;
2333 compo.u.complex = (Z_CompSpec *)
2334 odr_malloc(out, sizeof(*compo.u.complex));
2335 compo.u.complex->selectAlternativeSyntax = (bool_t *)
2336 odr_malloc(out, sizeof(bool_t));
2337 *compo.u.complex->selectAlternativeSyntax = 0;
2339 compo.u.complex->generic = (Z_Specification *)
2340 odr_malloc(out, sizeof(*compo.u.complex->generic));
2341 compo.u.complex->generic->which = Z_Schema_oid;
2342 compo.u.complex->generic->schema.oid = (Odr_oid *)
2343 odr_oiddup(out, oid_ent_to_oid(&prefschema, oid));
2344 if (!compo.u.complex->generic->schema.oid)
2346 /* OID wasn't a schema! Try record syntax instead. */
2347 prefschema.oclass = CLASS_RECSYN;
2348 compo.u.complex->generic->schema.oid = (Odr_oid *)
2349 odr_oiddup(out, oid_ent_to_oid(&prefschema, oid));
2351 if (!elementSetNames)
2352 compo.u.complex->generic->elementSpec = 0;
2355 compo.u.complex->generic->elementSpec = (Z_ElementSpec *)
2356 odr_malloc(out, sizeof(Z_ElementSpec));
2357 compo.u.complex->generic->elementSpec->which =
2358 Z_ElementSpec_elementSetName;
2359 compo.u.complex->generic->elementSpec->u.elementSetName =
2360 elementSetNames->u.generic;
2362 compo.u.complex->num_dbSpecific = 0;
2363 compo.u.complex->dbSpecific = 0;
2364 compo.u.complex->num_recordSyntax = 0;
2365 compo.u.complex->recordSyntax = 0;
2367 else if (elementSetNames)
2369 req->recordComposition = &compo;
2370 compo.which = Z_RecordComp_simple;
2371 compo.u.simple = elementSetNames;
2374 printf("Sent presentRequest (%d+%d).\n", setno, nos);
2379 static int send_SRW_presentRequest(const char *arg)
2381 char setstring[100];
2383 Z_SRW_PDU *sr = srw_sr;
2387 parse_show_args(arg, setstring, &setno, &nos);
2388 sr->u.request->startRecord = odr_intdup(out, setno);
2389 sr->u.request->maximumRecords = odr_intdup(out, nos);
2391 sr->u.request->recordSchema = record_schema;
2392 return send_srw(sr);
2396 static void close_session (void)
2403 nmem_destroy (session_mem);
2412 void process_close(Z_Close *req)
2414 Z_APDU *apdu = zget_APDU(out, Z_APDU_close);
2415 Z_Close *res = apdu->u.close;
2417 static char *reasons[] =
2422 "cost limit reached",
2424 "security violation",
2431 printf("Reason: %s, message: %s\n", reasons[*req->closeReason],
2432 req->diagnosticInformation ? req->diagnosticInformation : "NULL");
2437 *res->closeReason = Z_Close_finished;
2439 printf("Sent response.\n");
2444 static int cmd_show(const char *arg)
2446 if (protocol == PROTO_HTTP)
2453 if (!send_SRW_presentRequest(arg))
2463 printf("Not connected yet\n");
2466 if (!send_presentRequest(arg))
2472 int cmd_quit(const char *arg)
2474 printf("See you later, alligator.\n");
2480 int cmd_cancel(const char *arg)
2482 Z_APDU *apdu = zget_APDU(out, Z_APDU_triggerResourceControlRequest);
2483 Z_TriggerResourceControlRequest *req =
2484 apdu->u.triggerResourceControlRequest;
2489 printf("Session not initialized yet\n");
2494 if (!ODR_MASK_GET(session->options, Z_Options_triggerResourceCtrl))
2496 printf("Target doesn't support cancel (trigger resource ctrl)\n");
2499 *req->requestedAction = Z_TriggerResourceCtrl_cancel;
2500 req->resultSetWanted = &rfalse;
2503 printf("Sent cancel request\n");
2507 int send_scanrequest(const char *query, int pp, int num, const char *term)
2509 Z_APDU *apdu = zget_APDU(out, Z_APDU_scanRequest);
2510 Z_ScanRequest *req = apdu->u.scanRequest;
2515 if (queryType == QueryType_CCL2RPN)
2519 struct ccl_rpn_node *rpn;
2521 rpn = ccl_find_str (bibset, query, &error, &pos);
2524 printf("CCL ERROR: %s\n", ccl_err_msg(error));
2527 bib1.proto = PROTO_Z3950;
2528 bib1.oclass = CLASS_ATTSET;
2529 bib1.value = VAL_BIB1;
2530 req->attributeSet = oid_ent_to_oid (&bib1, oid);
2531 if (!(req->termListAndStartPoint = ccl_scan_query (out, rpn)))
2533 printf("Couldn't convert CCL to Scan term\n");
2536 ccl_rpn_delete (rpn);
2540 YAZ_PQF_Parser pqf_parser = yaz_pqf_create ();
2542 if (!(req->termListAndStartPoint =
2543 yaz_pqf_scan(pqf_parser, out, &req->attributeSet, query)))
2545 const char *pqf_msg;
2547 int code = yaz_pqf_error (pqf_parser, &pqf_msg, &off);
2548 printf("%*s^\n", off+7, "");
2549 printf("Prefix query error: %s (code %d)\n", pqf_msg, code);
2550 yaz_pqf_destroy (pqf_parser);
2553 yaz_pqf_destroy (pqf_parser);
2557 if (req->termListAndStartPoint->term &&
2558 req->termListAndStartPoint->term->which == Z_Term_general &&
2559 req->termListAndStartPoint->term->u.general)
2561 req->termListAndStartPoint->term->u.general->buf =
2562 (unsigned char *) odr_strdup(out, term);
2563 req->termListAndStartPoint->term->u.general->len =
2564 req->termListAndStartPoint->term->u.general->size =
2568 req->referenceId = set_refid (out);
2569 req->num_databaseNames = num_databaseNames;
2570 req->databaseNames = databaseNames;
2571 req->numberOfTermsRequested = #
2572 req->preferredPositionInResponse = &pp;
2577 int send_sortrequest(const char *arg, int newset)
2579 Z_APDU *apdu = zget_APDU(out, Z_APDU_sortRequest);
2580 Z_SortRequest *req = apdu->u.sortRequest;
2581 Z_SortKeySpecList *sksl = (Z_SortKeySpecList *)
2582 odr_malloc (out, sizeof(*sksl));
2588 sprintf (setstring, "%d", setnumber);
2590 sprintf (setstring, "default");
2592 req->referenceId = set_refid (out);
2594 req->num_inputResultSetNames = 1;
2595 req->inputResultSetNames = (Z_InternationalString **)
2596 odr_malloc (out, sizeof(*req->inputResultSetNames));
2597 req->inputResultSetNames[0] = odr_strdup (out, setstring);
2599 if (newset && setnumber >= 0)
2600 sprintf (setstring, "%d", ++setnumber);
2602 req->sortedResultSetName = odr_strdup (out, setstring);
2604 req->sortSequence = yaz_sort_spec (out, arg);
2605 if (!req->sortSequence)
2607 printf ("Missing sort specifications\n");
2614 void display_term(Z_TermInfo *t)
2617 printf("%s", t->displayTerm);
2618 else if (t->term->which == Z_Term_general)
2620 printf("%.*s", t->term->u.general->len, t->term->u.general->buf);
2621 sprintf(last_scan_line, "%.*s", t->term->u.general->len,
2622 t->term->u.general->buf);
2625 printf("Term (not general)");
2626 if (t->globalOccurrences)
2627 printf (" (%d)\n", *t->globalOccurrences);
2632 void process_scanResponse(Z_ScanResponse *res)
2635 Z_Entry **entries = NULL;
2636 int num_entries = 0;
2638 printf("Received ScanResponse\n");
2639 print_refid (res->referenceId);
2640 printf("%d entries", *res->numberOfEntriesReturned);
2641 if (res->positionOfTerm)
2642 printf (", position=%d", *res->positionOfTerm);
2644 if (*res->scanStatus != Z_Scan_success)
2645 printf("Scan returned code %d\n", *res->scanStatus);
2648 if ((entries = res->entries->entries))
2649 num_entries = res->entries->num_entries;
2650 for (i = 0; i < num_entries; i++)
2652 int pos_term = res->positionOfTerm ? *res->positionOfTerm : -1;
2653 if (entries[i]->which == Z_Entry_termInfo)
2655 printf("%c ", i + 1 == pos_term ? '*' : ' ');
2656 display_term(entries[i]->u.termInfo);
2659 display_diagrecs(&entries[i]->u.surrogateDiagnostic, 1);
2661 if (res->entries->nonsurrogateDiagnostics)
2662 display_diagrecs (res->entries->nonsurrogateDiagnostics,
2663 res->entries->num_nonsurrogateDiagnostics);
2666 void process_sortResponse(Z_SortResponse *res)
2668 printf("Received SortResponse: status=");
2669 switch (*res->sortStatus)
2671 case Z_SortStatus_success:
2672 printf ("success"); break;
2673 case Z_SortStatus_partial_1:
2674 printf ("partial"); break;
2675 case Z_SortStatus_failure:
2676 printf ("failure"); break;
2678 printf ("unknown (%d)", *res->sortStatus);
2681 print_refid (res->referenceId);
2682 if (res->diagnostics)
2683 display_diagrecs(res->diagnostics,
2684 res->num_diagnostics);
2687 void process_deleteResultSetResponse (Z_DeleteResultSetResponse *res)
2689 printf("Got deleteResultSetResponse status=%d\n",
2690 *res->deleteOperationStatus);
2691 if (res->deleteListStatuses)
2694 for (i = 0; i < res->deleteListStatuses->num; i++)
2696 printf ("%s status=%d\n", res->deleteListStatuses->elements[i]->id,
2697 *res->deleteListStatuses->elements[i]->status);
2702 int cmd_sort_generic(const char *arg, int newset)
2706 printf("Session not initialized yet\n");
2711 if (!ODR_MASK_GET(session->options, Z_Options_sort))
2713 printf("Target doesn't support sort\n");
2718 if (send_sortrequest(arg, newset) < 0)
2725 int cmd_sort(const char *arg)
2727 return cmd_sort_generic (arg, 0);
2730 int cmd_sort_newset (const char *arg)
2732 return cmd_sort_generic (arg, 1);
2735 int cmd_scan(const char *arg)
2744 printf("Session not initialized yet\n");
2748 if (!ODR_MASK_GET(session->options, Z_Options_scan))
2750 printf("Target doesn't support scan\n");
2755 strcpy (last_scan_query, arg);
2756 if (send_scanrequest(arg, 1, 20, 0) < 0)
2761 if (send_scanrequest(last_scan_query, 1, 20, last_scan_line) < 0)
2767 int cmd_schema(const char *arg)
2769 xfree(record_schema);
2772 record_schema = xstrdup(arg);
2776 int cmd_format(const char *arg)
2781 printf("Usage: format <recordsyntax>\n");
2784 nsyntax = oid_getvalbyname (arg);
2785 if (strcmp(arg, "none") && nsyntax == VAL_NONE)
2787 printf ("unknown record syntax\n");
2790 recordsyntax = nsyntax;
2794 int cmd_elements(const char *arg)
2796 static Z_ElementSetNames esn;
2797 static char what[100];
2801 elementSetNames = 0;
2805 esn.which = Z_ElementSetNames_generic;
2806 esn.u.generic = what;
2807 elementSetNames = &esn;
2811 int cmd_attributeset(const char *arg)
2817 printf("Usage: attributeset <setname>\n");
2820 sscanf(arg, "%s", what);
2821 if (p_query_attset (what))
2823 printf("Unknown attribute set name\n");
2829 int cmd_querytype (const char *arg)
2831 if (!strcmp (arg, "ccl"))
2832 queryType = QueryType_CCL;
2833 else if (!strcmp (arg, "prefix") || !strcmp(arg, "rpn"))
2834 queryType = QueryType_Prefix;
2835 else if (!strcmp (arg, "ccl2rpn") || !strcmp (arg, "cclrpn"))
2836 queryType = QueryType_CCL2RPN;
2837 else if (!strcmp(arg, "cql"))
2838 queryType = QueryType_CQL;
2839 else if (!strcmp (arg, "cql2rpn") || !strcmp (arg, "cqlrpn"))
2840 queryType = QueryType_CQL2RPN;
2843 printf ("Querytype must be one of:\n");
2844 printf (" prefix - Prefix query\n");
2845 printf (" ccl - CCL query\n");
2846 printf (" ccl2rpn - CCL query converted to RPN\n");
2847 printf (" cql - CQL\n");
2848 printf (" cql2rpn - CQL query converted to RPN\n");
2854 int cmd_refid (const char *arg)
2860 refid = (char *) xmalloc (strlen(arg)+1);
2861 strcpy (refid, arg);
2866 int cmd_close(const char *arg)
2875 apdu = zget_APDU(out, Z_APDU_close);
2876 req = apdu->u.close;
2877 *req->closeReason = Z_Close_finished;
2879 printf("Sent close request.\n");
2884 int cmd_packagename(const char* arg)
2886 xfree (esPackageName);
2887 esPackageName = NULL;
2889 esPackageName = xstrdup(arg);
2893 int cmd_proxy(const char* arg)
2898 yazProxy = xstrdup (arg);
2902 int cmd_marccharset(const char *arg)
2907 if (sscanf(arg, "%29s", l1) < 1)
2909 xfree (marcCharset);
2911 if (strcmp(l1, "-"))
2912 marcCharset = xstrdup(l1);
2916 int cmd_charset(const char* arg)
2918 char l1[30], l2[30];
2921 if (sscanf(arg, "%29s %29s", l1, l2) < 1)
2923 printf("Current negotiation character set is `%s'\n",
2924 negotiationCharset ? negotiationCharset: "none");
2925 printf("Current output character set is `%s'\n",
2926 outputCharset ? outputCharset: "none");
2929 xfree (negotiationCharset);
2930 negotiationCharset = NULL;
2931 if (*l1 && strcmp(l1, "-"))
2933 negotiationCharset = xstrdup(l1);
2934 printf ("Character set negotiation : %s\n", negotiationCharset);
2937 printf ("Character set negotiation disabled\n");
2940 xfree (outputCharset);
2942 if (!strcmp(l2, "auto") && codeset)
2946 printf ("output charset: %s\n", codeset);
2947 outputCharset = xstrdup(codeset);
2952 printf ("No codeset found on this system\n");
2954 else if (strcmp(l2, "-"))
2955 outputCharset = xstrdup(l2);
2957 printf ("Output charset conversion disabled\n");
2963 int cmd_lang(const char* arg)
2966 printf("Current language is `%s'\n", (yazLang)?yazLang:NULL);
2973 yazLang = (char *) xmalloc (strlen(arg)+1);
2974 strcpy (yazLang, arg);
2979 int cmd_source(const char* arg)
2981 /* first should open the file and read one line at a time.. */
2983 char line[1024], *cp;
2986 fprintf(stderr,"Error in source command use a filename\n");
2990 includeFile = fopen (arg, "r");
2993 fprintf(stderr,"Unable to open file %s for reading\n",arg);
2997 while(!feof(includeFile)) {
2998 memset(line,0,sizeof(line));
2999 fgets(line,sizeof(line),includeFile);
3001 if(strlen(line) < 2) continue;
3002 if(line[0] == '#') continue;
3004 if ((cp = strrchr (line, '\n')))
3007 process_cmd_line(line);
3010 if(fclose(includeFile)<0) {
3011 perror("unable to close include file");
3017 int cmd_subshell(const char* args)
3022 system(getenv("SHELL"));
3028 int cmd_set_berfile(const char *arg)
3030 if (ber_file && ber_file != stdout && ber_file != stderr)
3032 if (!strcmp(arg, ""))
3034 else if (!strcmp(arg, "-"))
3037 ber_file = fopen(arg, "a");
3041 int cmd_set_apdufile(const char *arg)
3043 if(apdu_file && apdu_file != stderr && apdu_file != stderr)
3045 if (!strcmp(arg, ""))
3047 else if (!strcmp(arg, "-"))
3051 apdu_file = fopen(arg, "a");
3053 perror("unable to open apdu log file");
3056 odr_setprint(print, apdu_file);
3060 int cmd_set_cclfile(const char* arg)
3064 bibset = ccl_qual_mk ();
3065 inf = fopen (arg, "r");
3067 perror("unable to open CCL file");
3070 ccl_qual_file (bibset, inf);
3073 strcpy(ccl_fields,arg);
3077 int cmd_set_cqlfile(const char* arg)
3079 cql_transform_t newcqltrans;
3081 if ((newcqltrans = cql_transform_open_fname(arg)) == 0) {
3082 perror("unable to open CQL file");
3086 cql_transform_close(cqltrans);
3088 cqltrans = newcqltrans;
3089 strcpy(cql_fields, arg);
3093 int cmd_set_auto_reconnect(const char* arg)
3095 if(strlen(arg)==0) {
3096 auto_reconnect = ! auto_reconnect;
3097 } else if(strcmp(arg,"on")==0) {
3099 } else if(strcmp(arg,"off")==0) {
3102 printf("Error use on or off\n");
3107 printf("Set auto reconnect enabled.\n");
3109 printf("Set auto reconnect disabled.\n");
3114 int cmd_set_marcdump(const char* arg)
3116 if(marc_file && marc_file != stderr) { /* don't close stdout*/
3120 if (!strcmp(arg, ""))
3122 else if (!strcmp(arg, "-"))
3126 marc_file = fopen(arg, "a");
3128 perror("unable to open marc log file");
3134 this command takes 3 arge {name class oid}
3136 int cmd_register_oid(const char* args) {
3141 {"appctx",CLASS_APPCTX},
3142 {"absyn",CLASS_ABSYN},
3143 {"attset",CLASS_ATTSET},
3144 {"transyn",CLASS_TRANSYN},
3145 {"diagset",CLASS_DIAGSET},
3146 {"recsyn",CLASS_RECSYN},
3147 {"resform",CLASS_RESFORM},
3148 {"accform",CLASS_ACCFORM},
3149 {"extserv",CLASS_EXTSERV},
3150 {"userinfo",CLASS_USERINFO},
3151 {"elemspec",CLASS_ELEMSPEC},
3152 {"varset",CLASS_VARSET},
3153 {"schema",CLASS_SCHEMA},
3154 {"tagset",CLASS_TAGSET},
3155 {"general",CLASS_GENERAL},
3156 {0,(enum oid_class) 0}
3158 char oname_str[101], oclass_str[101], oid_str[101];
3161 oid_class oidclass = CLASS_GENERAL;
3162 int val = 0, oid[OID_SIZE];
3163 struct oident * new_oident=NULL;
3165 if (sscanf (args, "%100[^ ] %100[^ ] %100s",
3166 oname_str,oclass_str, oid_str) < 1) {
3167 printf("Error in regristrate command \n");
3171 for (i = 0; oid_classes[i].className; i++) {
3172 if (!strcmp(oid_classes[i].className, oclass_str))
3174 oidclass=oid_classes[i].oclass;
3179 if(!(oid_classes[i].className)) {
3180 printf("Unknonwn oid class %s\n",oclass_str);
3188 while (isdigit (*name))
3190 val = val*10 + (*name - '0');
3203 new_oident=oid_addent (oid,PROTO_GENERAL,oidclass,oname_str,VAL_DYNAMIC);
3204 if(strcmp(new_oident->desc,oname_str)) {
3205 fprintf(stderr,"oid is already named as %s, regristration faild\n",
3211 int cmd_push_command(const char* arg)
3213 #if HAVE_READLINE_HISTORY_H
3217 fprintf(stderr,"Not compiled with the readline/history module\n");
3222 void source_rcfile()
3224 /* Look for a $HOME/.yazclientrc and source it if it exists */
3225 struct stat statbuf;
3227 char* homedir=getenv("HOME");
3229 if(!homedir) return;
3231 sprintf(buffer,"%s/.yazclientrc",homedir);
3233 if(stat(buffer,&statbuf)==0) {
3237 if(stat(".yazclientrc",&statbuf)==0) {
3238 cmd_source(".yazclientrc");
3243 static void initialize(void)
3248 if (!(out = odr_createmem(ODR_ENCODE)) ||
3249 !(in = odr_createmem(ODR_DECODE)) ||
3250 !(print = odr_createmem(ODR_PRINT)))
3252 fprintf(stderr, "failed to allocate ODR streams\n");
3257 setvbuf(stdout, 0, _IONBF, 0);
3259 odr_setprint(print, apdu_file);
3261 bibset = ccl_qual_mk ();
3262 inf = fopen (ccl_fields, "r");
3265 ccl_qual_file (bibset, inf);
3269 cqltrans = cql_transform_open_fname(cql_fields);
3270 /* If this fails, no problem: we detect cqltrans == 0 later */
3272 #if HAVE_READLINE_READLINE_H
3273 rl_attempted_completion_function = (CPPFunction*)readline_completer;
3277 for(i=0; i<maxOtherInfosSupported; ++i) {
3278 extraOtherInfos[i].oidval = -1;
3285 #if HAVE_GETTIMEOFDAY
3286 struct timeval tv_start, tv_end;
3290 static void handle_srw_record(Z_SRW_record *rec)
3292 if (rec->recordPosition)
3294 printf ("pos=%d", *rec->recordPosition);
3295 setno = *rec->recordPosition + 1;
3297 if (rec->recordSchema)
3298 printf (" schema=%s", rec->recordSchema);
3300 if (rec->recordData_buf && rec->recordData_len)
3301 fwrite(rec->recordData_buf, 1, rec->recordData_len, stdout);
3303 printf ("No data!");
3307 static void handle_srw_explain_response(Z_SRW_explainResponse *res)
3309 handle_srw_record(&res->record);
3312 static void handle_srw_response(Z_SRW_searchRetrieveResponse *res)
3316 printf ("Received SRW SearchRetrieve Response\n");
3318 for (i = 0; i<res->num_diagnostics; i++)
3320 if (res->diagnostics[i].uri)
3321 printf ("SRW diagnostic %s\n",
3322 res->diagnostics[i].uri);
3324 printf ("SRW diagnostic missing or could not be decoded\n");
3325 if (res->diagnostics[i].message)
3326 printf ("Message: %s\n", res->diagnostics[i].message);
3327 if (res->diagnostics[i].details)
3328 printf ("Details: %s\n", res->diagnostics[i].details);
3330 if (res->numberOfRecords)
3331 printf ("Number of hits: %d\n", *res->numberOfRecords);
3332 for (i = 0; i<res->num_records; i++)
3333 handle_srw_record(res->records + i);
3336 static void http_response(Z_HTTP_Response *hres)
3339 const char *content_type = z_HTTP_header_lookup(hres->headers,
3341 const char *connection_head = z_HTTP_header_lookup(hres->headers,
3343 if (content_type && !yaz_strcmp_del("text/xml", content_type, "; "))
3345 Z_SOAP *soap_package = 0;
3346 ODR o = odr_createmem(ODR_DECODE);
3347 Z_SOAP_Handler soap_handlers[2] = {
3348 {"http://www.loc.gov/zing/srw/", 0,
3349 (Z_SOAP_fun) yaz_srw_codec},
3352 ret = z_soap_codec(o, &soap_package,
3353 &hres->content_buf, &hres->content_len,
3355 if (!ret && soap_package->which == Z_SOAP_generic &&
3356 soap_package->u.generic->no == 0)
3358 Z_SRW_PDU *sr = soap_package->u.generic->p;
3359 if (sr->which == Z_SRW_searchRetrieve_response)
3360 handle_srw_response(sr->u.response);
3361 else if (sr->which == Z_SRW_explain_response)
3362 handle_srw_explain_response(sr->u.explain_response);
3366 else if (soap_package && (soap_package->which == Z_SOAP_fault
3367 || soap_package->which == Z_SOAP_error))
3369 printf ("HTTP Error Status=%d\n", hres->code);
3370 printf ("SOAP Fault code %s\n",
3371 soap_package->u.fault->fault_code);
3372 printf ("SOAP Fault string %s\n",
3373 soap_package->u.fault->fault_string);
3374 if (soap_package->u.fault->details)
3375 printf ("SOAP Details %s\n",
3376 soap_package->u.fault->details);
3384 if (hres->code != 200)
3386 printf ("HTTP Error Status=%d\n", hres->code);
3390 printf ("Decoding of SRW package failed\n");
3396 if (!strcmp(hres->version, "1.0"))
3398 /* HTTP 1.0: only if Keep-Alive we stay alive.. */
3399 if (!connection_head || strcmp(connection_head, "Keep-Alive"))
3404 /* HTTP 1.1: only if no close we stay alive .. */
3405 if (connection_head && !strcmp(connection_head, "close"))
3412 void wait_and_handle_response()
3414 int reconnect_ok = 1;
3417 int netbufferlen = 0;
3422 res = cs_get(conn, &netbuffer, &netbufferlen);
3423 if (reconnect_ok && res <= 0 && protocol == PROTO_HTTP)
3434 buf_out = odr_getbuf(out, &len_out, 0);
3436 do_hex_dump(buf_out, len_out);
3438 cs_put(conn, buf_out, len_out);
3446 printf("Target closed connection\n");
3451 odr_reset(in); /* release APDU from last round */
3453 do_hex_dump(netbuffer, res);
3454 odr_setbuf(in, netbuffer, res, 0);
3456 if (!z_GDU(in, &gdu, 0, 0))
3458 FILE *f = ber_file ? ber_file : stdout;
3459 odr_perror(in, "Decoding incoming APDU");
3460 fprintf(f, "[Near %d]\n", odr_offset(in));
3461 fprintf(f, "Packet dump:\n---------\n");
3462 odr_dumpBER(f, netbuffer, res);
3463 fprintf(f, "---------\n");
3466 z_GDU(print, &gdu, 0, 0);
3469 if (conn && cs_more(conn))
3474 odr_dumpBER(ber_file, netbuffer, res);
3475 if (apdu_file && !z_GDU(print, &gdu, 0, 0))
3477 odr_perror(print, "Failed to print incoming APDU");
3481 if (gdu->which == Z_GDU_Z3950)
3483 Z_APDU *apdu = gdu->u.z3950;
3486 case Z_APDU_initResponse:
3487 process_initResponse(apdu->u.initResponse);
3489 case Z_APDU_searchResponse:
3490 process_searchResponse(apdu->u.searchResponse);
3492 case Z_APDU_scanResponse:
3493 process_scanResponse(apdu->u.scanResponse);
3495 case Z_APDU_presentResponse:
3496 print_refid (apdu->u.presentResponse->referenceId);
3498 *apdu->u.presentResponse->numberOfRecordsReturned;
3499 if (apdu->u.presentResponse->records)
3500 display_records(apdu->u.presentResponse->records);
3502 printf("No records.\n");
3503 printf ("nextResultSetPosition = %d\n",
3504 *apdu->u.presentResponse->nextResultSetPosition);
3506 case Z_APDU_sortResponse:
3507 process_sortResponse(apdu->u.sortResponse);
3509 case Z_APDU_extendedServicesResponse:
3510 printf("Got extended services response\n");
3511 process_ESResponse(apdu->u.extendedServicesResponse);
3514 printf("Target has closed the association.\n");
3515 process_close(apdu->u.close);
3517 case Z_APDU_resourceControlRequest:
3518 process_resourceControlRequest
3519 (apdu->u.resourceControlRequest);
3521 case Z_APDU_deleteResultSetResponse:
3522 process_deleteResultSetResponse(apdu->u.
3523 deleteResultSetResponse);
3526 printf("Received unknown APDU type (%d).\n",
3532 else if (gdu->which == Z_GDU_HTTP_Response)
3534 http_response(gdu->u.HTTP_Response);
3537 if (conn && !cs_more(conn))
3542 #if HAVE_GETTIMEOFDAY
3543 gettimeofday (&tv_end, 0);
3545 printf ("S/U S/U=%ld/%ld %ld/%ld",
3546 (long) tv_start.tv_sec,
3547 (long) tv_start.tv_usec,
3548 (long) tv_end.tv_sec,
3549 (long) tv_end.tv_usec);
3551 printf ("Elapsed: %.6f\n",
3552 (double) tv_end.tv_usec / 1e6 + tv_end.tv_sec -
3553 ((double) tv_start.tv_usec / 1e6 + tv_start.tv_sec));
3560 int cmd_cclparse(const char* arg)
3563 struct ccl_rpn_node *rpn=NULL;
3566 rpn = ccl_find_str (bibset, arg, &error, &pos);
3569 printf ("%*s^ - ", 3+strlen(last_cmd)+1+pos, " ");
3570 printf ("%s\n", ccl_err_msg (error));
3576 ccl_pr_tree(rpn, stdout);
3580 ccl_rpn_delete(rpn);
3588 int cmd_set_otherinfo(const char* args)
3590 char oid[101], otherinfoString[101];
3595 sscan_res = sscanf (args, "%d %100[^ ] %100s", &otherinfoNo, oid, otherinfoString);
3597 /* reset this otherinfo */
3598 if(otherinfoNo>=maxOtherInfosSupported) {
3599 printf("Error otherinfo index to large (%d>%d)\n",otherinfoNo,maxOtherInfosSupported);
3601 extraOtherInfos[otherinfoNo].oidval = -1;
3602 if(extraOtherInfos[otherinfoNo].value) free(extraOtherInfos[otherinfoNo].value);
3606 printf("Error in set_otherinfo command \n");
3610 if(otherinfoNo>=maxOtherInfosSupported) {
3611 printf("Error otherinfo index to large (%d>%d)\n",otherinfoNo,maxOtherInfosSupported);
3614 oidval = oid_getvalbyname (oid);
3616 printf("Error in set_otherinfo command unknown oid %s \n",oid);
3619 extraOtherInfos[otherinfoNo].oidval = oidval;
3620 if(extraOtherInfos[otherinfoNo].value) free(extraOtherInfos[otherinfoNo].value);
3621 extraOtherInfos[otherinfoNo].value = strdup(otherinfoString);
3626 int cmd_list_otherinfo(const char* args)
3630 if(strlen(args)>0) {
3632 if( i >= maxOtherInfosSupported ) {
3633 printf("Error otherinfo index to large (%d>%d)\n",i,maxOtherInfosSupported);
3637 if(extraOtherInfos[i].oidval != -1)
3638 printf(" otherinfo %d %s %s\n",
3640 yaz_z3950_oid_value_to_str(
3641 (enum oid_value) extraOtherInfos[i].oidval,
3643 extraOtherInfos[i].value);
3646 for(i=0; i<maxOtherInfosSupported; ++i) {
3647 if(extraOtherInfos[i].oidval != -1)
3648 printf(" otherinfo %d %s %s\n",
3650 yaz_z3950_oid_value_to_str(
3651 (enum oid_value) extraOtherInfos[i].oidval,
3653 extraOtherInfos[i].value);
3661 int cmd_list_all(const char* args) {
3664 /* connection options */
3666 printf("Connected to : %s\n",last_open_command);
3668 if(last_open_command)
3669 printf("Not connected to : %s\n",last_open_command);
3671 printf("Not connected : \n");
3674 if(yazProxy) printf("using proxy : %s\n",yazProxy);
3676 printf("auto_reconnect : %s\n",auto_reconnect?"on":"off");
3679 printf("Authentication : none\n");
3681 switch(auth->which) {
3682 case Z_IdAuthentication_idPass:
3683 printf("Authentication : IdPass\n");
3684 printf(" Login User : %s\n",auth->u.idPass->userId?auth->u.idPass->userId:"");
3685 printf(" Login Group : %s\n",auth->u.idPass->groupId?auth->u.idPass->groupId:"");
3686 printf(" Password : %s\n",auth->u.idPass->password?auth->u.idPass->password:"");
3688 case Z_IdAuthentication_open:
3689 printf("Authentication : psOpen\n");
3690 printf(" Open string : %s\n",auth->u.open);
3693 printf("Authentication : Unknown\n");
3696 if (negotiationCharset)
3697 printf("Neg. Character set : `%s'\n", negotiationCharset);
3701 for (i = 0; i<num_databaseNames; i++) printf("%s ",databaseNames[i]);
3705 printf("CCL file : %s\n",ccl_fields);
3706 printf("CQL file : %s\n",cql_fields);
3707 printf("Query type : %s\n",query_type_as_string(queryType));
3709 printf("Named Result Sets : %s\n",setnumber==-1?"off":"on");
3711 /* piggy back options */
3712 printf("ssub/lslb/mspn : %d/%d/%d\n",smallSetUpperBound,largeSetLowerBound,mediumSetPresentNumber);
3714 /* print present related options */
3715 printf("Format : %s\n",yaz_z3950_oid_value_to_str(recordsyntax,CLASS_RECSYN));
3716 printf("Schema : %s\n",record_schema ? record_schema : "not set");
3717 printf("Elements : %s\n",elementSetNames?elementSetNames->u.generic:"");
3719 /* loging options */
3720 printf("APDU log : %s\n",apdu_file?"on":"off");
3721 printf("Record log : %s\n",marc_file?"on":"off");
3724 printf("Other Info: \n");
3725 cmd_list_otherinfo("");
3730 int cmd_clear_otherinfo(const char* args)
3732 if(strlen(args)>0) {
3734 otherinfoNo = atoi(args);
3735 if( otherinfoNo >= maxOtherInfosSupported ) {
3736 printf("Error otherinfo index to large (%d>%d)\n",otherinfoNo,maxOtherInfosSupported);
3740 if(extraOtherInfos[otherinfoNo].oidval != -1) {
3741 /* only clear if set. */
3742 extraOtherInfos[otherinfoNo].oidval=-1;
3743 free(extraOtherInfos[otherinfoNo].value);
3748 for(i=0; i<maxOtherInfosSupported; ++i) {
3749 if (extraOtherInfos[i].oidval!=-1 ) {
3750 extraOtherInfos[i].oidval=-1;
3751 free(extraOtherInfos[i].value);
3758 static int cmd_help (const char *line);
3760 typedef char *(*completerFunctionType)(const char *text, int state);
3764 int (*fun)(const char *arg);
3766 completerFunctionType rl_completerfunction;
3767 int complete_filenames;
3768 char **local_tabcompletes;
3770 {"open", cmd_open, "('tcp'|'ssl')':<host>[':'<port>][/<db>]",NULL,0,NULL},
3771 {"quit", cmd_quit, "",NULL,0,NULL},
3772 {"find", cmd_find, "<query>",NULL,0,NULL},
3773 {"delete", cmd_delete, "<setname>",NULL,0,NULL},
3774 {"base", cmd_base, "<base-name>",NULL,0,NULL},
3775 {"show", cmd_show, "<rec#>['+'<#recs>['+'<setname>]]",NULL,0,NULL},
3776 {"scan", cmd_scan, "<term>",NULL,0,NULL},
3777 {"sort", cmd_sort, "<sortkey> <flag> <sortkey> <flag> ...",NULL,0,NULL},
3778 {"sort+", cmd_sort_newset, "<sortkey> <flag> <sortkey> <flag> ...",NULL,0,NULL},
3779 {"authentication", cmd_authentication, "<acctstring>",NULL,0,NULL},
3780 {"lslb", cmd_lslb, "<largeSetLowerBound>",NULL,0,NULL},
3781 {"ssub", cmd_ssub, "<smallSetUpperBound>",NULL,0,NULL},
3782 {"mspn", cmd_mspn, "<mediumSetPresentNumber>",NULL,0,NULL},
3783 {"status", cmd_status, "",NULL,0,NULL},
3784 {"setnames", cmd_setnames, "",NULL,0,NULL},
3785 {"cancel", cmd_cancel, "",NULL,0,NULL},
3786 {"format", cmd_format, "<recordsyntax>",complete_format,0,NULL},
3787 {"schema", cmd_schema, "<schema>",complete_schema,0,NULL},
3788 {"elements", cmd_elements, "<elementSetName>",NULL,0,NULL},
3789 {"close", cmd_close, "",NULL,0,NULL},
3790 {"attributeset", cmd_attributeset, "<attrset>",complete_attributeset,0,NULL},
3791 {"querytype", cmd_querytype, "<type>",complete_querytype,0,NULL},
3792 {"refid", cmd_refid, "<id>",NULL,0,NULL},
3793 {"itemorder", cmd_itemorder, "ill|item <itemno>",NULL,0,NULL},
3794 {"update", cmd_update, "<action> <recid> [<file>]",NULL,0,NULL},
3795 {"update0", cmd_update0, "<action> <recid> [<file>]",NULL,0,NULL},
3796 {"packagename", cmd_packagename, "<packagename>",NULL,0,NULL},
3797 {"proxy", cmd_proxy, "[('tcp'|'ssl')]<host>[':'<port>]",NULL,0,NULL},
3798 {"charset", cmd_charset, "<nego_charset> <output_charset>",NULL,0,NULL},
3799 {"marccharset", cmd_marccharset, "<charset_name>",NULL,0,NULL},
3800 {"lang", cmd_lang, "<language_code>",NULL,0,NULL},
3801 {".", cmd_source, "<filename>",NULL,1,NULL},
3802 {"!", cmd_subshell, "Subshell command",NULL,1,NULL},
3803 {"set_apdufile", cmd_set_apdufile, "<filename>",NULL,1,NULL},
3804 {"set_berfile", cmd_set_berfile, "<filename>",NULL,1,NULL},
3805 {"set_marcdump", cmd_set_marcdump," <filename>",NULL,1,NULL},
3806 {"set_cclfile", cmd_set_cclfile," <filename>",NULL,1,NULL},
3807 {"set_cqlfile", cmd_set_cqlfile," <filename>",NULL,1,NULL},
3808 {"set_auto_reconnect", cmd_set_auto_reconnect," on|off",complete_auto_reconnect,1,NULL},
3809 {"set_otherinfo", cmd_set_otherinfo,"<otherinfoinddex> <oid> <string>",NULL,0,NULL},
3810 {"register_oid", cmd_register_oid,"<name> <class> <oid>",NULL,0,NULL},
3811 {"push_command", cmd_push_command,"<command>",command_generator,0,NULL},
3812 {"register_tab", cmd_register_tab,"<commandname> <tab>",command_generator,0,NULL},
3813 {"cclparse", cmd_cclparse,"<ccl find command>",NULL,0,NULL},
3814 {"list_otherinfo",cmd_list_otherinfo,"[otherinfoinddex]",NULL,0,NULL},
3815 {"list_all",cmd_list_all,"",NULL,0,NULL},
3816 {"clear_otherinfo",cmd_clear_otherinfo,"",NULL,0,NULL},
3817 /* Server Admin Functions */
3818 {"adm-reindex", cmd_adm_reindex, "<database-name>",NULL,0,NULL},
3819 {"adm-truncate", cmd_adm_truncate, "('database'|'index')<object-name>",NULL,0,NULL},
3820 {"adm-create", cmd_adm_create, "",NULL,0,NULL},
3821 {"adm-drop", cmd_adm_drop, "('database'|'index')<object-name>",NULL,0,NULL},
3822 {"adm-import", cmd_adm_import, "<record-type> <dir> <pattern>",NULL,0,NULL},
3823 {"adm-refresh", cmd_adm_refresh, "",NULL,0,NULL},
3824 {"adm-commit", cmd_adm_commit, "",NULL,0,NULL},
3825 {"adm-shutdown", cmd_adm_shutdown, "",NULL,0,NULL},
3826 {"adm-startup", cmd_adm_startup, "",NULL,0,NULL},
3827 {"explain", cmd_explain, "", NULL, 0, NULL},
3828 {"options", cmd_options, "", NULL, 0, NULL},
3829 {"zversion", cmd_zversion, "", NULL, 0, NULL},
3830 {"help", cmd_help, "", NULL,0,NULL},
3831 {"init", cmd_init, "", NULL,0,NULL},
3835 static int cmd_help (const char *line)
3841 sscanf (line, "%20s", topic);
3844 printf("Commands:\n");
3845 for (i = 0; cmd_array[i].cmd; i++)
3846 if (*topic == 0 || strcmp (topic, cmd_array[i].cmd) == 0)
3847 printf(" %s %s\n", cmd_array[i].cmd, cmd_array[i].ad);
3848 if (strcmp (topic, "find") == 0)
3851 printf (" \"term\" Simple Term\n");
3852 printf (" @attr [attset] type=value op Attribute\n");
3853 printf (" @and opl opr And\n");
3854 printf (" @or opl opr Or\n");
3855 printf (" @not opl opr And-Not\n");
3856 printf (" @set set Result set\n");
3858 printf ("Bib-1 attribute types\n");
3860 printf ("4=Title 7=ISBN 8=ISSN 30=Date 62=Abstract 1003=Author 1016=Any\n");
3861 printf ("2=Relation: ");
3862 printf ("1< 2<= 3= 4>= 5> 6!= 102=Relevance\n");
3863 printf ("3=Position: ");
3864 printf ("1=First in Field 2=First in subfield 3=Any position\n");
3865 printf ("4=Structure: ");
3866 printf ("1=Phrase 2=Word 3=Key 4=Year 5=Date 6=WordList\n");
3867 printf ("5=Truncation: ");
3868 printf ("1=Right 2=Left 3=L&R 100=No 101=# 102=Re-1 103=Re-2\n");
3869 printf ("6=Completeness:");
3870 printf ("1=Incomplete subfield 2=Complete subfield 3=Complete field\n");
3875 int cmd_register_tab(const char* arg) {
3877 char command[101], tabargument[101];
3882 if (sscanf (arg, "%100s %100s", command, tabargument) < 1) {
3886 /* locate the amdn in the list */
3887 for (i = 0; cmd_array[i].cmd; i++) {
3888 if (!strncmp(cmd_array[i].cmd, command, strlen(command))) {
3893 if(!cmd_array[i].cmd) {
3894 fprintf(stderr,"Unknown command %s\n",command);
3899 if(!cmd_array[i].local_tabcompletes)
3900 cmd_array[i].local_tabcompletes = (char **) calloc(1,sizeof(char**));
3904 tabslist = cmd_array[i].local_tabcompletes;
3905 for(;tabslist && *tabslist;tabslist++) {
3909 cmd_array[i].local_tabcompletes = (char **)
3910 realloc(cmd_array[i].local_tabcompletes,(num_of_tabs+2)*sizeof(char**));
3911 tabslist=cmd_array[i].local_tabcompletes;
3912 tabslist[num_of_tabs]=strdup(tabargument);
3913 tabslist[num_of_tabs+1]=NULL;
3918 void process_cmd_line(char* line)
3921 char word[32], arg[1024];
3923 #if HAVE_GETTIMEOFDAY
3924 gettimeofday (&tv_start, 0);
3927 if ((res = sscanf(line, "%31s %1023[^;]", word, arg)) <= 0)
3929 strcpy(word, last_cmd);
3934 strcpy(last_cmd, word);
3936 /* removed tailing spaces from the arg command */
3939 char* lastnonspace=NULL;
3947 *(++lastnonspace) = 0;
3950 for (i = 0; cmd_array[i].cmd; i++)
3951 if (!strncmp(cmd_array[i].cmd, word, strlen(word)))
3953 res = (*cmd_array[i].fun)(arg);
3957 if (!cmd_array[i].cmd) /* dump our help-screen */
3959 printf("Unknown command: %s.\n", word);
3960 printf("use help for list of commands\n");
3961 /* cmd_help (""); */
3965 if(apdu_file) fflush(apdu_file);
3968 wait_and_handle_response();
3977 char *command_generator(const char *text, int state)
3983 for( ; cmd_array[idx].cmd; ++idx) {
3984 if (!strncmp(cmd_array[idx].cmd,text,strlen(text))) {
3985 ++idx; /* skip this entry on the next run */
3986 return strdup(cmd_array[idx-1].cmd);
3994 This function only known how to complete on the first word
3996 char ** readline_completer(char *text, int start, int end) {
3997 #if HAVE_READLINE_READLINE_H
3999 completerFunctionType completerToUse;
4002 #if HAVE_READLINE_RL_COMPLETION_MATCHES
4003 char** res=rl_completion_matches(text,
4006 char** res=completion_matches(text,
4007 (CPFunction*)command_generator);
4009 rl_attempted_completion_over = 1;
4012 char arg[1024],word[32];
4014 if ((res = sscanf(rl_line_buffer, "%31s %1023[^;]", word, arg)) <= 0) {
4015 rl_attempted_completion_over = 1;
4019 for (i = 0; cmd_array[i].cmd; i++) {
4020 if (!strncmp(cmd_array[i].cmd, word, strlen(word))) {
4025 if(!cmd_array[i].cmd) return NULL;
4027 curret_global_list = cmd_array[i].local_tabcompletes;
4029 completerToUse = cmd_array[i].rl_completerfunction;
4030 if(completerToUse==NULL) /* if no pr. command completer is defined use the default completer */
4031 completerToUse = default_completer;
4033 if(completerToUse) {
4034 #ifdef HAVE_READLINE_RL_COMPLETION_MATCHES
4036 rl_completion_matches(text,
4040 completion_matches(text,
4041 (CPFunction*)completerToUse);
4043 if(!cmd_array[i].complete_filenames)
4044 rl_attempted_completion_over = 1;
4047 if(!cmd_array[i].complete_filenames)
4048 rl_attempted_completion_over = 1;
4058 static void client(void)
4064 #if HAVE_GETTIMEOFDAY
4065 gettimeofday (&tv_start, 0);
4070 char *line_in = NULL;
4071 #if HAVE_READLINE_READLINE_H
4074 line_in=readline(C_PROMPT);
4077 #if HAVE_READLINE_HISTORY_H
4079 add_history(line_in);
4081 strncpy(line, line_in, 1023);
4090 if (!fgets(line, 1023, stdin))
4092 if ((end_p = strchr (line, '\n')))
4095 process_cmd_line(line);
4099 static void show_version(void)
4103 yaz_version(vstr, 0);
4104 printf ("YAZ version: %s\n", YAZ_VERSION);
4105 if (strcmp(vstr, YAZ_VERSION))
4106 printf ("YAZ DLL/SO: %s\n", vstr);
4110 int main(int argc, char **argv)
4113 char *open_command = 0;
4114 char *auth_command = 0;
4119 if (!setlocale(LC_CTYPE, ""))
4120 fprintf (stderr, "setlocale failed\n");
4124 codeset = nl_langinfo(CODESET);
4128 outputCharset = xstrdup(codeset);
4130 ODR_MASK_SET(&z3950_options, Z_Options_search);
4131 ODR_MASK_SET(&z3950_options, Z_Options_present);
4132 ODR_MASK_SET(&z3950_options, Z_Options_namedResultSets);
4133 ODR_MASK_SET(&z3950_options, Z_Options_triggerResourceCtrl);
4134 ODR_MASK_SET(&z3950_options, Z_Options_scan);
4135 ODR_MASK_SET(&z3950_options, Z_Options_sort);
4136 ODR_MASK_SET(&z3950_options, Z_Options_extendedServices);
4137 ODR_MASK_SET(&z3950_options, Z_Options_delSet);
4139 while ((ret = options("k:c:q:a:b:m:v:p:u:t:Vxd:", argv, argc, &arg)) != -2)
4146 open_command = (char *) xmalloc (strlen(arg)+6);
4147 strcpy (open_command, "open ");
4148 strcat (open_command, arg);
4152 dump_file_prefix = arg;
4155 kilobytes = atoi(arg);
4158 if (!(marc_file = fopen (arg, "a")))
4165 outputCharset = xstrdup(arg);
4168 strncpy (ccl_fields, arg, sizeof(ccl_fields)-1);
4169 ccl_fields[sizeof(ccl_fields)-1] = '\0';
4172 strncpy (cql_fields, arg, sizeof(cql_fields)-1);
4173 cql_fields[sizeof(cql_fields)-1] = '\0';
4176 if (!strcmp(arg, "-"))
4179 ber_file=fopen(arg, "a");
4182 if (!strcmp(arg, "-"))
4185 apdu_file=fopen(arg, "a");
4191 yazProxy=strdup(arg);
4196 auth_command = (char *) xmalloc (strlen(arg)+6);
4197 strcpy (auth_command, "auth ");
4198 strcat (auth_command, arg);
4202 yaz_log_init(yaz_log_mask_str(arg), "", 0);
4208 fprintf (stderr, "Usage: %s [-m <marclog>] [ -a <apdulog>] "
4209 "[-b berdump] [-c cclfields] \n"
4210 "[-q cqlfields] [-p <proxy-addr>] [-u <auth>] "
4211 "[-k size] [-d dump] [-V] [<server-addr>]\n",
4219 #ifdef HAVE_GETTIMEOFDAY
4220 gettimeofday (&tv_start, 0);
4222 process_cmd_line (auth_command);
4223 #if HAVE_READLINE_HISTORY_H
4224 add_history(auth_command);
4226 xfree(auth_command);
4230 #ifdef HAVE_GETTIMEOFDAY
4231 gettimeofday (&tv_start, 0);
4233 process_cmd_line (open_command);
4234 #if HAVE_READLINE_HISTORY_H
4235 add_history(open_command);
4237 xfree(open_command);
4248 * vim600: sw=4 ts=8 fdm=marker
4249 * vim<600: sw=4 ts=8