2 * Copyright (c) 1995-2003, Index Data
3 * See the file LICENSE for details.
5 * $Id: client.c,v 1.184 2003-02-25 18:35:48 adam Exp $
23 #define S_ISREG(x) (x & _S_IFREG)
24 #define S_ISDIR(x) (x & _S_IFDIR)
27 #include <yaz/yaz-util.h>
29 #include <yaz/comstack.h>
31 #include <yaz/proto.h>
32 #include <yaz/marcdisp.h>
33 #include <yaz/diagbib1.h>
34 #include <yaz/otherinfo.h>
35 #include <yaz/charneg.h>
37 #include <yaz/pquery.h>
38 #include <yaz/sortspec.h>
42 #include <yaz/yaz-ccl.h>
44 #if HAVE_READLINE_READLINE_H
45 #include <readline/readline.h>
48 #if HAVE_READLINE_HISTORY_H
49 #include <readline/history.h>
56 #include "tabcomplete.h"
58 #define C_PROMPT "Z> "
60 static char *codeset = 0; /* character set for output */
62 static ODR out, in, print; /* encoding and decoding streams */
63 static FILE *apdu_file = 0;
64 static COMSTACK conn = 0; /* our z-association */
65 static Z_IdAuthentication *auth = 0; /* our current auth definition */
66 char *databaseNames[128];
67 int num_databaseNames = 0;
68 static Z_External *record_last = 0;
69 static int setnumber = -1; /* current result set number */
70 static int smallSetUpperBound = 0;
71 static int largeSetLowerBound = 1;
72 static int mediumSetPresentNumber = 0;
73 static Z_ElementSetNames *elementSetNames = 0;
74 static int setno = 1; /* current set offset */
75 static enum oid_proto protocol = PROTO_Z3950; /* current app protocol */
76 static enum oid_value recordsyntax = VAL_USMARC;
77 static enum oid_value schema = VAL_NONE;
78 static int sent_close = 0;
79 static NMEM session_mem = NULL; /* memory handle for init-response */
80 static Z_InitResponse *session = 0; /* session parameters */
81 static char last_scan_line[512] = "0";
82 static char last_scan_query[512] = "0";
83 static char ccl_fields[512] = "default.bib";
84 static char* esPackageName = 0;
85 static char* yazProxy = 0;
86 static int kilobytes = 1024;
87 static char* yazCharset = 0;
88 static char* yazLang = 0;
91 static char last_cmd[32] = "?";
92 static FILE *marcdump = 0;
93 static char *refid = NULL;
94 static char *last_open_command = NULL;
95 static int auto_reconnect = 0;
104 static QueryType queryType = QueryType_Prefix;
106 static CCL_bibset bibset; /* CCL bibset handle */
108 #if HAVE_READLINE_COMPLETION_OVER
111 /* readline doesn't have this var. Define it ourselves. */
112 int rl_attempted_completion_over = 0;
115 /* set this one to 1, to avoid decode of unknown MARCs */
116 #define AVOID_MARC_DECODE 1
118 /* nice helper macro as extensive tabbing gives spaces at the en of the args lines */
119 #define REMOVE_TAILING_BLANKS(a) {\
120 char* args_end=(a)+strlen(a)-1; \
121 while(isspace(*args_end)) {*args_end=0;--args_end;}; \
124 #define maxOtherInfosSupported 10
128 } extraOtherInfos[maxOtherInfosSupported];
131 void process_cmd_line(char* line);
132 char ** readline_completer(char *text, int start, int end);
133 char *command_generator(const char *text, int state);
134 char** curret_global_list=NULL;
135 int cmd_register_tab(char* arg);
137 ODR getODROutputStream()
142 const char* query_type_as_string(QueryType q)
145 case QueryType_Prefix: return "prefix (RPN sent to server)";
146 case QueryType_CCL: return "CCL (CCL sent to server) ";
147 case QueryType_CCL2RPN: return "CCL -> RPN (RPN sent to server)";
148 case QueryType_CQL: return "CQL (CQL sent to server)";
150 return "unknown Query type internal yaz-client error";
155 void do_hex_dump(char* buf,int len)
159 for( i=0; i<len ; i=i+16 )
162 for(x=0 ; i+x<len && x<16; ++x)
164 printf("%2.2X ",(unsigned int)((unsigned char)buf[i+x]));
171 void add_otherInfos(Z_APDU *a)
173 Z_OtherInformation **oi;
177 for(i=0; i<maxOtherInfosSupported; ++i)
179 if(extraOtherInfos[i].oidval != -1)
180 yaz_oi_set_string_oidval(oi, out, extraOtherInfos[i].oidval, 1, extraOtherInfos[i].value);
184 void send_apdu(Z_APDU *a)
193 z_APDU(print, &a, 0, 0);
196 if (!z_APDU(out, &a, 0, 0))
198 odr_perror(out, "Encoding APDU");
201 buf = odr_getbuf(out, &len, 0);
202 /* printf ("sending APDU of size %d\n", len); */
203 if (cs_put(conn, buf, len) < 0)
205 fprintf(stderr, "cs_put: %s", cs_errmsg(cs_errno(conn)));
209 do_hex_dump(buf,len);
210 odr_reset(out); /* release the APDU structure */
213 static void print_stringn(const unsigned char *buf, size_t len)
216 for (i = 0; i<len; i++)
217 if ((buf[i] <= 126 && buf[i] >= 32) || strchr ("\n\r\t\f", buf[i]))
218 printf ("%c", buf[i]);
220 printf ("\\X%02X", buf[i]);
223 static void print_refid (Z_ReferenceId *id)
227 printf ("Reference Id: ");
228 print_stringn (id->buf, id->len);
233 static Z_ReferenceId *set_refid (ODR out)
238 id = (Z_ReferenceId *) odr_malloc (out, sizeof(*id));
239 id->size = id->len = strlen(refid);
240 id->buf = (unsigned char *) odr_malloc (out, id->len);
241 memcpy (id->buf, refid, id->len);
245 /* INIT SERVICE ------------------------------- */
247 static void send_initRequest(const char* type_and_host)
249 Z_APDU *apdu = zget_APDU(out, Z_APDU_initRequest);
250 Z_InitRequest *req = apdu->u.initRequest;
252 ODR_MASK_SET(req->options, Z_Options_search);
253 ODR_MASK_SET(req->options, Z_Options_present);
254 ODR_MASK_SET(req->options, Z_Options_namedResultSets);
255 ODR_MASK_SET(req->options, Z_Options_triggerResourceCtrl);
256 ODR_MASK_SET(req->options, Z_Options_scan);
257 ODR_MASK_SET(req->options, Z_Options_sort);
258 ODR_MASK_SET(req->options, Z_Options_extendedServices);
259 ODR_MASK_SET(req->options, Z_Options_delSet);
261 ODR_MASK_SET(req->protocolVersion, Z_ProtocolVersion_1);
262 ODR_MASK_SET(req->protocolVersion, Z_ProtocolVersion_2);
263 ODR_MASK_SET(req->protocolVersion, Z_ProtocolVersion_3);
265 *req->maximumRecordSize = 1024*kilobytes;
266 *req->preferredMessageSize = 1024*kilobytes;
268 req->idAuthentication = auth;
270 req->referenceId = set_refid (out);
273 yaz_oi_set_string_oidval(&req->otherInfo, out, VAL_PROXY,
276 if (yazCharset || yazLang) {
277 Z_OtherInformation **p;
278 Z_OtherInformationUnit *p0;
280 yaz_oi_APDU(apdu, &p);
282 if ((p0=yaz_oi_update(p, out, NULL, 0, 0))) {
283 ODR_MASK_SET(req->options, Z_Options_negotiationModel);
285 p0->which = Z_OtherInfo_externallyDefinedInfo;
286 p0->information.externallyDefinedInfo =
287 yaz_set_proposal_charneg(out,
288 (const char**)&yazCharset, (yazCharset)?1:0,
289 (const char**)&yazLang, (yazLang)?1:0, 1);
294 printf("Sent initrequest.\n");
297 static int process_initResponse(Z_InitResponse *res)
299 /* save session parameters for later use */
300 session_mem = odr_extract_mem(in);
304 printf("Connection rejected by target.\n");
306 printf("Connection accepted by target.\n");
307 if (res->implementationId)
308 printf("ID : %s\n", res->implementationId);
309 if (res->implementationName)
310 printf("Name : %s\n", res->implementationName);
311 if (res->implementationVersion)
312 printf("Version: %s\n", res->implementationVersion);
313 if (res->userInformationField)
315 printf("UserInformationfield:\n");
316 if (!z_External(print, (Z_External**)&res-> userInformationField,
319 odr_perror(print, "Printing userinfo\n");
322 if (res->userInformationField->which == Z_External_octet)
324 printf("Guessing visiblestring:\n");
325 printf("'%s'\n", res->userInformationField->u. octet_aligned->buf);
330 if (ODR_MASK_GET(res->options, Z_Options_search))
332 if (ODR_MASK_GET(res->options, Z_Options_present))
334 if (ODR_MASK_GET(res->options, Z_Options_delSet))
336 if (ODR_MASK_GET(res->options, Z_Options_resourceReport))
337 printf (" resourceReport");
338 if (ODR_MASK_GET(res->options, Z_Options_resourceCtrl))
339 printf (" resourceCtrl");
340 if (ODR_MASK_GET(res->options, Z_Options_accessCtrl))
341 printf (" accessCtrl");
342 if (ODR_MASK_GET(res->options, Z_Options_scan))
344 if (ODR_MASK_GET(res->options, Z_Options_sort))
346 if (ODR_MASK_GET(res->options, Z_Options_extendedServices))
347 printf (" extendedServices");
348 if (ODR_MASK_GET(res->options, Z_Options_level_1Segmentation))
349 printf (" level1Segmentation");
350 if (ODR_MASK_GET(res->options, Z_Options_level_2Segmentation))
351 printf (" level2Segmentation");
352 if (ODR_MASK_GET(res->options, Z_Options_concurrentOperations))
353 printf (" concurrentOperations");
354 if (ODR_MASK_GET(res->options, Z_Options_namedResultSets))
356 printf (" namedResultSets");
359 if (ODR_MASK_GET(res->options, Z_Options_encapsulation))
360 printf (" encapsulation");
361 if (ODR_MASK_GET(res->options, Z_Options_resultCount))
362 printf (" resultCount");
363 if (ODR_MASK_GET(res->options, Z_Options_negotiationModel))
364 printf (" negotiationModel");
365 if (ODR_MASK_GET(res->options, Z_Options_duplicateDetection))
366 printf (" duplicateDetection");
367 if (ODR_MASK_GET(res->options, Z_Options_queryType104))
368 printf (" queryType104");
371 if (ODR_MASK_GET(res->options, Z_Options_negotiationModel)) {
373 Z_CharSetandLanguageNegotiation *p =
374 yaz_get_charneg_record(res->otherInfo);
378 char *charset=NULL, *lang=NULL;
381 yaz_get_response_charneg(session_mem, p, &charset, &lang,
384 printf("Accepted character set : %s\n", charset);
385 printf("Accepted code language : %s\n", lang ? lang : "none");
386 printf("Accepted records in ...: %d\n", selected );
393 static int cmd_base(char *arg)
400 printf("Usage: base <database> <database> ...\n");
403 for (i = 0; i<num_databaseNames; i++)
404 xfree (databaseNames[i]);
405 num_databaseNames = 0;
409 if (!(cp = strchr(arg, ' ')))
410 cp = arg + strlen(arg);
413 databaseNames[num_databaseNames] = (char *)xmalloc (1 + cp - arg);
414 memcpy (databaseNames[num_databaseNames], arg, cp - arg);
415 databaseNames[num_databaseNames][cp - arg] = '\0';
417 for (cp1 = databaseNames[num_databaseNames]; *cp1 ; cp1++)
429 void cmd_open_remember_last_open_command(char* arg, char* new_open_command)
431 if(last_open_command != arg)
433 if(last_open_command) xfree(last_open_command);
434 last_open_command = xstrdup(new_open_command);
438 int cmd_open(char *arg)
441 char type_and_host[101], base[101];
445 printf("Already connected.\n");
451 nmem_destroy (session_mem);
456 if (strncmp (arg, "unix:", 5) == 0)
459 conn = cs_create_host(arg, 1, &add);
460 cmd_open_remember_last_open_command(arg,arg);
465 if (sscanf (arg, "%100[^/]/%100s", type_and_host, base) < 1)
468 cmd_open_remember_last_open_command(arg,type_and_host);
470 conn = cs_create_host(yazProxy, 1, &add);
472 conn = cs_create_host(type_and_host, 1, &add);
476 printf ("Couldn't create comstack\n");
479 printf("Connecting...");
481 if (cs_connect(conn, add) < 0)
483 printf ("error = %s\n", cs_strerror(conn));
484 if (conn->cerrno == CSYSERR)
487 yaz_strerror(msg, sizeof(msg));
488 printf ("%s\n", msg);
496 send_initRequest(type_and_host);
508 if(!( auto_reconnect && last_open_command) ) return ;
510 open_command = (char *) xmalloc (strlen(last_open_command)+6);
511 strcpy (open_command, "open ");
513 strcat (open_command, last_open_command);
515 process_cmd_line(open_command);
520 int cmd_authentication(char *arg)
522 static Z_IdAuthentication au;
523 static char user[40], group[40], pass[40];
524 static Z_IdPass idPass;
529 printf("Auth field set to null\n");
533 r = sscanf (arg, "%39s %39s %39s", user, group, pass);
536 printf("Auth field set to null\n");
542 au.which = Z_IdAuthentication_open;
548 au.which = Z_IdAuthentication_idPass;
549 au.u.idPass = &idPass;
550 idPass.groupId = NULL;
551 idPass.userId = user;
552 idPass.password = group;
557 au.which = Z_IdAuthentication_idPass;
558 au.u.idPass = &idPass;
559 idPass.groupId = group;
560 idPass.userId = user;
561 idPass.password = pass;
566 /* SEARCH SERVICE ------------------------------ */
567 static void display_record(Z_External *r);
569 static void print_record(const unsigned char *buf, size_t len)
572 print_stringn (buf, len);
573 /* add newline if not already added ... */
574 if (i <= 0 || buf[i-1] != '\n')
578 static void display_record(Z_External *r)
580 oident *ent = oid_getentbyoid(r->direct_reference);
584 * Tell the user what we got.
586 if (r->direct_reference)
588 printf("Record type: ");
590 printf("%s\n", ent->desc);
591 else if (!odr_oid(print, &r->direct_reference, 0, 0))
593 odr_perror(print, "print oid");
597 /* Check if this is a known, ASN.1 type tucked away in an octet string */
598 if (ent && r->which == Z_External_octet)
600 Z_ext_typeent *type = z_ext_getentbyref(ent->value);
606 * Call the given decoder to process the record.
608 odr_setbuf(in, (char*)r->u.octet_aligned->buf,
609 r->u.octet_aligned->len, 0);
610 if (!(*type->fun)(in, (char **)&rr, 0, 0))
612 odr_perror(in, "Decoding constructed record.");
613 fprintf(stderr, "[Near %d]\n", odr_offset(in));
614 fprintf(stderr, "Packet dump:\n---------\n");
615 odr_dumpBER(stderr, (char*)r->u.octet_aligned->buf,
616 r->u.octet_aligned->len);
617 fprintf(stderr, "---------\n");
619 /* note just ignores the error ant print the bytes form the octet_aligned later */
622 * Note: we throw away the original, BER-encoded record here.
623 * Do something else with it if you want to keep it.
625 r->u.sutrs = (Z_SUTRS *) rr; /* we don't actually check the type here. */
626 r->which = type->what;
630 if (ent && ent->oclass != CLASS_RECSYN)
632 if (ent && ent->value == VAL_SOIF)
633 print_record((const unsigned char *) r->u.octet_aligned->buf,
634 r->u.octet_aligned->len);
635 else if (r->which == Z_External_octet)
637 const char *octet_buf = (char*)r->u.octet_aligned->buf;
638 if (ent->value == VAL_TEXT_XML || ent->value == VAL_APPLICATION_XML ||
639 ent->value == VAL_HTML)
641 print_record((const unsigned char *) octet_buf,
642 r->u.octet_aligned->len);
644 else if (ent->value == VAL_POSTSCRIPT)
646 int size = r->u.octet_aligned->len;
649 print_record((const unsigned char *) octet_buf, size);
654 #if AVOID_MARC_DECODE
655 /* primitive check for a marc OID 5.1-29 except 16 */
656 ent->oidsuffix[0] == 5 && ent->oidsuffix[1] < 30 &&
657 ent->oidsuffix[1] != 16
666 yaz_marc_t mt = yaz_marc_create();
668 if (yaz_marc_decode_buf(mt, octet_buf,r->u.octet_aligned->len,
672 if (ent->value == VAL_USMARC)
674 if (octet_buf[9] == 'a')
684 printf ("convert from %s to %s\n", from, codeset);
685 cd = yaz_iconv_open(codeset, from);
688 fwrite (result, 1, rlen, stdout);
692 size_t inbytesleft = rlen;
693 const char *inp = result;
697 size_t outbytesleft = sizeof(outbuf);
699 size_t r = yaz_iconv (cd, (char**) &inp,
701 &outp, &outbytesleft);
702 if (r == (size_t) (-1))
704 int e = yaz_iconv_error(cd);
705 if (e != YAZ_ICONV_E2BIG)
708 fwrite (outbuf, outp - outbuf, 1, stdout);
714 printf ("bad MARC. Dumping as it is:\n");
715 print_record((const unsigned char*) octet_buf,
716 r->u.octet_aligned->len);
718 yaz_marc_destroy(mt);
724 print_record((const unsigned char*) octet_buf,
725 r->u.octet_aligned->len);
729 fwrite (octet_buf, 1, r->u.octet_aligned->len, marcdump);
731 else if (ent && ent->value == VAL_SUTRS)
733 if (r->which != Z_External_sutrs)
735 printf("Expecting single SUTRS type for SUTRS.\n");
738 print_record(r->u.sutrs->buf, r->u.sutrs->len);
740 else if (ent && ent->value == VAL_GRS1)
743 if (r->which != Z_External_grs1)
745 printf("Expecting single GRS type for GRS.\n");
749 yaz_display_grs1(w, r->u.grs1, 0);
755 printf("Unknown record representation.\n");
756 if (!z_External(print, &r, 0, 0))
758 odr_perror(print, "Printing external");
764 static void display_diagrecs(Z_DiagRec **pp, int num)
768 Z_DefaultDiagFormat *r;
770 printf("Diagnostic message(s) from database:\n");
771 for (i = 0; i<num; i++)
773 Z_DiagRec *p = pp[i];
774 if (p->which != Z_DiagRec_defaultFormat)
776 printf("Diagnostic record not in default format.\n");
780 r = p->u.defaultFormat;
781 if (!(ent = oid_getentbyoid(r->diagnosticSetId)) ||
782 ent->oclass != CLASS_DIAGSET || ent->value != VAL_BIB1)
783 printf("Missing or unknown diagset\n");
784 printf(" [%d] %s", *r->condition, diagbib1_str(*r->condition));
787 case Z_DefaultDiagFormat_v2Addinfo:
788 printf (" -- v2 addinfo '%s'\n", r->u.v2Addinfo);
790 case Z_DefaultDiagFormat_v3Addinfo:
791 printf (" -- v3 addinfo '%s'\n", r->u.v3Addinfo);
798 static void display_nameplusrecord(Z_NamePlusRecord *p)
801 printf("[%s]", p->databaseName);
802 if (p->which == Z_NamePlusRecord_surrogateDiagnostic)
803 display_diagrecs(&p->u.surrogateDiagnostic, 1);
804 else if (p->which == Z_NamePlusRecord_databaseRecord)
805 display_record(p->u.databaseRecord);
808 static void display_records(Z_Records *p)
812 if (p->which == Z_Records_NSD)
814 Z_DiagRec dr, *dr_p = &dr;
815 dr.which = Z_DiagRec_defaultFormat;
816 dr.u.defaultFormat = p->u.nonSurrogateDiagnostic;
817 display_diagrecs (&dr_p, 1);
819 else if (p->which == Z_Records_multipleNSD)
820 display_diagrecs (p->u.multipleNonSurDiagnostics->diagRecs,
821 p->u.multipleNonSurDiagnostics->num_diagRecs);
824 printf("Records: %d\n", p->u.databaseOrSurDiagnostics->num_records);
825 for (i = 0; i < p->u.databaseOrSurDiagnostics->num_records; i++)
826 display_nameplusrecord(p->u.databaseOrSurDiagnostics->records[i]);
830 static int send_deleteResultSetRequest(char *arg)
835 Z_APDU *apdu = zget_APDU(out, Z_APDU_deleteResultSetRequest);
836 Z_DeleteResultSetRequest *req = apdu->u.deleteResultSetRequest;
838 req->referenceId = set_refid (out);
840 req->num_resultSetList =
841 sscanf (arg, "%30s %30s %30s %30s %30s %30s %30s %30s",
842 names[0], names[1], names[2], names[3],
843 names[4], names[5], names[6], names[7]);
845 req->deleteFunction = (int *)
846 odr_malloc (out, sizeof(*req->deleteFunction));
847 if (req->num_resultSetList > 0)
849 *req->deleteFunction = Z_DeleteRequest_list;
850 req->resultSetList = (char **)
851 odr_malloc (out, sizeof(*req->resultSetList)*
852 req->num_resultSetList);
853 for (i = 0; i<req->num_resultSetList; i++)
854 req->resultSetList[i] = names[i];
858 *req->deleteFunction = Z_DeleteRequest_all;
859 req->resultSetList = 0;
863 printf("Sent deleteResultSetRequest.\n");
867 static int send_searchRequest(char *arg)
869 Z_APDU *apdu = zget_APDU(out, Z_APDU_searchRequest);
870 Z_SearchRequest *req = apdu->u.searchRequest;
873 struct ccl_rpn_node *rpn = NULL;
876 Z_RPNQuery *RPNquery;
878 YAZ_PQF_Parser pqf_parser;
881 if (queryType == QueryType_CCL2RPN)
883 rpn = ccl_find_str(bibset, arg, &error, &pos);
886 printf("CCL ERROR: %s\n", ccl_err_msg(error));
890 req->referenceId = set_refid (out);
891 if (!strcmp(arg, "@big")) /* strictly for troublemaking */
893 static unsigned char big[2100];
896 /* send a very big referenceid to test transport stack etc. */
897 memset(big, 'A', 2100);
898 bigo.len = bigo.size = 2100;
900 req->referenceId = &bigo;
905 sprintf(setstring, "%d", ++setnumber);
906 req->resultSetName = setstring;
908 *req->smallSetUpperBound = smallSetUpperBound;
909 *req->largeSetLowerBound = largeSetLowerBound;
910 *req->mediumSetPresentNumber = mediumSetPresentNumber;
911 if (smallSetUpperBound > 0 || (largeSetLowerBound > 1 &&
912 mediumSetPresentNumber > 0))
916 prefsyn.proto = protocol;
917 prefsyn.oclass = CLASS_RECSYN;
918 prefsyn.value = recordsyntax;
919 req->preferredRecordSyntax =
920 odr_oiddup(out, oid_ent_to_oid(&prefsyn, oid));
921 req->smallSetElementSetNames =
922 req->mediumSetElementSetNames = elementSetNames;
924 req->num_databaseNames = num_databaseNames;
925 req->databaseNames = databaseNames;
931 case QueryType_Prefix:
932 query.which = Z_Query_type_1;
933 pqf_parser = yaz_pqf_create ();
934 RPNquery = yaz_pqf_parse (pqf_parser, out, arg);
939 int code = yaz_pqf_error (pqf_parser, &pqf_msg, &off);
940 printf("%*s^\n", off+4, "");
941 printf("Prefix query error: %s (code %d)\n", pqf_msg, code);
943 yaz_pqf_destroy (pqf_parser);
946 yaz_pqf_destroy (pqf_parser);
947 query.u.type_1 = RPNquery;
950 query.which = Z_Query_type_2;
951 query.u.type_2 = &ccl_query;
952 ccl_query.buf = (unsigned char*) arg;
953 ccl_query.len = strlen(arg);
955 case QueryType_CCL2RPN:
956 query.which = Z_Query_type_1;
957 RPNquery = ccl_rpn_query(out, rpn);
960 printf ("Couldn't convert from CCL to RPN\n");
963 query.u.type_1 = RPNquery;
964 ccl_rpn_delete (rpn);
967 query.which = Z_Query_type_104;
968 ext = (Z_External *) odr_malloc(out, sizeof(*ext));
969 ext->direct_reference = odr_getoidbystr(out, "1.2.840.10003.16.2");
970 ext->indirect_reference = 0;
972 ext->which = Z_External_CQL;
973 ext->u.cql = odr_strdup(out, arg);
974 query.u.type_104 = ext;
977 printf ("Unsupported query type\n");
982 printf("Sent searchRequest.\n");
986 /* display Query Expression as part of searchResult-1 */
987 static void display_queryExpression (Z_QueryExpression *qe)
991 if (qe->which == Z_QueryExpression_term)
993 if (qe->u.term->queryTerm)
995 Z_Term *term = qe->u.term->queryTerm;
999 printf (" %.*s", term->u.general->len, term->u.general->buf);
1001 case Z_Term_characterString:
1002 printf (" %s", term->u.characterString);
1004 case Z_Term_numeric:
1005 printf (" %d", *term->u.numeric);
1015 /* see if we can find USR:SearchResult-1 */
1016 static void display_searchResult (Z_OtherInformation *o)
1021 for (i = 0; i < o->num_elements; i++)
1023 if (o->list[i]->which == Z_OtherInfo_externallyDefinedInfo)
1025 Z_External *ext = o->list[i]->information.externallyDefinedInfo;
1027 if (ext->which == Z_External_searchResult1)
1030 Z_SearchInfoReport *sr = ext->u.searchResult1;
1031 printf ("SearchResult-1:");
1032 for (j = 0; j < sr->num; j++)
1034 if (!sr->elements[j]->subqueryExpression)
1036 display_queryExpression (
1037 sr->elements[j]->subqueryExpression);
1038 display_queryExpression (
1039 sr->elements[j]->subqueryInterpretation);
1040 display_queryExpression (
1041 sr->elements[j]->subqueryRecommendation);
1042 if (sr->elements[j]->subqueryCount)
1043 printf ("(%d)", *sr->elements[j]->subqueryCount);
1051 static int process_searchResponse(Z_SearchResponse *res)
1053 printf ("Received SearchResponse.\n");
1054 print_refid (res->referenceId);
1055 if (*res->searchStatus)
1056 printf("Search was a success.\n");
1058 printf("Search was a bloomin' failure.\n");
1059 printf("Number of hits: %d", *res->resultCount);
1061 printf (", setno %d", setnumber);
1063 display_searchResult (res->additionalSearchInfo);
1064 printf("records returned: %d\n",
1065 *res->numberOfRecordsReturned);
1066 setno += *res->numberOfRecordsReturned;
1068 display_records(res->records);
1072 static void print_level(int iLevel)
1075 for (i = 0; i < iLevel * 4; i++)
1079 static void print_int(int iLevel, const char *pTag, int *pInt)
1083 print_level(iLevel);
1084 printf("%s: %d\n", pTag, *pInt);
1088 static void print_string(int iLevel, const char *pTag, const char *pString)
1090 if (pString != NULL)
1092 print_level(iLevel);
1093 printf("%s: %s\n", pTag, pString);
1097 static void print_oid(int iLevel, const char *pTag, Odr_oid *pOid)
1103 print_level(iLevel);
1104 printf("%s:", pTag);
1105 for (; *pInt != -1; pInt++)
1106 printf(" %d", *pInt);
1111 static void print_referenceId(int iLevel, Z_ReferenceId *referenceId)
1113 if (referenceId != NULL)
1117 print_level(iLevel);
1118 printf("Ref Id (%d, %d): ", referenceId->len, referenceId->size);
1119 for (i = 0; i < referenceId->len; i++)
1120 printf("%c", referenceId->buf[i]);
1125 static void print_string_or_numeric(int iLevel, const char *pTag, Z_StringOrNumeric *pStringNumeric)
1127 if (pStringNumeric != NULL)
1129 switch (pStringNumeric->which)
1131 case Z_StringOrNumeric_string:
1132 print_string(iLevel, pTag, pStringNumeric->u.string);
1135 case Z_StringOrNumeric_numeric:
1136 print_int(iLevel, pTag, pStringNumeric->u.numeric);
1140 print_level(iLevel);
1141 printf("%s: valid type for Z_StringOrNumeric\n", pTag);
1147 static void print_universe_report_duplicate(
1149 Z_UniverseReportDuplicate *pUniverseReportDuplicate)
1151 if (pUniverseReportDuplicate != NULL)
1153 print_level(iLevel);
1154 printf("Universe Report Duplicate: \n");
1156 print_string_or_numeric(iLevel, "Hit No",
1157 pUniverseReportDuplicate->hitno);
1161 static void print_universe_report_hits(
1163 Z_UniverseReportHits *pUniverseReportHits)
1165 if (pUniverseReportHits != NULL)
1167 print_level(iLevel);
1168 printf("Universe Report Hits: \n");
1170 print_string_or_numeric(iLevel, "Database",
1171 pUniverseReportHits->database);
1172 print_string_or_numeric(iLevel, "Hits", pUniverseReportHits->hits);
1176 static void print_universe_report(int iLevel, Z_UniverseReport *pUniverseReport)
1178 if (pUniverseReport != NULL)
1180 print_level(iLevel);
1181 printf("Universe Report: \n");
1183 print_int(iLevel, "Total Hits", pUniverseReport->totalHits);
1184 switch (pUniverseReport->which)
1186 case Z_UniverseReport_databaseHits:
1187 print_universe_report_hits(iLevel,
1188 pUniverseReport->u.databaseHits);
1191 case Z_UniverseReport_duplicate:
1192 print_universe_report_duplicate(iLevel,
1193 pUniverseReport->u.duplicate);
1197 print_level(iLevel);
1198 printf("Type: %d\n", pUniverseReport->which);
1204 static void print_external(int iLevel, Z_External *pExternal)
1206 if (pExternal != NULL)
1208 print_level(iLevel);
1209 printf("External: \n");
1211 print_oid(iLevel, "Direct Reference", pExternal->direct_reference);
1212 print_int(iLevel, "InDirect Reference", pExternal->indirect_reference);
1213 print_string(iLevel, "Descriptor", pExternal->descriptor);
1214 switch (pExternal->which)
1216 case Z_External_universeReport:
1217 print_universe_report(iLevel, pExternal->u.universeReport);
1221 print_level(iLevel);
1222 printf("Type: %d\n", pExternal->which);
1228 static int process_resourceControlRequest (Z_ResourceControlRequest *req)
1230 printf ("Received ResourceControlRequest.\n");
1231 print_referenceId(1, req->referenceId);
1232 print_int(1, "Suspended Flag", req->suspendedFlag);
1233 print_int(1, "Partial Results Available", req->partialResultsAvailable);
1234 print_int(1, "Response Required", req->responseRequired);
1235 print_int(1, "Triggered Request Flag", req->triggeredRequestFlag);
1236 print_external(1, req->resourceReport);
1240 void process_ESResponse(Z_ExtendedServicesResponse *res)
1243 switch (*res->operationStatus)
1245 case Z_ExtendedServicesResponse_done:
1248 case Z_ExtendedServicesResponse_accepted:
1249 printf ("accepted\n");
1251 case Z_ExtendedServicesResponse_failure:
1252 printf ("failure\n");
1253 display_diagrecs(res->diagnostics, res->num_diagnostics);
1256 printf ("unknown\n");
1258 if ( (*res->operationStatus != Z_ExtendedServicesResponse_failure) &&
1259 (res->num_diagnostics != 0) ) {
1260 display_diagrecs(res->diagnostics, res->num_diagnostics);
1262 print_refid (res->referenceId);
1263 if (res->taskPackage &&
1264 res->taskPackage->which == Z_External_extendedService)
1266 Z_TaskPackage *taskPackage = res->taskPackage->u.extendedService;
1267 Odr_oct *id = taskPackage->targetReference;
1268 Z_External *ext = taskPackage->taskSpecificParameters;
1272 printf ("Target Reference: ");
1273 print_stringn (id->buf, id->len);
1276 if (ext->which == Z_External_update)
1278 Z_IUUpdateTaskPackage *utp = ext->u.update->u.taskPackage;
1279 if (utp && utp->targetPart)
1281 Z_IUTargetPart *targetPart = utp->targetPart;
1284 for (i = 0; i<targetPart->num_taskPackageRecords; i++)
1287 Z_IUTaskPackageRecordStructure *tpr =
1288 targetPart->taskPackageRecords[i];
1289 printf ("task package record %d\n", i+1);
1290 if (tpr->which == Z_IUTaskPackageRecordStructure_record)
1292 display_record (tpr->u.record);
1296 printf ("other type\n");
1304 const char *get_ill_element (void *clientData, const char *element)
1309 static Z_External *create_external_itemRequest()
1311 struct ill_get_ctl ctl;
1312 ILL_ItemRequest *req;
1314 int item_request_size = 0;
1315 char *item_request_buf = 0;
1319 ctl.f = get_ill_element;
1321 req = ill_get_ItemRequest(&ctl, "ill", 0);
1323 printf ("ill_get_ItemRequest failed\n");
1325 if (!ill_ItemRequest (out, &req, 0, 0))
1329 ill_ItemRequest(print, &req, 0, 0);
1332 item_request_buf = odr_getbuf (out, &item_request_size, 0);
1333 if (item_request_buf)
1334 odr_setbuf (out, item_request_buf, item_request_size, 1);
1335 printf ("Couldn't encode ItemRequest, size %d\n", item_request_size);
1342 item_request_buf = odr_getbuf (out, &item_request_size, 0);
1343 oid.proto = PROTO_GENERAL;
1344 oid.oclass = CLASS_GENERAL;
1345 oid.value = VAL_ISO_ILL_1;
1347 r = (Z_External *) odr_malloc (out, sizeof(*r));
1348 r->direct_reference = odr_oiddup(out,oid_getoidbyent(&oid));
1349 r->indirect_reference = 0;
1351 r->which = Z_External_single;
1353 r->u.single_ASN1_type = (Odr_oct *)
1354 odr_malloc (out, sizeof(*r->u.single_ASN1_type));
1355 r->u.single_ASN1_type->buf = (unsigned char *)
1356 odr_malloc (out, item_request_size);
1357 r->u.single_ASN1_type->len = item_request_size;
1358 r->u.single_ASN1_type->size = item_request_size;
1359 memcpy (r->u.single_ASN1_type->buf, item_request_buf,
1362 do_hex_dump(item_request_buf,item_request_size);
1367 static Z_External *create_external_ILL_APDU(int which)
1369 struct ill_get_ctl ctl;
1372 int ill_request_size = 0;
1373 char *ill_request_buf = 0;
1377 ctl.f = get_ill_element;
1379 ill_apdu = ill_get_APDU(&ctl, "ill", 0);
1381 if (!ill_APDU (out, &ill_apdu, 0, 0))
1385 printf ("-------------------\n");
1386 ill_APDU(print, &ill_apdu, 0, 0);
1388 printf ("-------------------\n");
1390 ill_request_buf = odr_getbuf (out, &ill_request_size, 0);
1391 if (ill_request_buf)
1392 odr_setbuf (out, ill_request_buf, ill_request_size, 1);
1393 printf ("Couldn't encode ILL-Request, size %d\n", ill_request_size);
1399 ill_request_buf = odr_getbuf (out, &ill_request_size, 0);
1401 oid.proto = PROTO_GENERAL;
1402 oid.oclass = CLASS_GENERAL;
1403 oid.value = VAL_ISO_ILL_1;
1405 r = (Z_External *) odr_malloc (out, sizeof(*r));
1406 r->direct_reference = odr_oiddup(out,oid_getoidbyent(&oid));
1407 r->indirect_reference = 0;
1409 r->which = Z_External_single;
1411 r->u.single_ASN1_type = (Odr_oct *)
1412 odr_malloc (out, sizeof(*r->u.single_ASN1_type));
1413 r->u.single_ASN1_type->buf = (unsigned char *)
1414 odr_malloc (out, ill_request_size);
1415 r->u.single_ASN1_type->len = ill_request_size;
1416 r->u.single_ASN1_type->size = ill_request_size;
1417 memcpy (r->u.single_ASN1_type->buf, ill_request_buf, ill_request_size);
1418 /* printf ("len = %d\n", ill_request_size); */
1419 /* do_hex_dump(ill_request_buf,ill_request_size); */
1420 /* printf("--- end of extenal\n"); */
1427 static Z_External *create_ItemOrderExternal(const char *type, int itemno)
1429 Z_External *r = (Z_External *) odr_malloc(out, sizeof(Z_External));
1430 oident ItemOrderRequest;
1432 ItemOrderRequest.proto = PROTO_Z3950;
1433 ItemOrderRequest.oclass = CLASS_EXTSERV;
1434 ItemOrderRequest.value = VAL_ITEMORDER;
1436 r->direct_reference = odr_oiddup(out,oid_getoidbyent(&ItemOrderRequest));
1437 r->indirect_reference = 0;
1440 r->which = Z_External_itemOrder;
1442 r->u.itemOrder = (Z_ItemOrder *) odr_malloc(out,sizeof(Z_ItemOrder));
1443 memset(r->u.itemOrder, 0, sizeof(Z_ItemOrder));
1444 r->u.itemOrder->which=Z_IOItemOrder_esRequest;
1446 r->u.itemOrder->u.esRequest = (Z_IORequest *)
1447 odr_malloc(out,sizeof(Z_IORequest));
1448 memset(r->u.itemOrder->u.esRequest, 0, sizeof(Z_IORequest));
1450 r->u.itemOrder->u.esRequest->toKeep = (Z_IOOriginPartToKeep *)
1451 odr_malloc(out,sizeof(Z_IOOriginPartToKeep));
1452 memset(r->u.itemOrder->u.esRequest->toKeep, 0, sizeof(Z_IOOriginPartToKeep));
1453 r->u.itemOrder->u.esRequest->notToKeep = (Z_IOOriginPartNotToKeep *)
1454 odr_malloc(out,sizeof(Z_IOOriginPartNotToKeep));
1455 memset(r->u.itemOrder->u.esRequest->notToKeep, 0, sizeof(Z_IOOriginPartNotToKeep));
1457 r->u.itemOrder->u.esRequest->toKeep->supplDescription = NULL;
1458 r->u.itemOrder->u.esRequest->toKeep->contact = NULL;
1459 r->u.itemOrder->u.esRequest->toKeep->addlBilling = NULL;
1461 r->u.itemOrder->u.esRequest->notToKeep->resultSetItem =
1462 (Z_IOResultSetItem *) odr_malloc(out, sizeof(Z_IOResultSetItem));
1463 memset(r->u.itemOrder->u.esRequest->notToKeep->resultSetItem, 0, sizeof(Z_IOResultSetItem));
1464 r->u.itemOrder->u.esRequest->notToKeep->resultSetItem->resultSetId = "1";
1466 r->u.itemOrder->u.esRequest->notToKeep->resultSetItem->item =
1467 (int *) odr_malloc(out, sizeof(int));
1468 *r->u.itemOrder->u.esRequest->notToKeep->resultSetItem->item = itemno;
1470 if (!strcmp (type, "item") || !strcmp(type, "2"))
1472 printf ("using item-request\n");
1473 r->u.itemOrder->u.esRequest->notToKeep->itemRequest =
1474 create_external_itemRequest();
1476 else if (!strcmp(type, "ill") || !strcmp(type, "1"))
1478 printf ("using ILL-request\n");
1479 r->u.itemOrder->u.esRequest->notToKeep->itemRequest =
1480 create_external_ILL_APDU(ILL_APDU_ILL_Request);
1482 else if (!strcmp(type, "xml") || !strcmp(type, "3"))
1484 const char *xml_buf =
1486 " <type>request</type>\n"
1487 " <libraryNo>000200</libraryNo>\n"
1488 " <borrowerTicketNo> 1212 </borrowerTicketNo>\n"
1490 r->u.itemOrder->u.esRequest->notToKeep->itemRequest =
1491 z_ext_record (out, VAL_TEXT_XML, xml_buf, strlen(xml_buf));
1494 r->u.itemOrder->u.esRequest->notToKeep->itemRequest = 0;
1499 static int send_itemorder(const char *type, int itemno)
1501 Z_APDU *apdu = zget_APDU(out, Z_APDU_extendedServicesRequest);
1502 Z_ExtendedServicesRequest *req = apdu->u.extendedServicesRequest;
1503 oident ItemOrderRequest;
1505 ItemOrderRequest.proto = PROTO_Z3950;
1506 ItemOrderRequest.oclass = CLASS_EXTSERV;
1507 ItemOrderRequest.value = VAL_ITEMORDER;
1508 req->packageType = odr_oiddup(out,oid_getoidbyent(&ItemOrderRequest));
1509 req->packageName = esPackageName;
1511 req->taskSpecificParameters = create_ItemOrderExternal(type, itemno);
1517 static int cmd_update(char *arg)
1519 Z_APDU *apdu = zget_APDU(out, Z_APDU_extendedServicesRequest );
1520 Z_ExtendedServicesRequest *req = apdu->u.extendedServicesRequest;
1523 Z_IUOriginPartToKeep *toKeep;
1524 Z_IUSuppliedRecords *notToKeep;
1526 char action[20], recid[20], fname[80];
1528 Z_External *record_this = 0;
1533 sscanf (arg, "%19s %19s %79s", action, recid, fname);
1535 if (!strcmp (action, "insert"))
1536 action_no = Z_IUOriginPartToKeep_recordInsert;
1537 else if (!strcmp (action, "replace"))
1538 action_no = Z_IUOriginPartToKeep_recordReplace;
1539 else if (!strcmp (action, "delete"))
1540 action_no = Z_IUOriginPartToKeep_recordDelete;
1541 else if (!strcmp (action, "update"))
1542 action_no = Z_IUOriginPartToKeep_specialUpdate;
1545 printf ("Bad action: %s\n", action);
1546 printf ("Possible values: insert, replace, delete, update\n");
1554 stat (fname, &status);
1555 if (S_ISREG(status.st_mode) && (inf = fopen(fname, "r")))
1557 size_t len = status.st_size;
1558 char *buf = (char *) xmalloc (len);
1560 fread (buf, 1, len, inf);
1564 record_this = z_ext_record (out, VAL_TEXT_XML, buf, len);
1570 printf ("File %s doesn't exist\n", fname);
1578 printf ("No last record (update ignored)\n");
1581 record_this = record_last;
1584 update_oid.proto = PROTO_Z3950;
1585 update_oid.oclass = CLASS_EXTSERV;
1586 update_oid.value = VAL_DBUPDATE;
1587 oid_ent_to_oid (&update_oid, oid);
1588 req->packageType = odr_oiddup(out,oid);
1589 req->packageName = esPackageName;
1591 req->referenceId = set_refid (out);
1593 r = req->taskSpecificParameters = (Z_External *)
1594 odr_malloc (out, sizeof(*r));
1595 r->direct_reference = odr_oiddup(out,oid);
1596 r->indirect_reference = 0;
1598 r->which = Z_External_update;
1599 r->u.update = (Z_IUUpdate *) odr_malloc(out, sizeof(*r->u.update));
1600 r->u.update->which = Z_IUUpdate_esRequest;
1601 r->u.update->u.esRequest = (Z_IUUpdateEsRequest *)
1602 odr_malloc(out, sizeof(*r->u.update->u.esRequest));
1603 toKeep = r->u.update->u.esRequest->toKeep = (Z_IUOriginPartToKeep *)
1604 odr_malloc(out, sizeof(*r->u.update->u.esRequest->toKeep));
1605 toKeep->databaseName = databaseNames[0];
1607 toKeep->elementSetName = 0;
1608 toKeep->actionQualifier = 0;
1609 toKeep->action = (int *) odr_malloc(out, sizeof(*toKeep->action));
1610 *toKeep->action = action_no;
1612 notToKeep = r->u.update->u.esRequest->notToKeep = (Z_IUSuppliedRecords *)
1613 odr_malloc(out, sizeof(*r->u.update->u.esRequest->notToKeep));
1615 notToKeep->elements = (Z_IUSuppliedRecords_elem **)
1616 odr_malloc(out, sizeof(*notToKeep->elements));
1617 notToKeep->elements[0] = (Z_IUSuppliedRecords_elem *)
1618 odr_malloc(out, sizeof(**notToKeep->elements));
1619 notToKeep->elements[0]->which = Z_IUSuppliedRecords_elem_opaque;
1622 notToKeep->elements[0]->u.opaque = (Odr_oct *)
1623 odr_malloc (out, sizeof(Odr_oct));
1624 notToKeep->elements[0]->u.opaque->buf = (unsigned char *) recid;
1625 notToKeep->elements[0]->u.opaque->size = strlen(recid);
1626 notToKeep->elements[0]->u.opaque->len = strlen(recid);
1629 notToKeep->elements[0]->u.opaque = 0;
1630 notToKeep->elements[0]->supplementalId = 0;
1631 notToKeep->elements[0]->correlationInfo = 0;
1632 notToKeep->elements[0]->record = record_this;
1639 static int cmd_itemorder(char *arg)
1644 if (sscanf (arg, "%10s %d", type, &itemno) != 2)
1647 printf("Item order request\n");
1649 send_itemorder(type, itemno);
1653 static int cmd_find(char *arg)
1657 printf("Find what?\n");
1665 printf("Not connected yet\n");
1669 if (!send_searchRequest(arg))
1674 static int cmd_delete(char *arg)
1678 printf("Not connected yet\n");
1681 if (!send_deleteResultSetRequest(arg))
1686 static int cmd_ssub(char *arg)
1688 if (!(smallSetUpperBound = atoi(arg)))
1693 static int cmd_lslb(char *arg)
1695 if (!(largeSetLowerBound = atoi(arg)))
1700 static int cmd_mspn(char *arg)
1702 if (!(mediumSetPresentNumber = atoi(arg)))
1707 static int cmd_status(char *arg)
1709 printf("smallSetUpperBound: %d\n", smallSetUpperBound);
1710 printf("largeSetLowerBound: %d\n", largeSetLowerBound);
1711 printf("mediumSetPresentNumber: %d\n", mediumSetPresentNumber);
1715 static int cmd_setnames(char *arg)
1717 if (*arg == '1') /* enable ? */
1719 else if (*arg == '0') /* disable ? */
1721 else if (setnumber < 0) /* no args, toggle .. */
1727 printf("Set numbering enabled.\n");
1729 printf("Set numbering disabled.\n");
1733 /* PRESENT SERVICE ----------------------------- */
1735 static int send_presentRequest(char *arg)
1737 Z_APDU *apdu = zget_APDU(out, Z_APDU_presentRequest);
1738 Z_PresentRequest *req = apdu->u.presentRequest;
1739 Z_RecordComposition compo;
1744 char setstring[100];
1746 req->referenceId = set_refid (out);
1747 if ((p = strchr(arg, '+')))
1754 if (p && (p=strchr(p+1, '+')))
1756 strcpy (setstring, p+1);
1757 req->resultSetId = setstring;
1759 else if (setnumber >= 0)
1761 sprintf(setstring, "%d", setnumber);
1762 req->resultSetId = setstring;
1764 req->resultSetStartPoint = &setno;
1765 req->numberOfRecordsRequested = &nos;
1766 prefsyn.proto = protocol;
1767 prefsyn.oclass = CLASS_RECSYN;
1768 prefsyn.value = recordsyntax;
1769 req->preferredRecordSyntax =
1770 odr_oiddup (out, oid_ent_to_oid(&prefsyn, oid));
1772 if (schema != VAL_NONE)
1776 prefschema.proto = protocol;
1777 prefschema.oclass = CLASS_SCHEMA;
1778 prefschema.value = schema;
1780 req->recordComposition = &compo;
1781 compo.which = Z_RecordComp_complex;
1782 compo.u.complex = (Z_CompSpec *)
1783 odr_malloc(out, sizeof(*compo.u.complex));
1784 compo.u.complex->selectAlternativeSyntax = (bool_t *)
1785 odr_malloc(out, sizeof(bool_t));
1786 *compo.u.complex->selectAlternativeSyntax = 0;
1788 compo.u.complex->generic = (Z_Specification *)
1789 odr_malloc(out, sizeof(*compo.u.complex->generic));
1790 compo.u.complex->generic->which = Z_Schema_oid;
1791 compo.u.complex->generic->schema.oid = (Odr_oid *)
1792 odr_oiddup(out, oid_ent_to_oid(&prefschema, oid));
1793 if (!compo.u.complex->generic->schema.oid)
1795 /* OID wasn't a schema! Try record syntax instead. */
1796 prefschema.oclass = CLASS_RECSYN;
1797 compo.u.complex->generic->schema.oid = (Odr_oid *)
1798 odr_oiddup(out, oid_ent_to_oid(&prefschema, oid));
1800 if (!elementSetNames)
1801 compo.u.complex->generic->elementSpec = 0;
1804 compo.u.complex->generic->elementSpec = (Z_ElementSpec *)
1805 odr_malloc(out, sizeof(Z_ElementSpec));
1806 compo.u.complex->generic->elementSpec->which =
1807 Z_ElementSpec_elementSetName;
1808 compo.u.complex->generic->elementSpec->u.elementSetName =
1809 elementSetNames->u.generic;
1811 compo.u.complex->num_dbSpecific = 0;
1812 compo.u.complex->dbSpecific = 0;
1813 compo.u.complex->num_recordSyntax = 0;
1814 compo.u.complex->recordSyntax = 0;
1816 else if (elementSetNames)
1818 req->recordComposition = &compo;
1819 compo.which = Z_RecordComp_simple;
1820 compo.u.simple = elementSetNames;
1823 printf("Sent presentRequest (%d+%d).\n", setno, nos);
1827 static void close_session (void)
1833 nmem_destroy (session_mem);
1839 void process_close(Z_Close *req)
1841 Z_APDU *apdu = zget_APDU(out, Z_APDU_close);
1842 Z_Close *res = apdu->u.close;
1844 static char *reasons[] =
1849 "cost limit reached",
1851 "security violation",
1858 printf("Reason: %s, message: %s\n", reasons[*req->closeReason],
1859 req->diagnosticInformation ? req->diagnosticInformation : "NULL");
1864 *res->closeReason = Z_Close_finished;
1866 printf("Sent response.\n");
1871 static int cmd_show(char *arg)
1875 printf("Not connected yet\n");
1878 if (!send_presentRequest(arg))
1883 int cmd_quit(char *arg)
1885 printf("See you later, alligator.\n");
1891 int cmd_cancel(char *arg)
1893 Z_APDU *apdu = zget_APDU(out, Z_APDU_triggerResourceControlRequest);
1894 Z_TriggerResourceControlRequest *req =
1895 apdu->u.triggerResourceControlRequest;
1900 printf("Session not initialized yet\n");
1903 if (!ODR_MASK_GET(session->options, Z_Options_triggerResourceCtrl))
1905 printf("Target doesn't support cancel (trigger resource ctrl)\n");
1908 *req->requestedAction = Z_TriggerResourceCtrl_cancel;
1909 req->resultSetWanted = &rfalse;
1912 printf("Sent cancel request\n");
1916 int send_scanrequest(const char *query, int pp, int num, const char *term)
1918 Z_APDU *apdu = zget_APDU(out, Z_APDU_scanRequest);
1919 Z_ScanRequest *req = apdu->u.scanRequest;
1922 if (queryType == QueryType_CCL2RPN)
1926 struct ccl_rpn_node *rpn;
1928 rpn = ccl_find_str (bibset, query, &error, &pos);
1931 printf("CCL ERROR: %s\n", ccl_err_msg(error));
1934 bib1.proto = PROTO_Z3950;
1935 bib1.oclass = CLASS_ATTSET;
1936 bib1.value = VAL_BIB1;
1937 req->attributeSet = oid_ent_to_oid (&bib1, oid);
1938 if (!(req->termListAndStartPoint = ccl_scan_query (out, rpn)))
1940 printf("Couldn't convert CCL to Scan term\n");
1943 ccl_rpn_delete (rpn);
1947 YAZ_PQF_Parser pqf_parser = yaz_pqf_create ();
1949 if (!(req->termListAndStartPoint =
1950 yaz_pqf_scan(pqf_parser, out, &req->attributeSet, query)))
1952 const char *pqf_msg;
1954 int code = yaz_pqf_error (pqf_parser, &pqf_msg, &off);
1955 printf("%*s^\n", off+7, "");
1956 printf("Prefix query error: %s (code %d)\n", pqf_msg, code);
1957 yaz_pqf_destroy (pqf_parser);
1960 yaz_pqf_destroy (pqf_parser);
1964 if (req->termListAndStartPoint->term &&
1965 req->termListAndStartPoint->term->which == Z_Term_general &&
1966 req->termListAndStartPoint->term->u.general)
1968 req->termListAndStartPoint->term->u.general->buf =
1969 (unsigned char *) odr_strdup(out, term);
1970 req->termListAndStartPoint->term->u.general->len =
1971 req->termListAndStartPoint->term->u.general->size =
1975 req->referenceId = set_refid (out);
1976 req->num_databaseNames = num_databaseNames;
1977 req->databaseNames = databaseNames;
1978 req->numberOfTermsRequested = #
1979 req->preferredPositionInResponse = &pp;
1984 int send_sortrequest(char *arg, int newset)
1986 Z_APDU *apdu = zget_APDU(out, Z_APDU_sortRequest);
1987 Z_SortRequest *req = apdu->u.sortRequest;
1988 Z_SortKeySpecList *sksl = (Z_SortKeySpecList *)
1989 odr_malloc (out, sizeof(*sksl));
1993 sprintf (setstring, "%d", setnumber);
1995 sprintf (setstring, "default");
1997 req->referenceId = set_refid (out);
1999 req->num_inputResultSetNames = 1;
2000 req->inputResultSetNames = (Z_InternationalString **)
2001 odr_malloc (out, sizeof(*req->inputResultSetNames));
2002 req->inputResultSetNames[0] = odr_strdup (out, setstring);
2004 if (newset && setnumber >= 0)
2005 sprintf (setstring, "%d", ++setnumber);
2007 req->sortedResultSetName = odr_strdup (out, setstring);
2009 req->sortSequence = yaz_sort_spec (out, arg);
2010 if (!req->sortSequence)
2012 printf ("Missing sort specifications\n");
2019 void display_term(Z_TermInfo *t)
2021 if (t->term->which == Z_Term_general)
2023 printf("%.*s", t->term->u.general->len, t->term->u.general->buf);
2024 sprintf(last_scan_line, "%.*s", t->term->u.general->len,
2025 t->term->u.general->buf);
2028 printf("Term (not general)");
2029 if (t->globalOccurrences)
2030 printf (" (%d)\n", *t->globalOccurrences);
2035 void process_scanResponse(Z_ScanResponse *res)
2038 Z_Entry **entries = NULL;
2039 int num_entries = 0;
2041 printf("Received ScanResponse\n");
2042 print_refid (res->referenceId);
2043 printf("%d entries", *res->numberOfEntriesReturned);
2044 if (res->positionOfTerm)
2045 printf (", position=%d", *res->positionOfTerm);
2047 if (*res->scanStatus != Z_Scan_success)
2048 printf("Scan returned code %d\n", *res->scanStatus);
2051 if ((entries = res->entries->entries))
2052 num_entries = res->entries->num_entries;
2053 for (i = 0; i < num_entries; i++)
2055 int pos_term = res->positionOfTerm ? *res->positionOfTerm : -1;
2056 if (entries[i]->which == Z_Entry_termInfo)
2058 printf("%c ", i + 1 == pos_term ? '*' : ' ');
2059 display_term(entries[i]->u.termInfo);
2062 display_diagrecs(&entries[i]->u.surrogateDiagnostic, 1);
2064 if (res->entries->nonsurrogateDiagnostics)
2065 display_diagrecs (res->entries->nonsurrogateDiagnostics,
2066 res->entries->num_nonsurrogateDiagnostics);
2069 void process_sortResponse(Z_SortResponse *res)
2071 printf("Received SortResponse: status=");
2072 switch (*res->sortStatus)
2074 case Z_SortStatus_success:
2075 printf ("success"); break;
2076 case Z_SortStatus_partial_1:
2077 printf ("partial"); break;
2078 case Z_SortStatus_failure:
2079 printf ("failure"); break;
2081 printf ("unknown (%d)", *res->sortStatus);
2084 print_refid (res->referenceId);
2085 if (res->diagnostics)
2086 display_diagrecs(res->diagnostics,
2087 res->num_diagnostics);
2090 void process_deleteResultSetResponse (Z_DeleteResultSetResponse *res)
2092 printf("Got deleteResultSetResponse status=%d\n",
2093 *res->deleteOperationStatus);
2094 if (res->deleteListStatuses)
2097 for (i = 0; i < res->deleteListStatuses->num; i++)
2099 printf ("%s status=%d\n", res->deleteListStatuses->elements[i]->id,
2100 *res->deleteListStatuses->elements[i]->status);
2105 int cmd_sort_generic(char *arg, int newset)
2109 printf("Session not initialized yet\n");
2112 if (!ODR_MASK_GET(session->options, Z_Options_sort))
2114 printf("Target doesn't support sort\n");
2119 if (send_sortrequest(arg, newset) < 0)
2126 int cmd_sort(char *arg)
2128 return cmd_sort_generic (arg, 0);
2131 int cmd_sort_newset (char *arg)
2133 return cmd_sort_generic (arg, 1);
2136 int cmd_scan(char *arg)
2143 printf("Session not initialized yet\n");
2147 if (!ODR_MASK_GET(session->options, Z_Options_scan))
2149 printf("Target doesn't support scan\n");
2154 strcpy (last_scan_query, arg);
2155 if (send_scanrequest(arg, 1, 20, 0) < 0)
2160 if (send_scanrequest(last_scan_query, 1, 20, last_scan_line) < 0)
2166 int cmd_schema(char *arg)
2173 schema = oid_getvalbyname (arg);
2174 if (schema == VAL_NONE)
2176 printf ("unknown schema\n");
2182 int cmd_format(char *arg)
2187 printf("Usage: format <recordsyntax>\n");
2190 nsyntax = oid_getvalbyname (arg);
2191 if (strcmp(arg, "none") && nsyntax == VAL_NONE)
2193 printf ("unknown record syntax\n");
2196 recordsyntax = nsyntax;
2200 int cmd_elements(char *arg)
2202 static Z_ElementSetNames esn;
2203 static char what[100];
2207 elementSetNames = 0;
2211 esn.which = Z_ElementSetNames_generic;
2212 esn.u.generic = what;
2213 elementSetNames = &esn;
2217 int cmd_attributeset(char *arg)
2223 printf("Usage: attributeset <setname>\n");
2226 sscanf(arg, "%s", what);
2227 if (p_query_attset (what))
2229 printf("Unknown attribute set name\n");
2235 int cmd_querytype (char *arg)
2237 if (!strcmp (arg, "ccl"))
2238 queryType = QueryType_CCL;
2239 else if (!strcmp (arg, "prefix") || !strcmp(arg, "rpn"))
2240 queryType = QueryType_Prefix;
2241 else if (!strcmp (arg, "ccl2rpn") || !strcmp (arg, "cclrpn"))
2242 queryType = QueryType_CCL2RPN;
2243 else if (!strcmp(arg, "cql"))
2244 queryType = QueryType_CQL;
2247 printf ("Querytype must be one of:\n");
2248 printf (" prefix - Prefix query\n");
2249 printf (" ccl - CCL query\n");
2250 printf (" ccl2rpn - CCL query converted to RPN\n");
2251 printf (" cql - CQL\n");
2257 int cmd_refid (char *arg)
2263 refid = (char *) xmalloc (strlen(arg)+1);
2264 strcpy (refid, arg);
2269 int cmd_close(char *arg)
2276 apdu = zget_APDU(out, Z_APDU_close);
2277 req = apdu->u.close;
2278 *req->closeReason = Z_Close_finished;
2280 printf("Sent close request.\n");
2285 int cmd_packagename(char* arg)
2287 xfree (esPackageName);
2288 esPackageName = NULL;
2291 esPackageName = (char *) xmalloc (strlen(arg)+1);
2292 strcpy (esPackageName, arg);
2297 int cmd_proxy(char* arg)
2308 yazProxy = (char *) xmalloc (strlen(arg)+1);
2309 strcpy (yazProxy, arg);
2314 int cmd_charset(char* arg)
2316 char l1[30], l2[30];
2319 if (sscanf(arg, "%29s %29s", l1, l2) < 1)
2321 printf("Current character set is `%s'\n", (yazCharset) ? yazCharset:NULL);
2327 yazCharset = xstrdup(l1);
2330 odr_set_charset (out, l1, l2);
2331 odr_set_charset (in, l2, l1);
2336 int cmd_lang(char* arg)
2339 printf("Current language is `%s'\n", (yazLang)?yazLang:NULL);
2346 yazLang = (char *) xmalloc (strlen(arg)+1);
2347 strcpy (yazLang, arg);
2352 int cmd_source(char* arg)
2354 /* first should open the file and read one line at a time.. */
2356 char line[1024], *cp;
2359 char* args_end=(arg)+strlen(arg)-1;
2360 while(isspace(*args_end))
2365 REMOVE_TAILING_BLANKS(arg);
2368 fprintf(stderr,"Error in source command use a filename\n");
2372 includeFile = fopen (arg, "r");
2375 fprintf(stderr,"Unable to open file %s for reading\n",arg);
2379 while(!feof(includeFile)) {
2380 memset(line,0,sizeof(line));
2381 fgets(line,sizeof(line),includeFile);
2383 if(strlen(line) < 2) continue;
2384 if(line[0] == '#') continue;
2386 if ((cp = strrchr (line, '\n')))
2389 process_cmd_line(line);
2392 if(fclose(includeFile)<0) {
2393 perror("unable to close include file");
2399 int cmd_subshell(char* args)
2404 system(getenv("SHELL"));
2410 int cmd_set_apdufile(char* arg)
2412 REMOVE_TAILING_BLANKS(arg);
2414 if(apdu_file && apdu_file != stderr) { /* don't close stdout*/
2415 perror("unable to close apdu log file");
2423 if(!strcmp(arg,"-"))
2426 apdu_file=fopen(arg, "a");
2429 perror("unable to open apdu log file no apdu log loaded");
2431 odr_setprint(print, apdu_file);
2437 int cmd_set_cclfile(char* arg)
2441 REMOVE_TAILING_BLANKS(arg);
2443 bibset = ccl_qual_mk ();
2444 inf = fopen (arg, "r");
2447 ccl_qual_file (bibset, inf);
2450 strcpy(ccl_fields,arg);
2455 int cmd_set_auto_reconnect(char* arg)
2457 REMOVE_TAILING_BLANKS(arg);
2459 if(strlen(arg)==0) {
2460 auto_reconnect = ! auto_reconnect;
2461 } else if(strcmp(arg,"on")==0) {
2463 } else if(strcmp(arg,"off")==0) {
2466 printf("Error use on or off\n");
2471 printf("Set auto reconnect enabled.\n");
2473 printf("Set auto reconnect disabled.\n");
2478 int cmd_set_marcdump(char* arg)
2480 if(marcdump && marcdump != stderr) { /* don't close stdout*/
2481 perror("unable to close apdu log file");
2489 if(!strcmp(arg,"-"))
2492 marcdump=fopen(arg, "a");
2495 perror("unable to open apdu marcdump file no marcdump done\n");
2501 int cmd_set_proxy(char* arg)
2503 if(yazProxy) free(yazProxy);
2506 if(strlen(arg) > 1) {
2507 yazProxy=strdup(arg);
2513 this command takes 3 arge {name class oid}
2515 int cmd_register_oid(char* args) {
2520 {"appctx",CLASS_APPCTX},
2521 {"absyn",CLASS_ABSYN},
2522 {"attset",CLASS_ATTSET},
2523 {"transyn",CLASS_TRANSYN},
2524 {"diagset",CLASS_DIAGSET},
2525 {"recsyn",CLASS_RECSYN},
2526 {"resform",CLASS_RESFORM},
2527 {"accform",CLASS_ACCFORM},
2528 {"extserv",CLASS_EXTSERV},
2529 {"userinfo",CLASS_USERINFO},
2530 {"elemspec",CLASS_ELEMSPEC},
2531 {"varset",CLASS_VARSET},
2532 {"schema",CLASS_SCHEMA},
2533 {"tagset",CLASS_TAGSET},
2534 {"general",CLASS_GENERAL},
2535 {0,(enum oid_class) 0}
2537 char oname_str[101], oclass_str[101], oid_str[101];
2540 oid_class oidclass = CLASS_GENERAL;
2541 int val = 0, oid[OID_SIZE];
2542 struct oident * new_oident=NULL;
2544 if (sscanf (args, "%100[^ ] %100[^ ] %100s",
2545 oname_str,oclass_str, oid_str) < 1) {
2546 printf("Error in regristrate command \n");
2550 for (i = 0; oid_classes[i].className; i++) {
2551 if (!strcmp(oid_classes[i].className, oclass_str))
2553 oidclass=oid_classes[i].oclass;
2558 if(!(oid_classes[i].className)) {
2559 printf("Unknonwn oid class %s\n",oclass_str);
2567 while (isdigit (*name))
2569 val = val*10 + (*name - '0');
2582 new_oident=oid_addent (oid,PROTO_GENERAL,oidclass,oname_str,VAL_DYNAMIC);
2583 if(strcmp(new_oident->desc,oname_str)) {
2584 fprintf(stderr,"oid is already named as %s, regristration faild\n",
2590 int cmd_push_command(char* arg)
2592 #if HAVE_READLINE_HISTORY_H
2596 fprintf(stderr,"Not compiled with the readline/history module\n");
2601 void source_rcfile()
2603 /* Look for a $HOME/.yazclientrc and source it if it exists */
2604 struct stat statbuf;
2606 char* homedir=getenv("HOME");
2608 if(!homedir) return;
2610 sprintf(buffer,"%s/.yazclientrc",homedir);
2612 if(stat(buffer,&statbuf)==0) {
2616 if(stat(".yazclientrc",&statbuf)==0) {
2617 cmd_source(".yazclientrc");
2622 static void initialize(void)
2627 if (!(out = odr_createmem(ODR_ENCODE)) ||
2628 !(in = odr_createmem(ODR_DECODE)) ||
2629 !(print = odr_createmem(ODR_PRINT)))
2631 fprintf(stderr, "failed to allocate ODR streams\n");
2636 setvbuf(stdout, 0, _IONBF, 0);
2638 odr_setprint(print, apdu_file);
2640 bibset = ccl_qual_mk ();
2641 inf = fopen (ccl_fields, "r");
2644 ccl_qual_file (bibset, inf);
2647 cmd_base("Default");
2649 #if HAVE_READLINE_READLINE_H
2650 rl_attempted_completion_function = (CPPFunction*)readline_completer;
2654 for(i=0; i<maxOtherInfosSupported; ++i) {
2655 extraOtherInfos[i].oidval = -1;
2662 #if HAVE_GETTIMEOFDAY
2663 struct timeval tv_start, tv_end;
2666 void wait_and_handle_responce()
2671 int netbufferlen = 0;
2679 if ((res = cs_get(conn, &netbuffer, &netbufferlen)) < 0)
2681 printf("Target closed connection\n");
2687 printf("Target closed connection.\n");
2691 odr_reset(in); /* release APDU from last round */
2693 odr_setbuf(in, netbuffer, res, 0);
2694 if (!z_APDU(in, &apdu, 0, 0))
2696 odr_perror(in, "Decoding incoming APDU");
2697 fprintf(stderr, "[Near %d]\n", odr_offset(in));
2698 fprintf(stderr, "Packet dump:\n---------\n");
2699 odr_dumpBER(stderr, netbuffer, res);
2700 fprintf(stderr, "---------\n");
2702 z_APDU(print, &apdu, 0, 0);
2706 if (apdu_file && !z_APDU(print, &apdu, 0, 0))
2708 odr_perror(print, "Failed to print incoming APDU");
2714 case Z_APDU_initResponse:
2715 process_initResponse(apdu->u.initResponse);
2717 case Z_APDU_searchResponse:
2718 process_searchResponse(apdu->u.searchResponse);
2720 case Z_APDU_scanResponse:
2721 process_scanResponse(apdu->u.scanResponse);
2723 case Z_APDU_presentResponse:
2724 print_refid (apdu->u.presentResponse->referenceId);
2726 *apdu->u.presentResponse->numberOfRecordsReturned;
2727 if (apdu->u.presentResponse->records)
2728 display_records(apdu->u.presentResponse->records);
2730 printf("No records.\n");
2731 printf ("nextResultSetPosition = %d\n",
2732 *apdu->u.presentResponse->nextResultSetPosition);
2734 case Z_APDU_sortResponse:
2735 process_sortResponse(apdu->u.sortResponse);
2737 case Z_APDU_extendedServicesResponse:
2738 printf("Got extended services response\n");
2739 process_ESResponse(apdu->u.extendedServicesResponse);
2742 printf("Target has closed the association.\n");
2743 process_close(apdu->u.close);
2745 case Z_APDU_resourceControlRequest:
2746 process_resourceControlRequest
2747 (apdu->u.resourceControlRequest);
2749 case Z_APDU_deleteResultSetResponse:
2750 process_deleteResultSetResponse(apdu->u.
2751 deleteResultSetResponse);
2754 printf("Received unknown APDU type (%d).\n",
2759 while (conn && cs_more(conn));
2760 #if HAVE_GETTIMEOFDAY
2761 gettimeofday (&tv_end, 0);
2763 printf ("S/U S/U=%ld/%ld %ld/%ld",
2764 (long) tv_start.tv_sec,
2765 (long) tv_start.tv_usec,
2766 (long) tv_end.tv_sec,
2767 (long) tv_end.tv_usec);
2769 printf ("Elapsed: %.6f\n",
2770 (double) tv_end.tv_usec / 1e6 + tv_end.tv_sec -
2771 ((double) tv_start.tv_usec / 1e6 + tv_start.tv_sec));
2778 int cmd_cclparse(char* arg)
2781 struct ccl_rpn_node *rpn=NULL;
2784 rpn = ccl_find_str (bibset, arg, &error, &pos);
2787 printf ("%*s^ - ", 3+strlen(last_cmd)+1+pos, " ");
2788 printf ("%s\n", ccl_err_msg (error));
2794 ccl_pr_tree(rpn, stdout);
2798 ccl_rpn_delete(rpn);
2806 int cmd_set_otherinfo(char* args)
2808 char oid[101], otherinfoString[101];
2813 sscan_res = sscanf (args, "%d %100[^ ] %100s", &otherinfoNo, oid, otherinfoString);
2815 /* reset this otherinfo */
2816 if(otherinfoNo>=maxOtherInfosSupported) {
2817 printf("Error otherinfo index to large (%d>%d)\n",otherinfoNo,maxOtherInfosSupported);
2819 extraOtherInfos[otherinfoNo].oidval = -1;
2820 if(extraOtherInfos[otherinfoNo].value) free(extraOtherInfos[otherinfoNo].value);
2824 printf("Error in set_otherinfo command \n");
2828 if(otherinfoNo>=maxOtherInfosSupported) {
2829 printf("Error otherinfo index to large (%d>%d)\n",otherinfoNo,maxOtherInfosSupported);
2833 oidval = oid_getvalbyname (oid);
2835 printf("Error in set_otherinfo command unknown oid %s \n",oid);
2838 extraOtherInfos[otherinfoNo].oidval = oidval;
2839 if(extraOtherInfos[otherinfoNo].value) free(extraOtherInfos[otherinfoNo].value);
2840 extraOtherInfos[otherinfoNo].value = strdup(otherinfoString);
2845 int cmd_list_otherinfo(char* args)
2849 if(strlen(args)>0) {
2851 if( i >= maxOtherInfosSupported ) {
2852 printf("Error otherinfo index to large (%d>%d)\n",i,maxOtherInfosSupported);
2856 if(extraOtherInfos[i].oidval != -1)
2857 printf(" otherinfo %d %s %s\n",
2859 yaz_z3950_oid_value_to_str(
2860 (enum oid_value) extraOtherInfos[i].oidval,
2862 extraOtherInfos[i].value);
2865 for(i=0; i<maxOtherInfosSupported; ++i) {
2866 if(extraOtherInfos[i].oidval != -1)
2867 printf(" otherinfo %d %s %s\n",
2869 yaz_z3950_oid_value_to_str(
2870 (enum oid_value) extraOtherInfos[i].oidval,
2872 extraOtherInfos[i].value);
2880 int cmd_list_all(char* args) {
2883 /* connection options */
2885 printf("Connected to : %s\n",last_open_command);
2887 if(last_open_command)
2888 printf("Not connected to : %s\n",last_open_command);
2890 printf("Not connected : \n");
2893 if(yazProxy) printf("using proxy : %s\n",yazProxy);
2895 printf("auto_reconnect : %s\n",auto_reconnect?"on":"off");
2898 printf("Authentication : none\n");
2900 switch(auth->which) {
2901 case Z_IdAuthentication_idPass:
2902 printf("Authentication : IdPass\n");
2903 printf(" Login User : %s\n",auth->u.idPass->userId?auth->u.idPass->userId:"");
2904 printf(" Login Group : %s\n",auth->u.idPass->groupId?auth->u.idPass->groupId:"");
2905 printf(" Password : %s\n",auth->u.idPass->password?auth->u.idPass->password:"");
2907 case Z_IdAuthentication_open:
2908 printf("Authentication : psOpen\n");
2909 printf(" Open string : %s\n",auth->u.open);
2912 printf("Authentication : Unknown\n");
2915 if ( yazCharset ) printf("Character set : `%s'\n", (yazCharset) ? yazCharset:NULL);
2919 for (i = 0; i<num_databaseNames; i++) printf("%s ",databaseNames[i]);
2923 printf("CCL file : %s\n",ccl_fields);
2924 printf("Query type : %s\n",query_type_as_string(queryType));
2926 printf("Named Result Sets : %s\n",setnumber==-1?"off":"on");
2928 /* piggy back options */
2929 printf("ssub/lslb/mspn : %d/%d/%d\n",smallSetUpperBound,largeSetLowerBound,mediumSetPresentNumber);
2931 /* print present related options */
2932 printf("Format : %s\n",yaz_z3950_oid_value_to_str(recordsyntax,CLASS_RECSYN));
2933 printf("Schema : %s\n",yaz_z3950_oid_value_to_str(schema,CLASS_SCHEMA));
2934 printf("Elements : %s\n",elementSetNames?elementSetNames->u.generic:"");
2936 /* loging options */
2937 printf("APDU log : %s\n",apdu_file?"on":"off");
2938 printf("Record log : %s\n",marcdump?"on":"off");
2941 printf("Other Info: \n");
2942 cmd_list_otherinfo("");
2947 int cmd_clear_otherinfo(char* args)
2949 if(strlen(args)>0) {
2951 otherinfoNo = atoi(args);
2952 if( otherinfoNo >= maxOtherInfosSupported ) {
2953 printf("Error otherinfo index to large (%d>%d)\n",otherinfoNo,maxOtherInfosSupported);
2957 if(extraOtherInfos[otherinfoNo].oidval != -1) {
2958 /* only clear if set. */
2959 extraOtherInfos[otherinfoNo].oidval=-1;
2960 free(extraOtherInfos[otherinfoNo].value);
2965 for(i=0; i<maxOtherInfosSupported; ++i) {
2966 if (extraOtherInfos[i].oidval!=-1 ) {
2967 extraOtherInfos[i].oidval=-1;
2968 free(extraOtherInfos[i].value);
2975 static int cmd_help (char *line);
2977 typedef char *(*completerFunctionType)(const char *text, int state);
2981 int (*fun)(char *arg);
2983 completerFunctionType rl_completerfunction;
2984 int complete_filenames;
2985 char **local_tabcompletes;
2987 {"open", cmd_open, "('tcp'|'ssl')':<host>[':'<port>][/<db>]",NULL,0,NULL},
2988 {"quit", cmd_quit, "",NULL,0,NULL},
2989 {"find", cmd_find, "<query>",NULL,0,NULL},
2990 {"delete", cmd_delete, "<setname>",NULL,0,NULL},
2991 {"base", cmd_base, "<base-name>",NULL,0,NULL},
2992 {"show", cmd_show, "<rec#>['+'<#recs>['+'<setname>]]",NULL,0,NULL},
2993 {"scan", cmd_scan, "<term>",NULL,0,NULL},
2994 {"sort", cmd_sort, "<sortkey> <flag> <sortkey> <flag> ...",NULL,0,NULL},
2995 {"sort+", cmd_sort_newset, "<sortkey> <flag> <sortkey> <flag> ...",NULL,0,NULL},
2996 {"authentication", cmd_authentication, "<acctstring>",NULL,0,NULL},
2997 {"lslb", cmd_lslb, "<largeSetLowerBound>",NULL,0,NULL},
2998 {"ssub", cmd_ssub, "<smallSetUpperBound>",NULL,0,NULL},
2999 {"mspn", cmd_mspn, "<mediumSetPresentNumber>",NULL,0,NULL},
3000 {"status", cmd_status, "",NULL,0,NULL},
3001 {"setnames", cmd_setnames, "",NULL,0,NULL},
3002 {"cancel", cmd_cancel, "",NULL,0,NULL},
3003 {"format", cmd_format, "<recordsyntax>",complete_format,0,NULL},
3004 {"schema", cmd_schema, "<schema>",complete_schema,0,NULL},
3005 {"elements", cmd_elements, "<elementSetName>",NULL,0,NULL},
3006 {"close", cmd_close, "",NULL,0,NULL},
3007 {"attributeset", cmd_attributeset, "<attrset>",complete_attributeset,0,NULL},
3008 {"querytype", cmd_querytype, "<type>",complete_querytype,0,NULL},
3009 {"refid", cmd_refid, "<id>",NULL,0,NULL},
3010 {"itemorder", cmd_itemorder, "ill|item <itemno>",NULL,0,NULL},
3011 {"update", cmd_update, "<action> <recid> [<file>]",NULL,0,NULL},
3012 {"packagename", cmd_packagename, "<packagename>",NULL,0,NULL},
3013 {"proxy", cmd_proxy, "[('tcp'|'ssl')]<host>[':'<port>]",NULL,0,NULL},
3014 {"charset", cmd_charset, "<charset_name>",NULL,0,NULL},
3015 {"lang", cmd_lang, "<language_code>",NULL,0,NULL},
3016 {".", cmd_source, "<filename>",NULL,1,NULL},
3017 {"!", cmd_subshell, "Subshell command",NULL,1,NULL},
3018 {"set_apdufile", cmd_set_apdufile, "<filename>",NULL,1,NULL},
3019 {"set_marcdump", cmd_set_marcdump," <filename>",NULL,1,NULL},
3020 {"set_cclfile", cmd_set_cclfile," <filename>",NULL,1,NULL},
3021 {"set_auto_reconnect", cmd_set_auto_reconnect," on|off",complete_auto_reconnect,1,NULL},
3022 {"set_otherinfo", cmd_set_otherinfo,"<otherinfoinddex> <oid> <string>",NULL,0,NULL},
3023 {"register_oid", cmd_register_oid,"<name> <class> <oid>",NULL,0,NULL},
3024 {"push_command", cmd_push_command,"<command>",command_generator,0,NULL},
3025 {"register_tab", cmd_register_tab,"<commandname> <tab>",command_generator,0,NULL},
3026 {"cclparse", cmd_cclparse,"<ccl find command>",NULL,0,NULL},
3027 {"list_otherinfo",cmd_list_otherinfo,"[otherinfoinddex]",NULL,0,NULL},
3028 {"list_all",cmd_list_all,"",NULL,0,NULL},
3029 {"clear_otherinfo",cmd_clear_otherinfo,"",NULL,0,NULL},
3030 /* Server Admin Functions */
3031 {"adm-reindex", cmd_adm_reindex, "<database-name>",NULL,0,NULL},
3032 {"adm-truncate", cmd_adm_truncate, "('database'|'index')<object-name>",NULL,0,NULL},
3033 {"adm-create", cmd_adm_create, "",NULL,0,NULL},
3034 {"adm-drop", cmd_adm_drop, "('database'|'index')<object-name>",NULL,0,NULL},
3035 {"adm-import", cmd_adm_import, "<record-type> <dir> <pattern>",NULL,0,NULL},
3036 {"adm-refresh", cmd_adm_refresh, "",NULL,0,NULL},
3037 {"adm-commit", cmd_adm_commit, "",NULL,0,NULL},
3038 {"adm-shutdown", cmd_adm_shutdown, "",NULL,0,NULL},
3039 {"adm-startup", cmd_adm_startup, "",NULL,0,NULL},
3040 {"help", cmd_help, "", NULL,0,NULL},
3044 static int cmd_help (char *line)
3050 sscanf (line, "%20s", topic);
3053 printf("Commands:\n");
3054 for (i = 0; cmd[i].cmd; i++)
3055 if (*topic == 0 || strcmp (topic, cmd[i].cmd) == 0)
3056 printf(" %s %s\n", cmd[i].cmd, cmd[i].ad);
3057 if (strcmp (topic, "find") == 0)
3060 printf (" \"term\" Simple Term\n");
3061 printf (" @attr [attset] type=value op Attribute\n");
3062 printf (" @and opl opr And\n");
3063 printf (" @or opl opr Or\n");
3064 printf (" @not opl opr And-Not\n");
3065 printf (" @set set Result set\n");
3067 printf ("Bib-1 attribute types\n");
3069 printf ("4=Title 7=ISBN 8=ISSN 30=Date 62=Abstract 1003=Author 1016=Any\n");
3070 printf ("2=Relation: ");
3071 printf ("1< 2<= 3= 4>= 5> 6!= 102=Relevance\n");
3072 printf ("3=Position: ");
3073 printf ("1=First in Field 2=First in subfield 3=Any position\n");
3074 printf ("4=Structure: ");
3075 printf ("1=Phrase 2=Word 3=Key 4=Year 5=Date 6=WordList\n");
3076 printf ("5=Truncation: ");
3077 printf ("1=Right 2=Left 3=L&R 100=No 101=# 102=Re-1 103=Re-2\n");
3078 printf ("6=Completeness:");
3079 printf ("1=Incomplete subfield 2=Complete subfield 3=Complete field\n");
3084 int cmd_register_tab(char* arg) {
3086 char command[101], tabargument[101];
3091 if (sscanf (arg, "%100s %100s", command, tabargument) < 1) {
3095 /* locate the amdn in the list */
3096 for (i = 0; cmd[i].cmd; i++) {
3097 if (!strncmp(cmd[i].cmd, command, strlen(command))) {
3103 fprintf(stderr,"Unknown command %s\n",command);
3108 if(!cmd[i].local_tabcompletes)
3109 cmd[i].local_tabcompletes = (char **) calloc(1,sizeof(char**));
3113 tabslist = cmd[i].local_tabcompletes;
3114 for(;tabslist && *tabslist;tabslist++) {
3118 cmd[i].local_tabcompletes = (char **)
3119 realloc(cmd[i].local_tabcompletes,(num_of_tabs+2)*sizeof(char**));
3120 tabslist=cmd[i].local_tabcompletes;
3121 tabslist[num_of_tabs]=strdup(tabargument);
3122 tabslist[num_of_tabs+1]=NULL;
3127 void process_cmd_line(char* line)
3130 char word[32], arg[1024];
3132 #if HAVE_GETTIMEOFDAY
3133 gettimeofday (&tv_start, 0);
3136 if ((res = sscanf(line, "%31s %1023[^;]", word, arg)) <= 0)
3138 strcpy(word, last_cmd);
3143 strcpy(last_cmd, word);
3145 /* removed tailing spaces from the arg command */
3148 char* lastnonspace=NULL;
3157 *(++lastnonspace) = 0;
3161 for (i = 0; cmd[i].cmd; i++)
3162 if (!strncmp(cmd[i].cmd, word, strlen(word)))
3164 res = (*cmd[i].fun)(arg);
3168 if (!cmd[i].cmd) /* dump our help-screen */
3170 printf("Unknown command: %s.\n", word);
3171 printf("use help for list of commands\n");
3172 /* cmd_help (""); */
3176 if(apdu_file) fflush(apdu_file);
3179 wait_and_handle_responce();
3188 char *command_generator(const char *text, int state)
3194 for( ; cmd[idx].cmd; ++idx) {
3195 if (!strncmp(cmd[idx].cmd,text,strlen(text))) {
3196 ++idx; /* skip this entry on the next run */
3197 return strdup(cmd[idx-1].cmd);
3205 This function only known how to complete on the first word
3207 char ** readline_completer(char *text, int start, int end) {
3208 #if HAVE_READLINE_READLINE_H
3210 completerFunctionType completerToUse;
3213 #if HAVE_READLINE_RL_COMPLETION_MATCHES
3214 char** res=rl_completion_matches(text,
3217 char** res=completion_matches(text,
3218 (CPFunction*)command_generator);
3220 rl_attempted_completion_over = 1;
3223 char arg[1024],word[32];
3225 if ((res = sscanf(rl_line_buffer, "%31s %1023[^;]", word, arg)) <= 0) {
3226 rl_attempted_completion_over = 1;
3230 for (i = 0; cmd[i].cmd; i++) {
3231 if (!strncmp(cmd[i].cmd, word, strlen(word))) {
3236 if(!cmd[i].cmd) return NULL;
3239 curret_global_list = cmd[i].local_tabcompletes;
3241 completerToUse = cmd[i].rl_completerfunction;
3242 if(completerToUse==NULL) /* if no pr. command completer is defined use the default completer */
3243 completerToUse = default_completer;
3245 if(completerToUse) {
3246 #ifdef HAVE_READLINE_RL_COMPLETION_MATCHES
3248 rl_completion_matches(text,
3252 completion_matches(text,
3253 (CPFunction*)completerToUse);
3255 if(!cmd[i].complete_filenames)
3256 rl_attempted_completion_over = 1;
3259 if(!cmd[i].complete_filenames)
3260 rl_attempted_completion_over = 1;
3270 static void client(void)
3276 #if HAVE_GETTIMEOFDAY
3277 gettimeofday (&tv_start, 0);
3282 char *line_in = NULL;
3283 #if HAVE_READLINE_READLINE_H
3286 line_in=readline(C_PROMPT);
3289 #if HAVE_READLINE_HISTORY_H
3291 add_history(line_in);
3293 strncpy(line, line_in, 1023);
3302 if (!fgets(line, 1023, stdin))
3304 if ((end_p = strchr (line, '\n')))
3307 process_cmd_line(line);
3311 int main(int argc, char **argv)
3314 char *open_command = 0;
3315 char *auth_command = 0;
3320 if (!setlocale(LC_CTYPE, ""))
3321 fprintf (stderr, "setlocale failed\n");
3325 codeset = nl_langinfo(CODESET);
3329 while ((ret = options("k:c:a:m:v:p:u:t:", argv, argc, &arg)) != -2)
3336 open_command = (char *) xmalloc (strlen(arg)+6);
3337 strcpy (open_command, "open ");
3338 strcat (open_command, arg);
3342 kilobytes = atoi(arg);
3345 if (!(marcdump = fopen (arg, "a")))
3355 strncpy (ccl_fields, arg, sizeof(ccl_fields)-1);
3356 ccl_fields[sizeof(ccl_fields)-1] = '\0';
3359 if (!strcmp(arg, "-"))
3362 apdu_file=fopen(arg, "a");
3365 yazProxy=strdup(arg);
3370 auth_command = (char *) xmalloc (strlen(arg)+6);
3371 strcpy (auth_command, "auth ");
3372 strcat (auth_command, arg);
3376 yaz_log_init (yaz_log_mask_str(arg), "", NULL);
3379 fprintf (stderr, "Usage: %s [-m <marclog>] [ -a <apdulog>] "
3380 "[-c cclfields]\n [-p <proxy-addr>] [-u <auth>] "
3381 "[-k size] [<server-addr>]\n",
3389 #ifdef HAVE_GETTIMEOFDAY
3390 gettimeofday (&tv_start, 0);
3392 process_cmd_line (auth_command);
3393 #if HAVE_READLINE_HISTORY_H
3394 add_history(auth_command);
3396 xfree(auth_command);
3400 #ifdef HAVE_GETTIMEOFDAY
3401 gettimeofday (&tv_start, 0);
3403 process_cmd_line (open_command);
3404 #if HAVE_READLINE_HISTORY_H
3405 add_history(open_command);
3407 xfree(open_command);
3418 * vim600: sw=4 ts=8 fdm=marker
3419 * vim<600: sw=4 ts=8