2 * Copyright (c) 1995-2003, Index Data
3 * See the file LICENSE for details.
5 * $Id: client.c,v 1.185 2003-03-11 11:07:47 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 cmd_open_remember_last_open_command(arg,type_and_host);
464 conn = cs_create_host(yazProxy, 1, &add);
466 conn = cs_create_host(arg, 1, &add);
469 printf ("Couldn't create comstack\n");
472 if (conn->protocol == PROTO_HTTP)
474 printf("HTTP transport not supported\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);
495 if (conn->protocol == PROTO_Z3950)
496 send_initRequest(type_and_host);
507 if(!( auto_reconnect && last_open_command) ) return ;
509 open_command = (char *) xmalloc (strlen(last_open_command)+6);
510 strcpy (open_command, "open ");
512 strcat (open_command, last_open_command);
514 process_cmd_line(open_command);
519 int cmd_authentication(const char *arg)
521 static Z_IdAuthentication au;
522 static char user[40], group[40], pass[40];
523 static Z_IdPass idPass;
528 printf("Auth field set to null\n");
532 r = sscanf (arg, "%39s %39s %39s", user, group, pass);
535 printf("Auth field set to null\n");
541 au.which = Z_IdAuthentication_open;
547 au.which = Z_IdAuthentication_idPass;
548 au.u.idPass = &idPass;
549 idPass.groupId = NULL;
550 idPass.userId = user;
551 idPass.password = group;
556 au.which = Z_IdAuthentication_idPass;
557 au.u.idPass = &idPass;
558 idPass.groupId = group;
559 idPass.userId = user;
560 idPass.password = pass;
565 /* SEARCH SERVICE ------------------------------ */
566 static void display_record(Z_External *r);
568 static void print_record(const unsigned char *buf, size_t len)
571 print_stringn (buf, len);
572 /* add newline if not already added ... */
573 if (i <= 0 || buf[i-1] != '\n')
577 static void display_record(Z_External *r)
579 oident *ent = oid_getentbyoid(r->direct_reference);
583 * Tell the user what we got.
585 if (r->direct_reference)
587 printf("Record type: ");
589 printf("%s\n", ent->desc);
590 else if (!odr_oid(print, &r->direct_reference, 0, 0))
592 odr_perror(print, "print oid");
596 /* Check if this is a known, ASN.1 type tucked away in an octet string */
597 if (ent && r->which == Z_External_octet)
599 Z_ext_typeent *type = z_ext_getentbyref(ent->value);
605 * Call the given decoder to process the record.
607 odr_setbuf(in, (char*)r->u.octet_aligned->buf,
608 r->u.octet_aligned->len, 0);
609 if (!(*type->fun)(in, (char **)&rr, 0, 0))
611 odr_perror(in, "Decoding constructed record.");
612 fprintf(stdout, "[Near %d]\n", odr_offset(in));
613 fprintf(stdout, "Packet dump:\n---------\n");
614 odr_dumpBER(stdout, (char*)r->u.octet_aligned->buf,
615 r->u.octet_aligned->len);
616 fprintf(stdout, "---------\n");
618 /* note just ignores the error ant print the bytes form the octet_aligned later */
621 * Note: we throw away the original, BER-encoded record here.
622 * Do something else with it if you want to keep it.
624 r->u.sutrs = (Z_SUTRS *) rr; /* we don't actually check the type here. */
625 r->which = type->what;
629 if (ent && ent->oclass != CLASS_RECSYN)
631 if (ent && ent->value == VAL_SOIF)
632 print_record((const unsigned char *) r->u.octet_aligned->buf,
633 r->u.octet_aligned->len);
634 else if (r->which == Z_External_octet)
636 const char *octet_buf = (char*)r->u.octet_aligned->buf;
637 if (ent->value == VAL_TEXT_XML || ent->value == VAL_APPLICATION_XML ||
638 ent->value == VAL_HTML)
640 print_record((const unsigned char *) octet_buf,
641 r->u.octet_aligned->len);
643 else if (ent->value == VAL_POSTSCRIPT)
645 int size = r->u.octet_aligned->len;
648 print_record((const unsigned char *) octet_buf, size);
653 #if AVOID_MARC_DECODE
654 /* primitive check for a marc OID 5.1-29 except 16 */
655 ent->oidsuffix[0] == 5 && ent->oidsuffix[1] < 30 &&
656 ent->oidsuffix[1] != 16
665 yaz_marc_t mt = yaz_marc_create();
667 if (yaz_marc_decode_buf(mt, octet_buf,r->u.octet_aligned->len,
671 if (ent->value == VAL_USMARC)
673 if (octet_buf[9] == 'a')
683 printf ("convert from %s to %s\n", from, codeset);
684 cd = yaz_iconv_open(codeset, from);
687 fwrite (result, 1, rlen, stdout);
691 size_t inbytesleft = rlen;
692 const char *inp = result;
696 size_t outbytesleft = sizeof(outbuf);
698 size_t r = yaz_iconv (cd, (char**) &inp,
700 &outp, &outbytesleft);
701 if (r == (size_t) (-1))
703 int e = yaz_iconv_error(cd);
704 if (e != YAZ_ICONV_E2BIG)
707 fwrite (outbuf, outp - outbuf, 1, stdout);
713 printf ("bad MARC. Dumping as it is:\n");
714 print_record((const unsigned char*) octet_buf,
715 r->u.octet_aligned->len);
717 yaz_marc_destroy(mt);
723 print_record((const unsigned char*) octet_buf,
724 r->u.octet_aligned->len);
728 fwrite (octet_buf, 1, r->u.octet_aligned->len, marc_file);
730 else if (ent && ent->value == VAL_SUTRS)
732 if (r->which != Z_External_sutrs)
734 printf("Expecting single SUTRS type for SUTRS.\n");
737 print_record(r->u.sutrs->buf, r->u.sutrs->len);
739 else if (ent && ent->value == VAL_GRS1)
742 if (r->which != Z_External_grs1)
744 printf("Expecting single GRS type for GRS.\n");
748 yaz_display_grs1(w, r->u.grs1, 0);
754 printf("Unknown record representation.\n");
755 if (!z_External(print, &r, 0, 0))
757 odr_perror(print, "Printing external");
763 static void display_diagrecs(Z_DiagRec **pp, int num)
767 Z_DefaultDiagFormat *r;
769 printf("Diagnostic message(s) from database:\n");
770 for (i = 0; i<num; i++)
772 Z_DiagRec *p = pp[i];
773 if (p->which != Z_DiagRec_defaultFormat)
775 printf("Diagnostic record not in default format.\n");
779 r = p->u.defaultFormat;
780 if (!(ent = oid_getentbyoid(r->diagnosticSetId)) ||
781 ent->oclass != CLASS_DIAGSET || ent->value != VAL_BIB1)
782 printf("Missing or unknown diagset\n");
783 printf(" [%d] %s", *r->condition, diagbib1_str(*r->condition));
786 case Z_DefaultDiagFormat_v2Addinfo:
787 printf (" -- v2 addinfo '%s'\n", r->u.v2Addinfo);
789 case Z_DefaultDiagFormat_v3Addinfo:
790 printf (" -- v3 addinfo '%s'\n", r->u.v3Addinfo);
797 static void display_nameplusrecord(Z_NamePlusRecord *p)
800 printf("[%s]", p->databaseName);
801 if (p->which == Z_NamePlusRecord_surrogateDiagnostic)
802 display_diagrecs(&p->u.surrogateDiagnostic, 1);
803 else if (p->which == Z_NamePlusRecord_databaseRecord)
804 display_record(p->u.databaseRecord);
807 static void display_records(Z_Records *p)
811 if (p->which == Z_Records_NSD)
813 Z_DiagRec dr, *dr_p = &dr;
814 dr.which = Z_DiagRec_defaultFormat;
815 dr.u.defaultFormat = p->u.nonSurrogateDiagnostic;
816 display_diagrecs (&dr_p, 1);
818 else if (p->which == Z_Records_multipleNSD)
819 display_diagrecs (p->u.multipleNonSurDiagnostics->diagRecs,
820 p->u.multipleNonSurDiagnostics->num_diagRecs);
823 printf("Records: %d\n", p->u.databaseOrSurDiagnostics->num_records);
824 for (i = 0; i < p->u.databaseOrSurDiagnostics->num_records; i++)
825 display_nameplusrecord(p->u.databaseOrSurDiagnostics->records[i]);
829 static int send_deleteResultSetRequest(const char *arg)
834 Z_APDU *apdu = zget_APDU(out, Z_APDU_deleteResultSetRequest);
835 Z_DeleteResultSetRequest *req = apdu->u.deleteResultSetRequest;
837 req->referenceId = set_refid (out);
839 req->num_resultSetList =
840 sscanf (arg, "%30s %30s %30s %30s %30s %30s %30s %30s",
841 names[0], names[1], names[2], names[3],
842 names[4], names[5], names[6], names[7]);
844 req->deleteFunction = (int *)
845 odr_malloc (out, sizeof(*req->deleteFunction));
846 if (req->num_resultSetList > 0)
848 *req->deleteFunction = Z_DeleteRequest_list;
849 req->resultSetList = (char **)
850 odr_malloc (out, sizeof(*req->resultSetList)*
851 req->num_resultSetList);
852 for (i = 0; i<req->num_resultSetList; i++)
853 req->resultSetList[i] = names[i];
857 *req->deleteFunction = Z_DeleteRequest_all;
858 req->resultSetList = 0;
862 printf("Sent deleteResultSetRequest.\n");
866 static int send_searchRequest(const char *arg)
868 Z_APDU *apdu = zget_APDU(out, Z_APDU_searchRequest);
869 Z_SearchRequest *req = apdu->u.searchRequest;
872 struct ccl_rpn_node *rpn = NULL;
875 Z_RPNQuery *RPNquery;
877 YAZ_PQF_Parser pqf_parser;
880 if (queryType == QueryType_CCL2RPN)
882 rpn = ccl_find_str(bibset, arg, &error, &pos);
885 printf("CCL ERROR: %s\n", ccl_err_msg(error));
889 req->referenceId = set_refid (out);
890 if (!strcmp(arg, "@big")) /* strictly for troublemaking */
892 static unsigned char big[2100];
895 /* send a very big referenceid to test transport stack etc. */
896 memset(big, 'A', 2100);
897 bigo.len = bigo.size = 2100;
899 req->referenceId = &bigo;
904 sprintf(setstring, "%d", ++setnumber);
905 req->resultSetName = setstring;
907 *req->smallSetUpperBound = smallSetUpperBound;
908 *req->largeSetLowerBound = largeSetLowerBound;
909 *req->mediumSetPresentNumber = mediumSetPresentNumber;
910 if (smallSetUpperBound > 0 || (largeSetLowerBound > 1 &&
911 mediumSetPresentNumber > 0))
915 prefsyn.proto = protocol;
916 prefsyn.oclass = CLASS_RECSYN;
917 prefsyn.value = recordsyntax;
918 req->preferredRecordSyntax =
919 odr_oiddup(out, oid_ent_to_oid(&prefsyn, oid));
920 req->smallSetElementSetNames =
921 req->mediumSetElementSetNames = elementSetNames;
923 req->num_databaseNames = num_databaseNames;
924 req->databaseNames = databaseNames;
930 case QueryType_Prefix:
931 query.which = Z_Query_type_1;
932 pqf_parser = yaz_pqf_create ();
933 RPNquery = yaz_pqf_parse (pqf_parser, out, arg);
938 int code = yaz_pqf_error (pqf_parser, &pqf_msg, &off);
939 printf("%*s^\n", off+4, "");
940 printf("Prefix query error: %s (code %d)\n", pqf_msg, code);
942 yaz_pqf_destroy (pqf_parser);
945 yaz_pqf_destroy (pqf_parser);
946 query.u.type_1 = RPNquery;
949 query.which = Z_Query_type_2;
950 query.u.type_2 = &ccl_query;
951 ccl_query.buf = (unsigned char*) arg;
952 ccl_query.len = strlen(arg);
954 case QueryType_CCL2RPN:
955 query.which = Z_Query_type_1;
956 RPNquery = ccl_rpn_query(out, rpn);
959 printf ("Couldn't convert from CCL to RPN\n");
962 query.u.type_1 = RPNquery;
963 ccl_rpn_delete (rpn);
966 query.which = Z_Query_type_104;
967 ext = (Z_External *) odr_malloc(out, sizeof(*ext));
968 ext->direct_reference = odr_getoidbystr(out, "1.2.840.10003.16.2");
969 ext->indirect_reference = 0;
971 ext->which = Z_External_CQL;
972 ext->u.cql = odr_strdup(out, arg);
973 query.u.type_104 = ext;
976 printf ("Unsupported query type\n");
981 printf("Sent searchRequest.\n");
985 /* display Query Expression as part of searchResult-1 */
986 static void display_queryExpression (Z_QueryExpression *qe)
990 if (qe->which == Z_QueryExpression_term)
992 if (qe->u.term->queryTerm)
994 Z_Term *term = qe->u.term->queryTerm;
998 printf (" %.*s", term->u.general->len, term->u.general->buf);
1000 case Z_Term_characterString:
1001 printf (" %s", term->u.characterString);
1003 case Z_Term_numeric:
1004 printf (" %d", *term->u.numeric);
1014 /* see if we can find USR:SearchResult-1 */
1015 static void display_searchResult (Z_OtherInformation *o)
1020 for (i = 0; i < o->num_elements; i++)
1022 if (o->list[i]->which == Z_OtherInfo_externallyDefinedInfo)
1024 Z_External *ext = o->list[i]->information.externallyDefinedInfo;
1026 if (ext->which == Z_External_searchResult1)
1029 Z_SearchInfoReport *sr = ext->u.searchResult1;
1030 printf ("SearchResult-1:");
1031 for (j = 0; j < sr->num; j++)
1033 if (!sr->elements[j]->subqueryExpression)
1035 display_queryExpression (
1036 sr->elements[j]->subqueryExpression);
1037 display_queryExpression (
1038 sr->elements[j]->subqueryInterpretation);
1039 display_queryExpression (
1040 sr->elements[j]->subqueryRecommendation);
1041 if (sr->elements[j]->subqueryCount)
1042 printf ("(%d)", *sr->elements[j]->subqueryCount);
1050 static int process_searchResponse(Z_SearchResponse *res)
1052 printf ("Received SearchResponse.\n");
1053 print_refid (res->referenceId);
1054 if (*res->searchStatus)
1055 printf("Search was a success.\n");
1057 printf("Search was a bloomin' failure.\n");
1058 printf("Number of hits: %d", *res->resultCount);
1060 printf (", setno %d", setnumber);
1062 display_searchResult (res->additionalSearchInfo);
1063 printf("records returned: %d\n",
1064 *res->numberOfRecordsReturned);
1065 setno += *res->numberOfRecordsReturned;
1067 display_records(res->records);
1071 static void print_level(int iLevel)
1074 for (i = 0; i < iLevel * 4; i++)
1078 static void print_int(int iLevel, const char *pTag, int *pInt)
1082 print_level(iLevel);
1083 printf("%s: %d\n", pTag, *pInt);
1087 static void print_string(int iLevel, const char *pTag, const char *pString)
1089 if (pString != NULL)
1091 print_level(iLevel);
1092 printf("%s: %s\n", pTag, pString);
1096 static void print_oid(int iLevel, const char *pTag, Odr_oid *pOid)
1102 print_level(iLevel);
1103 printf("%s:", pTag);
1104 for (; *pInt != -1; pInt++)
1105 printf(" %d", *pInt);
1110 static void print_referenceId(int iLevel, Z_ReferenceId *referenceId)
1112 if (referenceId != NULL)
1116 print_level(iLevel);
1117 printf("Ref Id (%d, %d): ", referenceId->len, referenceId->size);
1118 for (i = 0; i < referenceId->len; i++)
1119 printf("%c", referenceId->buf[i]);
1124 static void print_string_or_numeric(int iLevel, const char *pTag, Z_StringOrNumeric *pStringNumeric)
1126 if (pStringNumeric != NULL)
1128 switch (pStringNumeric->which)
1130 case Z_StringOrNumeric_string:
1131 print_string(iLevel, pTag, pStringNumeric->u.string);
1134 case Z_StringOrNumeric_numeric:
1135 print_int(iLevel, pTag, pStringNumeric->u.numeric);
1139 print_level(iLevel);
1140 printf("%s: valid type for Z_StringOrNumeric\n", pTag);
1146 static void print_universe_report_duplicate(
1148 Z_UniverseReportDuplicate *pUniverseReportDuplicate)
1150 if (pUniverseReportDuplicate != NULL)
1152 print_level(iLevel);
1153 printf("Universe Report Duplicate: \n");
1155 print_string_or_numeric(iLevel, "Hit No",
1156 pUniverseReportDuplicate->hitno);
1160 static void print_universe_report_hits(
1162 Z_UniverseReportHits *pUniverseReportHits)
1164 if (pUniverseReportHits != NULL)
1166 print_level(iLevel);
1167 printf("Universe Report Hits: \n");
1169 print_string_or_numeric(iLevel, "Database",
1170 pUniverseReportHits->database);
1171 print_string_or_numeric(iLevel, "Hits", pUniverseReportHits->hits);
1175 static void print_universe_report(int iLevel, Z_UniverseReport *pUniverseReport)
1177 if (pUniverseReport != NULL)
1179 print_level(iLevel);
1180 printf("Universe Report: \n");
1182 print_int(iLevel, "Total Hits", pUniverseReport->totalHits);
1183 switch (pUniverseReport->which)
1185 case Z_UniverseReport_databaseHits:
1186 print_universe_report_hits(iLevel,
1187 pUniverseReport->u.databaseHits);
1190 case Z_UniverseReport_duplicate:
1191 print_universe_report_duplicate(iLevel,
1192 pUniverseReport->u.duplicate);
1196 print_level(iLevel);
1197 printf("Type: %d\n", pUniverseReport->which);
1203 static void print_external(int iLevel, Z_External *pExternal)
1205 if (pExternal != NULL)
1207 print_level(iLevel);
1208 printf("External: \n");
1210 print_oid(iLevel, "Direct Reference", pExternal->direct_reference);
1211 print_int(iLevel, "InDirect Reference", pExternal->indirect_reference);
1212 print_string(iLevel, "Descriptor", pExternal->descriptor);
1213 switch (pExternal->which)
1215 case Z_External_universeReport:
1216 print_universe_report(iLevel, pExternal->u.universeReport);
1220 print_level(iLevel);
1221 printf("Type: %d\n", pExternal->which);
1227 static int process_resourceControlRequest (Z_ResourceControlRequest *req)
1229 printf ("Received ResourceControlRequest.\n");
1230 print_referenceId(1, req->referenceId);
1231 print_int(1, "Suspended Flag", req->suspendedFlag);
1232 print_int(1, "Partial Results Available", req->partialResultsAvailable);
1233 print_int(1, "Response Required", req->responseRequired);
1234 print_int(1, "Triggered Request Flag", req->triggeredRequestFlag);
1235 print_external(1, req->resourceReport);
1239 void process_ESResponse(Z_ExtendedServicesResponse *res)
1242 switch (*res->operationStatus)
1244 case Z_ExtendedServicesResponse_done:
1247 case Z_ExtendedServicesResponse_accepted:
1248 printf ("accepted\n");
1250 case Z_ExtendedServicesResponse_failure:
1251 printf ("failure\n");
1252 display_diagrecs(res->diagnostics, res->num_diagnostics);
1255 printf ("unknown\n");
1257 if ( (*res->operationStatus != Z_ExtendedServicesResponse_failure) &&
1258 (res->num_diagnostics != 0) ) {
1259 display_diagrecs(res->diagnostics, res->num_diagnostics);
1261 print_refid (res->referenceId);
1262 if (res->taskPackage &&
1263 res->taskPackage->which == Z_External_extendedService)
1265 Z_TaskPackage *taskPackage = res->taskPackage->u.extendedService;
1266 Odr_oct *id = taskPackage->targetReference;
1267 Z_External *ext = taskPackage->taskSpecificParameters;
1271 printf ("Target Reference: ");
1272 print_stringn (id->buf, id->len);
1275 if (ext->which == Z_External_update)
1277 Z_IUUpdateTaskPackage *utp = ext->u.update->u.taskPackage;
1278 if (utp && utp->targetPart)
1280 Z_IUTargetPart *targetPart = utp->targetPart;
1283 for (i = 0; i<targetPart->num_taskPackageRecords; i++)
1286 Z_IUTaskPackageRecordStructure *tpr =
1287 targetPart->taskPackageRecords[i];
1288 printf ("task package record %d\n", i+1);
1289 if (tpr->which == Z_IUTaskPackageRecordStructure_record)
1291 display_record (tpr->u.record);
1295 printf ("other type\n");
1303 const char *get_ill_element (void *clientData, const char *element)
1308 static Z_External *create_external_itemRequest()
1310 struct ill_get_ctl ctl;
1311 ILL_ItemRequest *req;
1313 int item_request_size = 0;
1314 char *item_request_buf = 0;
1318 ctl.f = get_ill_element;
1320 req = ill_get_ItemRequest(&ctl, "ill", 0);
1322 printf ("ill_get_ItemRequest failed\n");
1324 if (!ill_ItemRequest (out, &req, 0, 0))
1328 ill_ItemRequest(print, &req, 0, 0);
1331 item_request_buf = odr_getbuf (out, &item_request_size, 0);
1332 if (item_request_buf)
1333 odr_setbuf (out, item_request_buf, item_request_size, 1);
1334 printf ("Couldn't encode ItemRequest, size %d\n", item_request_size);
1341 item_request_buf = odr_getbuf (out, &item_request_size, 0);
1342 oid.proto = PROTO_GENERAL;
1343 oid.oclass = CLASS_GENERAL;
1344 oid.value = VAL_ISO_ILL_1;
1346 r = (Z_External *) odr_malloc (out, sizeof(*r));
1347 r->direct_reference = odr_oiddup(out,oid_getoidbyent(&oid));
1348 r->indirect_reference = 0;
1350 r->which = Z_External_single;
1352 r->u.single_ASN1_type = (Odr_oct *)
1353 odr_malloc (out, sizeof(*r->u.single_ASN1_type));
1354 r->u.single_ASN1_type->buf = (unsigned char *)
1355 odr_malloc (out, item_request_size);
1356 r->u.single_ASN1_type->len = item_request_size;
1357 r->u.single_ASN1_type->size = item_request_size;
1358 memcpy (r->u.single_ASN1_type->buf, item_request_buf,
1361 do_hex_dump(item_request_buf,item_request_size);
1366 static Z_External *create_external_ILL_APDU(int which)
1368 struct ill_get_ctl ctl;
1371 int ill_request_size = 0;
1372 char *ill_request_buf = 0;
1376 ctl.f = get_ill_element;
1378 ill_apdu = ill_get_APDU(&ctl, "ill", 0);
1380 if (!ill_APDU (out, &ill_apdu, 0, 0))
1384 printf ("-------------------\n");
1385 ill_APDU(print, &ill_apdu, 0, 0);
1387 printf ("-------------------\n");
1389 ill_request_buf = odr_getbuf (out, &ill_request_size, 0);
1390 if (ill_request_buf)
1391 odr_setbuf (out, ill_request_buf, ill_request_size, 1);
1392 printf ("Couldn't encode ILL-Request, size %d\n", ill_request_size);
1398 ill_request_buf = odr_getbuf (out, &ill_request_size, 0);
1400 oid.proto = PROTO_GENERAL;
1401 oid.oclass = CLASS_GENERAL;
1402 oid.value = VAL_ISO_ILL_1;
1404 r = (Z_External *) odr_malloc (out, sizeof(*r));
1405 r->direct_reference = odr_oiddup(out,oid_getoidbyent(&oid));
1406 r->indirect_reference = 0;
1408 r->which = Z_External_single;
1410 r->u.single_ASN1_type = (Odr_oct *)
1411 odr_malloc (out, sizeof(*r->u.single_ASN1_type));
1412 r->u.single_ASN1_type->buf = (unsigned char *)
1413 odr_malloc (out, ill_request_size);
1414 r->u.single_ASN1_type->len = ill_request_size;
1415 r->u.single_ASN1_type->size = ill_request_size;
1416 memcpy (r->u.single_ASN1_type->buf, ill_request_buf, ill_request_size);
1417 /* printf ("len = %d\n", ill_request_size); */
1418 /* do_hex_dump(ill_request_buf,ill_request_size); */
1419 /* printf("--- end of extenal\n"); */
1426 static Z_External *create_ItemOrderExternal(const char *type, int itemno)
1428 Z_External *r = (Z_External *) odr_malloc(out, sizeof(Z_External));
1429 oident ItemOrderRequest;
1431 ItemOrderRequest.proto = PROTO_Z3950;
1432 ItemOrderRequest.oclass = CLASS_EXTSERV;
1433 ItemOrderRequest.value = VAL_ITEMORDER;
1435 r->direct_reference = odr_oiddup(out,oid_getoidbyent(&ItemOrderRequest));
1436 r->indirect_reference = 0;
1439 r->which = Z_External_itemOrder;
1441 r->u.itemOrder = (Z_ItemOrder *) odr_malloc(out,sizeof(Z_ItemOrder));
1442 memset(r->u.itemOrder, 0, sizeof(Z_ItemOrder));
1443 r->u.itemOrder->which=Z_IOItemOrder_esRequest;
1445 r->u.itemOrder->u.esRequest = (Z_IORequest *)
1446 odr_malloc(out,sizeof(Z_IORequest));
1447 memset(r->u.itemOrder->u.esRequest, 0, sizeof(Z_IORequest));
1449 r->u.itemOrder->u.esRequest->toKeep = (Z_IOOriginPartToKeep *)
1450 odr_malloc(out,sizeof(Z_IOOriginPartToKeep));
1451 memset(r->u.itemOrder->u.esRequest->toKeep, 0, sizeof(Z_IOOriginPartToKeep));
1452 r->u.itemOrder->u.esRequest->notToKeep = (Z_IOOriginPartNotToKeep *)
1453 odr_malloc(out,sizeof(Z_IOOriginPartNotToKeep));
1454 memset(r->u.itemOrder->u.esRequest->notToKeep, 0, sizeof(Z_IOOriginPartNotToKeep));
1456 r->u.itemOrder->u.esRequest->toKeep->supplDescription = NULL;
1457 r->u.itemOrder->u.esRequest->toKeep->contact = NULL;
1458 r->u.itemOrder->u.esRequest->toKeep->addlBilling = NULL;
1460 r->u.itemOrder->u.esRequest->notToKeep->resultSetItem =
1461 (Z_IOResultSetItem *) odr_malloc(out, sizeof(Z_IOResultSetItem));
1462 memset(r->u.itemOrder->u.esRequest->notToKeep->resultSetItem, 0, sizeof(Z_IOResultSetItem));
1463 r->u.itemOrder->u.esRequest->notToKeep->resultSetItem->resultSetId = "1";
1465 r->u.itemOrder->u.esRequest->notToKeep->resultSetItem->item =
1466 (int *) odr_malloc(out, sizeof(int));
1467 *r->u.itemOrder->u.esRequest->notToKeep->resultSetItem->item = itemno;
1469 if (!strcmp (type, "item") || !strcmp(type, "2"))
1471 printf ("using item-request\n");
1472 r->u.itemOrder->u.esRequest->notToKeep->itemRequest =
1473 create_external_itemRequest();
1475 else if (!strcmp(type, "ill") || !strcmp(type, "1"))
1477 printf ("using ILL-request\n");
1478 r->u.itemOrder->u.esRequest->notToKeep->itemRequest =
1479 create_external_ILL_APDU(ILL_APDU_ILL_Request);
1481 else if (!strcmp(type, "xml") || !strcmp(type, "3"))
1483 const char *xml_buf =
1485 " <type>request</type>\n"
1486 " <libraryNo>000200</libraryNo>\n"
1487 " <borrowerTicketNo> 1212 </borrowerTicketNo>\n"
1489 r->u.itemOrder->u.esRequest->notToKeep->itemRequest =
1490 z_ext_record (out, VAL_TEXT_XML, xml_buf, strlen(xml_buf));
1493 r->u.itemOrder->u.esRequest->notToKeep->itemRequest = 0;
1498 static int send_itemorder(const char *type, int itemno)
1500 Z_APDU *apdu = zget_APDU(out, Z_APDU_extendedServicesRequest);
1501 Z_ExtendedServicesRequest *req = apdu->u.extendedServicesRequest;
1502 oident ItemOrderRequest;
1504 ItemOrderRequest.proto = PROTO_Z3950;
1505 ItemOrderRequest.oclass = CLASS_EXTSERV;
1506 ItemOrderRequest.value = VAL_ITEMORDER;
1507 req->packageType = odr_oiddup(out,oid_getoidbyent(&ItemOrderRequest));
1508 req->packageName = esPackageName;
1510 req->taskSpecificParameters = create_ItemOrderExternal(type, itemno);
1516 static int cmd_update(const char *arg)
1518 Z_APDU *apdu = zget_APDU(out, Z_APDU_extendedServicesRequest );
1519 Z_ExtendedServicesRequest *req = apdu->u.extendedServicesRequest;
1522 Z_IUOriginPartToKeep *toKeep;
1523 Z_IUSuppliedRecords *notToKeep;
1525 char action[20], recid[20], fname[80];
1527 Z_External *record_this = 0;
1532 sscanf (arg, "%19s %19s %79s", action, recid, fname);
1534 if (!strcmp (action, "insert"))
1535 action_no = Z_IUOriginPartToKeep_recordInsert;
1536 else if (!strcmp (action, "replace"))
1537 action_no = Z_IUOriginPartToKeep_recordReplace;
1538 else if (!strcmp (action, "delete"))
1539 action_no = Z_IUOriginPartToKeep_recordDelete;
1540 else if (!strcmp (action, "update"))
1541 action_no = Z_IUOriginPartToKeep_specialUpdate;
1544 printf ("Bad action: %s\n", action);
1545 printf ("Possible values: insert, replace, delete, update\n");
1553 stat (fname, &status);
1554 if (S_ISREG(status.st_mode) && (inf = fopen(fname, "r")))
1556 size_t len = status.st_size;
1557 char *buf = (char *) xmalloc (len);
1559 fread (buf, 1, len, inf);
1563 record_this = z_ext_record (out, VAL_TEXT_XML, buf, len);
1569 printf ("File %s doesn't exist\n", fname);
1577 printf ("No last record (update ignored)\n");
1580 record_this = record_last;
1583 update_oid.proto = PROTO_Z3950;
1584 update_oid.oclass = CLASS_EXTSERV;
1585 update_oid.value = VAL_DBUPDATE;
1586 oid_ent_to_oid (&update_oid, oid);
1587 req->packageType = odr_oiddup(out,oid);
1588 req->packageName = esPackageName;
1590 req->referenceId = set_refid (out);
1592 r = req->taskSpecificParameters = (Z_External *)
1593 odr_malloc (out, sizeof(*r));
1594 r->direct_reference = odr_oiddup(out,oid);
1595 r->indirect_reference = 0;
1597 r->which = Z_External_update;
1598 r->u.update = (Z_IUUpdate *) odr_malloc(out, sizeof(*r->u.update));
1599 r->u.update->which = Z_IUUpdate_esRequest;
1600 r->u.update->u.esRequest = (Z_IUUpdateEsRequest *)
1601 odr_malloc(out, sizeof(*r->u.update->u.esRequest));
1602 toKeep = r->u.update->u.esRequest->toKeep = (Z_IUOriginPartToKeep *)
1603 odr_malloc(out, sizeof(*r->u.update->u.esRequest->toKeep));
1604 toKeep->databaseName = databaseNames[0];
1606 toKeep->elementSetName = 0;
1607 toKeep->actionQualifier = 0;
1608 toKeep->action = (int *) odr_malloc(out, sizeof(*toKeep->action));
1609 *toKeep->action = action_no;
1611 notToKeep = r->u.update->u.esRequest->notToKeep = (Z_IUSuppliedRecords *)
1612 odr_malloc(out, sizeof(*r->u.update->u.esRequest->notToKeep));
1614 notToKeep->elements = (Z_IUSuppliedRecords_elem **)
1615 odr_malloc(out, sizeof(*notToKeep->elements));
1616 notToKeep->elements[0] = (Z_IUSuppliedRecords_elem *)
1617 odr_malloc(out, sizeof(**notToKeep->elements));
1618 notToKeep->elements[0]->which = Z_IUSuppliedRecords_elem_opaque;
1621 notToKeep->elements[0]->u.opaque = (Odr_oct *)
1622 odr_malloc (out, sizeof(Odr_oct));
1623 notToKeep->elements[0]->u.opaque->buf = (unsigned char *) recid;
1624 notToKeep->elements[0]->u.opaque->size = strlen(recid);
1625 notToKeep->elements[0]->u.opaque->len = strlen(recid);
1628 notToKeep->elements[0]->u.opaque = 0;
1629 notToKeep->elements[0]->supplementalId = 0;
1630 notToKeep->elements[0]->correlationInfo = 0;
1631 notToKeep->elements[0]->record = record_this;
1638 static int cmd_itemorder(const char *arg)
1643 if (sscanf (arg, "%10s %d", type, &itemno) != 2)
1646 printf("Item order request\n");
1648 send_itemorder(type, itemno);
1652 static int cmd_find(const char *arg)
1656 printf("Find what?\n");
1664 printf("Not connected yet\n");
1668 if (!send_searchRequest(arg))
1673 static int cmd_delete(const char *arg)
1677 printf("Not connected yet\n");
1680 if (!send_deleteResultSetRequest(arg))
1685 static int cmd_ssub(const char *arg)
1687 if (!(smallSetUpperBound = atoi(arg)))
1692 static int cmd_lslb(const char *arg)
1694 if (!(largeSetLowerBound = atoi(arg)))
1699 static int cmd_mspn(const char *arg)
1701 if (!(mediumSetPresentNumber = atoi(arg)))
1706 static int cmd_status(const char *arg)
1708 printf("smallSetUpperBound: %d\n", smallSetUpperBound);
1709 printf("largeSetLowerBound: %d\n", largeSetLowerBound);
1710 printf("mediumSetPresentNumber: %d\n", mediumSetPresentNumber);
1714 static int cmd_setnames(const char *arg)
1716 if (*arg == '1') /* enable ? */
1718 else if (*arg == '0') /* disable ? */
1720 else if (setnumber < 0) /* no args, toggle .. */
1726 printf("Set numbering enabled.\n");
1728 printf("Set numbering disabled.\n");
1732 /* PRESENT SERVICE ----------------------------- */
1734 static int send_presentRequest(const char *arg)
1736 Z_APDU *apdu = zget_APDU(out, Z_APDU_presentRequest);
1737 Z_PresentRequest *req = apdu->u.presentRequest;
1738 Z_RecordComposition compo;
1743 char setstring[100];
1745 req->referenceId = set_refid (out);
1746 if ((p = strchr(arg, '+')))
1753 if (p && (p=strchr(p+1, '+')))
1755 strcpy (setstring, p+1);
1756 req->resultSetId = setstring;
1758 else if (setnumber >= 0)
1760 sprintf(setstring, "%d", setnumber);
1761 req->resultSetId = setstring;
1763 req->resultSetStartPoint = &setno;
1764 req->numberOfRecordsRequested = &nos;
1765 prefsyn.proto = protocol;
1766 prefsyn.oclass = CLASS_RECSYN;
1767 prefsyn.value = recordsyntax;
1768 req->preferredRecordSyntax =
1769 odr_oiddup (out, oid_ent_to_oid(&prefsyn, oid));
1771 if (schema != VAL_NONE)
1775 prefschema.proto = protocol;
1776 prefschema.oclass = CLASS_SCHEMA;
1777 prefschema.value = schema;
1779 req->recordComposition = &compo;
1780 compo.which = Z_RecordComp_complex;
1781 compo.u.complex = (Z_CompSpec *)
1782 odr_malloc(out, sizeof(*compo.u.complex));
1783 compo.u.complex->selectAlternativeSyntax = (bool_t *)
1784 odr_malloc(out, sizeof(bool_t));
1785 *compo.u.complex->selectAlternativeSyntax = 0;
1787 compo.u.complex->generic = (Z_Specification *)
1788 odr_malloc(out, sizeof(*compo.u.complex->generic));
1789 compo.u.complex->generic->which = Z_Schema_oid;
1790 compo.u.complex->generic->schema.oid = (Odr_oid *)
1791 odr_oiddup(out, oid_ent_to_oid(&prefschema, oid));
1792 if (!compo.u.complex->generic->schema.oid)
1794 /* OID wasn't a schema! Try record syntax instead. */
1795 prefschema.oclass = CLASS_RECSYN;
1796 compo.u.complex->generic->schema.oid = (Odr_oid *)
1797 odr_oiddup(out, oid_ent_to_oid(&prefschema, oid));
1799 if (!elementSetNames)
1800 compo.u.complex->generic->elementSpec = 0;
1803 compo.u.complex->generic->elementSpec = (Z_ElementSpec *)
1804 odr_malloc(out, sizeof(Z_ElementSpec));
1805 compo.u.complex->generic->elementSpec->which =
1806 Z_ElementSpec_elementSetName;
1807 compo.u.complex->generic->elementSpec->u.elementSetName =
1808 elementSetNames->u.generic;
1810 compo.u.complex->num_dbSpecific = 0;
1811 compo.u.complex->dbSpecific = 0;
1812 compo.u.complex->num_recordSyntax = 0;
1813 compo.u.complex->recordSyntax = 0;
1815 else if (elementSetNames)
1817 req->recordComposition = &compo;
1818 compo.which = Z_RecordComp_simple;
1819 compo.u.simple = elementSetNames;
1822 printf("Sent presentRequest (%d+%d).\n", setno, nos);
1826 static void close_session (void)
1832 nmem_destroy (session_mem);
1841 void process_close(Z_Close *req)
1843 Z_APDU *apdu = zget_APDU(out, Z_APDU_close);
1844 Z_Close *res = apdu->u.close;
1846 static char *reasons[] =
1851 "cost limit reached",
1853 "security violation",
1860 printf("Reason: %s, message: %s\n", reasons[*req->closeReason],
1861 req->diagnosticInformation ? req->diagnosticInformation : "NULL");
1866 *res->closeReason = Z_Close_finished;
1868 printf("Sent response.\n");
1873 static int cmd_show(const char *arg)
1877 printf("Not connected yet\n");
1880 if (!send_presentRequest(arg))
1885 int cmd_quit(const char *arg)
1887 printf("See you later, alligator.\n");
1893 int cmd_cancel(const char *arg)
1895 Z_APDU *apdu = zget_APDU(out, Z_APDU_triggerResourceControlRequest);
1896 Z_TriggerResourceControlRequest *req =
1897 apdu->u.triggerResourceControlRequest;
1902 printf("Session not initialized yet\n");
1905 if (!ODR_MASK_GET(session->options, Z_Options_triggerResourceCtrl))
1907 printf("Target doesn't support cancel (trigger resource ctrl)\n");
1910 *req->requestedAction = Z_TriggerResourceCtrl_cancel;
1911 req->resultSetWanted = &rfalse;
1914 printf("Sent cancel request\n");
1918 int send_scanrequest(const char *query, int pp, int num, const char *term)
1920 Z_APDU *apdu = zget_APDU(out, Z_APDU_scanRequest);
1921 Z_ScanRequest *req = apdu->u.scanRequest;
1924 if (queryType == QueryType_CCL2RPN)
1928 struct ccl_rpn_node *rpn;
1930 rpn = ccl_find_str (bibset, query, &error, &pos);
1933 printf("CCL ERROR: %s\n", ccl_err_msg(error));
1936 bib1.proto = PROTO_Z3950;
1937 bib1.oclass = CLASS_ATTSET;
1938 bib1.value = VAL_BIB1;
1939 req->attributeSet = oid_ent_to_oid (&bib1, oid);
1940 if (!(req->termListAndStartPoint = ccl_scan_query (out, rpn)))
1942 printf("Couldn't convert CCL to Scan term\n");
1945 ccl_rpn_delete (rpn);
1949 YAZ_PQF_Parser pqf_parser = yaz_pqf_create ();
1951 if (!(req->termListAndStartPoint =
1952 yaz_pqf_scan(pqf_parser, out, &req->attributeSet, query)))
1954 const char *pqf_msg;
1956 int code = yaz_pqf_error (pqf_parser, &pqf_msg, &off);
1957 printf("%*s^\n", off+7, "");
1958 printf("Prefix query error: %s (code %d)\n", pqf_msg, code);
1959 yaz_pqf_destroy (pqf_parser);
1962 yaz_pqf_destroy (pqf_parser);
1966 if (req->termListAndStartPoint->term &&
1967 req->termListAndStartPoint->term->which == Z_Term_general &&
1968 req->termListAndStartPoint->term->u.general)
1970 req->termListAndStartPoint->term->u.general->buf =
1971 (unsigned char *) odr_strdup(out, term);
1972 req->termListAndStartPoint->term->u.general->len =
1973 req->termListAndStartPoint->term->u.general->size =
1977 req->referenceId = set_refid (out);
1978 req->num_databaseNames = num_databaseNames;
1979 req->databaseNames = databaseNames;
1980 req->numberOfTermsRequested = #
1981 req->preferredPositionInResponse = &pp;
1986 int send_sortrequest(const char *arg, int newset)
1988 Z_APDU *apdu = zget_APDU(out, Z_APDU_sortRequest);
1989 Z_SortRequest *req = apdu->u.sortRequest;
1990 Z_SortKeySpecList *sksl = (Z_SortKeySpecList *)
1991 odr_malloc (out, sizeof(*sksl));
1995 sprintf (setstring, "%d", setnumber);
1997 sprintf (setstring, "default");
1999 req->referenceId = set_refid (out);
2001 req->num_inputResultSetNames = 1;
2002 req->inputResultSetNames = (Z_InternationalString **)
2003 odr_malloc (out, sizeof(*req->inputResultSetNames));
2004 req->inputResultSetNames[0] = odr_strdup (out, setstring);
2006 if (newset && setnumber >= 0)
2007 sprintf (setstring, "%d", ++setnumber);
2009 req->sortedResultSetName = odr_strdup (out, setstring);
2011 req->sortSequence = yaz_sort_spec (out, arg);
2012 if (!req->sortSequence)
2014 printf ("Missing sort specifications\n");
2021 void display_term(Z_TermInfo *t)
2023 if (t->term->which == Z_Term_general)
2025 printf("%.*s", t->term->u.general->len, t->term->u.general->buf);
2026 sprintf(last_scan_line, "%.*s", t->term->u.general->len,
2027 t->term->u.general->buf);
2030 printf("Term (not general)");
2031 if (t->globalOccurrences)
2032 printf (" (%d)\n", *t->globalOccurrences);
2037 void process_scanResponse(Z_ScanResponse *res)
2040 Z_Entry **entries = NULL;
2041 int num_entries = 0;
2043 printf("Received ScanResponse\n");
2044 print_refid (res->referenceId);
2045 printf("%d entries", *res->numberOfEntriesReturned);
2046 if (res->positionOfTerm)
2047 printf (", position=%d", *res->positionOfTerm);
2049 if (*res->scanStatus != Z_Scan_success)
2050 printf("Scan returned code %d\n", *res->scanStatus);
2053 if ((entries = res->entries->entries))
2054 num_entries = res->entries->num_entries;
2055 for (i = 0; i < num_entries; i++)
2057 int pos_term = res->positionOfTerm ? *res->positionOfTerm : -1;
2058 if (entries[i]->which == Z_Entry_termInfo)
2060 printf("%c ", i + 1 == pos_term ? '*' : ' ');
2061 display_term(entries[i]->u.termInfo);
2064 display_diagrecs(&entries[i]->u.surrogateDiagnostic, 1);
2066 if (res->entries->nonsurrogateDiagnostics)
2067 display_diagrecs (res->entries->nonsurrogateDiagnostics,
2068 res->entries->num_nonsurrogateDiagnostics);
2071 void process_sortResponse(Z_SortResponse *res)
2073 printf("Received SortResponse: status=");
2074 switch (*res->sortStatus)
2076 case Z_SortStatus_success:
2077 printf ("success"); break;
2078 case Z_SortStatus_partial_1:
2079 printf ("partial"); break;
2080 case Z_SortStatus_failure:
2081 printf ("failure"); break;
2083 printf ("unknown (%d)", *res->sortStatus);
2086 print_refid (res->referenceId);
2087 if (res->diagnostics)
2088 display_diagrecs(res->diagnostics,
2089 res->num_diagnostics);
2092 void process_deleteResultSetResponse (Z_DeleteResultSetResponse *res)
2094 printf("Got deleteResultSetResponse status=%d\n",
2095 *res->deleteOperationStatus);
2096 if (res->deleteListStatuses)
2099 for (i = 0; i < res->deleteListStatuses->num; i++)
2101 printf ("%s status=%d\n", res->deleteListStatuses->elements[i]->id,
2102 *res->deleteListStatuses->elements[i]->status);
2107 int cmd_sort_generic(const char *arg, int newset)
2111 printf("Session not initialized yet\n");
2114 if (!ODR_MASK_GET(session->options, Z_Options_sort))
2116 printf("Target doesn't support sort\n");
2121 if (send_sortrequest(arg, newset) < 0)
2128 int cmd_sort(const char *arg)
2130 return cmd_sort_generic (arg, 0);
2133 int cmd_sort_newset (const char *arg)
2135 return cmd_sort_generic (arg, 1);
2138 int cmd_scan(const char *arg)
2145 printf("Session not initialized yet\n");
2149 if (!ODR_MASK_GET(session->options, Z_Options_scan))
2151 printf("Target doesn't support scan\n");
2156 strcpy (last_scan_query, arg);
2157 if (send_scanrequest(arg, 1, 20, 0) < 0)
2162 if (send_scanrequest(last_scan_query, 1, 20, last_scan_line) < 0)
2168 int cmd_schema(const char *arg)
2175 schema = oid_getvalbyname (arg);
2176 if (schema == VAL_NONE)
2178 printf ("unknown schema\n");
2184 int cmd_format(const char *arg)
2189 printf("Usage: format <recordsyntax>\n");
2192 nsyntax = oid_getvalbyname (arg);
2193 if (strcmp(arg, "none") && nsyntax == VAL_NONE)
2195 printf ("unknown record syntax\n");
2198 recordsyntax = nsyntax;
2202 int cmd_elements(const char *arg)
2204 static Z_ElementSetNames esn;
2205 static char what[100];
2209 elementSetNames = 0;
2213 esn.which = Z_ElementSetNames_generic;
2214 esn.u.generic = what;
2215 elementSetNames = &esn;
2219 int cmd_attributeset(const char *arg)
2225 printf("Usage: attributeset <setname>\n");
2228 sscanf(arg, "%s", what);
2229 if (p_query_attset (what))
2231 printf("Unknown attribute set name\n");
2237 int cmd_querytype (const char *arg)
2239 if (!strcmp (arg, "ccl"))
2240 queryType = QueryType_CCL;
2241 else if (!strcmp (arg, "prefix") || !strcmp(arg, "rpn"))
2242 queryType = QueryType_Prefix;
2243 else if (!strcmp (arg, "ccl2rpn") || !strcmp (arg, "cclrpn"))
2244 queryType = QueryType_CCL2RPN;
2245 else if (!strcmp(arg, "cql"))
2246 queryType = QueryType_CQL;
2249 printf ("Querytype must be one of:\n");
2250 printf (" prefix - Prefix query\n");
2251 printf (" ccl - CCL query\n");
2252 printf (" ccl2rpn - CCL query converted to RPN\n");
2253 printf (" cql - CQL\n");
2259 int cmd_refid (const char *arg)
2265 refid = (char *) xmalloc (strlen(arg)+1);
2266 strcpy (refid, arg);
2271 int cmd_close(const char *arg)
2278 apdu = zget_APDU(out, Z_APDU_close);
2279 req = apdu->u.close;
2280 *req->closeReason = Z_Close_finished;
2282 printf("Sent close request.\n");
2287 int cmd_packagename(const char* arg)
2289 xfree (esPackageName);
2290 esPackageName = NULL;
2293 esPackageName = (char *) xmalloc (strlen(arg)+1);
2294 strcpy (esPackageName, arg);
2299 int cmd_proxy(const char* arg)
2310 yazProxy = (char *) xmalloc (strlen(arg)+1);
2311 strcpy (yazProxy, arg);
2316 int cmd_charset(const char* arg)
2318 char l1[30], l2[30];
2321 if (sscanf(arg, "%29s %29s", l1, l2) < 1)
2323 printf("Current character set is `%s'\n", (yazCharset) ? yazCharset:NULL);
2329 yazCharset = xstrdup(l1);
2332 odr_set_charset (out, l1, l2);
2333 odr_set_charset (in, l2, l1);
2338 int cmd_lang(const char* arg)
2341 printf("Current language is `%s'\n", (yazLang)?yazLang:NULL);
2348 yazLang = (char *) xmalloc (strlen(arg)+1);
2349 strcpy (yazLang, arg);
2354 int cmd_source(const char* arg)
2356 /* first should open the file and read one line at a time.. */
2358 char line[1024], *cp;
2361 fprintf(stderr,"Error in source command use a filename\n");
2365 includeFile = fopen (arg, "r");
2368 fprintf(stderr,"Unable to open file %s for reading\n",arg);
2372 while(!feof(includeFile)) {
2373 memset(line,0,sizeof(line));
2374 fgets(line,sizeof(line),includeFile);
2376 if(strlen(line) < 2) continue;
2377 if(line[0] == '#') continue;
2379 if ((cp = strrchr (line, '\n')))
2382 process_cmd_line(line);
2385 if(fclose(includeFile)<0) {
2386 perror("unable to close include file");
2392 int cmd_subshell(const char* args)
2397 system(getenv("SHELL"));
2403 int cmd_set_berfile(const char *arg)
2405 if (ber_file && ber_file != stdout && ber_file != stderr)
2407 if (!strcmp(arg, ""))
2409 else if (!strcmp(arg, "-"))
2412 ber_file = fopen(arg, "a");
2416 int cmd_set_apdufile(const char *arg)
2418 if(apdu_file && apdu_file != stderr && apdu_file != stderr)
2420 if (!strcmp(arg, ""))
2422 else if (!strcmp(arg, "-"))
2426 apdu_file = fopen(arg, "a");
2428 perror("unable to open apdu log file");
2433 int cmd_set_cclfile(const char* arg)
2437 bibset = ccl_qual_mk ();
2438 inf = fopen (arg, "r");
2440 perror("unable to open CCL file");
2443 ccl_qual_file (bibset, inf);
2446 strcpy(ccl_fields,arg);
2450 int cmd_set_auto_reconnect(const char* arg)
2452 if(strlen(arg)==0) {
2453 auto_reconnect = ! auto_reconnect;
2454 } else if(strcmp(arg,"on")==0) {
2456 } else if(strcmp(arg,"off")==0) {
2459 printf("Error use on or off\n");
2464 printf("Set auto reconnect enabled.\n");
2466 printf("Set auto reconnect disabled.\n");
2471 int cmd_set_marcdump(const char* arg)
2473 if(marc_file && marc_file != stderr) { /* don't close stdout*/
2477 if (!strcmp(arg, ""))
2479 else if (!strcmp(arg, "-"))
2483 marc_file = fopen(arg, "a");
2485 perror("unable to open marc log file");
2490 int cmd_set_proxy(const char* arg)
2492 if(yazProxy) free(yazProxy);
2495 if(strlen(arg) > 1) {
2496 yazProxy=strdup(arg);
2502 this command takes 3 arge {name class oid}
2504 int cmd_register_oid(const char* args) {
2509 {"appctx",CLASS_APPCTX},
2510 {"absyn",CLASS_ABSYN},
2511 {"attset",CLASS_ATTSET},
2512 {"transyn",CLASS_TRANSYN},
2513 {"diagset",CLASS_DIAGSET},
2514 {"recsyn",CLASS_RECSYN},
2515 {"resform",CLASS_RESFORM},
2516 {"accform",CLASS_ACCFORM},
2517 {"extserv",CLASS_EXTSERV},
2518 {"userinfo",CLASS_USERINFO},
2519 {"elemspec",CLASS_ELEMSPEC},
2520 {"varset",CLASS_VARSET},
2521 {"schema",CLASS_SCHEMA},
2522 {"tagset",CLASS_TAGSET},
2523 {"general",CLASS_GENERAL},
2524 {0,(enum oid_class) 0}
2526 char oname_str[101], oclass_str[101], oid_str[101];
2529 oid_class oidclass = CLASS_GENERAL;
2530 int val = 0, oid[OID_SIZE];
2531 struct oident * new_oident=NULL;
2533 if (sscanf (args, "%100[^ ] %100[^ ] %100s",
2534 oname_str,oclass_str, oid_str) < 1) {
2535 printf("Error in regristrate command \n");
2539 for (i = 0; oid_classes[i].className; i++) {
2540 if (!strcmp(oid_classes[i].className, oclass_str))
2542 oidclass=oid_classes[i].oclass;
2547 if(!(oid_classes[i].className)) {
2548 printf("Unknonwn oid class %s\n",oclass_str);
2556 while (isdigit (*name))
2558 val = val*10 + (*name - '0');
2571 new_oident=oid_addent (oid,PROTO_GENERAL,oidclass,oname_str,VAL_DYNAMIC);
2572 if(strcmp(new_oident->desc,oname_str)) {
2573 fprintf(stderr,"oid is already named as %s, regristration faild\n",
2579 int cmd_push_command(const char* arg)
2581 #if HAVE_READLINE_HISTORY_H
2585 fprintf(stderr,"Not compiled with the readline/history module\n");
2590 void source_rcfile()
2592 /* Look for a $HOME/.yazclientrc and source it if it exists */
2593 struct stat statbuf;
2595 char* homedir=getenv("HOME");
2597 if(!homedir) return;
2599 sprintf(buffer,"%s/.yazclientrc",homedir);
2601 if(stat(buffer,&statbuf)==0) {
2605 if(stat(".yazclientrc",&statbuf)==0) {
2606 cmd_source(".yazclientrc");
2611 static void initialize(void)
2616 if (!(out = odr_createmem(ODR_ENCODE)) ||
2617 !(in = odr_createmem(ODR_DECODE)) ||
2618 !(print = odr_createmem(ODR_PRINT)))
2620 fprintf(stderr, "failed to allocate ODR streams\n");
2625 setvbuf(stdout, 0, _IONBF, 0);
2627 odr_setprint(print, apdu_file);
2629 bibset = ccl_qual_mk ();
2630 inf = fopen (ccl_fields, "r");
2633 ccl_qual_file (bibset, inf);
2636 cmd_base("Default");
2638 #if HAVE_READLINE_READLINE_H
2639 rl_attempted_completion_function = (CPPFunction*)readline_completer;
2643 for(i=0; i<maxOtherInfosSupported; ++i) {
2644 extraOtherInfos[i].oidval = -1;
2651 #if HAVE_GETTIMEOFDAY
2652 struct timeval tv_start, tv_end;
2655 void wait_and_handle_responce()
2660 int netbufferlen = 0;
2668 if ((res = cs_get(conn, &netbuffer, &netbufferlen)) < 0)
2670 printf("Target closed connection\n");
2676 printf("Target closed connection.\n");
2680 odr_reset(in); /* release APDU from last round */
2682 odr_setbuf(in, netbuffer, res, 0);
2683 if (!z_APDU(in, &apdu, 0, 0))
2685 FILE *f = ber_file ? ber_file : stdout;
2686 odr_perror(in, "Decoding incoming APDU");
2687 fprintf(f, "[Near %d]\n", odr_offset(in));
2688 fprintf(f, "Packet dump:\n---------\n");
2689 odr_dumpBER(f, netbuffer, res);
2690 fprintf(f, "---------\n");
2692 z_APDU(print, &apdu, 0, 0);
2697 odr_dumpBER(ber_file, netbuffer, res);
2698 if (apdu_file && !z_APDU(print, &apdu, 0, 0))
2700 odr_perror(print, "Failed to print incoming APDU");
2706 case Z_APDU_initResponse:
2707 process_initResponse(apdu->u.initResponse);
2709 case Z_APDU_searchResponse:
2710 process_searchResponse(apdu->u.searchResponse);
2712 case Z_APDU_scanResponse:
2713 process_scanResponse(apdu->u.scanResponse);
2715 case Z_APDU_presentResponse:
2716 print_refid (apdu->u.presentResponse->referenceId);
2718 *apdu->u.presentResponse->numberOfRecordsReturned;
2719 if (apdu->u.presentResponse->records)
2720 display_records(apdu->u.presentResponse->records);
2722 printf("No records.\n");
2723 printf ("nextResultSetPosition = %d\n",
2724 *apdu->u.presentResponse->nextResultSetPosition);
2726 case Z_APDU_sortResponse:
2727 process_sortResponse(apdu->u.sortResponse);
2729 case Z_APDU_extendedServicesResponse:
2730 printf("Got extended services response\n");
2731 process_ESResponse(apdu->u.extendedServicesResponse);
2734 printf("Target has closed the association.\n");
2735 process_close(apdu->u.close);
2737 case Z_APDU_resourceControlRequest:
2738 process_resourceControlRequest
2739 (apdu->u.resourceControlRequest);
2741 case Z_APDU_deleteResultSetResponse:
2742 process_deleteResultSetResponse(apdu->u.
2743 deleteResultSetResponse);
2746 printf("Received unknown APDU type (%d).\n",
2751 while (conn && cs_more(conn));
2752 #if HAVE_GETTIMEOFDAY
2753 gettimeofday (&tv_end, 0);
2755 printf ("S/U S/U=%ld/%ld %ld/%ld",
2756 (long) tv_start.tv_sec,
2757 (long) tv_start.tv_usec,
2758 (long) tv_end.tv_sec,
2759 (long) tv_end.tv_usec);
2761 printf ("Elapsed: %.6f\n",
2762 (double) tv_end.tv_usec / 1e6 + tv_end.tv_sec -
2763 ((double) tv_start.tv_usec / 1e6 + tv_start.tv_sec));
2770 int cmd_cclparse(const char* arg)
2773 struct ccl_rpn_node *rpn=NULL;
2776 rpn = ccl_find_str (bibset, arg, &error, &pos);
2779 printf ("%*s^ - ", 3+strlen(last_cmd)+1+pos, " ");
2780 printf ("%s\n", ccl_err_msg (error));
2786 ccl_pr_tree(rpn, stdout);
2790 ccl_rpn_delete(rpn);
2798 int cmd_set_otherinfo(const char* args)
2800 char oid[101], otherinfoString[101];
2805 sscan_res = sscanf (args, "%d %100[^ ] %100s", &otherinfoNo, oid, otherinfoString);
2807 /* reset this otherinfo */
2808 if(otherinfoNo>=maxOtherInfosSupported) {
2809 printf("Error otherinfo index to large (%d>%d)\n",otherinfoNo,maxOtherInfosSupported);
2811 extraOtherInfos[otherinfoNo].oidval = -1;
2812 if(extraOtherInfos[otherinfoNo].value) free(extraOtherInfos[otherinfoNo].value);
2816 printf("Error in set_otherinfo command \n");
2820 if(otherinfoNo>=maxOtherInfosSupported) {
2821 printf("Error otherinfo index to large (%d>%d)\n",otherinfoNo,maxOtherInfosSupported);
2825 oidval = oid_getvalbyname (oid);
2827 printf("Error in set_otherinfo command unknown oid %s \n",oid);
2830 extraOtherInfos[otherinfoNo].oidval = oidval;
2831 if(extraOtherInfos[otherinfoNo].value) free(extraOtherInfos[otherinfoNo].value);
2832 extraOtherInfos[otherinfoNo].value = strdup(otherinfoString);
2837 int cmd_list_otherinfo(const char* args)
2841 if(strlen(args)>0) {
2843 if( i >= maxOtherInfosSupported ) {
2844 printf("Error otherinfo index to large (%d>%d)\n",i,maxOtherInfosSupported);
2848 if(extraOtherInfos[i].oidval != -1)
2849 printf(" otherinfo %d %s %s\n",
2851 yaz_z3950_oid_value_to_str(
2852 (enum oid_value) extraOtherInfos[i].oidval,
2854 extraOtherInfos[i].value);
2857 for(i=0; i<maxOtherInfosSupported; ++i) {
2858 if(extraOtherInfos[i].oidval != -1)
2859 printf(" otherinfo %d %s %s\n",
2861 yaz_z3950_oid_value_to_str(
2862 (enum oid_value) extraOtherInfos[i].oidval,
2864 extraOtherInfos[i].value);
2872 int cmd_list_all(const char* args) {
2875 /* connection options */
2877 printf("Connected to : %s\n",last_open_command);
2879 if(last_open_command)
2880 printf("Not connected to : %s\n",last_open_command);
2882 printf("Not connected : \n");
2885 if(yazProxy) printf("using proxy : %s\n",yazProxy);
2887 printf("auto_reconnect : %s\n",auto_reconnect?"on":"off");
2890 printf("Authentication : none\n");
2892 switch(auth->which) {
2893 case Z_IdAuthentication_idPass:
2894 printf("Authentication : IdPass\n");
2895 printf(" Login User : %s\n",auth->u.idPass->userId?auth->u.idPass->userId:"");
2896 printf(" Login Group : %s\n",auth->u.idPass->groupId?auth->u.idPass->groupId:"");
2897 printf(" Password : %s\n",auth->u.idPass->password?auth->u.idPass->password:"");
2899 case Z_IdAuthentication_open:
2900 printf("Authentication : psOpen\n");
2901 printf(" Open string : %s\n",auth->u.open);
2904 printf("Authentication : Unknown\n");
2907 if ( yazCharset ) printf("Character set : `%s'\n", (yazCharset) ? yazCharset:NULL);
2911 for (i = 0; i<num_databaseNames; i++) printf("%s ",databaseNames[i]);
2915 printf("CCL file : %s\n",ccl_fields);
2916 printf("Query type : %s\n",query_type_as_string(queryType));
2918 printf("Named Result Sets : %s\n",setnumber==-1?"off":"on");
2920 /* piggy back options */
2921 printf("ssub/lslb/mspn : %d/%d/%d\n",smallSetUpperBound,largeSetLowerBound,mediumSetPresentNumber);
2923 /* print present related options */
2924 printf("Format : %s\n",yaz_z3950_oid_value_to_str(recordsyntax,CLASS_RECSYN));
2925 printf("Schema : %s\n",yaz_z3950_oid_value_to_str(schema,CLASS_SCHEMA));
2926 printf("Elements : %s\n",elementSetNames?elementSetNames->u.generic:"");
2928 /* loging options */
2929 printf("APDU log : %s\n",apdu_file?"on":"off");
2930 printf("Record log : %s\n",marc_file?"on":"off");
2933 printf("Other Info: \n");
2934 cmd_list_otherinfo("");
2939 int cmd_clear_otherinfo(const char* args)
2941 if(strlen(args)>0) {
2943 otherinfoNo = atoi(args);
2944 if( otherinfoNo >= maxOtherInfosSupported ) {
2945 printf("Error otherinfo index to large (%d>%d)\n",otherinfoNo,maxOtherInfosSupported);
2949 if(extraOtherInfos[otherinfoNo].oidval != -1) {
2950 /* only clear if set. */
2951 extraOtherInfos[otherinfoNo].oidval=-1;
2952 free(extraOtherInfos[otherinfoNo].value);
2957 for(i=0; i<maxOtherInfosSupported; ++i) {
2958 if (extraOtherInfos[i].oidval!=-1 ) {
2959 extraOtherInfos[i].oidval=-1;
2960 free(extraOtherInfos[i].value);
2967 static int cmd_help (const char *line);
2969 typedef char *(*completerFunctionType)(const char *text, int state);
2973 int (*fun)(const char *arg);
2975 completerFunctionType rl_completerfunction;
2976 int complete_filenames;
2977 char **local_tabcompletes;
2979 {"open", cmd_open, "('tcp'|'ssl')':<host>[':'<port>][/<db>]",NULL,0,NULL},
2980 {"quit", cmd_quit, "",NULL,0,NULL},
2981 {"find", cmd_find, "<query>",NULL,0,NULL},
2982 {"delete", cmd_delete, "<setname>",NULL,0,NULL},
2983 {"base", cmd_base, "<base-name>",NULL,0,NULL},
2984 {"show", cmd_show, "<rec#>['+'<#recs>['+'<setname>]]",NULL,0,NULL},
2985 {"scan", cmd_scan, "<term>",NULL,0,NULL},
2986 {"sort", cmd_sort, "<sortkey> <flag> <sortkey> <flag> ...",NULL,0,NULL},
2987 {"sort+", cmd_sort_newset, "<sortkey> <flag> <sortkey> <flag> ...",NULL,0,NULL},
2988 {"authentication", cmd_authentication, "<acctstring>",NULL,0,NULL},
2989 {"lslb", cmd_lslb, "<largeSetLowerBound>",NULL,0,NULL},
2990 {"ssub", cmd_ssub, "<smallSetUpperBound>",NULL,0,NULL},
2991 {"mspn", cmd_mspn, "<mediumSetPresentNumber>",NULL,0,NULL},
2992 {"status", cmd_status, "",NULL,0,NULL},
2993 {"setnames", cmd_setnames, "",NULL,0,NULL},
2994 {"cancel", cmd_cancel, "",NULL,0,NULL},
2995 {"format", cmd_format, "<recordsyntax>",complete_format,0,NULL},
2996 {"schema", cmd_schema, "<schema>",complete_schema,0,NULL},
2997 {"elements", cmd_elements, "<elementSetName>",NULL,0,NULL},
2998 {"close", cmd_close, "",NULL,0,NULL},
2999 {"attributeset", cmd_attributeset, "<attrset>",complete_attributeset,0,NULL},
3000 {"querytype", cmd_querytype, "<type>",complete_querytype,0,NULL},
3001 {"refid", cmd_refid, "<id>",NULL,0,NULL},
3002 {"itemorder", cmd_itemorder, "ill|item <itemno>",NULL,0,NULL},
3003 {"update", cmd_update, "<action> <recid> [<file>]",NULL,0,NULL},
3004 {"packagename", cmd_packagename, "<packagename>",NULL,0,NULL},
3005 {"proxy", cmd_proxy, "[('tcp'|'ssl')]<host>[':'<port>]",NULL,0,NULL},
3006 {"charset", cmd_charset, "<charset_name>",NULL,0,NULL},
3007 {"lang", cmd_lang, "<language_code>",NULL,0,NULL},
3008 {".", cmd_source, "<filename>",NULL,1,NULL},
3009 {"!", cmd_subshell, "Subshell command",NULL,1,NULL},
3010 {"set_apdufile", cmd_set_apdufile, "<filename>",NULL,1,NULL},
3011 {"set_berfile", cmd_set_berfile, "<filename>",NULL,1,NULL},
3012 {"set_marcdump", cmd_set_marcdump," <filename>",NULL,1,NULL},
3013 {"set_cclfile", cmd_set_cclfile," <filename>",NULL,1,NULL},
3014 {"set_auto_reconnect", cmd_set_auto_reconnect," on|off",complete_auto_reconnect,1,NULL},
3015 {"set_otherinfo", cmd_set_otherinfo,"<otherinfoinddex> <oid> <string>",NULL,0,NULL},
3016 {"register_oid", cmd_register_oid,"<name> <class> <oid>",NULL,0,NULL},
3017 {"push_command", cmd_push_command,"<command>",command_generator,0,NULL},
3018 {"register_tab", cmd_register_tab,"<commandname> <tab>",command_generator,0,NULL},
3019 {"cclparse", cmd_cclparse,"<ccl find command>",NULL,0,NULL},
3020 {"list_otherinfo",cmd_list_otherinfo,"[otherinfoinddex]",NULL,0,NULL},
3021 {"list_all",cmd_list_all,"",NULL,0,NULL},
3022 {"clear_otherinfo",cmd_clear_otherinfo,"",NULL,0,NULL},
3023 /* Server Admin Functions */
3024 {"adm-reindex", cmd_adm_reindex, "<database-name>",NULL,0,NULL},
3025 {"adm-truncate", cmd_adm_truncate, "('database'|'index')<object-name>",NULL,0,NULL},
3026 {"adm-create", cmd_adm_create, "",NULL,0,NULL},
3027 {"adm-drop", cmd_adm_drop, "('database'|'index')<object-name>",NULL,0,NULL},
3028 {"adm-import", cmd_adm_import, "<record-type> <dir> <pattern>",NULL,0,NULL},
3029 {"adm-refresh", cmd_adm_refresh, "",NULL,0,NULL},
3030 {"adm-commit", cmd_adm_commit, "",NULL,0,NULL},
3031 {"adm-shutdown", cmd_adm_shutdown, "",NULL,0,NULL},
3032 {"adm-startup", cmd_adm_startup, "",NULL,0,NULL},
3033 {"help", cmd_help, "", NULL,0,NULL},
3037 static int cmd_help (const char *line)
3043 sscanf (line, "%20s", topic);
3046 printf("Commands:\n");
3047 for (i = 0; cmd_array[i].cmd; i++)
3048 if (*topic == 0 || strcmp (topic, cmd_array[i].cmd) == 0)
3049 printf(" %s %s\n", cmd_array[i].cmd, cmd_array[i].ad);
3050 if (strcmp (topic, "find") == 0)
3053 printf (" \"term\" Simple Term\n");
3054 printf (" @attr [attset] type=value op Attribute\n");
3055 printf (" @and opl opr And\n");
3056 printf (" @or opl opr Or\n");
3057 printf (" @not opl opr And-Not\n");
3058 printf (" @set set Result set\n");
3060 printf ("Bib-1 attribute types\n");
3062 printf ("4=Title 7=ISBN 8=ISSN 30=Date 62=Abstract 1003=Author 1016=Any\n");
3063 printf ("2=Relation: ");
3064 printf ("1< 2<= 3= 4>= 5> 6!= 102=Relevance\n");
3065 printf ("3=Position: ");
3066 printf ("1=First in Field 2=First in subfield 3=Any position\n");
3067 printf ("4=Structure: ");
3068 printf ("1=Phrase 2=Word 3=Key 4=Year 5=Date 6=WordList\n");
3069 printf ("5=Truncation: ");
3070 printf ("1=Right 2=Left 3=L&R 100=No 101=# 102=Re-1 103=Re-2\n");
3071 printf ("6=Completeness:");
3072 printf ("1=Incomplete subfield 2=Complete subfield 3=Complete field\n");
3077 int cmd_register_tab(const char* arg) {
3079 char command[101], tabargument[101];
3084 if (sscanf (arg, "%100s %100s", command, tabargument) < 1) {
3088 /* locate the amdn in the list */
3089 for (i = 0; cmd_array[i].cmd; i++) {
3090 if (!strncmp(cmd_array[i].cmd, command, strlen(command))) {
3095 if(!cmd_array[i].cmd) {
3096 fprintf(stderr,"Unknown command %s\n",command);
3101 if(!cmd_array[i].local_tabcompletes)
3102 cmd_array[i].local_tabcompletes = (char **) calloc(1,sizeof(char**));
3106 tabslist = cmd_array[i].local_tabcompletes;
3107 for(;tabslist && *tabslist;tabslist++) {
3111 cmd_array[i].local_tabcompletes = (char **)
3112 realloc(cmd_array[i].local_tabcompletes,(num_of_tabs+2)*sizeof(char**));
3113 tabslist=cmd_array[i].local_tabcompletes;
3114 tabslist[num_of_tabs]=strdup(tabargument);
3115 tabslist[num_of_tabs+1]=NULL;
3120 void process_cmd_line(char* line)
3123 char word[32], arg[1024];
3125 #if HAVE_GETTIMEOFDAY
3126 gettimeofday (&tv_start, 0);
3129 if ((res = sscanf(line, "%31s %1023[^;]", word, arg)) <= 0)
3131 strcpy(word, last_cmd);
3136 strcpy(last_cmd, word);
3138 /* removed tailing spaces from the arg command */
3141 char* lastnonspace=NULL;
3149 *(++lastnonspace) = 0;
3152 for (i = 0; cmd_array[i].cmd; i++)
3153 if (!strncmp(cmd_array[i].cmd, word, strlen(word)))
3155 res = (*cmd_array[i].fun)(arg);
3159 if (!cmd_array[i].cmd) /* dump our help-screen */
3161 printf("Unknown command: %s.\n", word);
3162 printf("use help for list of commands\n");
3163 /* cmd_help (""); */
3167 if(apdu_file) fflush(apdu_file);
3170 wait_and_handle_responce();
3179 char *command_generator(const char *text, int state)
3185 for( ; cmd_array[idx].cmd; ++idx) {
3186 if (!strncmp(cmd_array[idx].cmd,text,strlen(text))) {
3187 ++idx; /* skip this entry on the next run */
3188 return strdup(cmd_array[idx-1].cmd);
3196 This function only known how to complete on the first word
3198 char ** readline_completer(char *text, int start, int end) {
3199 #if HAVE_READLINE_READLINE_H
3201 completerFunctionType completerToUse;
3204 #if HAVE_READLINE_RL_COMPLETION_MATCHES
3205 char** res=rl_completion_matches(text,
3208 char** res=completion_matches(text,
3209 (CPFunction*)command_generator);
3211 rl_attempted_completion_over = 1;
3214 char arg[1024],word[32];
3216 if ((res = sscanf(rl_line_buffer, "%31s %1023[^;]", word, arg)) <= 0) {
3217 rl_attempted_completion_over = 1;
3221 for (i = 0; cmd_array[i].cmd; i++) {
3222 if (!strncmp(cmd_array[i].cmd, word, strlen(word))) {
3227 if(!cmd_array[i].cmd) return NULL;
3229 curret_global_list = cmd_array[i].local_tabcompletes;
3231 completerToUse = cmd_array[i].rl_completerfunction;
3232 if(completerToUse==NULL) /* if no pr. command completer is defined use the default completer */
3233 completerToUse = default_completer;
3235 if(completerToUse) {
3236 #ifdef HAVE_READLINE_RL_COMPLETION_MATCHES
3238 rl_completion_matches(text,
3242 completion_matches(text,
3243 (CPFunction*)completerToUse);
3245 if(!cmd_array[i].complete_filenames)
3246 rl_attempted_completion_over = 1;
3249 if(!cmd_array[i].complete_filenames)
3250 rl_attempted_completion_over = 1;
3260 static void client(void)
3266 #if HAVE_GETTIMEOFDAY
3267 gettimeofday (&tv_start, 0);
3272 char *line_in = NULL;
3273 #if HAVE_READLINE_READLINE_H
3276 line_in=readline(C_PROMPT);
3279 #if HAVE_READLINE_HISTORY_H
3281 add_history(line_in);
3283 strncpy(line, line_in, 1023);
3292 if (!fgets(line, 1023, stdin))
3294 if ((end_p = strchr (line, '\n')))
3297 process_cmd_line(line);
3301 int main(int argc, char **argv)
3304 char *open_command = 0;
3305 char *auth_command = 0;
3310 if (!setlocale(LC_CTYPE, ""))
3311 fprintf (stderr, "setlocale failed\n");
3315 codeset = nl_langinfo(CODESET);
3319 while ((ret = options("k:c:a:b:m:v:p:u:t:", argv, argc, &arg)) != -2)
3326 open_command = (char *) xmalloc (strlen(arg)+6);
3327 strcpy (open_command, "open ");
3328 strcat (open_command, arg);
3332 kilobytes = atoi(arg);
3335 if (!(marc_file = fopen (arg, "a")))
3345 strncpy (ccl_fields, arg, sizeof(ccl_fields)-1);
3346 ccl_fields[sizeof(ccl_fields)-1] = '\0';
3349 if (!strcmp(arg, "-"))
3352 ber_file=fopen(arg, "a");
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 "[-b berdump] [-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