2 * Copyright (c) 1995-2003, Index Data
3 * See the file LICENSE for details.
5 * $Id: client.c,v 1.178 2003-01-06 08:20:26 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);
509 if(!( auto_reconnect && last_open_command) ) return ;
511 open_command = (char *) xmalloc (strlen(last_open_command)+6);
512 strcpy (open_command, "open ");
514 strcat (open_command, last_open_command);
516 process_cmd_line(open_command);
521 int cmd_authentication(char *arg)
523 static Z_IdAuthentication au;
524 static char user[40], group[40], pass[40];
525 static Z_IdPass idPass;
530 printf("Auth field set to null\n");
534 r = sscanf (arg, "%39s %39s %39s", user, group, pass);
537 printf("Auth field set to null\n");
543 au.which = Z_IdAuthentication_open;
549 au.which = Z_IdAuthentication_idPass;
550 au.u.idPass = &idPass;
551 idPass.groupId = NULL;
552 idPass.userId = user;
553 idPass.password = group;
558 au.which = Z_IdAuthentication_idPass;
559 au.u.idPass = &idPass;
560 idPass.groupId = group;
561 idPass.userId = user;
562 idPass.password = pass;
567 /* SEARCH SERVICE ------------------------------ */
568 static void display_record(Z_External *r);
570 static void print_record(const unsigned char *buf, size_t len)
573 print_stringn (buf, len);
574 /* add newline if not already added ... */
575 if (i <= 0 || buf[i-1] != '\n')
579 static void display_record(Z_External *r)
581 oident *ent = oid_getentbyoid(r->direct_reference);
585 * Tell the user what we got.
587 if (r->direct_reference)
589 printf("Record type: ");
591 printf("%s\n", ent->desc);
592 else if (!odr_oid(print, &r->direct_reference, 0, 0))
594 odr_perror(print, "print oid");
598 /* Check if this is a known, ASN.1 type tucked away in an octet string */
599 if (ent && r->which == Z_External_octet)
601 Z_ext_typeent *type = z_ext_getentbyref(ent->value);
607 * Call the given decoder to process the record.
609 odr_setbuf(in, (char*)r->u.octet_aligned->buf,
610 r->u.octet_aligned->len, 0);
611 if (!(*type->fun)(in, (char **)&rr, 0, 0))
613 odr_perror(in, "Decoding constructed record.");
614 fprintf(stderr, "[Near %d]\n", odr_offset(in));
615 fprintf(stderr, "Packet dump:\n---------\n");
616 odr_dumpBER(stderr, (char*)r->u.octet_aligned->buf,
617 r->u.octet_aligned->len);
618 fprintf(stderr, "---------\n");
620 /* note just ignores the error ant print the bytes form the octet_aligned later */
623 * Note: we throw away the original, BER-encoded record here.
624 * Do something else with it if you want to keep it.
626 r->u.sutrs = (Z_SUTRS *) rr; /* we don't actually check the type here. */
627 r->which = type->what;
631 if (ent && ent->oclass != CLASS_RECSYN)
633 if (ent && ent->value == VAL_SOIF)
634 print_record((const unsigned char *) r->u.octet_aligned->buf,
635 r->u.octet_aligned->len);
636 else if (r->which == Z_External_octet)
638 const char *octet_buf = (char*)r->u.octet_aligned->buf;
639 if (ent->value == VAL_TEXT_XML || ent->value == VAL_APPLICATION_XML ||
640 ent->value == VAL_HTML)
642 print_record((const unsigned char *) octet_buf,
643 r->u.octet_aligned->len);
645 else if (ent->value == VAL_POSTSCRIPT)
647 int size = r->u.octet_aligned->len;
650 print_record((const unsigned char *) octet_buf, size);
655 #if AVOID_MARC_DECODE
656 /* primitive check for a marc OID 5.1-29 except 16 */
657 ent->oidsuffix[0] == 5 && ent->oidsuffix[1] < 30 &&
658 ent->oidsuffix[1] != 16
667 yaz_marc_t mt = yaz_marc_create();
669 if (yaz_marc_decode_buf(mt, octet_buf,r->u.octet_aligned->len,
673 if (ent->value == VAL_USMARC)
675 if (octet_buf[9] == 'a')
685 printf ("convert from %s to %s\n", from, codeset);
686 cd = yaz_iconv_open(codeset, from);
689 fwrite (result, 1, rlen, stdout);
693 size_t inbytesleft = rlen;
694 const char *inp = result;
698 size_t outbytesleft = sizeof(outbuf);
700 size_t r = yaz_iconv (cd, (char**) &inp,
702 &outp, &outbytesleft);
703 if (r == (size_t) (-1))
705 int e = yaz_iconv_error(cd);
706 if (e != YAZ_ICONV_E2BIG)
709 fwrite (outbuf, outp - outbuf, 1, stdout);
715 printf ("bad MARC. Dumping as it is:\n");
716 print_record((const unsigned char*) octet_buf,
717 r->u.octet_aligned->len);
719 yaz_marc_destroy(mt);
725 print_record((const unsigned char*) octet_buf,
726 r->u.octet_aligned->len);
730 fwrite (octet_buf, 1, r->u.octet_aligned->len, marcdump);
732 else if (ent && ent->value == VAL_SUTRS)
734 if (r->which != Z_External_sutrs)
736 printf("Expecting single SUTRS type for SUTRS.\n");
739 print_record(r->u.sutrs->buf, r->u.sutrs->len);
741 else if (ent && ent->value == VAL_GRS1)
744 if (r->which != Z_External_grs1)
746 printf("Expecting single GRS type for GRS.\n");
750 yaz_display_grs1(w, r->u.grs1, 0);
756 printf("Unknown record representation.\n");
757 if (!z_External(print, &r, 0, 0))
759 odr_perror(print, "Printing external");
765 static void display_diagrecs(Z_DiagRec **pp, int num)
769 Z_DefaultDiagFormat *r;
771 printf("Diagnostic message(s) from database:\n");
772 for (i = 0; i<num; i++)
774 Z_DiagRec *p = pp[i];
775 if (p->which != Z_DiagRec_defaultFormat)
777 printf("Diagnostic record not in default format.\n");
781 r = p->u.defaultFormat;
782 if (!(ent = oid_getentbyoid(r->diagnosticSetId)) ||
783 ent->oclass != CLASS_DIAGSET || ent->value != VAL_BIB1)
784 printf("Missing or unknown diagset\n");
785 printf(" [%d] %s", *r->condition, diagbib1_str(*r->condition));
788 case Z_DefaultDiagFormat_v2Addinfo:
789 printf (" -- v2 addinfo '%s'\n", r->u.v2Addinfo);
791 case Z_DefaultDiagFormat_v3Addinfo:
792 printf (" -- v3 addinfo '%s'\n", r->u.v3Addinfo);
799 static void display_nameplusrecord(Z_NamePlusRecord *p)
802 printf("[%s]", p->databaseName);
803 if (p->which == Z_NamePlusRecord_surrogateDiagnostic)
804 display_diagrecs(&p->u.surrogateDiagnostic, 1);
805 else if (p->which == Z_NamePlusRecord_databaseRecord)
806 display_record(p->u.databaseRecord);
809 static void display_records(Z_Records *p)
813 if (p->which == Z_Records_NSD)
815 Z_DiagRec dr, *dr_p = &dr;
816 dr.which = Z_DiagRec_defaultFormat;
817 dr.u.defaultFormat = p->u.nonSurrogateDiagnostic;
818 display_diagrecs (&dr_p, 1);
820 else if (p->which == Z_Records_multipleNSD)
821 display_diagrecs (p->u.multipleNonSurDiagnostics->diagRecs,
822 p->u.multipleNonSurDiagnostics->num_diagRecs);
825 printf("Records: %d\n", p->u.databaseOrSurDiagnostics->num_records);
826 for (i = 0; i < p->u.databaseOrSurDiagnostics->num_records; i++)
827 display_nameplusrecord(p->u.databaseOrSurDiagnostics->records[i]);
831 static int send_deleteResultSetRequest(char *arg)
836 Z_APDU *apdu = zget_APDU(out, Z_APDU_deleteResultSetRequest);
837 Z_DeleteResultSetRequest *req = apdu->u.deleteResultSetRequest;
839 req->referenceId = set_refid (out);
841 req->num_resultSetList =
842 sscanf (arg, "%30s %30s %30s %30s %30s %30s %30s %30s",
843 names[0], names[1], names[2], names[3],
844 names[4], names[5], names[6], names[7]);
846 req->deleteFunction = (int *)
847 odr_malloc (out, sizeof(*req->deleteFunction));
848 if (req->num_resultSetList > 0)
850 *req->deleteFunction = Z_DeleteRequest_list;
851 req->resultSetList = (char **)
852 odr_malloc (out, sizeof(*req->resultSetList)*
853 req->num_resultSetList);
854 for (i = 0; i<req->num_resultSetList; i++)
855 req->resultSetList[i] = names[i];
859 *req->deleteFunction = Z_DeleteRequest_all;
860 req->resultSetList = 0;
864 printf("Sent deleteResultSetRequest.\n");
868 static int send_searchRequest(char *arg)
870 Z_APDU *apdu = zget_APDU(out, Z_APDU_searchRequest);
871 Z_SearchRequest *req = apdu->u.searchRequest;
874 struct ccl_rpn_node *rpn = NULL;
877 Z_RPNQuery *RPNquery;
879 YAZ_PQF_Parser pqf_parser;
882 if (queryType == QueryType_CCL2RPN)
884 rpn = ccl_find_str(bibset, arg, &error, &pos);
887 printf("CCL ERROR: %s\n", ccl_err_msg(error));
891 req->referenceId = set_refid (out);
892 if (!strcmp(arg, "@big")) /* strictly for troublemaking */
894 static unsigned char big[2100];
897 /* send a very big referenceid to test transport stack etc. */
898 memset(big, 'A', 2100);
899 bigo.len = bigo.size = 2100;
901 req->referenceId = &bigo;
906 sprintf(setstring, "%d", ++setnumber);
907 req->resultSetName = setstring;
909 *req->smallSetUpperBound = smallSetUpperBound;
910 *req->largeSetLowerBound = largeSetLowerBound;
911 *req->mediumSetPresentNumber = mediumSetPresentNumber;
912 if (smallSetUpperBound > 0 || (largeSetLowerBound > 1 &&
913 mediumSetPresentNumber > 0))
917 prefsyn.proto = protocol;
918 prefsyn.oclass = CLASS_RECSYN;
919 prefsyn.value = recordsyntax;
920 req->preferredRecordSyntax =
921 odr_oiddup(out, oid_ent_to_oid(&prefsyn, oid));
922 req->smallSetElementSetNames =
923 req->mediumSetElementSetNames = elementSetNames;
925 req->num_databaseNames = num_databaseNames;
926 req->databaseNames = databaseNames;
932 case QueryType_Prefix:
933 query.which = Z_Query_type_1;
934 pqf_parser = yaz_pqf_create ();
935 RPNquery = yaz_pqf_parse (pqf_parser, out, arg);
940 int code = yaz_pqf_error (pqf_parser, &pqf_msg, &off);
941 printf("%*s^\n", off+4, "");
942 printf("Prefix query error: %s (code %d)\n", pqf_msg, code);
944 yaz_pqf_destroy (pqf_parser);
947 yaz_pqf_destroy (pqf_parser);
948 query.u.type_1 = RPNquery;
951 query.which = Z_Query_type_2;
952 query.u.type_2 = &ccl_query;
953 ccl_query.buf = (unsigned char*) arg;
954 ccl_query.len = strlen(arg);
956 case QueryType_CCL2RPN:
957 query.which = Z_Query_type_1;
958 RPNquery = ccl_rpn_query(out, rpn);
961 printf ("Couldn't convert from CCL to RPN\n");
964 query.u.type_1 = RPNquery;
965 ccl_rpn_delete (rpn);
968 query.which = Z_Query_type_104;
969 ext = odr_malloc(out, sizeof(*ext));
970 ext->direct_reference = odr_getoidbystr(out, "1.2.840.10003.16.2");
971 ext->indirect_reference = 0;
973 ext->which = Z_External_CQL;
974 ext->u.cql = odr_strdup(out, arg);
975 query.u.type_104 = ext;
978 printf ("Unsupported query type\n");
983 printf("Sent searchRequest.\n");
987 /* display Query Expression as part of searchResult-1 */
988 static void display_queryExpression (Z_QueryExpression *qe)
992 if (qe->which == Z_QueryExpression_term)
994 if (qe->u.term->queryTerm)
996 Z_Term *term = qe->u.term->queryTerm;
1000 printf (" %.*s", term->u.general->len, term->u.general->buf);
1002 case Z_Term_characterString:
1003 printf (" %s", term->u.characterString);
1005 case Z_Term_numeric:
1006 printf (" %d", *term->u.numeric);
1016 /* see if we can find USR:SearchResult-1 */
1017 static void display_searchResult (Z_OtherInformation *o)
1022 for (i = 0; i < o->num_elements; i++)
1024 if (o->list[i]->which == Z_OtherInfo_externallyDefinedInfo)
1026 Z_External *ext = o->list[i]->information.externallyDefinedInfo;
1028 if (ext->which == Z_External_searchResult1)
1031 Z_SearchInfoReport *sr = ext->u.searchResult1;
1032 printf ("SearchResult-1:");
1033 for (j = 0; j < sr->num; j++)
1035 if (!sr->elements[j]->subqueryExpression)
1037 display_queryExpression (
1038 sr->elements[j]->subqueryExpression);
1039 display_queryExpression (
1040 sr->elements[j]->subqueryInterpretation);
1041 display_queryExpression (
1042 sr->elements[j]->subqueryRecommendation);
1043 if (sr->elements[j]->subqueryCount)
1044 printf ("(%d)", *sr->elements[j]->subqueryCount);
1052 static int process_searchResponse(Z_SearchResponse *res)
1054 printf ("Received SearchResponse.\n");
1055 print_refid (res->referenceId);
1056 if (*res->searchStatus)
1057 printf("Search was a success.\n");
1059 printf("Search was a bloomin' failure.\n");
1060 printf("Number of hits: %d", *res->resultCount);
1062 printf (", setno %d", setnumber);
1064 display_searchResult (res->additionalSearchInfo);
1065 printf("records returned: %d\n",
1066 *res->numberOfRecordsReturned);
1067 setno += *res->numberOfRecordsReturned;
1069 display_records(res->records);
1073 static void print_level(int iLevel)
1076 for (i = 0; i < iLevel * 4; i++)
1080 static void print_int(int iLevel, const char *pTag, int *pInt)
1084 print_level(iLevel);
1085 printf("%s: %d\n", pTag, *pInt);
1089 static void print_string(int iLevel, const char *pTag, const char *pString)
1091 if (pString != NULL)
1093 print_level(iLevel);
1094 printf("%s: %s\n", pTag, pString);
1098 static void print_oid(int iLevel, const char *pTag, Odr_oid *pOid)
1104 print_level(iLevel);
1105 printf("%s:", pTag);
1106 for (; *pInt != -1; pInt++)
1107 printf(" %d", *pInt);
1112 static void print_referenceId(int iLevel, Z_ReferenceId *referenceId)
1114 if (referenceId != NULL)
1118 print_level(iLevel);
1119 printf("Ref Id (%d, %d): ", referenceId->len, referenceId->size);
1120 for (i = 0; i < referenceId->len; i++)
1121 printf("%c", referenceId->buf[i]);
1126 static void print_string_or_numeric(int iLevel, const char *pTag, Z_StringOrNumeric *pStringNumeric)
1128 if (pStringNumeric != NULL)
1130 switch (pStringNumeric->which)
1132 case Z_StringOrNumeric_string:
1133 print_string(iLevel, pTag, pStringNumeric->u.string);
1136 case Z_StringOrNumeric_numeric:
1137 print_int(iLevel, pTag, pStringNumeric->u.numeric);
1141 print_level(iLevel);
1142 printf("%s: valid type for Z_StringOrNumeric\n", pTag);
1148 static void print_universe_report_duplicate(
1150 Z_UniverseReportDuplicate *pUniverseReportDuplicate)
1152 if (pUniverseReportDuplicate != NULL)
1154 print_level(iLevel);
1155 printf("Universe Report Duplicate: \n");
1157 print_string_or_numeric(iLevel, "Hit No",
1158 pUniverseReportDuplicate->hitno);
1162 static void print_universe_report_hits(
1164 Z_UniverseReportHits *pUniverseReportHits)
1166 if (pUniverseReportHits != NULL)
1168 print_level(iLevel);
1169 printf("Universe Report Hits: \n");
1171 print_string_or_numeric(iLevel, "Database",
1172 pUniverseReportHits->database);
1173 print_string_or_numeric(iLevel, "Hits", pUniverseReportHits->hits);
1177 static void print_universe_report(int iLevel, Z_UniverseReport *pUniverseReport)
1179 if (pUniverseReport != NULL)
1181 print_level(iLevel);
1182 printf("Universe Report: \n");
1184 print_int(iLevel, "Total Hits", pUniverseReport->totalHits);
1185 switch (pUniverseReport->which)
1187 case Z_UniverseReport_databaseHits:
1188 print_universe_report_hits(iLevel,
1189 pUniverseReport->u.databaseHits);
1192 case Z_UniverseReport_duplicate:
1193 print_universe_report_duplicate(iLevel,
1194 pUniverseReport->u.duplicate);
1198 print_level(iLevel);
1199 printf("Type: %d\n", pUniverseReport->which);
1205 static void print_external(int iLevel, Z_External *pExternal)
1207 if (pExternal != NULL)
1209 print_level(iLevel);
1210 printf("External: \n");
1212 print_oid(iLevel, "Direct Reference", pExternal->direct_reference);
1213 print_int(iLevel, "InDirect Reference", pExternal->indirect_reference);
1214 print_string(iLevel, "Descriptor", pExternal->descriptor);
1215 switch (pExternal->which)
1217 case Z_External_universeReport:
1218 print_universe_report(iLevel, pExternal->u.universeReport);
1222 print_level(iLevel);
1223 printf("Type: %d\n", pExternal->which);
1229 static int process_resourceControlRequest (Z_ResourceControlRequest *req)
1231 printf ("Received ResourceControlRequest.\n");
1232 print_referenceId(1, req->referenceId);
1233 print_int(1, "Suspended Flag", req->suspendedFlag);
1234 print_int(1, "Partial Results Available", req->partialResultsAvailable);
1235 print_int(1, "Response Required", req->responseRequired);
1236 print_int(1, "Triggered Request Flag", req->triggeredRequestFlag);
1237 print_external(1, req->resourceReport);
1241 void process_ESResponse(Z_ExtendedServicesResponse *res)
1244 switch (*res->operationStatus)
1246 case Z_ExtendedServicesResponse_done:
1249 case Z_ExtendedServicesResponse_accepted:
1250 printf ("accepted\n");
1252 case Z_ExtendedServicesResponse_failure:
1253 printf ("failure\n");
1254 display_diagrecs(res->diagnostics, res->num_diagnostics);
1257 printf ("unknown\n");
1259 if ( (*res->operationStatus != Z_ExtendedServicesResponse_failure) &&
1260 (res->num_diagnostics != 0) ) {
1261 display_diagrecs(res->diagnostics, res->num_diagnostics);
1263 print_refid (res->referenceId);
1264 if (res->taskPackage &&
1265 res->taskPackage->which == Z_External_extendedService)
1267 Z_TaskPackage *taskPackage = res->taskPackage->u.extendedService;
1268 Odr_oct *id = taskPackage->targetReference;
1269 Z_External *ext = taskPackage->taskSpecificParameters;
1273 printf ("Target Reference: ");
1274 print_stringn (id->buf, id->len);
1277 if (ext->which == Z_External_update)
1279 Z_IUUpdateTaskPackage *utp = ext->u.update->u.taskPackage;
1280 if (utp && utp->targetPart)
1282 Z_IUTargetPart *targetPart = utp->targetPart;
1285 for (i = 0; i<targetPart->num_taskPackageRecords; i++)
1288 Z_IUTaskPackageRecordStructure *tpr =
1289 targetPart->taskPackageRecords[i];
1290 printf ("task package record %d\n", i+1);
1291 if (tpr->which == Z_IUTaskPackageRecordStructure_record)
1293 display_record (tpr->u.record);
1297 printf ("other type\n");
1305 const char *get_ill_element (void *clientData, const char *element)
1310 static Z_External *create_external_itemRequest()
1312 struct ill_get_ctl ctl;
1313 ILL_ItemRequest *req;
1315 int item_request_size = 0;
1316 char *item_request_buf = 0;
1320 ctl.f = get_ill_element;
1322 req = ill_get_ItemRequest(&ctl, "ill", 0);
1324 printf ("ill_get_ItemRequest failed\n");
1326 if (!ill_ItemRequest (out, &req, 0, 0))
1330 ill_ItemRequest(print, &req, 0, 0);
1333 item_request_buf = odr_getbuf (out, &item_request_size, 0);
1334 if (item_request_buf)
1335 odr_setbuf (out, item_request_buf, item_request_size, 1);
1336 printf ("Couldn't encode ItemRequest, size %d\n", item_request_size);
1343 item_request_buf = odr_getbuf (out, &item_request_size, 0);
1344 oid.proto = PROTO_GENERAL;
1345 oid.oclass = CLASS_GENERAL;
1346 oid.value = VAL_ISO_ILL_1;
1348 r = (Z_External *) odr_malloc (out, sizeof(*r));
1349 r->direct_reference = odr_oiddup(out,oid_getoidbyent(&oid));
1350 r->indirect_reference = 0;
1352 r->which = Z_External_single;
1354 r->u.single_ASN1_type = (Odr_oct *)
1355 odr_malloc (out, sizeof(*r->u.single_ASN1_type));
1356 r->u.single_ASN1_type->buf = (unsigned char *)
1357 odr_malloc (out, item_request_size);
1358 r->u.single_ASN1_type->len = item_request_size;
1359 r->u.single_ASN1_type->size = item_request_size;
1360 memcpy (r->u.single_ASN1_type->buf, item_request_buf,
1363 do_hex_dump(item_request_buf,item_request_size);
1368 static Z_External *create_external_ILL_APDU(int which)
1370 struct ill_get_ctl ctl;
1373 int ill_request_size = 0;
1374 char *ill_request_buf = 0;
1378 ctl.f = get_ill_element;
1380 ill_apdu = ill_get_APDU(&ctl, "ill", 0);
1382 if (!ill_APDU (out, &ill_apdu, 0, 0))
1386 printf ("-------------------\n");
1387 ill_APDU(print, &ill_apdu, 0, 0);
1389 printf ("-------------------\n");
1391 ill_request_buf = odr_getbuf (out, &ill_request_size, 0);
1392 if (ill_request_buf)
1393 odr_setbuf (out, ill_request_buf, ill_request_size, 1);
1394 printf ("Couldn't encode ILL-Request, size %d\n", ill_request_size);
1400 ill_request_buf = odr_getbuf (out, &ill_request_size, 0);
1402 oid.proto = PROTO_GENERAL;
1403 oid.oclass = CLASS_GENERAL;
1404 oid.value = VAL_ISO_ILL_1;
1406 r = (Z_External *) odr_malloc (out, sizeof(*r));
1407 r->direct_reference = odr_oiddup(out,oid_getoidbyent(&oid));
1408 r->indirect_reference = 0;
1410 r->which = Z_External_single;
1412 r->u.single_ASN1_type = (Odr_oct *)
1413 odr_malloc (out, sizeof(*r->u.single_ASN1_type));
1414 r->u.single_ASN1_type->buf = (unsigned char *)
1415 odr_malloc (out, ill_request_size);
1416 r->u.single_ASN1_type->len = ill_request_size;
1417 r->u.single_ASN1_type->size = ill_request_size;
1418 memcpy (r->u.single_ASN1_type->buf, ill_request_buf, ill_request_size);
1419 /* printf ("len = %d\n", ill_request_size); */
1420 /* do_hex_dump(ill_request_buf,ill_request_size); */
1421 /* printf("--- end of extenal\n"); */
1428 static Z_External *create_ItemOrderExternal(const char *type, int itemno)
1430 Z_External *r = (Z_External *) odr_malloc(out, sizeof(Z_External));
1431 oident ItemOrderRequest;
1433 ItemOrderRequest.proto = PROTO_Z3950;
1434 ItemOrderRequest.oclass = CLASS_EXTSERV;
1435 ItemOrderRequest.value = VAL_ITEMORDER;
1437 r->direct_reference = odr_oiddup(out,oid_getoidbyent(&ItemOrderRequest));
1438 r->indirect_reference = 0;
1441 r->which = Z_External_itemOrder;
1443 r->u.itemOrder = (Z_ItemOrder *) odr_malloc(out,sizeof(Z_ItemOrder));
1444 memset(r->u.itemOrder, 0, sizeof(Z_ItemOrder));
1445 r->u.itemOrder->which=Z_IOItemOrder_esRequest;
1447 r->u.itemOrder->u.esRequest = (Z_IORequest *)
1448 odr_malloc(out,sizeof(Z_IORequest));
1449 memset(r->u.itemOrder->u.esRequest, 0, sizeof(Z_IORequest));
1451 r->u.itemOrder->u.esRequest->toKeep = (Z_IOOriginPartToKeep *)
1452 odr_malloc(out,sizeof(Z_IOOriginPartToKeep));
1453 memset(r->u.itemOrder->u.esRequest->toKeep, 0, sizeof(Z_IOOriginPartToKeep));
1454 r->u.itemOrder->u.esRequest->notToKeep = (Z_IOOriginPartNotToKeep *)
1455 odr_malloc(out,sizeof(Z_IOOriginPartNotToKeep));
1456 memset(r->u.itemOrder->u.esRequest->notToKeep, 0, sizeof(Z_IOOriginPartNotToKeep));
1458 r->u.itemOrder->u.esRequest->toKeep->supplDescription = NULL;
1459 r->u.itemOrder->u.esRequest->toKeep->contact = NULL;
1460 r->u.itemOrder->u.esRequest->toKeep->addlBilling = NULL;
1462 r->u.itemOrder->u.esRequest->notToKeep->resultSetItem =
1463 (Z_IOResultSetItem *) odr_malloc(out, sizeof(Z_IOResultSetItem));
1464 memset(r->u.itemOrder->u.esRequest->notToKeep->resultSetItem, 0, sizeof(Z_IOResultSetItem));
1465 r->u.itemOrder->u.esRequest->notToKeep->resultSetItem->resultSetId = "1";
1467 r->u.itemOrder->u.esRequest->notToKeep->resultSetItem->item =
1468 (int *) odr_malloc(out, sizeof(int));
1469 *r->u.itemOrder->u.esRequest->notToKeep->resultSetItem->item = itemno;
1471 if (!strcmp (type, "item") || !strcmp(type, "2"))
1473 printf ("using item-request\n");
1474 r->u.itemOrder->u.esRequest->notToKeep->itemRequest =
1475 create_external_itemRequest();
1477 else if (!strcmp(type, "ill") || !strcmp(type, "1"))
1479 printf ("using ILL-request\n");
1480 r->u.itemOrder->u.esRequest->notToKeep->itemRequest =
1481 create_external_ILL_APDU(ILL_APDU_ILL_Request);
1483 else if (!strcmp(type, "xml") || !strcmp(type, "3"))
1485 const char *xml_buf =
1487 " <type>request</type>\n"
1488 " <libraryNo>000200</libraryNo>\n"
1489 " <borrowerTicketNo> 1212 </borrowerTicketNo>\n"
1491 r->u.itemOrder->u.esRequest->notToKeep->itemRequest =
1492 z_ext_record (out, VAL_TEXT_XML, xml_buf, strlen(xml_buf));
1495 r->u.itemOrder->u.esRequest->notToKeep->itemRequest = 0;
1500 static int send_itemorder(const char *type, int itemno)
1502 Z_APDU *apdu = zget_APDU(out, Z_APDU_extendedServicesRequest);
1503 Z_ExtendedServicesRequest *req = apdu->u.extendedServicesRequest;
1504 oident ItemOrderRequest;
1506 ItemOrderRequest.proto = PROTO_Z3950;
1507 ItemOrderRequest.oclass = CLASS_EXTSERV;
1508 ItemOrderRequest.value = VAL_ITEMORDER;
1509 req->packageType = odr_oiddup(out,oid_getoidbyent(&ItemOrderRequest));
1510 req->packageName = esPackageName;
1512 req->taskSpecificParameters = create_ItemOrderExternal(type, itemno);
1518 static int cmd_update(char *arg)
1520 Z_APDU *apdu = zget_APDU(out, Z_APDU_extendedServicesRequest );
1521 Z_ExtendedServicesRequest *req = apdu->u.extendedServicesRequest;
1524 Z_IUOriginPartToKeep *toKeep;
1525 Z_IUSuppliedRecords *notToKeep;
1527 char action[20], recid[20], fname[80];
1529 Z_External *record_this = 0;
1534 sscanf (arg, "%19s %19s %79s", action, recid, fname);
1536 if (!strcmp (action, "insert"))
1537 action_no = Z_IUOriginPartToKeep_recordInsert;
1538 else if (!strcmp (action, "replace"))
1539 action_no = Z_IUOriginPartToKeep_recordReplace;
1540 else if (!strcmp (action, "delete"))
1541 action_no = Z_IUOriginPartToKeep_recordDelete;
1542 else if (!strcmp (action, "update"))
1543 action_no = Z_IUOriginPartToKeep_specialUpdate;
1546 printf ("Bad action: %s\n", action);
1547 printf ("Possible values: insert, replace, delete, update\n");
1555 stat (fname, &status);
1556 if (S_ISREG(status.st_mode) && (inf = fopen(fname, "r")))
1558 size_t len = status.st_size;
1559 char *buf = (char *) xmalloc (len);
1561 fread (buf, 1, len, inf);
1565 record_this = z_ext_record (out, VAL_TEXT_XML, buf, len);
1571 printf ("File %s doesn't exist\n", fname);
1579 printf ("No last record (update ignored)\n");
1582 record_this = record_last;
1585 update_oid.proto = PROTO_Z3950;
1586 update_oid.oclass = CLASS_EXTSERV;
1587 update_oid.value = VAL_DBUPDATE;
1588 oid_ent_to_oid (&update_oid, oid);
1589 req->packageType = odr_oiddup(out,oid);
1590 req->packageName = esPackageName;
1592 req->referenceId = set_refid (out);
1594 r = req->taskSpecificParameters = (Z_External *)
1595 odr_malloc (out, sizeof(*r));
1596 r->direct_reference = odr_oiddup(out,oid);
1597 r->indirect_reference = 0;
1599 r->which = Z_External_update;
1600 r->u.update = (Z_IUUpdate *) odr_malloc(out, sizeof(*r->u.update));
1601 r->u.update->which = Z_IUUpdate_esRequest;
1602 r->u.update->u.esRequest = (Z_IUUpdateEsRequest *)
1603 odr_malloc(out, sizeof(*r->u.update->u.esRequest));
1604 toKeep = r->u.update->u.esRequest->toKeep = (Z_IUOriginPartToKeep *)
1605 odr_malloc(out, sizeof(*r->u.update->u.esRequest->toKeep));
1606 toKeep->databaseName = databaseNames[0];
1608 toKeep->elementSetName = 0;
1609 toKeep->actionQualifier = 0;
1610 toKeep->action = (int *) odr_malloc(out, sizeof(*toKeep->action));
1611 *toKeep->action = action_no;
1613 notToKeep = r->u.update->u.esRequest->notToKeep = (Z_IUSuppliedRecords *)
1614 odr_malloc(out, sizeof(*r->u.update->u.esRequest->notToKeep));
1616 notToKeep->elements = (Z_IUSuppliedRecords_elem **)
1617 odr_malloc(out, sizeof(*notToKeep->elements));
1618 notToKeep->elements[0] = (Z_IUSuppliedRecords_elem *)
1619 odr_malloc(out, sizeof(**notToKeep->elements));
1620 notToKeep->elements[0]->which = Z_IUSuppliedRecords_elem_opaque;
1623 notToKeep->elements[0]->u.opaque = (Odr_oct *)
1624 odr_malloc (out, sizeof(Odr_oct));
1625 notToKeep->elements[0]->u.opaque->buf = (unsigned char *) recid;
1626 notToKeep->elements[0]->u.opaque->size = strlen(recid);
1627 notToKeep->elements[0]->u.opaque->len = strlen(recid);
1630 notToKeep->elements[0]->u.opaque = 0;
1631 notToKeep->elements[0]->supplementalId = 0;
1632 notToKeep->elements[0]->correlationInfo = 0;
1633 notToKeep->elements[0]->record = record_this;
1640 static int cmd_itemorder(char *arg)
1645 if (sscanf (arg, "%10s %d", type, &itemno) != 2)
1648 printf("Item order request\n");
1650 send_itemorder(type, itemno);
1654 static int cmd_find(char *arg)
1658 printf("Find what?\n");
1666 printf("Not connected yet\n");
1670 if (!send_searchRequest(arg))
1675 static int cmd_delete(char *arg)
1679 printf("Not connected yet\n");
1682 if (!send_deleteResultSetRequest(arg))
1687 static int cmd_ssub(char *arg)
1689 if (!(smallSetUpperBound = atoi(arg)))
1694 static int cmd_lslb(char *arg)
1696 if (!(largeSetLowerBound = atoi(arg)))
1701 static int cmd_mspn(char *arg)
1703 if (!(mediumSetPresentNumber = atoi(arg)))
1708 static int cmd_status(char *arg)
1710 printf("smallSetUpperBound: %d\n", smallSetUpperBound);
1711 printf("largeSetLowerBound: %d\n", largeSetLowerBound);
1712 printf("mediumSetPresentNumber: %d\n", mediumSetPresentNumber);
1716 static int cmd_setnames(char *arg)
1718 if (*arg == '1') /* enable ? */
1720 else if (*arg == '0') /* disable ? */
1722 else if (setnumber < 0) /* no args, toggle .. */
1728 printf("Set numbering enabled.\n");
1730 printf("Set numbering disabled.\n");
1734 /* PRESENT SERVICE ----------------------------- */
1736 static int send_presentRequest(char *arg)
1738 Z_APDU *apdu = zget_APDU(out, Z_APDU_presentRequest);
1739 Z_PresentRequest *req = apdu->u.presentRequest;
1740 Z_RecordComposition compo;
1745 char setstring[100];
1747 req->referenceId = set_refid (out);
1748 if ((p = strchr(arg, '+')))
1755 if (p && (p=strchr(p+1, '+')))
1757 strcpy (setstring, p+1);
1758 req->resultSetId = setstring;
1760 else if (setnumber >= 0)
1762 sprintf(setstring, "%d", setnumber);
1763 req->resultSetId = setstring;
1765 req->resultSetStartPoint = &setno;
1766 req->numberOfRecordsRequested = &nos;
1767 prefsyn.proto = protocol;
1768 prefsyn.oclass = CLASS_RECSYN;
1769 prefsyn.value = recordsyntax;
1770 req->preferredRecordSyntax =
1771 odr_oiddup (out, oid_ent_to_oid(&prefsyn, oid));
1773 if (schema != VAL_NONE)
1777 prefschema.proto = protocol;
1778 prefschema.oclass = CLASS_SCHEMA;
1779 prefschema.value = schema;
1781 req->recordComposition = &compo;
1782 compo.which = Z_RecordComp_complex;
1783 compo.u.complex = (Z_CompSpec *)
1784 odr_malloc(out, sizeof(*compo.u.complex));
1785 compo.u.complex->selectAlternativeSyntax = (bool_t *)
1786 odr_malloc(out, sizeof(bool_t));
1787 *compo.u.complex->selectAlternativeSyntax = 0;
1789 compo.u.complex->generic = (Z_Specification *)
1790 odr_malloc(out, sizeof(*compo.u.complex->generic));
1791 compo.u.complex->generic->schema = (Odr_oid *)
1792 odr_oiddup(out, oid_ent_to_oid(&prefschema, oid));
1793 if (!compo.u.complex->generic->schema)
1795 /* OID wasn't a schema! Try record syntax instead. */
1796 prefschema.oclass = CLASS_RECSYN;
1797 compo.u.complex->generic->schema = (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)
2186 printf("Usage: format <recordsyntax>\n");
2189 recordsyntax = oid_getvalbyname (arg);
2190 if (recordsyntax == VAL_NONE)
2192 printf ("unknown record syntax\n");
2198 int cmd_elements(char *arg)
2200 static Z_ElementSetNames esn;
2201 static char what[100];
2205 elementSetNames = 0;
2209 esn.which = Z_ElementSetNames_generic;
2210 esn.u.generic = what;
2211 elementSetNames = &esn;
2215 int cmd_attributeset(char *arg)
2221 printf("Usage: attributeset <setname>\n");
2224 sscanf(arg, "%s", what);
2225 if (p_query_attset (what))
2227 printf("Unknown attribute set name\n");
2233 int cmd_querytype (char *arg)
2235 if (!strcmp (arg, "ccl"))
2236 queryType = QueryType_CCL;
2237 else if (!strcmp (arg, "prefix") || !strcmp(arg, "rpn"))
2238 queryType = QueryType_Prefix;
2239 else if (!strcmp (arg, "ccl2rpn") || !strcmp (arg, "cclrpn"))
2240 queryType = QueryType_CCL2RPN;
2241 else if (!strcmp(arg, "cql"))
2242 queryType = QueryType_CQL;
2245 printf ("Querytype must be one of:\n");
2246 printf (" prefix - Prefix query\n");
2247 printf (" ccl - CCL query\n");
2248 printf (" ccl2rpn - CCL query converted to RPN\n");
2249 printf (" cql - CQL\n");
2255 int cmd_refid (char *arg)
2261 refid = (char *) xmalloc (strlen(arg)+1);
2262 strcpy (refid, arg);
2267 int cmd_close(char *arg)
2274 apdu = zget_APDU(out, Z_APDU_close);
2275 req = apdu->u.close;
2276 *req->closeReason = Z_Close_finished;
2278 printf("Sent close request.\n");
2283 int cmd_packagename(char* arg)
2285 xfree (esPackageName);
2286 esPackageName = NULL;
2289 esPackageName = (char *) xmalloc (strlen(arg)+1);
2290 strcpy (esPackageName, arg);
2295 int cmd_proxy(char* arg)
2306 yazProxy = (char *) xmalloc (strlen(arg)+1);
2307 strcpy (yazProxy, arg);
2312 int cmd_charset(char* arg)
2314 char l1[30], l2[30];
2317 if (sscanf(arg, "%29s %29s", l1, l2) < 1)
2319 printf("Current character set is `%s'\n", (yazCharset) ? yazCharset:NULL);
2325 yazCharset = xstrdup(l1);
2328 odr_set_charset (out, l1, l2);
2329 odr_set_charset (in, l2, l1);
2334 int cmd_lang(char* arg)
2337 printf("Current language is `%s'\n", (yazLang)?yazLang:NULL);
2344 yazLang = (char *) xmalloc (strlen(arg)+1);
2345 strcpy (yazLang, arg);
2350 int cmd_source(char* arg)
2352 /* first should open the file and read one line at a time.. */
2354 char line[1024], *cp;
2357 char* args_end=(arg)+strlen(arg)-1;
2358 while(isspace(*args_end))
2363 REMOVE_TAILING_BLANKS(arg);
2366 fprintf(stderr,"Error in source command use a filename\n");
2370 includeFile = fopen (arg, "r");
2373 fprintf(stderr,"Unable to open file %s for reading\n",arg);
2377 while(!feof(includeFile)) {
2378 memset(line,0,sizeof(line));
2379 fgets(line,sizeof(line),includeFile);
2381 if(strlen(line) < 2) continue;
2382 if(line[0] == '#') continue;
2384 if ((cp = strrchr (line, '\n')))
2387 process_cmd_line(line);
2390 if(fclose(includeFile)<0) {
2391 perror("unable to close include file");
2397 int cmd_subshell(char* args)
2402 system(getenv("SHELL"));
2408 int cmd_set_apdufile(char* arg)
2410 REMOVE_TAILING_BLANKS(arg);
2412 if(apdu_file && apdu_file != stderr) { /* don't close stdout*/
2413 perror("unable to close apdu log file");
2421 if(!strcmp(arg,"-"))
2424 apdu_file=fopen(arg, "a");
2427 perror("unable to open apdu log file no apdu log loaded");
2429 odr_setprint(print, apdu_file);
2435 int cmd_set_cclfile(char* arg)
2439 REMOVE_TAILING_BLANKS(arg);
2441 bibset = ccl_qual_mk ();
2442 inf = fopen (arg, "r");
2445 ccl_qual_file (bibset, inf);
2448 strcpy(ccl_fields,arg);
2453 int cmd_set_auto_reconnect(char* arg)
2455 REMOVE_TAILING_BLANKS(arg);
2457 if(strlen(arg)==0) {
2458 auto_reconnect = ! auto_reconnect;
2459 } else if(strcmp(arg,"on")==0) {
2461 } else if(strcmp(arg,"off")==0) {
2464 printf("Error use on or off\n");
2469 printf("Set auto reconnect enabled.\n");
2471 printf("Set auto reconnect disabled.\n");
2476 int cmd_set_marcdump(char* arg)
2478 if(marcdump && marcdump != stderr) { /* don't close stdout*/
2479 perror("unable to close apdu log file");
2487 if(!strcmp(arg,"-"))
2490 marcdump=fopen(arg, "a");
2493 perror("unable to open apdu marcdump file no marcdump done\n");
2499 int cmd_set_proxy(char* arg)
2501 if(yazProxy) free(yazProxy);
2504 if(strlen(arg) > 1) {
2505 yazProxy=strdup(arg);
2511 this command takes 3 arge {name class oid}
2513 int cmd_register_oid(char* args) {
2518 {"appctx",CLASS_APPCTX},
2519 {"absyn",CLASS_ABSYN},
2520 {"attset",CLASS_ATTSET},
2521 {"transyn",CLASS_TRANSYN},
2522 {"diagset",CLASS_DIAGSET},
2523 {"recsyn",CLASS_RECSYN},
2524 {"resform",CLASS_RESFORM},
2525 {"accform",CLASS_ACCFORM},
2526 {"extserv",CLASS_EXTSERV},
2527 {"userinfo",CLASS_USERINFO},
2528 {"elemspec",CLASS_ELEMSPEC},
2529 {"varset",CLASS_VARSET},
2530 {"schema",CLASS_SCHEMA},
2531 {"tagset",CLASS_TAGSET},
2532 {"general",CLASS_GENERAL},
2533 {0,(enum oid_class) 0}
2535 char oname_str[101], oclass_str[101], oid_str[101];
2538 oid_class oidclass = CLASS_GENERAL;
2539 int val = 0, oid[OID_SIZE];
2540 struct oident * new_oident=NULL;
2542 if (sscanf (args, "%100[^ ] %100[^ ] %100s",
2543 oname_str,oclass_str, oid_str) < 1) {
2544 printf("Error in regristrate command \n");
2548 for (i = 0; oid_classes[i].className; i++) {
2549 if (!strcmp(oid_classes[i].className, oclass_str))
2551 oidclass=oid_classes[i].oclass;
2556 if(!(oid_classes[i].className)) {
2557 printf("Unknonwn oid class %s\n",oclass_str);
2565 while (isdigit (*name))
2567 val = val*10 + (*name - '0');
2580 new_oident=oid_addent (oid,PROTO_GENERAL,oidclass,oname_str,VAL_DYNAMIC);
2581 if(strcmp(new_oident->desc,oname_str)) {
2582 fprintf(stderr,"oid is already named as %s, regristration faild\n",
2588 int cmd_push_command(char* arg)
2590 #if HAVE_READLINE_HISTORY_H
2594 fprintf(stderr,"Not compiled with the readline/history module\n");
2599 void source_rcfile()
2601 /* Look for a $HOME/.yazclientrc and source it if it exists */
2602 struct stat statbuf;
2604 char* homedir=getenv("HOME");
2606 if(!homedir) return;
2608 sprintf(buffer,"%s/.yazclientrc",homedir);
2610 if(stat(buffer,&statbuf)==0) {
2614 if(stat(".yazclientrc",&statbuf)==0) {
2615 cmd_source(".yazclientrc");
2620 static void initialize(void)
2625 if (!(out = odr_createmem(ODR_ENCODE)) ||
2626 !(in = odr_createmem(ODR_DECODE)) ||
2627 !(print = odr_createmem(ODR_PRINT)))
2629 fprintf(stderr, "failed to allocate ODR streams\n");
2634 setvbuf(stdout, 0, _IONBF, 0);
2636 odr_setprint(print, apdu_file);
2638 bibset = ccl_qual_mk ();
2639 inf = fopen (ccl_fields, "r");
2642 ccl_qual_file (bibset, inf);
2645 cmd_base("Default");
2647 #if HAVE_READLINE_READLINE_H
2648 rl_attempted_completion_function = (CPPFunction*)readline_completer;
2652 for(i=0; i<maxOtherInfosSupported; ++i) {
2653 extraOtherInfos[i].oidval = -1;
2660 #if HAVE_GETTIMEOFDAY
2661 struct timeval tv_start, tv_end;
2664 void wait_and_handle_responce()
2669 int netbufferlen = 0;
2677 if ((res = cs_get(conn, &netbuffer, &netbufferlen)) < 0)
2679 printf("Target closed connection\n");
2685 printf("Target closed connection.\n");
2689 odr_reset(in); /* release APDU from last round */
2691 odr_setbuf(in, netbuffer, res, 0);
2692 if (!z_APDU(in, &apdu, 0, 0))
2694 odr_perror(in, "Decoding incoming APDU");
2695 fprintf(stderr, "[Near %d]\n", odr_offset(in));
2696 fprintf(stderr, "Packet dump:\n---------\n");
2697 odr_dumpBER(stderr, netbuffer, res);
2698 fprintf(stderr, "---------\n");
2700 z_APDU(print, &apdu, 0, 0);
2704 if (apdu_file && !z_APDU(print, &apdu, 0, 0))
2706 odr_perror(print, "Failed to print incoming APDU");
2712 case Z_APDU_initResponse:
2713 process_initResponse(apdu->u.initResponse);
2715 case Z_APDU_searchResponse:
2716 process_searchResponse(apdu->u.searchResponse);
2718 case Z_APDU_scanResponse:
2719 process_scanResponse(apdu->u.scanResponse);
2721 case Z_APDU_presentResponse:
2722 print_refid (apdu->u.presentResponse->referenceId);
2724 *apdu->u.presentResponse->numberOfRecordsReturned;
2725 if (apdu->u.presentResponse->records)
2726 display_records(apdu->u.presentResponse->records);
2728 printf("No records.\n");
2729 printf ("nextResultSetPosition = %d\n",
2730 *apdu->u.presentResponse->nextResultSetPosition);
2732 case Z_APDU_sortResponse:
2733 process_sortResponse(apdu->u.sortResponse);
2735 case Z_APDU_extendedServicesResponse:
2736 printf("Got extended services response\n");
2737 process_ESResponse(apdu->u.extendedServicesResponse);
2740 printf("Target has closed the association.\n");
2741 process_close(apdu->u.close);
2743 case Z_APDU_resourceControlRequest:
2744 process_resourceControlRequest
2745 (apdu->u.resourceControlRequest);
2747 case Z_APDU_deleteResultSetResponse:
2748 process_deleteResultSetResponse(apdu->u.
2749 deleteResultSetResponse);
2752 printf("Received unknown APDU type (%d).\n",
2757 while (conn && cs_more(conn));
2758 #if HAVE_GETTIMEOFDAY
2759 gettimeofday (&tv_end, 0);
2761 printf ("S/U S/U=%ld/%ld %ld/%ld",
2762 (long) tv_start.tv_sec,
2763 (long) tv_start.tv_usec,
2764 (long) tv_end.tv_sec,
2765 (long) tv_end.tv_usec);
2767 printf ("Elapsed: %.6f\n",
2768 (double) tv_end.tv_usec / 1e6 + tv_end.tv_sec -
2769 ((double) tv_start.tv_usec / 1e6 + tv_start.tv_sec));
2776 int cmd_cclparse(char* arg)
2779 struct ccl_rpn_node *rpn=NULL;
2782 rpn = ccl_find_str (bibset, arg, &error, &pos);
2785 printf ("%*s^ - ", 3+strlen(last_cmd)+1+pos, " ");
2786 printf ("%s\n", ccl_err_msg (error));
2792 ccl_pr_tree(rpn, stdout);
2796 ccl_rpn_delete(rpn);
2804 int cmd_set_otherinfo(char* args)
2806 char oid[101], otherinfoString[101];
2811 sscan_res = sscanf (args, "%d %100[^ ] %100s", &otherinfoNo, oid, otherinfoString);
2813 /* reset this otherinfo */
2814 if(otherinfoNo>=maxOtherInfosSupported) {
2815 printf("Error otherinfo index to large (%d>%d)\n",otherinfoNo,maxOtherInfosSupported);
2817 extraOtherInfos[otherinfoNo].oidval = -1;
2818 if(extraOtherInfos[otherinfoNo].value) free(extraOtherInfos[otherinfoNo].value);
2822 printf("Error in set_otherinfo command \n");
2826 if(otherinfoNo>=maxOtherInfosSupported) {
2827 printf("Error otherinfo index to large (%d>%d)\n",otherinfoNo,maxOtherInfosSupported);
2831 oidval = oid_getvalbyname (oid);
2833 printf("Error in set_otherinfo command unknown oid %s \n",oid);
2836 extraOtherInfos[otherinfoNo].oidval = oidval;
2837 if(extraOtherInfos[otherinfoNo].value) free(extraOtherInfos[otherinfoNo].value);
2838 extraOtherInfos[otherinfoNo].value = strdup(otherinfoString);
2843 int cmd_list_otherinfo(char* args)
2847 if(strlen(args)>0) {
2849 if( i >= maxOtherInfosSupported ) {
2850 printf("Error otherinfo index to large (%d>%d)\n",i,maxOtherInfosSupported);
2854 if(extraOtherInfos[i].oidval != -1)
2855 printf(" otherinfo %d %s %s\n",
2857 yaz_z3950_oid_value_to_str(
2858 (enum oid_value) extraOtherInfos[i].oidval,
2860 extraOtherInfos[i].value);
2863 for(i=0; i<maxOtherInfosSupported; ++i) {
2864 if(extraOtherInfos[i].oidval != -1)
2865 printf(" otherinfo %d %s %s\n",
2867 yaz_z3950_oid_value_to_str(
2868 (enum oid_value) extraOtherInfos[i].oidval,
2870 extraOtherInfos[i].value);
2878 int cmd_list_all(char* args) {
2881 /* connection options */
2883 printf("Connected to : %s\n",last_open_command);
2885 if(last_open_command)
2886 printf("Not connected to : %s\n",last_open_command);
2888 printf("Not connected : \n");
2891 if(yazProxy) printf("using proxy : %s\n",yazProxy);
2893 printf("auto_reconnect : %s\n",auto_reconnect?"on":"off");
2896 printf("Authentication : none\n");
2898 switch(auth->which) {
2899 case Z_IdAuthentication_idPass:
2900 printf("Authentication : IdPass\n");
2901 printf(" Login User : %s\n",auth->u.idPass->userId?auth->u.idPass->userId:"");
2902 printf(" Login Group : %s\n",auth->u.idPass->groupId?auth->u.idPass->groupId:"");
2903 printf(" Password : %s\n",auth->u.idPass->password?auth->u.idPass->password:"");
2905 case Z_IdAuthentication_open:
2906 printf("Authentication : psOpen\n");
2907 printf(" Open string : %s\n",auth->u.open);
2910 printf("Authentication : Unknown\n");
2913 if ( yazCharset ) printf("Character set : `%s'\n", (yazCharset) ? yazCharset:NULL);
2917 for (i = 0; i<num_databaseNames; i++) printf("%s ",databaseNames[i]);
2921 printf("CCL file : %s\n",ccl_fields);
2922 printf("Query type : %s\n",query_type_as_string(queryType));
2924 printf("Named Result Sets : %s\n",setnumber==-1?"off":"on");
2926 /* piggy back options */
2927 printf("ssub/lslb/mspn : %d/%d/%d\n",smallSetUpperBound,largeSetLowerBound,mediumSetPresentNumber);
2929 /* print present related options */
2930 printf("Format : %s\n",yaz_z3950_oid_value_to_str(recordsyntax,CLASS_RECSYN));
2931 printf("Schema : %s\n",yaz_z3950_oid_value_to_str(schema,CLASS_SCHEMA));
2932 printf("Elements : %s\n",elementSetNames?elementSetNames->u.generic:"");
2934 /* loging options */
2935 printf("APDU log : %s\n",apdu_file?"on":"off");
2936 printf("Record log : %s\n",marcdump?"on":"off");
2939 printf("Other Info: \n");
2940 cmd_list_otherinfo("");
2945 int cmd_clear_otherinfo(char* args)
2947 if(strlen(args)>0) {
2949 otherinfoNo = atoi(args);
2950 if( otherinfoNo >= maxOtherInfosSupported ) {
2951 printf("Error otherinfo index to large (%d>%d)\n",otherinfoNo,maxOtherInfosSupported);
2955 if(extraOtherInfos[otherinfoNo].oidval != -1) {
2956 /* only clear if set. */
2957 extraOtherInfos[otherinfoNo].oidval=-1;
2958 free(extraOtherInfos[otherinfoNo].value);
2963 for(i=0; i<maxOtherInfosSupported; ++i) {
2964 if (extraOtherInfos[i].oidval!=-1 ) {
2965 extraOtherInfos[i].oidval=-1;
2966 free(extraOtherInfos[i].value);
2973 static int cmd_help (char *line);
2975 typedef char *(*completerFunctionType)(const char *text, int state);
2979 int (*fun)(char *arg);
2981 completerFunctionType rl_completerfunction;
2982 int complete_filenames;
2983 char **local_tabcompletes;
2985 {"open", cmd_open, "('tcp'|'ssl')':<host>[':'<port>][/<db>]",NULL,0,NULL},
2986 {"quit", cmd_quit, "",NULL,0,NULL},
2987 {"find", cmd_find, "<query>",NULL,0,NULL},
2988 {"delete", cmd_delete, "<setname>",NULL,0,NULL},
2989 {"base", cmd_base, "<base-name>",NULL,0,NULL},
2990 {"show", cmd_show, "<rec#>['+'<#recs>['+'<setname>]]",NULL,0,NULL},
2991 {"scan", cmd_scan, "<term>",NULL,0,NULL},
2992 {"sort", cmd_sort, "<sortkey> <flag> <sortkey> <flag> ...",NULL,0,NULL},
2993 {"sort+", cmd_sort_newset, "<sortkey> <flag> <sortkey> <flag> ...",NULL,0,NULL},
2994 {"authentication", cmd_authentication, "<acctstring>",NULL,0,NULL},
2995 {"lslb", cmd_lslb, "<largeSetLowerBound>",NULL,0,NULL},
2996 {"ssub", cmd_ssub, "<smallSetUpperBound>",NULL,0,NULL},
2997 {"mspn", cmd_mspn, "<mediumSetPresentNumber>",NULL,0,NULL},
2998 {"status", cmd_status, "",NULL,0,NULL},
2999 {"setnames", cmd_setnames, "",NULL,0,NULL},
3000 {"cancel", cmd_cancel, "",NULL,0,NULL},
3001 {"format", cmd_format, "<recordsyntax>",complete_format,0,NULL},
3002 {"schema", cmd_schema, "<schema>",complete_schema,0,NULL},
3003 {"elements", cmd_elements, "<elementSetName>",NULL,0,NULL},
3004 {"close", cmd_close, "",NULL,0,NULL},
3005 {"attributeset", cmd_attributeset, "<attrset>",complete_attributeset,0,NULL},
3006 {"querytype", cmd_querytype, "<type>",complete_querytype,0,NULL},
3007 {"refid", cmd_refid, "<id>",NULL,0,NULL},
3008 {"itemorder", cmd_itemorder, "ill|item <itemno>",NULL,0,NULL},
3009 {"update", cmd_update, "<action> <recid> [<file>]",NULL,0,NULL},
3010 {"packagename", cmd_packagename, "<packagename>",NULL,0,NULL},
3011 {"proxy", cmd_proxy, "[('tcp'|'ssl')]<host>[':'<port>]",NULL,0,NULL},
3012 {"charset", cmd_charset, "<charset_name>",NULL,0,NULL},
3013 {"lang", cmd_lang, "<language_code>",NULL,0,NULL},
3014 {".", cmd_source, "<filename>",NULL,1,NULL},
3015 {"!", cmd_subshell, "Subshell command",NULL,1,NULL},
3016 {"set_apdufile", cmd_set_apdufile, "<filename>",NULL,1,NULL},
3017 {"set_marcdump", cmd_set_marcdump," <filename>",NULL,1,NULL},
3018 {"set_cclfile", cmd_set_cclfile," <filename>",NULL,1,NULL},
3019 {"set_auto_reconnect", cmd_set_auto_reconnect," on|off",complete_auto_reconnect,1,NULL},
3020 {"set_otherinfo", cmd_set_otherinfo,"<otherinfoinddex> <oid> <string>",NULL,0,NULL},
3021 {"register_oid", cmd_register_oid,"<name> <class> <oid>",NULL,0,NULL},
3022 {"push_command", cmd_push_command,"<command>",command_generator,0,NULL},
3023 {"register_tab", cmd_register_tab,"<commandname> <tab>",command_generator,0,NULL},
3024 {"cclparse", cmd_cclparse,"<ccl find command>",NULL,0,NULL},
3025 {"list_otherinfo",cmd_list_otherinfo,"[otherinfoinddex]",NULL,0,NULL},
3026 {"list_all",cmd_list_all,"",NULL,0,NULL},
3027 {"clear_otherinfo",cmd_clear_otherinfo,"",NULL,0,NULL},
3028 /* Server Admin Functions */
3029 {"adm-reindex", cmd_adm_reindex, "<database-name>",NULL,0,NULL},
3030 {"adm-truncate", cmd_adm_truncate, "('database'|'index')<object-name>",NULL,0,NULL},
3031 {"adm-create", cmd_adm_create, "",NULL,0,NULL},
3032 {"adm-drop", cmd_adm_drop, "('database'|'index')<object-name>",NULL,0,NULL},
3033 {"adm-import", cmd_adm_import, "<record-type> <dir> <pattern>",NULL,0,NULL},
3034 {"adm-refresh", cmd_adm_refresh, "",NULL,0,NULL},
3035 {"adm-commit", cmd_adm_commit, "",NULL,0,NULL},
3036 {"adm-shutdown", cmd_adm_shutdown, "",NULL,0,NULL},
3037 {"adm-startup", cmd_adm_startup, "",NULL,0,NULL},
3038 {"help", cmd_help, "", NULL,0,NULL},
3042 static int cmd_help (char *line)
3048 sscanf (line, "%20s", topic);
3051 printf("Commands:\n");
3052 for (i = 0; cmd[i].cmd; i++)
3053 if (*topic == 0 || strcmp (topic, cmd[i].cmd) == 0)
3054 printf(" %s %s\n", cmd[i].cmd, cmd[i].ad);
3055 if (strcmp (topic, "find") == 0)
3058 printf (" \"term\" Simple Term\n");
3059 printf (" @attr [attset] type=value op Attribute\n");
3060 printf (" @and opl opr And\n");
3061 printf (" @or opl opr Or\n");
3062 printf (" @not opl opr And-Not\n");
3063 printf (" @set set Result set\n");
3065 printf ("Bib-1 attribute types\n");
3067 printf ("4=Title 7=ISBN 8=ISSN 30=Date 62=Abstract 1003=Author 1016=Any\n");
3068 printf ("2=Relation: ");
3069 printf ("1< 2<= 3= 4>= 5> 6!= 102=Relevance\n");
3070 printf ("3=Position: ");
3071 printf ("1=First in Field 2=First in subfield 3=Any position\n");
3072 printf ("4=Structure: ");
3073 printf ("1=Phrase 2=Word 3=Key 4=Year 5=Date 6=WordList\n");
3074 printf ("5=Truncation: ");
3075 printf ("1=Right 2=Left 3=L&R 100=No 101=# 102=Re-1 103=Re-2\n");
3076 printf ("6=Completeness:");
3077 printf ("1=Incomplete subfield 2=Complete subfield 3=Complete field\n");
3082 int cmd_register_tab(char* arg) {
3084 char command[101], tabargument[101];
3089 if (sscanf (arg, "%100s %100s", command, tabargument) < 1) {
3093 /* locate the amdn in the list */
3094 for (i = 0; cmd[i].cmd; i++) {
3095 if (!strncmp(cmd[i].cmd, command, strlen(command))) {
3101 fprintf(stderr,"Unknown command %s\n",command);
3106 if(!cmd[i].local_tabcompletes)
3107 cmd[i].local_tabcompletes = (char **) calloc(1,sizeof(char**));
3111 tabslist = cmd[i].local_tabcompletes;
3112 for(;tabslist && *tabslist;tabslist++) {
3116 cmd[i].local_tabcompletes = (char **)
3117 realloc(cmd[i].local_tabcompletes,(num_of_tabs+2)*sizeof(char**));
3118 tabslist=cmd[i].local_tabcompletes;
3119 tabslist[num_of_tabs]=strdup(tabargument);
3120 tabslist[num_of_tabs+1]=NULL;
3125 void process_cmd_line(char* line)
3128 char word[32], arg[1024];
3130 #if HAVE_GETTIMEOFDAY
3131 gettimeofday (&tv_start, 0);
3134 if ((res = sscanf(line, "%31s %1023[^;]", word, arg)) <= 0)
3136 strcpy(word, last_cmd);
3141 strcpy(last_cmd, word);
3143 /* removed tailing spaces from the arg command */
3146 char* lastnonspace=NULL;
3155 *(++lastnonspace) = 0;
3159 for (i = 0; cmd[i].cmd; i++)
3160 if (!strncmp(cmd[i].cmd, word, strlen(word)))
3162 res = (*cmd[i].fun)(arg);
3166 if (!cmd[i].cmd) /* dump our help-screen */
3168 printf("Unknown command: %s.\n", word);
3169 printf("use help for list of commands\n");
3170 /* cmd_help (""); */
3174 if(apdu_file) fflush(apdu_file);
3177 wait_and_handle_responce();
3186 char *command_generator(const char *text, int state)
3192 for( ; cmd[idx].cmd; ++idx) {
3193 if (!strncmp(cmd[idx].cmd,text,strlen(text))) {
3194 ++idx; /* skip this entry on the next run */
3195 return strdup(cmd[idx-1].cmd);
3203 This function only known how to complete on the first word
3205 char ** readline_completer(char *text, int start, int end) {
3206 #if HAVE_READLINE_READLINE_H
3208 completerFunctionType completerToUse;
3211 #if HAVE_READLINE_RL_COMPLETION_MATCHES
3212 char** res=rl_completion_matches(text,
3215 char** res=completion_matches(text,
3216 (CPFunction*)command_generator);
3218 rl_attempted_completion_over = 1;
3221 char arg[1024],word[32];
3223 if ((res = sscanf(rl_line_buffer, "%31s %1023[^;]", word, arg)) <= 0) {
3224 rl_attempted_completion_over = 1;
3228 for (i = 0; cmd[i].cmd; i++) {
3229 if (!strncmp(cmd[i].cmd, word, strlen(word))) {
3234 if(!cmd[i].cmd) return NULL;
3237 curret_global_list = cmd[i].local_tabcompletes;
3239 completerToUse = cmd[i].rl_completerfunction;
3240 if(completerToUse==NULL) /* if no pr. command completer is defined use the default completer */
3241 completerToUse = default_completer;
3243 if(completerToUse) {
3244 #ifdef HAVE_READLINE_RL_COMPLETION_MATCHES
3246 rl_completion_matches(text,
3250 completion_matches(text,
3251 (CPFunction*)completerToUse);
3253 if(!cmd[i].complete_filenames)
3254 rl_attempted_completion_over = 1;
3257 if(!cmd[i].complete_filenames)
3258 rl_attempted_completion_over = 1;
3268 static void client(void)
3274 #if HAVE_GETTIMEOFDAY
3275 gettimeofday (&tv_start, 0);
3280 char *line_in = NULL;
3281 #if HAVE_READLINE_READLINE_H
3284 line_in=readline(C_PROMPT);
3287 #if HAVE_READLINE_HISTORY_H
3289 add_history(line_in);
3291 strncpy(line, line_in, 1023);
3300 if (!fgets(line, 1023, stdin))
3302 if ((end_p = strchr (line, '\n')))
3305 process_cmd_line(line);
3309 int main(int argc, char **argv)
3312 char *open_command = 0;
3313 char *auth_command = 0;
3318 if (!setlocale(LC_CTYPE, ""))
3319 fprintf (stderr, "setlocale failed\n");
3322 codeset = nl_langinfo(CODESET);
3325 while ((ret = options("k:c:a:m:v:p:u:t:", argv, argc, &arg)) != -2)
3332 open_command = (char *) xmalloc (strlen(arg)+6);
3333 strcpy (open_command, "open ");
3334 strcat (open_command, arg);
3338 kilobytes = atoi(arg);
3341 if (!(marcdump = fopen (arg, "a")))
3351 strncpy (ccl_fields, arg, sizeof(ccl_fields)-1);
3352 ccl_fields[sizeof(ccl_fields)-1] = '\0';
3355 if (!strcmp(arg, "-"))
3358 apdu_file=fopen(arg, "a");
3361 yazProxy=strdup(arg);
3366 auth_command = (char *) xmalloc (strlen(arg)+6);
3367 strcpy (auth_command, "auth ");
3368 strcat (auth_command, arg);
3372 yaz_log_init (yaz_log_mask_str(arg), "", NULL);
3375 fprintf (stderr, "Usage: %s [-m <marclog>] [ -a <apdulog>] "
3376 "[-c cclfields]\n [-p <proxy-addr>] [-u <auth>] "
3377 "[-k size] [<server-addr>]\n",
3385 #ifdef HAVE_GETTIMEOFDAY
3386 gettimeofday (&tv_start, 0);
3388 process_cmd_line (auth_command);
3389 #if HAVE_READLINE_HISTORY_H
3390 add_history(auth_command);
3392 xfree(auth_command);
3396 #ifdef HAVE_GETTIMEOFDAY
3397 gettimeofday (&tv_start, 0);
3399 process_cmd_line (open_command);
3400 #if HAVE_READLINE_HISTORY_H
3401 add_history(open_command);
3403 xfree(open_command);
3414 * vim600: sw=4 ts=8 fdm=marker
3415 * vim<600: sw=4 ts=8