2 * Copyright (c) 1995-2003, Index Data
3 * See the file LICENSE for details.
5 * $Id: client.c,v 1.186 2003-03-19 09:45:55 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>
55 #include "tabcomplete.h"
57 #define C_PROMPT "Z> "
59 static char *codeset = 0; /* character set for output */
61 static ODR out, in, print; /* encoding and decoding streams */
62 static FILE *apdu_file = 0;
63 static FILE *ber_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;
90 static char last_cmd[32] = "?";
91 static FILE *marc_file = 0;
92 static char *refid = NULL;
93 static char *last_open_command = NULL;
94 static int auto_reconnect = 0;
103 static QueryType queryType = QueryType_Prefix;
105 static CCL_bibset bibset; /* CCL bibset handle */
107 #if HAVE_READLINE_COMPLETION_OVER
110 /* readline doesn't have this var. Define it ourselves. */
111 int rl_attempted_completion_over = 0;
114 /* set this one to 1, to avoid decode of unknown MARCs */
115 #define AVOID_MARC_DECODE 1
117 #define maxOtherInfosSupported 10
121 } extraOtherInfos[maxOtherInfosSupported];
124 void process_cmd_line(char* line);
125 char ** readline_completer(char *text, int start, int end);
126 char *command_generator(const char *text, int state);
127 char** curret_global_list=NULL;
128 int cmd_register_tab(const char* arg);
130 static void close_session (void);
132 ODR getODROutputStream()
137 const char* query_type_as_string(QueryType q)
140 case QueryType_Prefix: return "prefix (RPN sent to server)";
141 case QueryType_CCL: return "CCL (CCL sent to server) ";
142 case QueryType_CCL2RPN: return "CCL -> RPN (RPN sent to server)";
143 case QueryType_CQL: return "CQL (CQL sent to server)";
145 return "unknown Query type internal yaz-client error";
150 void do_hex_dump(char* buf,int len)
154 for( i=0; i<len ; i=i+16 )
157 for(x=0 ; i+x<len && x<16; ++x)
159 printf("%2.2X ",(unsigned int)((unsigned char)buf[i+x]));
166 void add_otherInfos(Z_APDU *a)
168 Z_OtherInformation **oi;
172 for(i=0; i<maxOtherInfosSupported; ++i)
174 if(extraOtherInfos[i].oidval != -1)
175 yaz_oi_set_string_oidval(oi, out, extraOtherInfos[i].oidval,
176 1, extraOtherInfos[i].value);
180 void send_apdu(Z_APDU *a)
189 z_APDU(print, &a, 0, 0);
192 if (!z_APDU(out, &a, 0, 0))
194 odr_perror(out, "Encoding APDU");
198 buf = odr_getbuf(out, &len, 0);
200 odr_dumpBER(ber_file, buf, len);
201 /* printf ("sending APDU of size %d\n", len); */
202 if (cs_put(conn, buf, len) < 0)
204 fprintf(stderr, "cs_put: %s", cs_errmsg(cs_errno(conn)));
208 do_hex_dump(buf,len);
209 odr_reset(out); /* release the APDU structure */
212 static void print_stringn(const unsigned char *buf, size_t len)
215 for (i = 0; i<len; i++)
216 if ((buf[i] <= 126 && buf[i] >= 32) || strchr ("\n\r\t\f", buf[i]))
217 printf ("%c", buf[i]);
219 printf ("\\X%02X", buf[i]);
222 static void print_refid (Z_ReferenceId *id)
226 printf ("Reference Id: ");
227 print_stringn (id->buf, id->len);
232 static Z_ReferenceId *set_refid (ODR out)
237 id = (Z_ReferenceId *) odr_malloc (out, sizeof(*id));
238 id->size = id->len = strlen(refid);
239 id->buf = (unsigned char *) odr_malloc (out, id->len);
240 memcpy (id->buf, refid, id->len);
244 /* INIT SERVICE ------------------------------- */
246 static void send_initRequest(const char* type_and_host)
248 Z_APDU *apdu = zget_APDU(out, Z_APDU_initRequest);
249 Z_InitRequest *req = apdu->u.initRequest;
251 ODR_MASK_SET(req->options, Z_Options_search);
252 ODR_MASK_SET(req->options, Z_Options_present);
253 ODR_MASK_SET(req->options, Z_Options_namedResultSets);
254 ODR_MASK_SET(req->options, Z_Options_triggerResourceCtrl);
255 ODR_MASK_SET(req->options, Z_Options_scan);
256 ODR_MASK_SET(req->options, Z_Options_sort);
257 ODR_MASK_SET(req->options, Z_Options_extendedServices);
258 ODR_MASK_SET(req->options, Z_Options_delSet);
260 ODR_MASK_SET(req->protocolVersion, Z_ProtocolVersion_1);
261 ODR_MASK_SET(req->protocolVersion, Z_ProtocolVersion_2);
262 ODR_MASK_SET(req->protocolVersion, Z_ProtocolVersion_3);
264 *req->maximumRecordSize = 1024*kilobytes;
265 *req->preferredMessageSize = 1024*kilobytes;
267 req->idAuthentication = auth;
269 req->referenceId = set_refid (out);
272 yaz_oi_set_string_oidval(&req->otherInfo, out, VAL_PROXY,
275 if (yazCharset || yazLang) {
276 Z_OtherInformation **p;
277 Z_OtherInformationUnit *p0;
279 yaz_oi_APDU(apdu, &p);
281 if ((p0=yaz_oi_update(p, out, NULL, 0, 0))) {
282 ODR_MASK_SET(req->options, Z_Options_negotiationModel);
284 p0->which = Z_OtherInfo_externallyDefinedInfo;
285 p0->information.externallyDefinedInfo =
286 yaz_set_proposal_charneg(out,
287 (const char**)&yazCharset, (yazCharset)?1:0,
288 (const char**)&yazLang, (yazLang)?1:0, 1);
293 printf("Sent initrequest.\n");
296 static int process_initResponse(Z_InitResponse *res)
299 /* save session parameters for later use */
300 session_mem = odr_extract_mem(in);
303 for (ver = 0; ver<5; ver++)
304 if (!ODR_MASK_GET(res->protocolVersion, ver))
308 printf("Connection rejected by v%d target.\n", ver);
310 printf("Connection accepted by v%d target.\n", ver);
311 if (res->implementationId)
312 printf("ID : %s\n", res->implementationId);
313 if (res->implementationName)
314 printf("Name : %s\n", res->implementationName);
315 if (res->implementationVersion)
316 printf("Version: %s\n", res->implementationVersion);
317 if (res->userInformationField)
319 printf("UserInformationfield:\n");
320 if (!z_External(print, (Z_External**)&res-> userInformationField,
323 odr_perror(print, "Printing userinfo\n");
326 if (res->userInformationField->which == Z_External_octet)
328 printf("Guessing visiblestring:\n");
329 printf("'%s'\n", res->userInformationField->u. octet_aligned->buf);
334 if (ODR_MASK_GET(res->options, Z_Options_search))
336 if (ODR_MASK_GET(res->options, Z_Options_present))
338 if (ODR_MASK_GET(res->options, Z_Options_delSet))
340 if (ODR_MASK_GET(res->options, Z_Options_resourceReport))
341 printf (" resourceReport");
342 if (ODR_MASK_GET(res->options, Z_Options_resourceCtrl))
343 printf (" resourceCtrl");
344 if (ODR_MASK_GET(res->options, Z_Options_accessCtrl))
345 printf (" accessCtrl");
346 if (ODR_MASK_GET(res->options, Z_Options_scan))
348 if (ODR_MASK_GET(res->options, Z_Options_sort))
350 if (ODR_MASK_GET(res->options, Z_Options_extendedServices))
351 printf (" extendedServices");
352 if (ODR_MASK_GET(res->options, Z_Options_level_1Segmentation))
353 printf (" level1Segmentation");
354 if (ODR_MASK_GET(res->options, Z_Options_level_2Segmentation))
355 printf (" level2Segmentation");
356 if (ODR_MASK_GET(res->options, Z_Options_concurrentOperations))
357 printf (" concurrentOperations");
358 if (ODR_MASK_GET(res->options, Z_Options_namedResultSets))
360 printf (" namedResultSets");
363 if (ODR_MASK_GET(res->options, Z_Options_encapsulation))
364 printf (" encapsulation");
365 if (ODR_MASK_GET(res->options, Z_Options_resultCount))
366 printf (" resultCount");
367 if (ODR_MASK_GET(res->options, Z_Options_negotiationModel))
368 printf (" negotiationModel");
369 if (ODR_MASK_GET(res->options, Z_Options_duplicateDetection))
370 printf (" duplicateDetection");
371 if (ODR_MASK_GET(res->options, Z_Options_queryType104))
372 printf (" queryType104");
375 if (ODR_MASK_GET(res->options, Z_Options_negotiationModel)) {
377 Z_CharSetandLanguageNegotiation *p =
378 yaz_get_charneg_record(res->otherInfo);
382 char *charset=NULL, *lang=NULL;
385 yaz_get_response_charneg(session_mem, p, &charset, &lang,
388 printf("Accepted character set : %s\n", charset);
389 printf("Accepted code language : %s\n", lang ? lang : "none");
390 printf("Accepted records in ...: %d\n", selected );
397 static int cmd_base(const char *arg)
404 printf("Usage: base <database> <database> ...\n");
407 for (i = 0; i<num_databaseNames; i++)
408 xfree (databaseNames[i]);
409 num_databaseNames = 0;
413 if (!(cp = strchr(arg, ' ')))
414 cp = arg + strlen(arg);
417 databaseNames[num_databaseNames] = (char *)xmalloc (1 + cp - arg);
418 memcpy (databaseNames[num_databaseNames], arg, cp - arg);
419 databaseNames[num_databaseNames][cp - arg] = '\0';
421 for (cp1 = databaseNames[num_databaseNames]; *cp1 ; cp1++)
433 void cmd_open_remember_last_open_command(const char* arg, char* new_open_command)
435 if(last_open_command != arg)
437 if(last_open_command) xfree(last_open_command);
438 last_open_command = xstrdup(new_open_command);
442 int cmd_open(const char *arg)
445 char type_and_host[101];
446 const char *basep = 0;
449 printf("Already connected.\n");
455 nmem_destroy (session_mem);
459 cs_get_host_args(arg, &basep);
461 strncpy(type_and_host, arg, sizeof(type_and_host)-1);
462 type_and_host[sizeof(type_and_host)-1] = '\0';
464 cmd_open_remember_last_open_command(arg,type_and_host);
467 conn = cs_create_host(yazProxy, 1, &add);
469 conn = cs_create_host(arg, 1, &add);
472 printf ("Couldn't create comstack\n");
475 if (conn->protocol == PROTO_HTTP)
477 printf("HTTP transport not supported\n");
482 printf("Connecting...");
484 if (cs_connect(conn, add) < 0)
486 printf ("error = %s\n", cs_strerror(conn));
487 if (conn->cerrno == CSYSERR)
490 yaz_strerror(msg, sizeof(msg));
491 printf ("%s\n", msg);
498 if (conn->protocol == PROTO_Z3950)
499 send_initRequest(type_and_host);
510 if(!( auto_reconnect && last_open_command) ) return ;
512 open_command = (char *) xmalloc (strlen(last_open_command)+6);
513 strcpy (open_command, "open ");
515 strcat (open_command, last_open_command);
517 process_cmd_line(open_command);
522 int cmd_authentication(const char *arg)
524 static Z_IdAuthentication au;
525 static char user[40], group[40], pass[40];
526 static Z_IdPass idPass;
531 printf("Auth field set to null\n");
535 r = sscanf (arg, "%39s %39s %39s", user, group, pass);
538 printf("Auth field set to null\n");
544 au.which = Z_IdAuthentication_open;
550 au.which = Z_IdAuthentication_idPass;
551 au.u.idPass = &idPass;
552 idPass.groupId = NULL;
553 idPass.userId = user;
554 idPass.password = group;
559 au.which = Z_IdAuthentication_idPass;
560 au.u.idPass = &idPass;
561 idPass.groupId = group;
562 idPass.userId = user;
563 idPass.password = pass;
568 /* SEARCH SERVICE ------------------------------ */
569 static void display_record(Z_External *r);
571 static void print_record(const unsigned char *buf, size_t len)
574 print_stringn (buf, len);
575 /* add newline if not already added ... */
576 if (i <= 0 || buf[i-1] != '\n')
580 static void display_record(Z_External *r)
582 oident *ent = oid_getentbyoid(r->direct_reference);
586 * Tell the user what we got.
588 if (r->direct_reference)
590 printf("Record type: ");
592 printf("%s\n", ent->desc);
593 else if (!odr_oid(print, &r->direct_reference, 0, 0))
595 odr_perror(print, "print oid");
599 /* Check if this is a known, ASN.1 type tucked away in an octet string */
600 if (ent && r->which == Z_External_octet)
602 Z_ext_typeent *type = z_ext_getentbyref(ent->value);
608 * Call the given decoder to process the record.
610 odr_setbuf(in, (char*)r->u.octet_aligned->buf,
611 r->u.octet_aligned->len, 0);
612 if (!(*type->fun)(in, (char **)&rr, 0, 0))
614 odr_perror(in, "Decoding constructed record.");
615 fprintf(stdout, "[Near %d]\n", odr_offset(in));
616 fprintf(stdout, "Packet dump:\n---------\n");
617 odr_dumpBER(stdout, (char*)r->u.octet_aligned->buf,
618 r->u.octet_aligned->len);
619 fprintf(stdout, "---------\n");
621 /* note just ignores the error ant print the bytes form the octet_aligned later */
624 * Note: we throw away the original, BER-encoded record here.
625 * Do something else with it if you want to keep it.
627 r->u.sutrs = (Z_SUTRS *) rr; /* we don't actually check the type here. */
628 r->which = type->what;
632 if (ent && ent->oclass != CLASS_RECSYN)
634 if (ent && ent->value == VAL_SOIF)
635 print_record((const unsigned char *) r->u.octet_aligned->buf,
636 r->u.octet_aligned->len);
637 else if (r->which == Z_External_octet)
639 const char *octet_buf = (char*)r->u.octet_aligned->buf;
640 if (ent->value == VAL_TEXT_XML || ent->value == VAL_APPLICATION_XML ||
641 ent->value == VAL_HTML)
643 print_record((const unsigned char *) octet_buf,
644 r->u.octet_aligned->len);
646 else if (ent->value == VAL_POSTSCRIPT)
648 int size = r->u.octet_aligned->len;
651 print_record((const unsigned char *) octet_buf, size);
656 #if AVOID_MARC_DECODE
657 /* primitive check for a marc OID 5.1-29 except 16 */
658 ent->oidsuffix[0] == 5 && ent->oidsuffix[1] < 30 &&
659 ent->oidsuffix[1] != 16
668 yaz_marc_t mt = yaz_marc_create();
670 if (yaz_marc_decode_buf(mt, octet_buf,r->u.octet_aligned->len,
674 if (ent->value == VAL_USMARC)
676 if (octet_buf[9] == 'a')
686 printf ("convert from %s to %s\n", from, codeset);
687 cd = yaz_iconv_open(codeset, from);
690 fwrite (result, 1, rlen, stdout);
694 size_t inbytesleft = rlen;
695 const char *inp = result;
699 size_t outbytesleft = sizeof(outbuf);
701 size_t r = yaz_iconv (cd, (char**) &inp,
703 &outp, &outbytesleft);
704 if (r == (size_t) (-1))
706 int e = yaz_iconv_error(cd);
707 if (e != YAZ_ICONV_E2BIG)
710 fwrite (outbuf, outp - outbuf, 1, stdout);
716 printf ("bad MARC. Dumping as it is:\n");
717 print_record((const unsigned char*) octet_buf,
718 r->u.octet_aligned->len);
720 yaz_marc_destroy(mt);
726 print_record((const unsigned char*) octet_buf,
727 r->u.octet_aligned->len);
731 fwrite (octet_buf, 1, r->u.octet_aligned->len, marc_file);
733 else if (ent && ent->value == VAL_SUTRS)
735 if (r->which != Z_External_sutrs)
737 printf("Expecting single SUTRS type for SUTRS.\n");
740 print_record(r->u.sutrs->buf, r->u.sutrs->len);
742 else if (ent && ent->value == VAL_GRS1)
745 if (r->which != Z_External_grs1)
747 printf("Expecting single GRS type for GRS.\n");
751 yaz_display_grs1(w, r->u.grs1, 0);
757 printf("Unknown record representation.\n");
758 if (!z_External(print, &r, 0, 0))
760 odr_perror(print, "Printing external");
766 static void display_diagrecs(Z_DiagRec **pp, int num)
770 Z_DefaultDiagFormat *r;
772 printf("Diagnostic message(s) from database:\n");
773 for (i = 0; i<num; i++)
775 Z_DiagRec *p = pp[i];
776 if (p->which != Z_DiagRec_defaultFormat)
778 printf("Diagnostic record not in default format.\n");
782 r = p->u.defaultFormat;
783 if (!(ent = oid_getentbyoid(r->diagnosticSetId)) ||
784 ent->oclass != CLASS_DIAGSET || ent->value != VAL_BIB1)
785 printf("Missing or unknown diagset\n");
786 printf(" [%d] %s", *r->condition, diagbib1_str(*r->condition));
789 case Z_DefaultDiagFormat_v2Addinfo:
790 printf (" -- v2 addinfo '%s'\n", r->u.v2Addinfo);
792 case Z_DefaultDiagFormat_v3Addinfo:
793 printf (" -- v3 addinfo '%s'\n", r->u.v3Addinfo);
800 static void display_nameplusrecord(Z_NamePlusRecord *p)
803 printf("[%s]", p->databaseName);
804 if (p->which == Z_NamePlusRecord_surrogateDiagnostic)
805 display_diagrecs(&p->u.surrogateDiagnostic, 1);
806 else if (p->which == Z_NamePlusRecord_databaseRecord)
807 display_record(p->u.databaseRecord);
810 static void display_records(Z_Records *p)
814 if (p->which == Z_Records_NSD)
816 Z_DiagRec dr, *dr_p = &dr;
817 dr.which = Z_DiagRec_defaultFormat;
818 dr.u.defaultFormat = p->u.nonSurrogateDiagnostic;
819 display_diagrecs (&dr_p, 1);
821 else if (p->which == Z_Records_multipleNSD)
822 display_diagrecs (p->u.multipleNonSurDiagnostics->diagRecs,
823 p->u.multipleNonSurDiagnostics->num_diagRecs);
826 printf("Records: %d\n", p->u.databaseOrSurDiagnostics->num_records);
827 for (i = 0; i < p->u.databaseOrSurDiagnostics->num_records; i++)
828 display_nameplusrecord(p->u.databaseOrSurDiagnostics->records[i]);
832 static int send_deleteResultSetRequest(const char *arg)
837 Z_APDU *apdu = zget_APDU(out, Z_APDU_deleteResultSetRequest);
838 Z_DeleteResultSetRequest *req = apdu->u.deleteResultSetRequest;
840 req->referenceId = set_refid (out);
842 req->num_resultSetList =
843 sscanf (arg, "%30s %30s %30s %30s %30s %30s %30s %30s",
844 names[0], names[1], names[2], names[3],
845 names[4], names[5], names[6], names[7]);
847 req->deleteFunction = (int *)
848 odr_malloc (out, sizeof(*req->deleteFunction));
849 if (req->num_resultSetList > 0)
851 *req->deleteFunction = Z_DeleteRequest_list;
852 req->resultSetList = (char **)
853 odr_malloc (out, sizeof(*req->resultSetList)*
854 req->num_resultSetList);
855 for (i = 0; i<req->num_resultSetList; i++)
856 req->resultSetList[i] = names[i];
860 *req->deleteFunction = Z_DeleteRequest_all;
861 req->resultSetList = 0;
865 printf("Sent deleteResultSetRequest.\n");
869 static int send_searchRequest(const char *arg)
871 Z_APDU *apdu = zget_APDU(out, Z_APDU_searchRequest);
872 Z_SearchRequest *req = apdu->u.searchRequest;
875 struct ccl_rpn_node *rpn = NULL;
878 Z_RPNQuery *RPNquery;
880 YAZ_PQF_Parser pqf_parser;
883 if (queryType == QueryType_CCL2RPN)
885 rpn = ccl_find_str(bibset, arg, &error, &pos);
888 printf("CCL ERROR: %s\n", ccl_err_msg(error));
892 req->referenceId = set_refid (out);
893 if (!strcmp(arg, "@big")) /* strictly for troublemaking */
895 static unsigned char big[2100];
898 /* send a very big referenceid to test transport stack etc. */
899 memset(big, 'A', 2100);
900 bigo.len = bigo.size = 2100;
902 req->referenceId = &bigo;
907 sprintf(setstring, "%d", ++setnumber);
908 req->resultSetName = setstring;
910 *req->smallSetUpperBound = smallSetUpperBound;
911 *req->largeSetLowerBound = largeSetLowerBound;
912 *req->mediumSetPresentNumber = mediumSetPresentNumber;
913 if (smallSetUpperBound > 0 || (largeSetLowerBound > 1 &&
914 mediumSetPresentNumber > 0))
918 prefsyn.proto = protocol;
919 prefsyn.oclass = CLASS_RECSYN;
920 prefsyn.value = recordsyntax;
921 req->preferredRecordSyntax =
922 odr_oiddup(out, oid_ent_to_oid(&prefsyn, oid));
923 req->smallSetElementSetNames =
924 req->mediumSetElementSetNames = elementSetNames;
926 req->num_databaseNames = num_databaseNames;
927 req->databaseNames = databaseNames;
933 case QueryType_Prefix:
934 query.which = Z_Query_type_1;
935 pqf_parser = yaz_pqf_create ();
936 RPNquery = yaz_pqf_parse (pqf_parser, out, arg);
941 int code = yaz_pqf_error (pqf_parser, &pqf_msg, &off);
942 printf("%*s^\n", off+4, "");
943 printf("Prefix query error: %s (code %d)\n", pqf_msg, code);
945 yaz_pqf_destroy (pqf_parser);
948 yaz_pqf_destroy (pqf_parser);
949 query.u.type_1 = RPNquery;
952 query.which = Z_Query_type_2;
953 query.u.type_2 = &ccl_query;
954 ccl_query.buf = (unsigned char*) arg;
955 ccl_query.len = strlen(arg);
957 case QueryType_CCL2RPN:
958 query.which = Z_Query_type_1;
959 RPNquery = ccl_rpn_query(out, rpn);
962 printf ("Couldn't convert from CCL to RPN\n");
965 query.u.type_1 = RPNquery;
966 ccl_rpn_delete (rpn);
969 query.which = Z_Query_type_104;
970 ext = (Z_External *) odr_malloc(out, sizeof(*ext));
971 ext->direct_reference = odr_getoidbystr(out, "1.2.840.10003.16.2");
972 ext->indirect_reference = 0;
974 ext->which = Z_External_CQL;
975 ext->u.cql = odr_strdup(out, arg);
976 query.u.type_104 = ext;
979 printf ("Unsupported query type\n");
984 printf("Sent searchRequest.\n");
988 /* display Query Expression as part of searchResult-1 */
989 static void display_queryExpression (Z_QueryExpression *qe)
993 if (qe->which == Z_QueryExpression_term)
995 if (qe->u.term->queryTerm)
997 Z_Term *term = qe->u.term->queryTerm;
1000 case Z_Term_general:
1001 printf (" %.*s", term->u.general->len, term->u.general->buf);
1003 case Z_Term_characterString:
1004 printf (" %s", term->u.characterString);
1006 case Z_Term_numeric:
1007 printf (" %d", *term->u.numeric);
1017 /* see if we can find USR:SearchResult-1 */
1018 static void display_searchResult (Z_OtherInformation *o)
1023 for (i = 0; i < o->num_elements; i++)
1025 if (o->list[i]->which == Z_OtherInfo_externallyDefinedInfo)
1027 Z_External *ext = o->list[i]->information.externallyDefinedInfo;
1029 if (ext->which == Z_External_searchResult1)
1032 Z_SearchInfoReport *sr = ext->u.searchResult1;
1033 printf ("SearchResult-1:");
1034 for (j = 0; j < sr->num; j++)
1036 if (!sr->elements[j]->subqueryExpression)
1038 display_queryExpression (
1039 sr->elements[j]->subqueryExpression);
1040 display_queryExpression (
1041 sr->elements[j]->subqueryInterpretation);
1042 display_queryExpression (
1043 sr->elements[j]->subqueryRecommendation);
1044 if (sr->elements[j]->subqueryCount)
1045 printf ("(%d)", *sr->elements[j]->subqueryCount);
1053 static int process_searchResponse(Z_SearchResponse *res)
1055 printf ("Received SearchResponse.\n");
1056 print_refid (res->referenceId);
1057 if (*res->searchStatus)
1058 printf("Search was a success.\n");
1060 printf("Search was a bloomin' failure.\n");
1061 printf("Number of hits: %d", *res->resultCount);
1063 printf (", setno %d", setnumber);
1065 display_searchResult (res->additionalSearchInfo);
1066 printf("records returned: %d\n",
1067 *res->numberOfRecordsReturned);
1068 setno += *res->numberOfRecordsReturned;
1070 display_records(res->records);
1074 static void print_level(int iLevel)
1077 for (i = 0; i < iLevel * 4; i++)
1081 static void print_int(int iLevel, const char *pTag, int *pInt)
1085 print_level(iLevel);
1086 printf("%s: %d\n", pTag, *pInt);
1090 static void print_string(int iLevel, const char *pTag, const char *pString)
1092 if (pString != NULL)
1094 print_level(iLevel);
1095 printf("%s: %s\n", pTag, pString);
1099 static void print_oid(int iLevel, const char *pTag, Odr_oid *pOid)
1105 print_level(iLevel);
1106 printf("%s:", pTag);
1107 for (; *pInt != -1; pInt++)
1108 printf(" %d", *pInt);
1113 static void print_referenceId(int iLevel, Z_ReferenceId *referenceId)
1115 if (referenceId != NULL)
1119 print_level(iLevel);
1120 printf("Ref Id (%d, %d): ", referenceId->len, referenceId->size);
1121 for (i = 0; i < referenceId->len; i++)
1122 printf("%c", referenceId->buf[i]);
1127 static void print_string_or_numeric(int iLevel, const char *pTag, Z_StringOrNumeric *pStringNumeric)
1129 if (pStringNumeric != NULL)
1131 switch (pStringNumeric->which)
1133 case Z_StringOrNumeric_string:
1134 print_string(iLevel, pTag, pStringNumeric->u.string);
1137 case Z_StringOrNumeric_numeric:
1138 print_int(iLevel, pTag, pStringNumeric->u.numeric);
1142 print_level(iLevel);
1143 printf("%s: valid type for Z_StringOrNumeric\n", pTag);
1149 static void print_universe_report_duplicate(
1151 Z_UniverseReportDuplicate *pUniverseReportDuplicate)
1153 if (pUniverseReportDuplicate != NULL)
1155 print_level(iLevel);
1156 printf("Universe Report Duplicate: \n");
1158 print_string_or_numeric(iLevel, "Hit No",
1159 pUniverseReportDuplicate->hitno);
1163 static void print_universe_report_hits(
1165 Z_UniverseReportHits *pUniverseReportHits)
1167 if (pUniverseReportHits != NULL)
1169 print_level(iLevel);
1170 printf("Universe Report Hits: \n");
1172 print_string_or_numeric(iLevel, "Database",
1173 pUniverseReportHits->database);
1174 print_string_or_numeric(iLevel, "Hits", pUniverseReportHits->hits);
1178 static void print_universe_report(int iLevel, Z_UniverseReport *pUniverseReport)
1180 if (pUniverseReport != NULL)
1182 print_level(iLevel);
1183 printf("Universe Report: \n");
1185 print_int(iLevel, "Total Hits", pUniverseReport->totalHits);
1186 switch (pUniverseReport->which)
1188 case Z_UniverseReport_databaseHits:
1189 print_universe_report_hits(iLevel,
1190 pUniverseReport->u.databaseHits);
1193 case Z_UniverseReport_duplicate:
1194 print_universe_report_duplicate(iLevel,
1195 pUniverseReport->u.duplicate);
1199 print_level(iLevel);
1200 printf("Type: %d\n", pUniverseReport->which);
1206 static void print_external(int iLevel, Z_External *pExternal)
1208 if (pExternal != NULL)
1210 print_level(iLevel);
1211 printf("External: \n");
1213 print_oid(iLevel, "Direct Reference", pExternal->direct_reference);
1214 print_int(iLevel, "InDirect Reference", pExternal->indirect_reference);
1215 print_string(iLevel, "Descriptor", pExternal->descriptor);
1216 switch (pExternal->which)
1218 case Z_External_universeReport:
1219 print_universe_report(iLevel, pExternal->u.universeReport);
1223 print_level(iLevel);
1224 printf("Type: %d\n", pExternal->which);
1230 static int process_resourceControlRequest (Z_ResourceControlRequest *req)
1232 printf ("Received ResourceControlRequest.\n");
1233 print_referenceId(1, req->referenceId);
1234 print_int(1, "Suspended Flag", req->suspendedFlag);
1235 print_int(1, "Partial Results Available", req->partialResultsAvailable);
1236 print_int(1, "Response Required", req->responseRequired);
1237 print_int(1, "Triggered Request Flag", req->triggeredRequestFlag);
1238 print_external(1, req->resourceReport);
1242 void process_ESResponse(Z_ExtendedServicesResponse *res)
1245 switch (*res->operationStatus)
1247 case Z_ExtendedServicesResponse_done:
1250 case Z_ExtendedServicesResponse_accepted:
1251 printf ("accepted\n");
1253 case Z_ExtendedServicesResponse_failure:
1254 printf ("failure\n");
1255 display_diagrecs(res->diagnostics, res->num_diagnostics);
1258 printf ("unknown\n");
1260 if ( (*res->operationStatus != Z_ExtendedServicesResponse_failure) &&
1261 (res->num_diagnostics != 0) ) {
1262 display_diagrecs(res->diagnostics, res->num_diagnostics);
1264 print_refid (res->referenceId);
1265 if (res->taskPackage &&
1266 res->taskPackage->which == Z_External_extendedService)
1268 Z_TaskPackage *taskPackage = res->taskPackage->u.extendedService;
1269 Odr_oct *id = taskPackage->targetReference;
1270 Z_External *ext = taskPackage->taskSpecificParameters;
1274 printf ("Target Reference: ");
1275 print_stringn (id->buf, id->len);
1278 if (ext->which == Z_External_update)
1280 Z_IUUpdateTaskPackage *utp = ext->u.update->u.taskPackage;
1281 if (utp && utp->targetPart)
1283 Z_IUTargetPart *targetPart = utp->targetPart;
1286 for (i = 0; i<targetPart->num_taskPackageRecords; i++)
1289 Z_IUTaskPackageRecordStructure *tpr =
1290 targetPart->taskPackageRecords[i];
1291 printf ("task package record %d\n", i+1);
1292 if (tpr->which == Z_IUTaskPackageRecordStructure_record)
1294 display_record (tpr->u.record);
1298 printf ("other type\n");
1306 const char *get_ill_element (void *clientData, const char *element)
1311 static Z_External *create_external_itemRequest()
1313 struct ill_get_ctl ctl;
1314 ILL_ItemRequest *req;
1316 int item_request_size = 0;
1317 char *item_request_buf = 0;
1321 ctl.f = get_ill_element;
1323 req = ill_get_ItemRequest(&ctl, "ill", 0);
1325 printf ("ill_get_ItemRequest failed\n");
1327 if (!ill_ItemRequest (out, &req, 0, 0))
1331 ill_ItemRequest(print, &req, 0, 0);
1334 item_request_buf = odr_getbuf (out, &item_request_size, 0);
1335 if (item_request_buf)
1336 odr_setbuf (out, item_request_buf, item_request_size, 1);
1337 printf ("Couldn't encode ItemRequest, size %d\n", item_request_size);
1344 item_request_buf = odr_getbuf (out, &item_request_size, 0);
1345 oid.proto = PROTO_GENERAL;
1346 oid.oclass = CLASS_GENERAL;
1347 oid.value = VAL_ISO_ILL_1;
1349 r = (Z_External *) odr_malloc (out, sizeof(*r));
1350 r->direct_reference = odr_oiddup(out,oid_getoidbyent(&oid));
1351 r->indirect_reference = 0;
1353 r->which = Z_External_single;
1355 r->u.single_ASN1_type = (Odr_oct *)
1356 odr_malloc (out, sizeof(*r->u.single_ASN1_type));
1357 r->u.single_ASN1_type->buf = (unsigned char *)
1358 odr_malloc (out, item_request_size);
1359 r->u.single_ASN1_type->len = item_request_size;
1360 r->u.single_ASN1_type->size = item_request_size;
1361 memcpy (r->u.single_ASN1_type->buf, item_request_buf,
1364 do_hex_dump(item_request_buf,item_request_size);
1369 static Z_External *create_external_ILL_APDU(int which)
1371 struct ill_get_ctl ctl;
1374 int ill_request_size = 0;
1375 char *ill_request_buf = 0;
1379 ctl.f = get_ill_element;
1381 ill_apdu = ill_get_APDU(&ctl, "ill", 0);
1383 if (!ill_APDU (out, &ill_apdu, 0, 0))
1387 printf ("-------------------\n");
1388 ill_APDU(print, &ill_apdu, 0, 0);
1390 printf ("-------------------\n");
1392 ill_request_buf = odr_getbuf (out, &ill_request_size, 0);
1393 if (ill_request_buf)
1394 odr_setbuf (out, ill_request_buf, ill_request_size, 1);
1395 printf ("Couldn't encode ILL-Request, size %d\n", ill_request_size);
1401 ill_request_buf = odr_getbuf (out, &ill_request_size, 0);
1403 oid.proto = PROTO_GENERAL;
1404 oid.oclass = CLASS_GENERAL;
1405 oid.value = VAL_ISO_ILL_1;
1407 r = (Z_External *) odr_malloc (out, sizeof(*r));
1408 r->direct_reference = odr_oiddup(out,oid_getoidbyent(&oid));
1409 r->indirect_reference = 0;
1411 r->which = Z_External_single;
1413 r->u.single_ASN1_type = (Odr_oct *)
1414 odr_malloc (out, sizeof(*r->u.single_ASN1_type));
1415 r->u.single_ASN1_type->buf = (unsigned char *)
1416 odr_malloc (out, ill_request_size);
1417 r->u.single_ASN1_type->len = ill_request_size;
1418 r->u.single_ASN1_type->size = ill_request_size;
1419 memcpy (r->u.single_ASN1_type->buf, ill_request_buf, ill_request_size);
1420 /* printf ("len = %d\n", ill_request_size); */
1421 /* do_hex_dump(ill_request_buf,ill_request_size); */
1422 /* printf("--- end of extenal\n"); */
1429 static Z_External *create_ItemOrderExternal(const char *type, int itemno)
1431 Z_External *r = (Z_External *) odr_malloc(out, sizeof(Z_External));
1432 oident ItemOrderRequest;
1434 ItemOrderRequest.proto = PROTO_Z3950;
1435 ItemOrderRequest.oclass = CLASS_EXTSERV;
1436 ItemOrderRequest.value = VAL_ITEMORDER;
1438 r->direct_reference = odr_oiddup(out,oid_getoidbyent(&ItemOrderRequest));
1439 r->indirect_reference = 0;
1442 r->which = Z_External_itemOrder;
1444 r->u.itemOrder = (Z_ItemOrder *) odr_malloc(out,sizeof(Z_ItemOrder));
1445 memset(r->u.itemOrder, 0, sizeof(Z_ItemOrder));
1446 r->u.itemOrder->which=Z_IOItemOrder_esRequest;
1448 r->u.itemOrder->u.esRequest = (Z_IORequest *)
1449 odr_malloc(out,sizeof(Z_IORequest));
1450 memset(r->u.itemOrder->u.esRequest, 0, sizeof(Z_IORequest));
1452 r->u.itemOrder->u.esRequest->toKeep = (Z_IOOriginPartToKeep *)
1453 odr_malloc(out,sizeof(Z_IOOriginPartToKeep));
1454 memset(r->u.itemOrder->u.esRequest->toKeep, 0, sizeof(Z_IOOriginPartToKeep));
1455 r->u.itemOrder->u.esRequest->notToKeep = (Z_IOOriginPartNotToKeep *)
1456 odr_malloc(out,sizeof(Z_IOOriginPartNotToKeep));
1457 memset(r->u.itemOrder->u.esRequest->notToKeep, 0, sizeof(Z_IOOriginPartNotToKeep));
1459 r->u.itemOrder->u.esRequest->toKeep->supplDescription = NULL;
1460 r->u.itemOrder->u.esRequest->toKeep->contact = NULL;
1461 r->u.itemOrder->u.esRequest->toKeep->addlBilling = NULL;
1463 r->u.itemOrder->u.esRequest->notToKeep->resultSetItem =
1464 (Z_IOResultSetItem *) odr_malloc(out, sizeof(Z_IOResultSetItem));
1465 memset(r->u.itemOrder->u.esRequest->notToKeep->resultSetItem, 0, sizeof(Z_IOResultSetItem));
1466 r->u.itemOrder->u.esRequest->notToKeep->resultSetItem->resultSetId = "1";
1468 r->u.itemOrder->u.esRequest->notToKeep->resultSetItem->item =
1469 (int *) odr_malloc(out, sizeof(int));
1470 *r->u.itemOrder->u.esRequest->notToKeep->resultSetItem->item = itemno;
1472 if (!strcmp (type, "item") || !strcmp(type, "2"))
1474 printf ("using item-request\n");
1475 r->u.itemOrder->u.esRequest->notToKeep->itemRequest =
1476 create_external_itemRequest();
1478 else if (!strcmp(type, "ill") || !strcmp(type, "1"))
1480 printf ("using ILL-request\n");
1481 r->u.itemOrder->u.esRequest->notToKeep->itemRequest =
1482 create_external_ILL_APDU(ILL_APDU_ILL_Request);
1484 else if (!strcmp(type, "xml") || !strcmp(type, "3"))
1486 const char *xml_buf =
1488 " <type>request</type>\n"
1489 " <libraryNo>000200</libraryNo>\n"
1490 " <borrowerTicketNo> 1212 </borrowerTicketNo>\n"
1492 r->u.itemOrder->u.esRequest->notToKeep->itemRequest =
1493 z_ext_record (out, VAL_TEXT_XML, xml_buf, strlen(xml_buf));
1496 r->u.itemOrder->u.esRequest->notToKeep->itemRequest = 0;
1501 static int send_itemorder(const char *type, int itemno)
1503 Z_APDU *apdu = zget_APDU(out, Z_APDU_extendedServicesRequest);
1504 Z_ExtendedServicesRequest *req = apdu->u.extendedServicesRequest;
1505 oident ItemOrderRequest;
1507 ItemOrderRequest.proto = PROTO_Z3950;
1508 ItemOrderRequest.oclass = CLASS_EXTSERV;
1509 ItemOrderRequest.value = VAL_ITEMORDER;
1510 req->packageType = odr_oiddup(out,oid_getoidbyent(&ItemOrderRequest));
1511 req->packageName = esPackageName;
1513 req->taskSpecificParameters = create_ItemOrderExternal(type, itemno);
1519 static int cmd_update(const char *arg)
1521 Z_APDU *apdu = zget_APDU(out, Z_APDU_extendedServicesRequest );
1522 Z_ExtendedServicesRequest *req = apdu->u.extendedServicesRequest;
1525 Z_IUOriginPartToKeep *toKeep;
1526 Z_IUSuppliedRecords *notToKeep;
1528 char action[20], recid[20], fname[80];
1530 Z_External *record_this = 0;
1535 sscanf (arg, "%19s %19s %79s", action, recid, fname);
1537 if (!strcmp (action, "insert"))
1538 action_no = Z_IUOriginPartToKeep_recordInsert;
1539 else if (!strcmp (action, "replace"))
1540 action_no = Z_IUOriginPartToKeep_recordReplace;
1541 else if (!strcmp (action, "delete"))
1542 action_no = Z_IUOriginPartToKeep_recordDelete;
1543 else if (!strcmp (action, "update"))
1544 action_no = Z_IUOriginPartToKeep_specialUpdate;
1547 printf ("Bad action: %s\n", action);
1548 printf ("Possible values: insert, replace, delete, update\n");
1556 stat (fname, &status);
1557 if (S_ISREG(status.st_mode) && (inf = fopen(fname, "r")))
1559 size_t len = status.st_size;
1560 char *buf = (char *) xmalloc (len);
1562 fread (buf, 1, len, inf);
1566 record_this = z_ext_record (out, VAL_TEXT_XML, buf, len);
1572 printf ("File %s doesn't exist\n", fname);
1580 printf ("No last record (update ignored)\n");
1583 record_this = record_last;
1586 update_oid.proto = PROTO_Z3950;
1587 update_oid.oclass = CLASS_EXTSERV;
1588 update_oid.value = VAL_DBUPDATE;
1589 oid_ent_to_oid (&update_oid, oid);
1590 req->packageType = odr_oiddup(out,oid);
1591 req->packageName = esPackageName;
1593 req->referenceId = set_refid (out);
1595 r = req->taskSpecificParameters = (Z_External *)
1596 odr_malloc (out, sizeof(*r));
1597 r->direct_reference = odr_oiddup(out,oid);
1598 r->indirect_reference = 0;
1600 r->which = Z_External_update;
1601 r->u.update = (Z_IUUpdate *) odr_malloc(out, sizeof(*r->u.update));
1602 r->u.update->which = Z_IUUpdate_esRequest;
1603 r->u.update->u.esRequest = (Z_IUUpdateEsRequest *)
1604 odr_malloc(out, sizeof(*r->u.update->u.esRequest));
1605 toKeep = r->u.update->u.esRequest->toKeep = (Z_IUOriginPartToKeep *)
1606 odr_malloc(out, sizeof(*r->u.update->u.esRequest->toKeep));
1607 toKeep->databaseName = databaseNames[0];
1609 toKeep->elementSetName = 0;
1610 toKeep->actionQualifier = 0;
1611 toKeep->action = (int *) odr_malloc(out, sizeof(*toKeep->action));
1612 *toKeep->action = action_no;
1614 notToKeep = r->u.update->u.esRequest->notToKeep = (Z_IUSuppliedRecords *)
1615 odr_malloc(out, sizeof(*r->u.update->u.esRequest->notToKeep));
1617 notToKeep->elements = (Z_IUSuppliedRecords_elem **)
1618 odr_malloc(out, sizeof(*notToKeep->elements));
1619 notToKeep->elements[0] = (Z_IUSuppliedRecords_elem *)
1620 odr_malloc(out, sizeof(**notToKeep->elements));
1621 notToKeep->elements[0]->which = Z_IUSuppliedRecords_elem_opaque;
1624 notToKeep->elements[0]->u.opaque = (Odr_oct *)
1625 odr_malloc (out, sizeof(Odr_oct));
1626 notToKeep->elements[0]->u.opaque->buf = (unsigned char *) recid;
1627 notToKeep->elements[0]->u.opaque->size = strlen(recid);
1628 notToKeep->elements[0]->u.opaque->len = strlen(recid);
1631 notToKeep->elements[0]->u.opaque = 0;
1632 notToKeep->elements[0]->supplementalId = 0;
1633 notToKeep->elements[0]->correlationInfo = 0;
1634 notToKeep->elements[0]->record = record_this;
1641 static int cmd_itemorder(const char *arg)
1646 if (sscanf (arg, "%10s %d", type, &itemno) != 2)
1649 printf("Item order request\n");
1651 send_itemorder(type, itemno);
1655 static int cmd_find(const char *arg)
1659 printf("Find what?\n");
1667 printf("Not connected yet\n");
1671 if (!send_searchRequest(arg))
1676 static int cmd_delete(const char *arg)
1680 printf("Not connected yet\n");
1683 if (!send_deleteResultSetRequest(arg))
1688 static int cmd_ssub(const char *arg)
1690 if (!(smallSetUpperBound = atoi(arg)))
1695 static int cmd_lslb(const char *arg)
1697 if (!(largeSetLowerBound = atoi(arg)))
1702 static int cmd_mspn(const char *arg)
1704 if (!(mediumSetPresentNumber = atoi(arg)))
1709 static int cmd_status(const char *arg)
1711 printf("smallSetUpperBound: %d\n", smallSetUpperBound);
1712 printf("largeSetLowerBound: %d\n", largeSetLowerBound);
1713 printf("mediumSetPresentNumber: %d\n", mediumSetPresentNumber);
1717 static int cmd_setnames(const char *arg)
1719 if (*arg == '1') /* enable ? */
1721 else if (*arg == '0') /* disable ? */
1723 else if (setnumber < 0) /* no args, toggle .. */
1729 printf("Set numbering enabled.\n");
1731 printf("Set numbering disabled.\n");
1735 /* PRESENT SERVICE ----------------------------- */
1737 static int send_presentRequest(const char *arg)
1739 Z_APDU *apdu = zget_APDU(out, Z_APDU_presentRequest);
1740 Z_PresentRequest *req = apdu->u.presentRequest;
1741 Z_RecordComposition compo;
1746 char setstring[100];
1748 req->referenceId = set_refid (out);
1749 if ((p = strchr(arg, '+')))
1756 if (p && (p=strchr(p+1, '+')))
1758 strcpy (setstring, p+1);
1759 req->resultSetId = setstring;
1761 else if (setnumber >= 0)
1763 sprintf(setstring, "%d", setnumber);
1764 req->resultSetId = setstring;
1766 req->resultSetStartPoint = &setno;
1767 req->numberOfRecordsRequested = &nos;
1768 prefsyn.proto = protocol;
1769 prefsyn.oclass = CLASS_RECSYN;
1770 prefsyn.value = recordsyntax;
1771 req->preferredRecordSyntax =
1772 odr_oiddup (out, oid_ent_to_oid(&prefsyn, oid));
1774 if (schema != VAL_NONE)
1778 prefschema.proto = protocol;
1779 prefschema.oclass = CLASS_SCHEMA;
1780 prefschema.value = schema;
1782 req->recordComposition = &compo;
1783 compo.which = Z_RecordComp_complex;
1784 compo.u.complex = (Z_CompSpec *)
1785 odr_malloc(out, sizeof(*compo.u.complex));
1786 compo.u.complex->selectAlternativeSyntax = (bool_t *)
1787 odr_malloc(out, sizeof(bool_t));
1788 *compo.u.complex->selectAlternativeSyntax = 0;
1790 compo.u.complex->generic = (Z_Specification *)
1791 odr_malloc(out, sizeof(*compo.u.complex->generic));
1792 compo.u.complex->generic->which = Z_Schema_oid;
1793 compo.u.complex->generic->schema.oid = (Odr_oid *)
1794 odr_oiddup(out, oid_ent_to_oid(&prefschema, oid));
1795 if (!compo.u.complex->generic->schema.oid)
1797 /* OID wasn't a schema! Try record syntax instead. */
1798 prefschema.oclass = CLASS_RECSYN;
1799 compo.u.complex->generic->schema.oid = (Odr_oid *)
1800 odr_oiddup(out, oid_ent_to_oid(&prefschema, oid));
1802 if (!elementSetNames)
1803 compo.u.complex->generic->elementSpec = 0;
1806 compo.u.complex->generic->elementSpec = (Z_ElementSpec *)
1807 odr_malloc(out, sizeof(Z_ElementSpec));
1808 compo.u.complex->generic->elementSpec->which =
1809 Z_ElementSpec_elementSetName;
1810 compo.u.complex->generic->elementSpec->u.elementSetName =
1811 elementSetNames->u.generic;
1813 compo.u.complex->num_dbSpecific = 0;
1814 compo.u.complex->dbSpecific = 0;
1815 compo.u.complex->num_recordSyntax = 0;
1816 compo.u.complex->recordSyntax = 0;
1818 else if (elementSetNames)
1820 req->recordComposition = &compo;
1821 compo.which = Z_RecordComp_simple;
1822 compo.u.simple = elementSetNames;
1825 printf("Sent presentRequest (%d+%d).\n", setno, nos);
1829 static void close_session (void)
1835 nmem_destroy (session_mem);
1844 void process_close(Z_Close *req)
1846 Z_APDU *apdu = zget_APDU(out, Z_APDU_close);
1847 Z_Close *res = apdu->u.close;
1849 static char *reasons[] =
1854 "cost limit reached",
1856 "security violation",
1863 printf("Reason: %s, message: %s\n", reasons[*req->closeReason],
1864 req->diagnosticInformation ? req->diagnosticInformation : "NULL");
1869 *res->closeReason = Z_Close_finished;
1871 printf("Sent response.\n");
1876 static int cmd_show(const char *arg)
1880 printf("Not connected yet\n");
1883 if (!send_presentRequest(arg))
1888 int cmd_quit(const char *arg)
1890 printf("See you later, alligator.\n");
1896 int cmd_cancel(const char *arg)
1898 Z_APDU *apdu = zget_APDU(out, Z_APDU_triggerResourceControlRequest);
1899 Z_TriggerResourceControlRequest *req =
1900 apdu->u.triggerResourceControlRequest;
1905 printf("Session not initialized yet\n");
1908 if (!ODR_MASK_GET(session->options, Z_Options_triggerResourceCtrl))
1910 printf("Target doesn't support cancel (trigger resource ctrl)\n");
1913 *req->requestedAction = Z_TriggerResourceCtrl_cancel;
1914 req->resultSetWanted = &rfalse;
1917 printf("Sent cancel request\n");
1921 int send_scanrequest(const char *query, int pp, int num, const char *term)
1923 Z_APDU *apdu = zget_APDU(out, Z_APDU_scanRequest);
1924 Z_ScanRequest *req = apdu->u.scanRequest;
1927 if (queryType == QueryType_CCL2RPN)
1931 struct ccl_rpn_node *rpn;
1933 rpn = ccl_find_str (bibset, query, &error, &pos);
1936 printf("CCL ERROR: %s\n", ccl_err_msg(error));
1939 bib1.proto = PROTO_Z3950;
1940 bib1.oclass = CLASS_ATTSET;
1941 bib1.value = VAL_BIB1;
1942 req->attributeSet = oid_ent_to_oid (&bib1, oid);
1943 if (!(req->termListAndStartPoint = ccl_scan_query (out, rpn)))
1945 printf("Couldn't convert CCL to Scan term\n");
1948 ccl_rpn_delete (rpn);
1952 YAZ_PQF_Parser pqf_parser = yaz_pqf_create ();
1954 if (!(req->termListAndStartPoint =
1955 yaz_pqf_scan(pqf_parser, out, &req->attributeSet, query)))
1957 const char *pqf_msg;
1959 int code = yaz_pqf_error (pqf_parser, &pqf_msg, &off);
1960 printf("%*s^\n", off+7, "");
1961 printf("Prefix query error: %s (code %d)\n", pqf_msg, code);
1962 yaz_pqf_destroy (pqf_parser);
1965 yaz_pqf_destroy (pqf_parser);
1969 if (req->termListAndStartPoint->term &&
1970 req->termListAndStartPoint->term->which == Z_Term_general &&
1971 req->termListAndStartPoint->term->u.general)
1973 req->termListAndStartPoint->term->u.general->buf =
1974 (unsigned char *) odr_strdup(out, term);
1975 req->termListAndStartPoint->term->u.general->len =
1976 req->termListAndStartPoint->term->u.general->size =
1980 req->referenceId = set_refid (out);
1981 req->num_databaseNames = num_databaseNames;
1982 req->databaseNames = databaseNames;
1983 req->numberOfTermsRequested = #
1984 req->preferredPositionInResponse = &pp;
1989 int send_sortrequest(const char *arg, int newset)
1991 Z_APDU *apdu = zget_APDU(out, Z_APDU_sortRequest);
1992 Z_SortRequest *req = apdu->u.sortRequest;
1993 Z_SortKeySpecList *sksl = (Z_SortKeySpecList *)
1994 odr_malloc (out, sizeof(*sksl));
1998 sprintf (setstring, "%d", setnumber);
2000 sprintf (setstring, "default");
2002 req->referenceId = set_refid (out);
2004 req->num_inputResultSetNames = 1;
2005 req->inputResultSetNames = (Z_InternationalString **)
2006 odr_malloc (out, sizeof(*req->inputResultSetNames));
2007 req->inputResultSetNames[0] = odr_strdup (out, setstring);
2009 if (newset && setnumber >= 0)
2010 sprintf (setstring, "%d", ++setnumber);
2012 req->sortedResultSetName = odr_strdup (out, setstring);
2014 req->sortSequence = yaz_sort_spec (out, arg);
2015 if (!req->sortSequence)
2017 printf ("Missing sort specifications\n");
2024 void display_term(Z_TermInfo *t)
2026 if (t->term->which == Z_Term_general)
2028 printf("%.*s", t->term->u.general->len, t->term->u.general->buf);
2029 sprintf(last_scan_line, "%.*s", t->term->u.general->len,
2030 t->term->u.general->buf);
2033 printf("Term (not general)");
2034 if (t->globalOccurrences)
2035 printf (" (%d)\n", *t->globalOccurrences);
2040 void process_scanResponse(Z_ScanResponse *res)
2043 Z_Entry **entries = NULL;
2044 int num_entries = 0;
2046 printf("Received ScanResponse\n");
2047 print_refid (res->referenceId);
2048 printf("%d entries", *res->numberOfEntriesReturned);
2049 if (res->positionOfTerm)
2050 printf (", position=%d", *res->positionOfTerm);
2052 if (*res->scanStatus != Z_Scan_success)
2053 printf("Scan returned code %d\n", *res->scanStatus);
2056 if ((entries = res->entries->entries))
2057 num_entries = res->entries->num_entries;
2058 for (i = 0; i < num_entries; i++)
2060 int pos_term = res->positionOfTerm ? *res->positionOfTerm : -1;
2061 if (entries[i]->which == Z_Entry_termInfo)
2063 printf("%c ", i + 1 == pos_term ? '*' : ' ');
2064 display_term(entries[i]->u.termInfo);
2067 display_diagrecs(&entries[i]->u.surrogateDiagnostic, 1);
2069 if (res->entries->nonsurrogateDiagnostics)
2070 display_diagrecs (res->entries->nonsurrogateDiagnostics,
2071 res->entries->num_nonsurrogateDiagnostics);
2074 void process_sortResponse(Z_SortResponse *res)
2076 printf("Received SortResponse: status=");
2077 switch (*res->sortStatus)
2079 case Z_SortStatus_success:
2080 printf ("success"); break;
2081 case Z_SortStatus_partial_1:
2082 printf ("partial"); break;
2083 case Z_SortStatus_failure:
2084 printf ("failure"); break;
2086 printf ("unknown (%d)", *res->sortStatus);
2089 print_refid (res->referenceId);
2090 if (res->diagnostics)
2091 display_diagrecs(res->diagnostics,
2092 res->num_diagnostics);
2095 void process_deleteResultSetResponse (Z_DeleteResultSetResponse *res)
2097 printf("Got deleteResultSetResponse status=%d\n",
2098 *res->deleteOperationStatus);
2099 if (res->deleteListStatuses)
2102 for (i = 0; i < res->deleteListStatuses->num; i++)
2104 printf ("%s status=%d\n", res->deleteListStatuses->elements[i]->id,
2105 *res->deleteListStatuses->elements[i]->status);
2110 int cmd_sort_generic(const char *arg, int newset)
2114 printf("Session not initialized yet\n");
2117 if (!ODR_MASK_GET(session->options, Z_Options_sort))
2119 printf("Target doesn't support sort\n");
2124 if (send_sortrequest(arg, newset) < 0)
2131 int cmd_sort(const char *arg)
2133 return cmd_sort_generic (arg, 0);
2136 int cmd_sort_newset (const char *arg)
2138 return cmd_sort_generic (arg, 1);
2141 int cmd_scan(const char *arg)
2148 printf("Session not initialized yet\n");
2152 if (!ODR_MASK_GET(session->options, Z_Options_scan))
2154 printf("Target doesn't support scan\n");
2159 strcpy (last_scan_query, arg);
2160 if (send_scanrequest(arg, 1, 20, 0) < 0)
2165 if (send_scanrequest(last_scan_query, 1, 20, last_scan_line) < 0)
2171 int cmd_schema(const char *arg)
2178 schema = oid_getvalbyname (arg);
2179 if (schema == VAL_NONE)
2181 printf ("unknown schema\n");
2187 int cmd_format(const char *arg)
2192 printf("Usage: format <recordsyntax>\n");
2195 nsyntax = oid_getvalbyname (arg);
2196 if (strcmp(arg, "none") && nsyntax == VAL_NONE)
2198 printf ("unknown record syntax\n");
2201 recordsyntax = nsyntax;
2205 int cmd_elements(const char *arg)
2207 static Z_ElementSetNames esn;
2208 static char what[100];
2212 elementSetNames = 0;
2216 esn.which = Z_ElementSetNames_generic;
2217 esn.u.generic = what;
2218 elementSetNames = &esn;
2222 int cmd_attributeset(const char *arg)
2228 printf("Usage: attributeset <setname>\n");
2231 sscanf(arg, "%s", what);
2232 if (p_query_attset (what))
2234 printf("Unknown attribute set name\n");
2240 int cmd_querytype (const char *arg)
2242 if (!strcmp (arg, "ccl"))
2243 queryType = QueryType_CCL;
2244 else if (!strcmp (arg, "prefix") || !strcmp(arg, "rpn"))
2245 queryType = QueryType_Prefix;
2246 else if (!strcmp (arg, "ccl2rpn") || !strcmp (arg, "cclrpn"))
2247 queryType = QueryType_CCL2RPN;
2248 else if (!strcmp(arg, "cql"))
2249 queryType = QueryType_CQL;
2252 printf ("Querytype must be one of:\n");
2253 printf (" prefix - Prefix query\n");
2254 printf (" ccl - CCL query\n");
2255 printf (" ccl2rpn - CCL query converted to RPN\n");
2256 printf (" cql - CQL\n");
2262 int cmd_refid (const char *arg)
2268 refid = (char *) xmalloc (strlen(arg)+1);
2269 strcpy (refid, arg);
2274 int cmd_close(const char *arg)
2281 apdu = zget_APDU(out, Z_APDU_close);
2282 req = apdu->u.close;
2283 *req->closeReason = Z_Close_finished;
2285 printf("Sent close request.\n");
2290 int cmd_packagename(const char* arg)
2292 xfree (esPackageName);
2293 esPackageName = NULL;
2296 esPackageName = (char *) xmalloc (strlen(arg)+1);
2297 strcpy (esPackageName, arg);
2302 int cmd_proxy(const char* arg)
2313 yazProxy = (char *) xmalloc (strlen(arg)+1);
2314 strcpy (yazProxy, arg);
2319 int cmd_charset(const char* arg)
2321 char l1[30], l2[30];
2324 if (sscanf(arg, "%29s %29s", l1, l2) < 1)
2326 printf("Current character set is `%s'\n", (yazCharset) ? yazCharset:NULL);
2332 yazCharset = xstrdup(l1);
2335 odr_set_charset (out, l1, l2);
2336 odr_set_charset (in, l2, l1);
2341 int cmd_lang(const char* arg)
2344 printf("Current language is `%s'\n", (yazLang)?yazLang:NULL);
2351 yazLang = (char *) xmalloc (strlen(arg)+1);
2352 strcpy (yazLang, arg);
2357 int cmd_source(const char* arg)
2359 /* first should open the file and read one line at a time.. */
2361 char line[1024], *cp;
2364 fprintf(stderr,"Error in source command use a filename\n");
2368 includeFile = fopen (arg, "r");
2371 fprintf(stderr,"Unable to open file %s for reading\n",arg);
2375 while(!feof(includeFile)) {
2376 memset(line,0,sizeof(line));
2377 fgets(line,sizeof(line),includeFile);
2379 if(strlen(line) < 2) continue;
2380 if(line[0] == '#') continue;
2382 if ((cp = strrchr (line, '\n')))
2385 process_cmd_line(line);
2388 if(fclose(includeFile)<0) {
2389 perror("unable to close include file");
2395 int cmd_subshell(const char* args)
2400 system(getenv("SHELL"));
2406 int cmd_set_berfile(const char *arg)
2408 if (ber_file && ber_file != stdout && ber_file != stderr)
2410 if (!strcmp(arg, ""))
2412 else if (!strcmp(arg, "-"))
2415 ber_file = fopen(arg, "a");
2419 int cmd_set_apdufile(const char *arg)
2421 if(apdu_file && apdu_file != stderr && apdu_file != stderr)
2423 if (!strcmp(arg, ""))
2425 else if (!strcmp(arg, "-"))
2429 apdu_file = fopen(arg, "a");
2431 perror("unable to open apdu log file");
2436 int cmd_set_cclfile(const char* arg)
2440 bibset = ccl_qual_mk ();
2441 inf = fopen (arg, "r");
2443 perror("unable to open CCL file");
2446 ccl_qual_file (bibset, inf);
2449 strcpy(ccl_fields,arg);
2453 int cmd_set_auto_reconnect(const char* arg)
2455 if(strlen(arg)==0) {
2456 auto_reconnect = ! auto_reconnect;
2457 } else if(strcmp(arg,"on")==0) {
2459 } else if(strcmp(arg,"off")==0) {
2462 printf("Error use on or off\n");
2467 printf("Set auto reconnect enabled.\n");
2469 printf("Set auto reconnect disabled.\n");
2474 int cmd_set_marcdump(const char* arg)
2476 if(marc_file && marc_file != stderr) { /* don't close stdout*/
2480 if (!strcmp(arg, ""))
2482 else if (!strcmp(arg, "-"))
2486 marc_file = fopen(arg, "a");
2488 perror("unable to open marc log file");
2493 int cmd_set_proxy(const char* arg)
2495 if(yazProxy) free(yazProxy);
2498 if(strlen(arg) > 1) {
2499 yazProxy=strdup(arg);
2505 this command takes 3 arge {name class oid}
2507 int cmd_register_oid(const char* args) {
2512 {"appctx",CLASS_APPCTX},
2513 {"absyn",CLASS_ABSYN},
2514 {"attset",CLASS_ATTSET},
2515 {"transyn",CLASS_TRANSYN},
2516 {"diagset",CLASS_DIAGSET},
2517 {"recsyn",CLASS_RECSYN},
2518 {"resform",CLASS_RESFORM},
2519 {"accform",CLASS_ACCFORM},
2520 {"extserv",CLASS_EXTSERV},
2521 {"userinfo",CLASS_USERINFO},
2522 {"elemspec",CLASS_ELEMSPEC},
2523 {"varset",CLASS_VARSET},
2524 {"schema",CLASS_SCHEMA},
2525 {"tagset",CLASS_TAGSET},
2526 {"general",CLASS_GENERAL},
2527 {0,(enum oid_class) 0}
2529 char oname_str[101], oclass_str[101], oid_str[101];
2532 oid_class oidclass = CLASS_GENERAL;
2533 int val = 0, oid[OID_SIZE];
2534 struct oident * new_oident=NULL;
2536 if (sscanf (args, "%100[^ ] %100[^ ] %100s",
2537 oname_str,oclass_str, oid_str) < 1) {
2538 printf("Error in regristrate command \n");
2542 for (i = 0; oid_classes[i].className; i++) {
2543 if (!strcmp(oid_classes[i].className, oclass_str))
2545 oidclass=oid_classes[i].oclass;
2550 if(!(oid_classes[i].className)) {
2551 printf("Unknonwn oid class %s\n",oclass_str);
2559 while (isdigit (*name))
2561 val = val*10 + (*name - '0');
2574 new_oident=oid_addent (oid,PROTO_GENERAL,oidclass,oname_str,VAL_DYNAMIC);
2575 if(strcmp(new_oident->desc,oname_str)) {
2576 fprintf(stderr,"oid is already named as %s, regristration faild\n",
2582 int cmd_push_command(const char* arg)
2584 #if HAVE_READLINE_HISTORY_H
2588 fprintf(stderr,"Not compiled with the readline/history module\n");
2593 void source_rcfile()
2595 /* Look for a $HOME/.yazclientrc and source it if it exists */
2596 struct stat statbuf;
2598 char* homedir=getenv("HOME");
2600 if(!homedir) return;
2602 sprintf(buffer,"%s/.yazclientrc",homedir);
2604 if(stat(buffer,&statbuf)==0) {
2608 if(stat(".yazclientrc",&statbuf)==0) {
2609 cmd_source(".yazclientrc");
2614 static void initialize(void)
2619 if (!(out = odr_createmem(ODR_ENCODE)) ||
2620 !(in = odr_createmem(ODR_DECODE)) ||
2621 !(print = odr_createmem(ODR_PRINT)))
2623 fprintf(stderr, "failed to allocate ODR streams\n");
2628 setvbuf(stdout, 0, _IONBF, 0);
2630 odr_setprint(print, apdu_file);
2632 bibset = ccl_qual_mk ();
2633 inf = fopen (ccl_fields, "r");
2636 ccl_qual_file (bibset, inf);
2639 cmd_base("Default");
2641 #if HAVE_READLINE_READLINE_H
2642 rl_attempted_completion_function = (CPPFunction*)readline_completer;
2646 for(i=0; i<maxOtherInfosSupported; ++i) {
2647 extraOtherInfos[i].oidval = -1;
2654 #if HAVE_GETTIMEOFDAY
2655 struct timeval tv_start, tv_end;
2658 void wait_and_handle_responce()
2663 int netbufferlen = 0;
2671 if ((res = cs_get(conn, &netbuffer, &netbufferlen)) < 0)
2673 printf("Target closed connection\n");
2679 printf("Target closed connection.\n");
2683 odr_reset(in); /* release APDU from last round */
2685 odr_setbuf(in, netbuffer, res, 0);
2686 if (!z_APDU(in, &apdu, 0, 0))
2688 FILE *f = ber_file ? ber_file : stdout;
2689 odr_perror(in, "Decoding incoming APDU");
2690 fprintf(f, "[Near %d]\n", odr_offset(in));
2691 fprintf(f, "Packet dump:\n---------\n");
2692 odr_dumpBER(f, netbuffer, res);
2693 fprintf(f, "---------\n");
2695 z_APDU(print, &apdu, 0, 0);
2700 odr_dumpBER(ber_file, netbuffer, res);
2701 if (apdu_file && !z_APDU(print, &apdu, 0, 0))
2703 odr_perror(print, "Failed to print incoming APDU");
2709 case Z_APDU_initResponse:
2710 process_initResponse(apdu->u.initResponse);
2712 case Z_APDU_searchResponse:
2713 process_searchResponse(apdu->u.searchResponse);
2715 case Z_APDU_scanResponse:
2716 process_scanResponse(apdu->u.scanResponse);
2718 case Z_APDU_presentResponse:
2719 print_refid (apdu->u.presentResponse->referenceId);
2721 *apdu->u.presentResponse->numberOfRecordsReturned;
2722 if (apdu->u.presentResponse->records)
2723 display_records(apdu->u.presentResponse->records);
2725 printf("No records.\n");
2726 printf ("nextResultSetPosition = %d\n",
2727 *apdu->u.presentResponse->nextResultSetPosition);
2729 case Z_APDU_sortResponse:
2730 process_sortResponse(apdu->u.sortResponse);
2732 case Z_APDU_extendedServicesResponse:
2733 printf("Got extended services response\n");
2734 process_ESResponse(apdu->u.extendedServicesResponse);
2737 printf("Target has closed the association.\n");
2738 process_close(apdu->u.close);
2740 case Z_APDU_resourceControlRequest:
2741 process_resourceControlRequest
2742 (apdu->u.resourceControlRequest);
2744 case Z_APDU_deleteResultSetResponse:
2745 process_deleteResultSetResponse(apdu->u.
2746 deleteResultSetResponse);
2749 printf("Received unknown APDU type (%d).\n",
2754 while (conn && cs_more(conn));
2755 #if HAVE_GETTIMEOFDAY
2756 gettimeofday (&tv_end, 0);
2758 printf ("S/U S/U=%ld/%ld %ld/%ld",
2759 (long) tv_start.tv_sec,
2760 (long) tv_start.tv_usec,
2761 (long) tv_end.tv_sec,
2762 (long) tv_end.tv_usec);
2764 printf ("Elapsed: %.6f\n",
2765 (double) tv_end.tv_usec / 1e6 + tv_end.tv_sec -
2766 ((double) tv_start.tv_usec / 1e6 + tv_start.tv_sec));
2773 int cmd_cclparse(const char* arg)
2776 struct ccl_rpn_node *rpn=NULL;
2779 rpn = ccl_find_str (bibset, arg, &error, &pos);
2782 printf ("%*s^ - ", 3+strlen(last_cmd)+1+pos, " ");
2783 printf ("%s\n", ccl_err_msg (error));
2789 ccl_pr_tree(rpn, stdout);
2793 ccl_rpn_delete(rpn);
2801 int cmd_set_otherinfo(const char* args)
2803 char oid[101], otherinfoString[101];
2808 sscan_res = sscanf (args, "%d %100[^ ] %100s", &otherinfoNo, oid, otherinfoString);
2810 /* reset this otherinfo */
2811 if(otherinfoNo>=maxOtherInfosSupported) {
2812 printf("Error otherinfo index to large (%d>%d)\n",otherinfoNo,maxOtherInfosSupported);
2814 extraOtherInfos[otherinfoNo].oidval = -1;
2815 if(extraOtherInfos[otherinfoNo].value) free(extraOtherInfos[otherinfoNo].value);
2819 printf("Error in set_otherinfo command \n");
2823 if(otherinfoNo>=maxOtherInfosSupported) {
2824 printf("Error otherinfo index to large (%d>%d)\n",otherinfoNo,maxOtherInfosSupported);
2828 oidval = oid_getvalbyname (oid);
2830 printf("Error in set_otherinfo command unknown oid %s \n",oid);
2833 extraOtherInfos[otherinfoNo].oidval = oidval;
2834 if(extraOtherInfos[otherinfoNo].value) free(extraOtherInfos[otherinfoNo].value);
2835 extraOtherInfos[otherinfoNo].value = strdup(otherinfoString);
2840 int cmd_list_otherinfo(const char* args)
2844 if(strlen(args)>0) {
2846 if( i >= maxOtherInfosSupported ) {
2847 printf("Error otherinfo index to large (%d>%d)\n",i,maxOtherInfosSupported);
2851 if(extraOtherInfos[i].oidval != -1)
2852 printf(" otherinfo %d %s %s\n",
2854 yaz_z3950_oid_value_to_str(
2855 (enum oid_value) extraOtherInfos[i].oidval,
2857 extraOtherInfos[i].value);
2860 for(i=0; i<maxOtherInfosSupported; ++i) {
2861 if(extraOtherInfos[i].oidval != -1)
2862 printf(" otherinfo %d %s %s\n",
2864 yaz_z3950_oid_value_to_str(
2865 (enum oid_value) extraOtherInfos[i].oidval,
2867 extraOtherInfos[i].value);
2875 int cmd_list_all(const char* args) {
2878 /* connection options */
2880 printf("Connected to : %s\n",last_open_command);
2882 if(last_open_command)
2883 printf("Not connected to : %s\n",last_open_command);
2885 printf("Not connected : \n");
2888 if(yazProxy) printf("using proxy : %s\n",yazProxy);
2890 printf("auto_reconnect : %s\n",auto_reconnect?"on":"off");
2893 printf("Authentication : none\n");
2895 switch(auth->which) {
2896 case Z_IdAuthentication_idPass:
2897 printf("Authentication : IdPass\n");
2898 printf(" Login User : %s\n",auth->u.idPass->userId?auth->u.idPass->userId:"");
2899 printf(" Login Group : %s\n",auth->u.idPass->groupId?auth->u.idPass->groupId:"");
2900 printf(" Password : %s\n",auth->u.idPass->password?auth->u.idPass->password:"");
2902 case Z_IdAuthentication_open:
2903 printf("Authentication : psOpen\n");
2904 printf(" Open string : %s\n",auth->u.open);
2907 printf("Authentication : Unknown\n");
2910 if ( yazCharset ) printf("Character set : `%s'\n", (yazCharset) ? yazCharset:NULL);
2914 for (i = 0; i<num_databaseNames; i++) printf("%s ",databaseNames[i]);
2918 printf("CCL file : %s\n",ccl_fields);
2919 printf("Query type : %s\n",query_type_as_string(queryType));
2921 printf("Named Result Sets : %s\n",setnumber==-1?"off":"on");
2923 /* piggy back options */
2924 printf("ssub/lslb/mspn : %d/%d/%d\n",smallSetUpperBound,largeSetLowerBound,mediumSetPresentNumber);
2926 /* print present related options */
2927 printf("Format : %s\n",yaz_z3950_oid_value_to_str(recordsyntax,CLASS_RECSYN));
2928 printf("Schema : %s\n",yaz_z3950_oid_value_to_str(schema,CLASS_SCHEMA));
2929 printf("Elements : %s\n",elementSetNames?elementSetNames->u.generic:"");
2931 /* loging options */
2932 printf("APDU log : %s\n",apdu_file?"on":"off");
2933 printf("Record log : %s\n",marc_file?"on":"off");
2936 printf("Other Info: \n");
2937 cmd_list_otherinfo("");
2942 int cmd_clear_otherinfo(const char* args)
2944 if(strlen(args)>0) {
2946 otherinfoNo = atoi(args);
2947 if( otherinfoNo >= maxOtherInfosSupported ) {
2948 printf("Error otherinfo index to large (%d>%d)\n",otherinfoNo,maxOtherInfosSupported);
2952 if(extraOtherInfos[otherinfoNo].oidval != -1) {
2953 /* only clear if set. */
2954 extraOtherInfos[otherinfoNo].oidval=-1;
2955 free(extraOtherInfos[otherinfoNo].value);
2960 for(i=0; i<maxOtherInfosSupported; ++i) {
2961 if (extraOtherInfos[i].oidval!=-1 ) {
2962 extraOtherInfos[i].oidval=-1;
2963 free(extraOtherInfos[i].value);
2970 static int cmd_help (const char *line);
2972 typedef char *(*completerFunctionType)(const char *text, int state);
2976 int (*fun)(const char *arg);
2978 completerFunctionType rl_completerfunction;
2979 int complete_filenames;
2980 char **local_tabcompletes;
2982 {"open", cmd_open, "('tcp'|'ssl')':<host>[':'<port>][/<db>]",NULL,0,NULL},
2983 {"quit", cmd_quit, "",NULL,0,NULL},
2984 {"find", cmd_find, "<query>",NULL,0,NULL},
2985 {"delete", cmd_delete, "<setname>",NULL,0,NULL},
2986 {"base", cmd_base, "<base-name>",NULL,0,NULL},
2987 {"show", cmd_show, "<rec#>['+'<#recs>['+'<setname>]]",NULL,0,NULL},
2988 {"scan", cmd_scan, "<term>",NULL,0,NULL},
2989 {"sort", cmd_sort, "<sortkey> <flag> <sortkey> <flag> ...",NULL,0,NULL},
2990 {"sort+", cmd_sort_newset, "<sortkey> <flag> <sortkey> <flag> ...",NULL,0,NULL},
2991 {"authentication", cmd_authentication, "<acctstring>",NULL,0,NULL},
2992 {"lslb", cmd_lslb, "<largeSetLowerBound>",NULL,0,NULL},
2993 {"ssub", cmd_ssub, "<smallSetUpperBound>",NULL,0,NULL},
2994 {"mspn", cmd_mspn, "<mediumSetPresentNumber>",NULL,0,NULL},
2995 {"status", cmd_status, "",NULL,0,NULL},
2996 {"setnames", cmd_setnames, "",NULL,0,NULL},
2997 {"cancel", cmd_cancel, "",NULL,0,NULL},
2998 {"format", cmd_format, "<recordsyntax>",complete_format,0,NULL},
2999 {"schema", cmd_schema, "<schema>",complete_schema,0,NULL},
3000 {"elements", cmd_elements, "<elementSetName>",NULL,0,NULL},
3001 {"close", cmd_close, "",NULL,0,NULL},
3002 {"attributeset", cmd_attributeset, "<attrset>",complete_attributeset,0,NULL},
3003 {"querytype", cmd_querytype, "<type>",complete_querytype,0,NULL},
3004 {"refid", cmd_refid, "<id>",NULL,0,NULL},
3005 {"itemorder", cmd_itemorder, "ill|item <itemno>",NULL,0,NULL},
3006 {"update", cmd_update, "<action> <recid> [<file>]",NULL,0,NULL},
3007 {"packagename", cmd_packagename, "<packagename>",NULL,0,NULL},
3008 {"proxy", cmd_proxy, "[('tcp'|'ssl')]<host>[':'<port>]",NULL,0,NULL},
3009 {"charset", cmd_charset, "<charset_name>",NULL,0,NULL},
3010 {"lang", cmd_lang, "<language_code>",NULL,0,NULL},
3011 {".", cmd_source, "<filename>",NULL,1,NULL},
3012 {"!", cmd_subshell, "Subshell command",NULL,1,NULL},
3013 {"set_apdufile", cmd_set_apdufile, "<filename>",NULL,1,NULL},
3014 {"set_berfile", cmd_set_berfile, "<filename>",NULL,1,NULL},
3015 {"set_marcdump", cmd_set_marcdump," <filename>",NULL,1,NULL},
3016 {"set_cclfile", cmd_set_cclfile," <filename>",NULL,1,NULL},
3017 {"set_auto_reconnect", cmd_set_auto_reconnect," on|off",complete_auto_reconnect,1,NULL},
3018 {"set_otherinfo", cmd_set_otherinfo,"<otherinfoinddex> <oid> <string>",NULL,0,NULL},
3019 {"register_oid", cmd_register_oid,"<name> <class> <oid>",NULL,0,NULL},
3020 {"push_command", cmd_push_command,"<command>",command_generator,0,NULL},
3021 {"register_tab", cmd_register_tab,"<commandname> <tab>",command_generator,0,NULL},
3022 {"cclparse", cmd_cclparse,"<ccl find command>",NULL,0,NULL},
3023 {"list_otherinfo",cmd_list_otherinfo,"[otherinfoinddex]",NULL,0,NULL},
3024 {"list_all",cmd_list_all,"",NULL,0,NULL},
3025 {"clear_otherinfo",cmd_clear_otherinfo,"",NULL,0,NULL},
3026 /* Server Admin Functions */
3027 {"adm-reindex", cmd_adm_reindex, "<database-name>",NULL,0,NULL},
3028 {"adm-truncate", cmd_adm_truncate, "('database'|'index')<object-name>",NULL,0,NULL},
3029 {"adm-create", cmd_adm_create, "",NULL,0,NULL},
3030 {"adm-drop", cmd_adm_drop, "('database'|'index')<object-name>",NULL,0,NULL},
3031 {"adm-import", cmd_adm_import, "<record-type> <dir> <pattern>",NULL,0,NULL},
3032 {"adm-refresh", cmd_adm_refresh, "",NULL,0,NULL},
3033 {"adm-commit", cmd_adm_commit, "",NULL,0,NULL},
3034 {"adm-shutdown", cmd_adm_shutdown, "",NULL,0,NULL},
3035 {"adm-startup", cmd_adm_startup, "",NULL,0,NULL},
3036 {"help", cmd_help, "", NULL,0,NULL},
3040 static int cmd_help (const char *line)
3046 sscanf (line, "%20s", topic);
3049 printf("Commands:\n");
3050 for (i = 0; cmd_array[i].cmd; i++)
3051 if (*topic == 0 || strcmp (topic, cmd_array[i].cmd) == 0)
3052 printf(" %s %s\n", cmd_array[i].cmd, cmd_array[i].ad);
3053 if (strcmp (topic, "find") == 0)
3056 printf (" \"term\" Simple Term\n");
3057 printf (" @attr [attset] type=value op Attribute\n");
3058 printf (" @and opl opr And\n");
3059 printf (" @or opl opr Or\n");
3060 printf (" @not opl opr And-Not\n");
3061 printf (" @set set Result set\n");
3063 printf ("Bib-1 attribute types\n");
3065 printf ("4=Title 7=ISBN 8=ISSN 30=Date 62=Abstract 1003=Author 1016=Any\n");
3066 printf ("2=Relation: ");
3067 printf ("1< 2<= 3= 4>= 5> 6!= 102=Relevance\n");
3068 printf ("3=Position: ");
3069 printf ("1=First in Field 2=First in subfield 3=Any position\n");
3070 printf ("4=Structure: ");
3071 printf ("1=Phrase 2=Word 3=Key 4=Year 5=Date 6=WordList\n");
3072 printf ("5=Truncation: ");
3073 printf ("1=Right 2=Left 3=L&R 100=No 101=# 102=Re-1 103=Re-2\n");
3074 printf ("6=Completeness:");
3075 printf ("1=Incomplete subfield 2=Complete subfield 3=Complete field\n");
3080 int cmd_register_tab(const char* arg) {
3082 char command[101], tabargument[101];
3087 if (sscanf (arg, "%100s %100s", command, tabargument) < 1) {
3091 /* locate the amdn in the list */
3092 for (i = 0; cmd_array[i].cmd; i++) {
3093 if (!strncmp(cmd_array[i].cmd, command, strlen(command))) {
3098 if(!cmd_array[i].cmd) {
3099 fprintf(stderr,"Unknown command %s\n",command);
3104 if(!cmd_array[i].local_tabcompletes)
3105 cmd_array[i].local_tabcompletes = (char **) calloc(1,sizeof(char**));
3109 tabslist = cmd_array[i].local_tabcompletes;
3110 for(;tabslist && *tabslist;tabslist++) {
3114 cmd_array[i].local_tabcompletes = (char **)
3115 realloc(cmd_array[i].local_tabcompletes,(num_of_tabs+2)*sizeof(char**));
3116 tabslist=cmd_array[i].local_tabcompletes;
3117 tabslist[num_of_tabs]=strdup(tabargument);
3118 tabslist[num_of_tabs+1]=NULL;
3123 void process_cmd_line(char* line)
3126 char word[32], arg[1024];
3128 #if HAVE_GETTIMEOFDAY
3129 gettimeofday (&tv_start, 0);
3132 if ((res = sscanf(line, "%31s %1023[^;]", word, arg)) <= 0)
3134 strcpy(word, last_cmd);
3139 strcpy(last_cmd, word);
3141 /* removed tailing spaces from the arg command */
3144 char* lastnonspace=NULL;
3152 *(++lastnonspace) = 0;
3155 for (i = 0; cmd_array[i].cmd; i++)
3156 if (!strncmp(cmd_array[i].cmd, word, strlen(word)))
3158 res = (*cmd_array[i].fun)(arg);
3162 if (!cmd_array[i].cmd) /* dump our help-screen */
3164 printf("Unknown command: %s.\n", word);
3165 printf("use help for list of commands\n");
3166 /* cmd_help (""); */
3170 if(apdu_file) fflush(apdu_file);
3173 wait_and_handle_responce();
3182 char *command_generator(const char *text, int state)
3188 for( ; cmd_array[idx].cmd; ++idx) {
3189 if (!strncmp(cmd_array[idx].cmd,text,strlen(text))) {
3190 ++idx; /* skip this entry on the next run */
3191 return strdup(cmd_array[idx-1].cmd);
3199 This function only known how to complete on the first word
3201 char ** readline_completer(char *text, int start, int end) {
3202 #if HAVE_READLINE_READLINE_H
3204 completerFunctionType completerToUse;
3207 #if HAVE_READLINE_RL_COMPLETION_MATCHES
3208 char** res=rl_completion_matches(text,
3211 char** res=completion_matches(text,
3212 (CPFunction*)command_generator);
3214 rl_attempted_completion_over = 1;
3217 char arg[1024],word[32];
3219 if ((res = sscanf(rl_line_buffer, "%31s %1023[^;]", word, arg)) <= 0) {
3220 rl_attempted_completion_over = 1;
3224 for (i = 0; cmd_array[i].cmd; i++) {
3225 if (!strncmp(cmd_array[i].cmd, word, strlen(word))) {
3230 if(!cmd_array[i].cmd) return NULL;
3232 curret_global_list = cmd_array[i].local_tabcompletes;
3234 completerToUse = cmd_array[i].rl_completerfunction;
3235 if(completerToUse==NULL) /* if no pr. command completer is defined use the default completer */
3236 completerToUse = default_completer;
3238 if(completerToUse) {
3239 #ifdef HAVE_READLINE_RL_COMPLETION_MATCHES
3241 rl_completion_matches(text,
3245 completion_matches(text,
3246 (CPFunction*)completerToUse);
3248 if(!cmd_array[i].complete_filenames)
3249 rl_attempted_completion_over = 1;
3252 if(!cmd_array[i].complete_filenames)
3253 rl_attempted_completion_over = 1;
3263 static void client(void)
3269 #if HAVE_GETTIMEOFDAY
3270 gettimeofday (&tv_start, 0);
3275 char *line_in = NULL;
3276 #if HAVE_READLINE_READLINE_H
3279 line_in=readline(C_PROMPT);
3282 #if HAVE_READLINE_HISTORY_H
3284 add_history(line_in);
3286 strncpy(line, line_in, 1023);
3295 if (!fgets(line, 1023, stdin))
3297 if ((end_p = strchr (line, '\n')))
3300 process_cmd_line(line);
3304 int main(int argc, char **argv)
3307 char *open_command = 0;
3308 char *auth_command = 0;
3313 if (!setlocale(LC_CTYPE, ""))
3314 fprintf (stderr, "setlocale failed\n");
3318 codeset = nl_langinfo(CODESET);
3322 while ((ret = options("k:c:a:b:m:v:p:u:t:", argv, argc, &arg)) != -2)
3329 open_command = (char *) xmalloc (strlen(arg)+6);
3330 strcpy (open_command, "open ");
3331 strcat (open_command, arg);
3335 kilobytes = atoi(arg);
3338 if (!(marc_file = fopen (arg, "a")))
3348 strncpy (ccl_fields, arg, sizeof(ccl_fields)-1);
3349 ccl_fields[sizeof(ccl_fields)-1] = '\0';
3352 if (!strcmp(arg, "-"))
3355 ber_file=fopen(arg, "a");
3358 if (!strcmp(arg, "-"))
3361 apdu_file=fopen(arg, "a");
3364 yazProxy=strdup(arg);
3369 auth_command = (char *) xmalloc (strlen(arg)+6);
3370 strcpy (auth_command, "auth ");
3371 strcat (auth_command, arg);
3375 yaz_log_init (yaz_log_mask_str(arg), "", NULL);
3378 fprintf (stderr, "Usage: %s [-m <marclog>] [ -a <apdulog>] "
3379 "[-b berdump] [-c cclfields]\n [-p <proxy-addr>] [-u <auth>] "
3380 "[-k size] [<server-addr>]\n",
3388 #ifdef HAVE_GETTIMEOFDAY
3389 gettimeofday (&tv_start, 0);
3391 process_cmd_line (auth_command);
3392 #if HAVE_READLINE_HISTORY_H
3393 add_history(auth_command);
3395 xfree(auth_command);
3399 #ifdef HAVE_GETTIMEOFDAY
3400 gettimeofday (&tv_start, 0);
3402 process_cmd_line (open_command);
3403 #if HAVE_READLINE_HISTORY_H
3404 add_history(open_command);
3406 xfree(open_command);
3417 * vim600: sw=4 ts=8 fdm=marker
3418 * vim<600: sw=4 ts=8