2 * Copyright (c) 1995-2002, Index Data
3 * See the file LICENSE for details.
5 * $Id: client.c,v 1.177 2002-12-16 13:30:41 adam Exp $
23 #define S_ISREG(x) (x & _S_IFREG)
24 #define S_ISDIR(x) (x & _S_IFDIR)
27 #include <yaz/yaz-util.h>
29 #include <yaz/comstack.h>
31 #include <yaz/proto.h>
32 #include <yaz/marcdisp.h>
33 #include <yaz/diagbib1.h>
34 #include <yaz/otherinfo.h>
35 #include <yaz/charneg.h>
37 #include <yaz/pquery.h>
38 #include <yaz/sortspec.h>
42 #include <yaz/yaz-ccl.h>
44 #if HAVE_READLINE_READLINE_H
45 #include <readline/readline.h>
48 #if HAVE_READLINE_HISTORY_H
49 #include <readline/history.h>
56 #include "tabcomplete.h"
58 #define C_PROMPT "Z> "
60 static char *codeset = 0; /* character set for output */
62 static ODR out, in, print; /* encoding and decoding streams */
63 static FILE *apdu_file = 0;
64 static COMSTACK conn = 0; /* our z-association */
65 static Z_IdAuthentication *auth = 0; /* our current auth definition */
66 char *databaseNames[128];
67 int num_databaseNames = 0;
68 static Z_External *record_last = 0;
69 static int setnumber = -1; /* current result set number */
70 static int smallSetUpperBound = 0;
71 static int largeSetLowerBound = 1;
72 static int mediumSetPresentNumber = 0;
73 static Z_ElementSetNames *elementSetNames = 0;
74 static int setno = 1; /* current set offset */
75 static enum oid_proto protocol = PROTO_Z3950; /* current app protocol */
76 static enum oid_value recordsyntax = VAL_USMARC;
77 static enum oid_value schema = VAL_NONE;
78 static int sent_close = 0;
79 static NMEM session_mem = NULL; /* memory handle for init-response */
80 static Z_InitResponse *session = 0; /* session parameters */
81 static char last_scan_line[512] = "0";
82 static char last_scan_query[512] = "0";
83 static char ccl_fields[512] = "default.bib";
84 static char* esPackageName = 0;
85 static char* yazProxy = 0;
86 static int kilobytes = 1024;
87 static char* yazCharset = 0;
88 static char* yazLang = 0;
91 static char last_cmd[32] = "?";
92 static FILE *marcdump = 0;
93 static char *refid = NULL;
94 static char *last_open_command = NULL;
95 static int auto_reconnect = 0;
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 /* nice helper macro as extensive tabbing gives spaces at the en of the args lines */
118 #define REMOVE_TAILING_BLANKS(a) {\
119 char* args_end=(a)+strlen(a)-1; \
120 while(isspace(*args_end)) {*args_end=0;--args_end;}; \
123 #define maxOtherInfosSupported 10
127 } extraOtherInfos[maxOtherInfosSupported];
130 void process_cmd_line(char* line);
131 char ** readline_completer(char *text, int start, int end);
132 char *command_generator(const char *text, int state);
133 char** curret_global_list=NULL;
134 int cmd_register_tab(char* arg);
136 ODR getODROutputStream()
141 const char* query_type_as_string(QueryType q)
144 case QueryType_Prefix: return "prefix (RPN sent to server)";
145 case QueryType_CCL: return "CCL (CCL sent to server) ";
146 case QueryType_CCL2RPN: return "CCL -> RPN (RPN sent to server)";
148 return "unknown Query type internal yaz-client error";
153 void do_hex_dump(char* buf,int len)
157 for( i=0; i<len ; i=i+16 )
160 for(x=0 ; i+x<len && x<16; ++x)
162 printf("%2.2X ",(unsigned int)((unsigned char)buf[i+x]));
169 void add_otherInfos(Z_APDU *a)
171 Z_OtherInformation **oi;
175 for(i=0; i<maxOtherInfosSupported; ++i)
177 if(extraOtherInfos[i].oidval != -1)
178 yaz_oi_set_string_oidval(oi, out, extraOtherInfos[i].oidval, 1, extraOtherInfos[i].value);
182 void send_apdu(Z_APDU *a)
191 z_APDU(print, &a, 0, 0);
194 if (!z_APDU(out, &a, 0, 0))
196 odr_perror(out, "Encoding APDU");
199 buf = odr_getbuf(out, &len, 0);
200 /* printf ("sending APDU of size %d\n", len); */
201 if (cs_put(conn, buf, len) < 0)
203 fprintf(stderr, "cs_put: %s", cs_errmsg(cs_errno(conn)));
207 do_hex_dump(buf,len);
208 odr_reset(out); /* release the APDU structure */
211 static void print_stringn(const unsigned char *buf, size_t len)
214 for (i = 0; i<len; i++)
215 if ((buf[i] <= 126 && buf[i] >= 32) || strchr ("\n\r\t\f", buf[i]))
216 printf ("%c", buf[i]);
218 printf ("\\X%02X", buf[i]);
221 static void print_refid (Z_ReferenceId *id)
225 printf ("Reference Id: ");
226 print_stringn (id->buf, id->len);
231 static Z_ReferenceId *set_refid (ODR out)
236 id = (Z_ReferenceId *) odr_malloc (out, sizeof(*id));
237 id->size = id->len = strlen(refid);
238 id->buf = (unsigned char *) odr_malloc (out, id->len);
239 memcpy (id->buf, refid, id->len);
243 /* INIT SERVICE ------------------------------- */
245 static void send_initRequest(const char* type_and_host)
247 Z_APDU *apdu = zget_APDU(out, Z_APDU_initRequest);
248 Z_InitRequest *req = apdu->u.initRequest;
250 ODR_MASK_SET(req->options, Z_Options_search);
251 ODR_MASK_SET(req->options, Z_Options_present);
252 ODR_MASK_SET(req->options, Z_Options_namedResultSets);
253 ODR_MASK_SET(req->options, Z_Options_triggerResourceCtrl);
254 ODR_MASK_SET(req->options, Z_Options_scan);
255 ODR_MASK_SET(req->options, Z_Options_sort);
256 ODR_MASK_SET(req->options, Z_Options_extendedServices);
257 ODR_MASK_SET(req->options, Z_Options_delSet);
259 ODR_MASK_SET(req->protocolVersion, Z_ProtocolVersion_1);
260 ODR_MASK_SET(req->protocolVersion, Z_ProtocolVersion_2);
261 ODR_MASK_SET(req->protocolVersion, Z_ProtocolVersion_3);
263 *req->maximumRecordSize = 1024*kilobytes;
264 *req->preferredMessageSize = 1024*kilobytes;
266 req->idAuthentication = auth;
268 req->referenceId = set_refid (out);
271 yaz_oi_set_string_oidval(&req->otherInfo, out, VAL_PROXY,
274 if (yazCharset || yazLang) {
275 Z_OtherInformation **p;
276 Z_OtherInformationUnit *p0;
278 yaz_oi_APDU(apdu, &p);
280 if ((p0=yaz_oi_update(p, out, NULL, 0, 0))) {
281 ODR_MASK_SET(req->options, Z_Options_negotiationModel);
283 p0->which = Z_OtherInfo_externallyDefinedInfo;
284 p0->information.externallyDefinedInfo =
285 yaz_set_proposal_charneg(out,
286 (const char**)&yazCharset, (yazCharset)?1:0,
287 (const char**)&yazLang, (yazLang)?1:0, 1);
292 printf("Sent initrequest.\n");
295 static int process_initResponse(Z_InitResponse *res)
297 /* save session parameters for later use */
298 session_mem = odr_extract_mem(in);
302 printf("Connection rejected by target.\n");
304 printf("Connection accepted by target.\n");
305 if (res->implementationId)
306 printf("ID : %s\n", res->implementationId);
307 if (res->implementationName)
308 printf("Name : %s\n", res->implementationName);
309 if (res->implementationVersion)
310 printf("Version: %s\n", res->implementationVersion);
311 if (res->userInformationField)
313 printf("UserInformationfield:\n");
314 if (!z_External(print, (Z_External**)&res-> userInformationField,
317 odr_perror(print, "Printing userinfo\n");
320 if (res->userInformationField->which == Z_External_octet)
322 printf("Guessing visiblestring:\n");
323 printf("'%s'\n", res->userInformationField->u. octet_aligned->buf);
328 if (ODR_MASK_GET(res->options, Z_Options_search))
330 if (ODR_MASK_GET(res->options, Z_Options_present))
332 if (ODR_MASK_GET(res->options, Z_Options_delSet))
334 if (ODR_MASK_GET(res->options, Z_Options_resourceReport))
335 printf (" resourceReport");
336 if (ODR_MASK_GET(res->options, Z_Options_resourceCtrl))
337 printf (" resourceCtrl");
338 if (ODR_MASK_GET(res->options, Z_Options_accessCtrl))
339 printf (" accessCtrl");
340 if (ODR_MASK_GET(res->options, Z_Options_scan))
342 if (ODR_MASK_GET(res->options, Z_Options_sort))
344 if (ODR_MASK_GET(res->options, Z_Options_extendedServices))
345 printf (" extendedServices");
346 if (ODR_MASK_GET(res->options, Z_Options_level_1Segmentation))
347 printf (" level1Segmentation");
348 if (ODR_MASK_GET(res->options, Z_Options_level_2Segmentation))
349 printf (" level2Segmentation");
350 if (ODR_MASK_GET(res->options, Z_Options_concurrentOperations))
351 printf (" concurrentOperations");
352 if (ODR_MASK_GET(res->options, Z_Options_namedResultSets))
354 printf (" namedResultSets");
357 if (ODR_MASK_GET(res->options, Z_Options_encapsulation))
358 printf (" encapsulation");
359 if (ODR_MASK_GET(res->options, Z_Options_resultCount))
360 printf (" resultCount");
361 if (ODR_MASK_GET(res->options, Z_Options_negotiationModel))
362 printf (" negotiationModel");
363 if (ODR_MASK_GET(res->options, Z_Options_duplicateDetection))
364 printf (" duplicateDetection");
365 if (ODR_MASK_GET(res->options, Z_Options_queryType104))
366 printf (" queryType104");
369 if (ODR_MASK_GET(res->options, Z_Options_negotiationModel)) {
371 Z_CharSetandLanguageNegotiation *p =
372 yaz_get_charneg_record(res->otherInfo);
376 char *charset=NULL, *lang=NULL;
379 yaz_get_response_charneg(session_mem, p, &charset, &lang,
382 printf("Accepted character set : %s\n", charset);
383 printf("Accepted code language : %s\n", lang ? lang : "none");
384 printf("Accepted records in ...: %d\n", selected );
391 static int cmd_base(char *arg)
398 printf("Usage: base <database> <database> ...\n");
401 for (i = 0; i<num_databaseNames; i++)
402 xfree (databaseNames[i]);
403 num_databaseNames = 0;
407 if (!(cp = strchr(arg, ' ')))
408 cp = arg + strlen(arg);
411 databaseNames[num_databaseNames] = (char *)xmalloc (1 + cp - arg);
412 memcpy (databaseNames[num_databaseNames], arg, cp - arg);
413 databaseNames[num_databaseNames][cp - arg] = '\0';
415 for (cp1 = databaseNames[num_databaseNames]; *cp1 ; cp1++)
427 void cmd_open_remember_last_open_command(char* arg, char* new_open_command)
429 if(last_open_command != arg)
431 if(last_open_command) xfree(last_open_command);
432 last_open_command = xstrdup(new_open_command);
436 int cmd_open(char *arg)
439 char type_and_host[101], base[101];
443 printf("Already connected.\n");
449 nmem_destroy (session_mem);
454 if (strncmp (arg, "unix:", 5) == 0)
457 conn = cs_create_host(arg, 1, &add);
458 cmd_open_remember_last_open_command(arg,arg);
463 if (sscanf (arg, "%100[^/]/%100s", type_and_host, base) < 1)
466 cmd_open_remember_last_open_command(arg,type_and_host);
468 conn = cs_create_host(yazProxy, 1, &add);
470 conn = cs_create_host(type_and_host, 1, &add);
474 printf ("Couldn't create comstack\n");
477 printf("Connecting...");
479 if (cs_connect(conn, add) < 0)
481 printf ("error = %s\n", cs_strerror(conn));
482 if (conn->cerrno == CSYSERR)
485 yaz_strerror(msg, sizeof(msg));
486 printf ("%s\n", msg);
494 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(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(stderr, "[Near %d]\n", odr_offset(in));
613 fprintf(stderr, "Packet dump:\n---------\n");
614 odr_dumpBER(stderr, (char*)r->u.octet_aligned->buf,
615 r->u.octet_aligned->len);
616 fprintf(stderr, "---------\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, marcdump);
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(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(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;
879 if (queryType == QueryType_CCL2RPN)
881 rpn = ccl_find_str(bibset, arg, &error, &pos);
884 printf("CCL ERROR: %s\n", ccl_err_msg(error));
888 req->referenceId = set_refid (out);
889 if (!strcmp(arg, "@big")) /* strictly for troublemaking */
891 static unsigned char big[2100];
894 /* send a very big referenceid to test transport stack etc. */
895 memset(big, 'A', 2100);
896 bigo.len = bigo.size = 2100;
898 req->referenceId = &bigo;
903 sprintf(setstring, "%d", ++setnumber);
904 req->resultSetName = setstring;
906 *req->smallSetUpperBound = smallSetUpperBound;
907 *req->largeSetLowerBound = largeSetLowerBound;
908 *req->mediumSetPresentNumber = mediumSetPresentNumber;
909 if (smallSetUpperBound > 0 || (largeSetLowerBound > 1 &&
910 mediumSetPresentNumber > 0))
914 prefsyn.proto = protocol;
915 prefsyn.oclass = CLASS_RECSYN;
916 prefsyn.value = recordsyntax;
917 req->preferredRecordSyntax =
918 odr_oiddup(out, oid_ent_to_oid(&prefsyn, oid));
919 req->smallSetElementSetNames =
920 req->mediumSetElementSetNames = elementSetNames;
922 req->num_databaseNames = num_databaseNames;
923 req->databaseNames = databaseNames;
929 case QueryType_Prefix:
930 query.which = Z_Query_type_1;
931 pqf_parser = yaz_pqf_create ();
932 RPNquery = yaz_pqf_parse (pqf_parser, out, arg);
937 int code = yaz_pqf_error (pqf_parser, &pqf_msg, &off);
938 printf("%*s^\n", off+4, "");
939 printf("Prefix query error: %s (code %d)\n", pqf_msg, code);
941 yaz_pqf_destroy (pqf_parser);
944 yaz_pqf_destroy (pqf_parser);
945 query.u.type_1 = RPNquery;
948 query.which = Z_Query_type_2;
949 query.u.type_2 = &ccl_query;
950 ccl_query.buf = (unsigned char*) arg;
951 ccl_query.len = strlen(arg);
953 case QueryType_CCL2RPN:
954 query.which = Z_Query_type_1;
955 RPNquery = ccl_rpn_query(out, rpn);
958 printf ("Couldn't convert from CCL to RPN\n");
961 query.u.type_1 = RPNquery;
962 ccl_rpn_delete (rpn);
965 printf ("Unsupported query type\n");
970 printf("Sent searchRequest.\n");
974 /* display Query Expression as part of searchResult-1 */
975 static void display_queryExpression (Z_QueryExpression *qe)
979 if (qe->which == Z_QueryExpression_term)
981 if (qe->u.term->queryTerm)
983 Z_Term *term = qe->u.term->queryTerm;
987 printf (" %.*s", term->u.general->len, term->u.general->buf);
989 case Z_Term_characterString:
990 printf (" %s", term->u.characterString);
993 printf (" %d", *term->u.numeric);
1003 /* see if we can find USR:SearchResult-1 */
1004 static void display_searchResult (Z_OtherInformation *o)
1009 for (i = 0; i < o->num_elements; i++)
1011 if (o->list[i]->which == Z_OtherInfo_externallyDefinedInfo)
1013 Z_External *ext = o->list[i]->information.externallyDefinedInfo;
1015 if (ext->which == Z_External_searchResult1)
1018 Z_SearchInfoReport *sr = ext->u.searchResult1;
1019 printf ("SearchResult-1:");
1020 for (j = 0; j < sr->num; j++)
1022 if (!sr->elements[j]->subqueryExpression)
1024 display_queryExpression (
1025 sr->elements[j]->subqueryExpression);
1026 display_queryExpression (
1027 sr->elements[j]->subqueryInterpretation);
1028 display_queryExpression (
1029 sr->elements[j]->subqueryRecommendation);
1030 if (sr->elements[j]->subqueryCount)
1031 printf ("(%d)", *sr->elements[j]->subqueryCount);
1039 static int process_searchResponse(Z_SearchResponse *res)
1041 printf ("Received SearchResponse.\n");
1042 print_refid (res->referenceId);
1043 if (*res->searchStatus)
1044 printf("Search was a success.\n");
1046 printf("Search was a bloomin' failure.\n");
1047 printf("Number of hits: %d", *res->resultCount);
1049 printf (", setno %d", setnumber);
1051 display_searchResult (res->additionalSearchInfo);
1052 printf("records returned: %d\n",
1053 *res->numberOfRecordsReturned);
1054 setno += *res->numberOfRecordsReturned;
1056 display_records(res->records);
1060 static void print_level(int iLevel)
1063 for (i = 0; i < iLevel * 4; i++)
1067 static void print_int(int iLevel, const char *pTag, int *pInt)
1071 print_level(iLevel);
1072 printf("%s: %d\n", pTag, *pInt);
1076 static void print_string(int iLevel, const char *pTag, const char *pString)
1078 if (pString != NULL)
1080 print_level(iLevel);
1081 printf("%s: %s\n", pTag, pString);
1085 static void print_oid(int iLevel, const char *pTag, Odr_oid *pOid)
1091 print_level(iLevel);
1092 printf("%s:", pTag);
1093 for (; *pInt != -1; pInt++)
1094 printf(" %d", *pInt);
1099 static void print_referenceId(int iLevel, Z_ReferenceId *referenceId)
1101 if (referenceId != NULL)
1105 print_level(iLevel);
1106 printf("Ref Id (%d, %d): ", referenceId->len, referenceId->size);
1107 for (i = 0; i < referenceId->len; i++)
1108 printf("%c", referenceId->buf[i]);
1113 static void print_string_or_numeric(int iLevel, const char *pTag, Z_StringOrNumeric *pStringNumeric)
1115 if (pStringNumeric != NULL)
1117 switch (pStringNumeric->which)
1119 case Z_StringOrNumeric_string:
1120 print_string(iLevel, pTag, pStringNumeric->u.string);
1123 case Z_StringOrNumeric_numeric:
1124 print_int(iLevel, pTag, pStringNumeric->u.numeric);
1128 print_level(iLevel);
1129 printf("%s: valid type for Z_StringOrNumeric\n", pTag);
1135 static void print_universe_report_duplicate(
1137 Z_UniverseReportDuplicate *pUniverseReportDuplicate)
1139 if (pUniverseReportDuplicate != NULL)
1141 print_level(iLevel);
1142 printf("Universe Report Duplicate: \n");
1144 print_string_or_numeric(iLevel, "Hit No",
1145 pUniverseReportDuplicate->hitno);
1149 static void print_universe_report_hits(
1151 Z_UniverseReportHits *pUniverseReportHits)
1153 if (pUniverseReportHits != NULL)
1155 print_level(iLevel);
1156 printf("Universe Report Hits: \n");
1158 print_string_or_numeric(iLevel, "Database",
1159 pUniverseReportHits->database);
1160 print_string_or_numeric(iLevel, "Hits", pUniverseReportHits->hits);
1164 static void print_universe_report(int iLevel, Z_UniverseReport *pUniverseReport)
1166 if (pUniverseReport != NULL)
1168 print_level(iLevel);
1169 printf("Universe Report: \n");
1171 print_int(iLevel, "Total Hits", pUniverseReport->totalHits);
1172 switch (pUniverseReport->which)
1174 case Z_UniverseReport_databaseHits:
1175 print_universe_report_hits(iLevel,
1176 pUniverseReport->u.databaseHits);
1179 case Z_UniverseReport_duplicate:
1180 print_universe_report_duplicate(iLevel,
1181 pUniverseReport->u.duplicate);
1185 print_level(iLevel);
1186 printf("Type: %d\n", pUniverseReport->which);
1192 static void print_external(int iLevel, Z_External *pExternal)
1194 if (pExternal != NULL)
1196 print_level(iLevel);
1197 printf("External: \n");
1199 print_oid(iLevel, "Direct Reference", pExternal->direct_reference);
1200 print_int(iLevel, "InDirect Reference", pExternal->indirect_reference);
1201 print_string(iLevel, "Descriptor", pExternal->descriptor);
1202 switch (pExternal->which)
1204 case Z_External_universeReport:
1205 print_universe_report(iLevel, pExternal->u.universeReport);
1209 print_level(iLevel);
1210 printf("Type: %d\n", pExternal->which);
1216 static int process_resourceControlRequest (Z_ResourceControlRequest *req)
1218 printf ("Received ResourceControlRequest.\n");
1219 print_referenceId(1, req->referenceId);
1220 print_int(1, "Suspended Flag", req->suspendedFlag);
1221 print_int(1, "Partial Results Available", req->partialResultsAvailable);
1222 print_int(1, "Response Required", req->responseRequired);
1223 print_int(1, "Triggered Request Flag", req->triggeredRequestFlag);
1224 print_external(1, req->resourceReport);
1228 void process_ESResponse(Z_ExtendedServicesResponse *res)
1231 switch (*res->operationStatus)
1233 case Z_ExtendedServicesResponse_done:
1236 case Z_ExtendedServicesResponse_accepted:
1237 printf ("accepted\n");
1239 case Z_ExtendedServicesResponse_failure:
1240 printf ("failure\n");
1241 display_diagrecs(res->diagnostics, res->num_diagnostics);
1244 printf ("unknown\n");
1246 if ( (*res->operationStatus != Z_ExtendedServicesResponse_failure) &&
1247 (res->num_diagnostics != 0) ) {
1248 display_diagrecs(res->diagnostics, res->num_diagnostics);
1250 print_refid (res->referenceId);
1251 if (res->taskPackage &&
1252 res->taskPackage->which == Z_External_extendedService)
1254 Z_TaskPackage *taskPackage = res->taskPackage->u.extendedService;
1255 Odr_oct *id = taskPackage->targetReference;
1256 Z_External *ext = taskPackage->taskSpecificParameters;
1260 printf ("Target Reference: ");
1261 print_stringn (id->buf, id->len);
1264 if (ext->which == Z_External_update)
1266 Z_IUUpdateTaskPackage *utp = ext->u.update->u.taskPackage;
1267 if (utp && utp->targetPart)
1269 Z_IUTargetPart *targetPart = utp->targetPart;
1272 for (i = 0; i<targetPart->num_taskPackageRecords; i++)
1275 Z_IUTaskPackageRecordStructure *tpr =
1276 targetPart->taskPackageRecords[i];
1277 printf ("task package record %d\n", i+1);
1278 if (tpr->which == Z_IUTaskPackageRecordStructure_record)
1280 display_record (tpr->u.record);
1284 printf ("other type\n");
1292 const char *get_ill_element (void *clientData, const char *element)
1297 static Z_External *create_external_itemRequest()
1299 struct ill_get_ctl ctl;
1300 ILL_ItemRequest *req;
1302 int item_request_size = 0;
1303 char *item_request_buf = 0;
1307 ctl.f = get_ill_element;
1309 req = ill_get_ItemRequest(&ctl, "ill", 0);
1311 printf ("ill_get_ItemRequest failed\n");
1313 if (!ill_ItemRequest (out, &req, 0, 0))
1317 ill_ItemRequest(print, &req, 0, 0);
1320 item_request_buf = odr_getbuf (out, &item_request_size, 0);
1321 if (item_request_buf)
1322 odr_setbuf (out, item_request_buf, item_request_size, 1);
1323 printf ("Couldn't encode ItemRequest, size %d\n", item_request_size);
1330 item_request_buf = odr_getbuf (out, &item_request_size, 0);
1331 oid.proto = PROTO_GENERAL;
1332 oid.oclass = CLASS_GENERAL;
1333 oid.value = VAL_ISO_ILL_1;
1335 r = (Z_External *) odr_malloc (out, sizeof(*r));
1336 r->direct_reference = odr_oiddup(out,oid_getoidbyent(&oid));
1337 r->indirect_reference = 0;
1339 r->which = Z_External_single;
1341 r->u.single_ASN1_type = (Odr_oct *)
1342 odr_malloc (out, sizeof(*r->u.single_ASN1_type));
1343 r->u.single_ASN1_type->buf = (unsigned char *)
1344 odr_malloc (out, item_request_size);
1345 r->u.single_ASN1_type->len = item_request_size;
1346 r->u.single_ASN1_type->size = item_request_size;
1347 memcpy (r->u.single_ASN1_type->buf, item_request_buf,
1350 do_hex_dump(item_request_buf,item_request_size);
1355 static Z_External *create_external_ILL_APDU(int which)
1357 struct ill_get_ctl ctl;
1360 int ill_request_size = 0;
1361 char *ill_request_buf = 0;
1365 ctl.f = get_ill_element;
1367 ill_apdu = ill_get_APDU(&ctl, "ill", 0);
1369 if (!ill_APDU (out, &ill_apdu, 0, 0))
1373 printf ("-------------------\n");
1374 ill_APDU(print, &ill_apdu, 0, 0);
1376 printf ("-------------------\n");
1378 ill_request_buf = odr_getbuf (out, &ill_request_size, 0);
1379 if (ill_request_buf)
1380 odr_setbuf (out, ill_request_buf, ill_request_size, 1);
1381 printf ("Couldn't encode ILL-Request, size %d\n", ill_request_size);
1387 ill_request_buf = odr_getbuf (out, &ill_request_size, 0);
1389 oid.proto = PROTO_GENERAL;
1390 oid.oclass = CLASS_GENERAL;
1391 oid.value = VAL_ISO_ILL_1;
1393 r = (Z_External *) odr_malloc (out, sizeof(*r));
1394 r->direct_reference = odr_oiddup(out,oid_getoidbyent(&oid));
1395 r->indirect_reference = 0;
1397 r->which = Z_External_single;
1399 r->u.single_ASN1_type = (Odr_oct *)
1400 odr_malloc (out, sizeof(*r->u.single_ASN1_type));
1401 r->u.single_ASN1_type->buf = (unsigned char *)
1402 odr_malloc (out, ill_request_size);
1403 r->u.single_ASN1_type->len = ill_request_size;
1404 r->u.single_ASN1_type->size = ill_request_size;
1405 memcpy (r->u.single_ASN1_type->buf, ill_request_buf, ill_request_size);
1406 /* printf ("len = %d\n", ill_request_size); */
1407 /* do_hex_dump(ill_request_buf,ill_request_size); */
1408 /* printf("--- end of extenal\n"); */
1415 static Z_External *create_ItemOrderExternal(const char *type, int itemno)
1417 Z_External *r = (Z_External *) odr_malloc(out, sizeof(Z_External));
1418 oident ItemOrderRequest;
1420 ItemOrderRequest.proto = PROTO_Z3950;
1421 ItemOrderRequest.oclass = CLASS_EXTSERV;
1422 ItemOrderRequest.value = VAL_ITEMORDER;
1424 r->direct_reference = odr_oiddup(out,oid_getoidbyent(&ItemOrderRequest));
1425 r->indirect_reference = 0;
1428 r->which = Z_External_itemOrder;
1430 r->u.itemOrder = (Z_ItemOrder *) odr_malloc(out,sizeof(Z_ItemOrder));
1431 memset(r->u.itemOrder, 0, sizeof(Z_ItemOrder));
1432 r->u.itemOrder->which=Z_IOItemOrder_esRequest;
1434 r->u.itemOrder->u.esRequest = (Z_IORequest *)
1435 odr_malloc(out,sizeof(Z_IORequest));
1436 memset(r->u.itemOrder->u.esRequest, 0, sizeof(Z_IORequest));
1438 r->u.itemOrder->u.esRequest->toKeep = (Z_IOOriginPartToKeep *)
1439 odr_malloc(out,sizeof(Z_IOOriginPartToKeep));
1440 memset(r->u.itemOrder->u.esRequest->toKeep, 0, sizeof(Z_IOOriginPartToKeep));
1441 r->u.itemOrder->u.esRequest->notToKeep = (Z_IOOriginPartNotToKeep *)
1442 odr_malloc(out,sizeof(Z_IOOriginPartNotToKeep));
1443 memset(r->u.itemOrder->u.esRequest->notToKeep, 0, sizeof(Z_IOOriginPartNotToKeep));
1445 r->u.itemOrder->u.esRequest->toKeep->supplDescription = NULL;
1446 r->u.itemOrder->u.esRequest->toKeep->contact = NULL;
1447 r->u.itemOrder->u.esRequest->toKeep->addlBilling = NULL;
1449 r->u.itemOrder->u.esRequest->notToKeep->resultSetItem =
1450 (Z_IOResultSetItem *) odr_malloc(out, sizeof(Z_IOResultSetItem));
1451 memset(r->u.itemOrder->u.esRequest->notToKeep->resultSetItem, 0, sizeof(Z_IOResultSetItem));
1452 r->u.itemOrder->u.esRequest->notToKeep->resultSetItem->resultSetId = "1";
1454 r->u.itemOrder->u.esRequest->notToKeep->resultSetItem->item =
1455 (int *) odr_malloc(out, sizeof(int));
1456 *r->u.itemOrder->u.esRequest->notToKeep->resultSetItem->item = itemno;
1458 if (!strcmp (type, "item") || !strcmp(type, "2"))
1460 printf ("using item-request\n");
1461 r->u.itemOrder->u.esRequest->notToKeep->itemRequest =
1462 create_external_itemRequest();
1464 else if (!strcmp(type, "ill") || !strcmp(type, "1"))
1466 printf ("using ILL-request\n");
1467 r->u.itemOrder->u.esRequest->notToKeep->itemRequest =
1468 create_external_ILL_APDU(ILL_APDU_ILL_Request);
1470 else if (!strcmp(type, "xml") || !strcmp(type, "3"))
1472 const char *xml_buf =
1474 " <type>request</type>\n"
1475 " <libraryNo>000200</libraryNo>\n"
1476 " <borrowerTicketNo> 1212 </borrowerTicketNo>\n"
1478 r->u.itemOrder->u.esRequest->notToKeep->itemRequest =
1479 z_ext_record (out, VAL_TEXT_XML, xml_buf, strlen(xml_buf));
1482 r->u.itemOrder->u.esRequest->notToKeep->itemRequest = 0;
1487 static int send_itemorder(const char *type, int itemno)
1489 Z_APDU *apdu = zget_APDU(out, Z_APDU_extendedServicesRequest);
1490 Z_ExtendedServicesRequest *req = apdu->u.extendedServicesRequest;
1491 oident ItemOrderRequest;
1493 ItemOrderRequest.proto = PROTO_Z3950;
1494 ItemOrderRequest.oclass = CLASS_EXTSERV;
1495 ItemOrderRequest.value = VAL_ITEMORDER;
1496 req->packageType = odr_oiddup(out,oid_getoidbyent(&ItemOrderRequest));
1497 req->packageName = esPackageName;
1499 req->taskSpecificParameters = create_ItemOrderExternal(type, itemno);
1505 static int cmd_update(char *arg)
1507 Z_APDU *apdu = zget_APDU(out, Z_APDU_extendedServicesRequest );
1508 Z_ExtendedServicesRequest *req = apdu->u.extendedServicesRequest;
1511 Z_IUOriginPartToKeep *toKeep;
1512 Z_IUSuppliedRecords *notToKeep;
1514 char action[20], recid[20], fname[80];
1516 Z_External *record_this = 0;
1521 sscanf (arg, "%19s %19s %79s", action, recid, fname);
1523 if (!strcmp (action, "insert"))
1524 action_no = Z_IUOriginPartToKeep_recordInsert;
1525 else if (!strcmp (action, "replace"))
1526 action_no = Z_IUOriginPartToKeep_recordReplace;
1527 else if (!strcmp (action, "delete"))
1528 action_no = Z_IUOriginPartToKeep_recordDelete;
1529 else if (!strcmp (action, "update"))
1530 action_no = Z_IUOriginPartToKeep_specialUpdate;
1533 printf ("Bad action: %s\n", action);
1534 printf ("Possible values: insert, replace, delete, update\n");
1542 stat (fname, &status);
1543 if (S_ISREG(status.st_mode) && (inf = fopen(fname, "r")))
1545 size_t len = status.st_size;
1546 char *buf = (char *) xmalloc (len);
1548 fread (buf, 1, len, inf);
1552 record_this = z_ext_record (out, VAL_TEXT_XML, buf, len);
1558 printf ("File %s doesn't exist\n", fname);
1566 printf ("No last record (update ignored)\n");
1569 record_this = record_last;
1572 update_oid.proto = PROTO_Z3950;
1573 update_oid.oclass = CLASS_EXTSERV;
1574 update_oid.value = VAL_DBUPDATE;
1575 oid_ent_to_oid (&update_oid, oid);
1576 req->packageType = odr_oiddup(out,oid);
1577 req->packageName = esPackageName;
1579 req->referenceId = set_refid (out);
1581 r = req->taskSpecificParameters = (Z_External *)
1582 odr_malloc (out, sizeof(*r));
1583 r->direct_reference = odr_oiddup(out,oid);
1584 r->indirect_reference = 0;
1586 r->which = Z_External_update;
1587 r->u.update = (Z_IUUpdate *) odr_malloc(out, sizeof(*r->u.update));
1588 r->u.update->which = Z_IUUpdate_esRequest;
1589 r->u.update->u.esRequest = (Z_IUUpdateEsRequest *)
1590 odr_malloc(out, sizeof(*r->u.update->u.esRequest));
1591 toKeep = r->u.update->u.esRequest->toKeep = (Z_IUOriginPartToKeep *)
1592 odr_malloc(out, sizeof(*r->u.update->u.esRequest->toKeep));
1593 toKeep->databaseName = databaseNames[0];
1595 toKeep->elementSetName = 0;
1596 toKeep->actionQualifier = 0;
1597 toKeep->action = (int *) odr_malloc(out, sizeof(*toKeep->action));
1598 *toKeep->action = action_no;
1600 notToKeep = r->u.update->u.esRequest->notToKeep = (Z_IUSuppliedRecords *)
1601 odr_malloc(out, sizeof(*r->u.update->u.esRequest->notToKeep));
1603 notToKeep->elements = (Z_IUSuppliedRecords_elem **)
1604 odr_malloc(out, sizeof(*notToKeep->elements));
1605 notToKeep->elements[0] = (Z_IUSuppliedRecords_elem *)
1606 odr_malloc(out, sizeof(**notToKeep->elements));
1607 notToKeep->elements[0]->which = Z_IUSuppliedRecords_elem_opaque;
1610 notToKeep->elements[0]->u.opaque = (Odr_oct *)
1611 odr_malloc (out, sizeof(Odr_oct));
1612 notToKeep->elements[0]->u.opaque->buf = (unsigned char *) recid;
1613 notToKeep->elements[0]->u.opaque->size = strlen(recid);
1614 notToKeep->elements[0]->u.opaque->len = strlen(recid);
1617 notToKeep->elements[0]->u.opaque = 0;
1618 notToKeep->elements[0]->supplementalId = 0;
1619 notToKeep->elements[0]->correlationInfo = 0;
1620 notToKeep->elements[0]->record = record_this;
1627 static int cmd_itemorder(char *arg)
1632 if (sscanf (arg, "%10s %d", type, &itemno) != 2)
1635 printf("Item order request\n");
1637 send_itemorder(type, itemno);
1641 static int cmd_find(char *arg)
1645 printf("Find what?\n");
1653 printf("Not connected yet\n");
1657 if (!send_searchRequest(arg))
1662 static int cmd_delete(char *arg)
1666 printf("Not connected yet\n");
1669 if (!send_deleteResultSetRequest(arg))
1674 static int cmd_ssub(char *arg)
1676 if (!(smallSetUpperBound = atoi(arg)))
1681 static int cmd_lslb(char *arg)
1683 if (!(largeSetLowerBound = atoi(arg)))
1688 static int cmd_mspn(char *arg)
1690 if (!(mediumSetPresentNumber = atoi(arg)))
1695 static int cmd_status(char *arg)
1697 printf("smallSetUpperBound: %d\n", smallSetUpperBound);
1698 printf("largeSetLowerBound: %d\n", largeSetLowerBound);
1699 printf("mediumSetPresentNumber: %d\n", mediumSetPresentNumber);
1703 static int cmd_setnames(char *arg)
1705 if (*arg == '1') /* enable ? */
1707 else if (*arg == '0') /* disable ? */
1709 else if (setnumber < 0) /* no args, toggle .. */
1715 printf("Set numbering enabled.\n");
1717 printf("Set numbering disabled.\n");
1721 /* PRESENT SERVICE ----------------------------- */
1723 static int send_presentRequest(char *arg)
1725 Z_APDU *apdu = zget_APDU(out, Z_APDU_presentRequest);
1726 Z_PresentRequest *req = apdu->u.presentRequest;
1727 Z_RecordComposition compo;
1732 char setstring[100];
1734 req->referenceId = set_refid (out);
1735 if ((p = strchr(arg, '+')))
1742 if (p && (p=strchr(p+1, '+')))
1744 strcpy (setstring, p+1);
1745 req->resultSetId = setstring;
1747 else if (setnumber >= 0)
1749 sprintf(setstring, "%d", setnumber);
1750 req->resultSetId = setstring;
1752 req->resultSetStartPoint = &setno;
1753 req->numberOfRecordsRequested = &nos;
1754 prefsyn.proto = protocol;
1755 prefsyn.oclass = CLASS_RECSYN;
1756 prefsyn.value = recordsyntax;
1757 req->preferredRecordSyntax =
1758 odr_oiddup (out, oid_ent_to_oid(&prefsyn, oid));
1760 if (schema != VAL_NONE)
1764 prefschema.proto = protocol;
1765 prefschema.oclass = CLASS_SCHEMA;
1766 prefschema.value = schema;
1768 req->recordComposition = &compo;
1769 compo.which = Z_RecordComp_complex;
1770 compo.u.complex = (Z_CompSpec *)
1771 odr_malloc(out, sizeof(*compo.u.complex));
1772 compo.u.complex->selectAlternativeSyntax = (bool_t *)
1773 odr_malloc(out, sizeof(bool_t));
1774 *compo.u.complex->selectAlternativeSyntax = 0;
1776 compo.u.complex->generic = (Z_Specification *)
1777 odr_malloc(out, sizeof(*compo.u.complex->generic));
1778 compo.u.complex->generic->schema = (Odr_oid *)
1779 odr_oiddup(out, oid_ent_to_oid(&prefschema, oid));
1780 if (!compo.u.complex->generic->schema)
1782 /* OID wasn't a schema! Try record syntax instead. */
1783 prefschema.oclass = CLASS_RECSYN;
1784 compo.u.complex->generic->schema = (Odr_oid *)
1785 odr_oiddup(out, oid_ent_to_oid(&prefschema, oid));
1787 if (!elementSetNames)
1788 compo.u.complex->generic->elementSpec = 0;
1791 compo.u.complex->generic->elementSpec = (Z_ElementSpec *)
1792 odr_malloc(out, sizeof(Z_ElementSpec));
1793 compo.u.complex->generic->elementSpec->which =
1794 Z_ElementSpec_elementSetName;
1795 compo.u.complex->generic->elementSpec->u.elementSetName =
1796 elementSetNames->u.generic;
1798 compo.u.complex->num_dbSpecific = 0;
1799 compo.u.complex->dbSpecific = 0;
1800 compo.u.complex->num_recordSyntax = 0;
1801 compo.u.complex->recordSyntax = 0;
1803 else if (elementSetNames)
1805 req->recordComposition = &compo;
1806 compo.which = Z_RecordComp_simple;
1807 compo.u.simple = elementSetNames;
1810 printf("Sent presentRequest (%d+%d).\n", setno, nos);
1814 static void close_session (void)
1820 nmem_destroy (session_mem);
1826 void process_close(Z_Close *req)
1828 Z_APDU *apdu = zget_APDU(out, Z_APDU_close);
1829 Z_Close *res = apdu->u.close;
1831 static char *reasons[] =
1836 "cost limit reached",
1838 "security violation",
1845 printf("Reason: %s, message: %s\n", reasons[*req->closeReason],
1846 req->diagnosticInformation ? req->diagnosticInformation : "NULL");
1851 *res->closeReason = Z_Close_finished;
1853 printf("Sent response.\n");
1858 static int cmd_show(char *arg)
1862 printf("Not connected yet\n");
1865 if (!send_presentRequest(arg))
1870 int cmd_quit(char *arg)
1872 printf("See you later, alligator.\n");
1878 int cmd_cancel(char *arg)
1880 Z_APDU *apdu = zget_APDU(out, Z_APDU_triggerResourceControlRequest);
1881 Z_TriggerResourceControlRequest *req =
1882 apdu->u.triggerResourceControlRequest;
1887 printf("Session not initialized yet\n");
1890 if (!ODR_MASK_GET(session->options, Z_Options_triggerResourceCtrl))
1892 printf("Target doesn't support cancel (trigger resource ctrl)\n");
1895 *req->requestedAction = Z_TriggerResourceCtrl_cancel;
1896 req->resultSetWanted = &rfalse;
1899 printf("Sent cancel request\n");
1903 int send_scanrequest(const char *query, int pp, int num, const char *term)
1905 Z_APDU *apdu = zget_APDU(out, Z_APDU_scanRequest);
1906 Z_ScanRequest *req = apdu->u.scanRequest;
1909 if (queryType == QueryType_CCL2RPN)
1913 struct ccl_rpn_node *rpn;
1915 rpn = ccl_find_str (bibset, query, &error, &pos);
1918 printf("CCL ERROR: %s\n", ccl_err_msg(error));
1921 bib1.proto = PROTO_Z3950;
1922 bib1.oclass = CLASS_ATTSET;
1923 bib1.value = VAL_BIB1;
1924 req->attributeSet = oid_ent_to_oid (&bib1, oid);
1925 if (!(req->termListAndStartPoint = ccl_scan_query (out, rpn)))
1927 printf("Couldn't convert CCL to Scan term\n");
1930 ccl_rpn_delete (rpn);
1934 YAZ_PQF_Parser pqf_parser = yaz_pqf_create ();
1936 if (!(req->termListAndStartPoint =
1937 yaz_pqf_scan(pqf_parser, out, &req->attributeSet, query)))
1939 const char *pqf_msg;
1941 int code = yaz_pqf_error (pqf_parser, &pqf_msg, &off);
1942 printf("%*s^\n", off+7, "");
1943 printf("Prefix query error: %s (code %d)\n", pqf_msg, code);
1944 yaz_pqf_destroy (pqf_parser);
1947 yaz_pqf_destroy (pqf_parser);
1951 if (req->termListAndStartPoint->term &&
1952 req->termListAndStartPoint->term->which == Z_Term_general &&
1953 req->termListAndStartPoint->term->u.general)
1955 req->termListAndStartPoint->term->u.general->buf =
1956 (unsigned char *) odr_strdup(out, term);
1957 req->termListAndStartPoint->term->u.general->len =
1958 req->termListAndStartPoint->term->u.general->size =
1962 req->referenceId = set_refid (out);
1963 req->num_databaseNames = num_databaseNames;
1964 req->databaseNames = databaseNames;
1965 req->numberOfTermsRequested = #
1966 req->preferredPositionInResponse = &pp;
1971 int send_sortrequest(char *arg, int newset)
1973 Z_APDU *apdu = zget_APDU(out, Z_APDU_sortRequest);
1974 Z_SortRequest *req = apdu->u.sortRequest;
1975 Z_SortKeySpecList *sksl = (Z_SortKeySpecList *)
1976 odr_malloc (out, sizeof(*sksl));
1980 sprintf (setstring, "%d", setnumber);
1982 sprintf (setstring, "default");
1984 req->referenceId = set_refid (out);
1986 req->num_inputResultSetNames = 1;
1987 req->inputResultSetNames = (Z_InternationalString **)
1988 odr_malloc (out, sizeof(*req->inputResultSetNames));
1989 req->inputResultSetNames[0] = odr_strdup (out, setstring);
1991 if (newset && setnumber >= 0)
1992 sprintf (setstring, "%d", ++setnumber);
1994 req->sortedResultSetName = odr_strdup (out, setstring);
1996 req->sortSequence = yaz_sort_spec (out, arg);
1997 if (!req->sortSequence)
1999 printf ("Missing sort specifications\n");
2006 void display_term(Z_TermInfo *t)
2008 if (t->term->which == Z_Term_general)
2010 printf("%.*s", t->term->u.general->len, t->term->u.general->buf);
2011 sprintf(last_scan_line, "%.*s", t->term->u.general->len,
2012 t->term->u.general->buf);
2015 printf("Term (not general)");
2016 if (t->globalOccurrences)
2017 printf (" (%d)\n", *t->globalOccurrences);
2022 void process_scanResponse(Z_ScanResponse *res)
2025 Z_Entry **entries = NULL;
2026 int num_entries = 0;
2028 printf("Received ScanResponse\n");
2029 print_refid (res->referenceId);
2030 printf("%d entries", *res->numberOfEntriesReturned);
2031 if (res->positionOfTerm)
2032 printf (", position=%d", *res->positionOfTerm);
2034 if (*res->scanStatus != Z_Scan_success)
2035 printf("Scan returned code %d\n", *res->scanStatus);
2038 if ((entries = res->entries->entries))
2039 num_entries = res->entries->num_entries;
2040 for (i = 0; i < num_entries; i++)
2042 int pos_term = res->positionOfTerm ? *res->positionOfTerm : -1;
2043 if (entries[i]->which == Z_Entry_termInfo)
2045 printf("%c ", i + 1 == pos_term ? '*' : ' ');
2046 display_term(entries[i]->u.termInfo);
2049 display_diagrecs(&entries[i]->u.surrogateDiagnostic, 1);
2051 if (res->entries->nonsurrogateDiagnostics)
2052 display_diagrecs (res->entries->nonsurrogateDiagnostics,
2053 res->entries->num_nonsurrogateDiagnostics);
2056 void process_sortResponse(Z_SortResponse *res)
2058 printf("Received SortResponse: status=");
2059 switch (*res->sortStatus)
2061 case Z_SortStatus_success:
2062 printf ("success"); break;
2063 case Z_SortStatus_partial_1:
2064 printf ("partial"); break;
2065 case Z_SortStatus_failure:
2066 printf ("failure"); break;
2068 printf ("unknown (%d)", *res->sortStatus);
2071 print_refid (res->referenceId);
2072 if (res->diagnostics)
2073 display_diagrecs(res->diagnostics,
2074 res->num_diagnostics);
2077 void process_deleteResultSetResponse (Z_DeleteResultSetResponse *res)
2079 printf("Got deleteResultSetResponse status=%d\n",
2080 *res->deleteOperationStatus);
2081 if (res->deleteListStatuses)
2084 for (i = 0; i < res->deleteListStatuses->num; i++)
2086 printf ("%s status=%d\n", res->deleteListStatuses->elements[i]->id,
2087 *res->deleteListStatuses->elements[i]->status);
2092 int cmd_sort_generic(char *arg, int newset)
2096 printf("Session not initialized yet\n");
2099 if (!ODR_MASK_GET(session->options, Z_Options_sort))
2101 printf("Target doesn't support sort\n");
2106 if (send_sortrequest(arg, newset) < 0)
2113 int cmd_sort(char *arg)
2115 return cmd_sort_generic (arg, 0);
2118 int cmd_sort_newset (char *arg)
2120 return cmd_sort_generic (arg, 1);
2123 int cmd_scan(char *arg)
2130 printf("Session not initialized yet\n");
2134 if (!ODR_MASK_GET(session->options, Z_Options_scan))
2136 printf("Target doesn't support scan\n");
2141 strcpy (last_scan_query, arg);
2142 if (send_scanrequest(arg, 1, 20, 0) < 0)
2147 if (send_scanrequest(last_scan_query, 1, 20, last_scan_line) < 0)
2153 int cmd_schema(char *arg)
2160 schema = oid_getvalbyname (arg);
2161 if (schema == VAL_NONE)
2163 printf ("unknown schema\n");
2169 int cmd_format(char *arg)
2173 printf("Usage: format <recordsyntax>\n");
2176 recordsyntax = oid_getvalbyname (arg);
2177 if (recordsyntax == VAL_NONE)
2179 printf ("unknown record syntax\n");
2185 int cmd_elements(char *arg)
2187 static Z_ElementSetNames esn;
2188 static char what[100];
2192 elementSetNames = 0;
2196 esn.which = Z_ElementSetNames_generic;
2197 esn.u.generic = what;
2198 elementSetNames = &esn;
2202 int cmd_attributeset(char *arg)
2208 printf("Usage: attributeset <setname>\n");
2211 sscanf(arg, "%s", what);
2212 if (p_query_attset (what))
2214 printf("Unknown attribute set name\n");
2220 int cmd_querytype (char *arg)
2222 if (!strcmp (arg, "ccl"))
2223 queryType = QueryType_CCL;
2224 else if (!strcmp (arg, "prefix") || !strcmp(arg, "rpn"))
2225 queryType = QueryType_Prefix;
2226 else if (!strcmp (arg, "ccl2rpn") || !strcmp (arg, "cclrpn"))
2227 queryType = QueryType_CCL2RPN;
2230 printf ("Querytype must be one of:\n");
2231 printf (" prefix - Prefix query\n");
2232 printf (" ccl - CCL query\n");
2233 printf (" ccl2rpn - CCL query converted to RPN\n");
2239 int cmd_refid (char *arg)
2245 refid = (char *) xmalloc (strlen(arg)+1);
2246 strcpy (refid, arg);
2251 int cmd_close(char *arg)
2258 apdu = zget_APDU(out, Z_APDU_close);
2259 req = apdu->u.close;
2260 *req->closeReason = Z_Close_finished;
2262 printf("Sent close request.\n");
2267 int cmd_packagename(char* arg)
2269 xfree (esPackageName);
2270 esPackageName = NULL;
2273 esPackageName = (char *) xmalloc (strlen(arg)+1);
2274 strcpy (esPackageName, arg);
2279 int cmd_proxy(char* arg)
2290 yazProxy = (char *) xmalloc (strlen(arg)+1);
2291 strcpy (yazProxy, arg);
2296 int cmd_charset(char* arg)
2298 char l1[30], l2[30];
2301 if (sscanf(arg, "%29s %29s", l1, l2) < 1)
2303 printf("Current character set is `%s'\n", (yazCharset) ? yazCharset:NULL);
2309 yazCharset = xstrdup(l1);
2312 odr_set_charset (out, l1, l2);
2313 odr_set_charset (in, l2, l1);
2318 int cmd_lang(char* arg)
2321 printf("Current language is `%s'\n", (yazLang)?yazLang:NULL);
2328 yazLang = (char *) xmalloc (strlen(arg)+1);
2329 strcpy (yazLang, arg);
2334 int cmd_source(char* arg)
2336 /* first should open the file and read one line at a time.. */
2338 char line[1024], *cp;
2341 char* args_end=(arg)+strlen(arg)-1;
2342 while(isspace(*args_end))
2347 REMOVE_TAILING_BLANKS(arg);
2350 fprintf(stderr,"Error in source command use a filename\n");
2354 includeFile = fopen (arg, "r");
2357 fprintf(stderr,"Unable to open file %s for reading\n",arg);
2361 while(!feof(includeFile)) {
2362 memset(line,0,sizeof(line));
2363 fgets(line,sizeof(line),includeFile);
2365 if(strlen(line) < 2) continue;
2366 if(line[0] == '#') continue;
2368 if ((cp = strrchr (line, '\n')))
2371 process_cmd_line(line);
2374 if(fclose(includeFile)<0) {
2375 perror("unable to close include file");
2381 int cmd_subshell(char* args)
2386 system(getenv("SHELL"));
2392 int cmd_set_apdufile(char* arg)
2394 REMOVE_TAILING_BLANKS(arg);
2396 if(apdu_file && apdu_file != stderr) { /* don't close stdout*/
2397 perror("unable to close apdu log file");
2405 if(!strcmp(arg,"-"))
2408 apdu_file=fopen(arg, "a");
2411 perror("unable to open apdu log file no apdu log loaded");
2413 odr_setprint(print, apdu_file);
2419 int cmd_set_cclfile(char* arg)
2423 REMOVE_TAILING_BLANKS(arg);
2425 bibset = ccl_qual_mk ();
2426 inf = fopen (arg, "r");
2429 ccl_qual_file (bibset, inf);
2432 strcpy(ccl_fields,arg);
2437 int cmd_set_auto_reconnect(char* arg)
2439 REMOVE_TAILING_BLANKS(arg);
2441 if(strlen(arg)==0) {
2442 auto_reconnect = ! auto_reconnect;
2443 } else if(strcmp(arg,"on")==0) {
2445 } else if(strcmp(arg,"off")==0) {
2448 printf("Error use on or off\n");
2453 printf("Set auto reconnect enabled.\n");
2455 printf("Set auto reconnect disabled.\n");
2460 int cmd_set_marcdump(char* arg)
2462 if(marcdump && marcdump != stderr) { /* don't close stdout*/
2463 perror("unable to close apdu log file");
2471 if(!strcmp(arg,"-"))
2474 marcdump=fopen(arg, "a");
2477 perror("unable to open apdu marcdump file no marcdump done\n");
2483 int cmd_set_proxy(char* arg)
2485 if(yazProxy) free(yazProxy);
2488 if(strlen(arg) > 1) {
2489 yazProxy=strdup(arg);
2495 this command takes 3 arge {name class oid}
2497 int cmd_register_oid(char* args) {
2502 {"appctx",CLASS_APPCTX},
2503 {"absyn",CLASS_ABSYN},
2504 {"attset",CLASS_ATTSET},
2505 {"transyn",CLASS_TRANSYN},
2506 {"diagset",CLASS_DIAGSET},
2507 {"recsyn",CLASS_RECSYN},
2508 {"resform",CLASS_RESFORM},
2509 {"accform",CLASS_ACCFORM},
2510 {"extserv",CLASS_EXTSERV},
2511 {"userinfo",CLASS_USERINFO},
2512 {"elemspec",CLASS_ELEMSPEC},
2513 {"varset",CLASS_VARSET},
2514 {"schema",CLASS_SCHEMA},
2515 {"tagset",CLASS_TAGSET},
2516 {"general",CLASS_GENERAL},
2517 {0,(enum oid_class) 0}
2519 char oname_str[101], oclass_str[101], oid_str[101];
2522 oid_class oidclass = CLASS_GENERAL;
2523 int val = 0, oid[OID_SIZE];
2524 struct oident * new_oident=NULL;
2526 if (sscanf (args, "%100[^ ] %100[^ ] %100s",
2527 oname_str,oclass_str, oid_str) < 1) {
2528 printf("Error in regristrate command \n");
2532 for (i = 0; oid_classes[i].className; i++) {
2533 if (!strcmp(oid_classes[i].className, oclass_str))
2535 oidclass=oid_classes[i].oclass;
2540 if(!(oid_classes[i].className)) {
2541 printf("Unknonwn oid class %s\n",oclass_str);
2549 while (isdigit (*name))
2551 val = val*10 + (*name - '0');
2564 new_oident=oid_addent (oid,PROTO_GENERAL,oidclass,oname_str,VAL_DYNAMIC);
2565 if(strcmp(new_oident->desc,oname_str)) {
2566 fprintf(stderr,"oid is already named as %s, regristration faild\n",
2572 int cmd_push_command(char* arg)
2574 #if HAVE_READLINE_HISTORY_H
2578 fprintf(stderr,"Not compiled with the readline/history module\n");
2583 void source_rcfile()
2585 /* Look for a $HOME/.yazclientrc and source it if it exists */
2586 struct stat statbuf;
2588 char* homedir=getenv("HOME");
2590 if(!homedir) return;
2592 sprintf(buffer,"%s/.yazclientrc",homedir);
2594 if(stat(buffer,&statbuf)==0) {
2598 if(stat(".yazclientrc",&statbuf)==0) {
2599 cmd_source(".yazclientrc");
2604 static void initialize(void)
2609 if (!(out = odr_createmem(ODR_ENCODE)) ||
2610 !(in = odr_createmem(ODR_DECODE)) ||
2611 !(print = odr_createmem(ODR_PRINT)))
2613 fprintf(stderr, "failed to allocate ODR streams\n");
2618 setvbuf(stdout, 0, _IONBF, 0);
2620 odr_setprint(print, apdu_file);
2622 bibset = ccl_qual_mk ();
2623 inf = fopen (ccl_fields, "r");
2626 ccl_qual_file (bibset, inf);
2629 cmd_base("Default");
2631 #if HAVE_READLINE_READLINE_H
2632 rl_attempted_completion_function = (CPPFunction*)readline_completer;
2636 for(i=0; i<maxOtherInfosSupported; ++i) {
2637 extraOtherInfos[i].oidval = -1;
2644 #if HAVE_GETTIMEOFDAY
2645 struct timeval tv_start, tv_end;
2648 void wait_and_handle_responce()
2653 int netbufferlen = 0;
2661 if ((res = cs_get(conn, &netbuffer, &netbufferlen)) < 0)
2663 printf("Target closed connection\n");
2669 printf("Target closed connection.\n");
2673 odr_reset(in); /* release APDU from last round */
2675 odr_setbuf(in, netbuffer, res, 0);
2676 if (!z_APDU(in, &apdu, 0, 0))
2678 odr_perror(in, "Decoding incoming APDU");
2679 fprintf(stderr, "[Near %d]\n", odr_offset(in));
2680 fprintf(stderr, "Packet dump:\n---------\n");
2681 odr_dumpBER(stderr, netbuffer, res);
2682 fprintf(stderr, "---------\n");
2684 z_APDU(print, &apdu, 0, 0);
2688 if (apdu_file && !z_APDU(print, &apdu, 0, 0))
2690 odr_perror(print, "Failed to print incoming APDU");
2696 case Z_APDU_initResponse:
2697 process_initResponse(apdu->u.initResponse);
2699 case Z_APDU_searchResponse:
2700 process_searchResponse(apdu->u.searchResponse);
2702 case Z_APDU_scanResponse:
2703 process_scanResponse(apdu->u.scanResponse);
2705 case Z_APDU_presentResponse:
2706 print_refid (apdu->u.presentResponse->referenceId);
2708 *apdu->u.presentResponse->numberOfRecordsReturned;
2709 if (apdu->u.presentResponse->records)
2710 display_records(apdu->u.presentResponse->records);
2712 printf("No records.\n");
2713 printf ("nextResultSetPosition = %d\n",
2714 *apdu->u.presentResponse->nextResultSetPosition);
2716 case Z_APDU_sortResponse:
2717 process_sortResponse(apdu->u.sortResponse);
2719 case Z_APDU_extendedServicesResponse:
2720 printf("Got extended services response\n");
2721 process_ESResponse(apdu->u.extendedServicesResponse);
2724 printf("Target has closed the association.\n");
2725 process_close(apdu->u.close);
2727 case Z_APDU_resourceControlRequest:
2728 process_resourceControlRequest
2729 (apdu->u.resourceControlRequest);
2731 case Z_APDU_deleteResultSetResponse:
2732 process_deleteResultSetResponse(apdu->u.
2733 deleteResultSetResponse);
2736 printf("Received unknown APDU type (%d).\n",
2741 while (conn && cs_more(conn));
2742 #if HAVE_GETTIMEOFDAY
2743 gettimeofday (&tv_end, 0);
2745 printf ("S/U S/U=%ld/%ld %ld/%ld",
2746 (long) tv_start.tv_sec,
2747 (long) tv_start.tv_usec,
2748 (long) tv_end.tv_sec,
2749 (long) tv_end.tv_usec);
2751 printf ("Elapsed: %.6f\n",
2752 (double) tv_end.tv_usec / 1e6 + tv_end.tv_sec -
2753 ((double) tv_start.tv_usec / 1e6 + tv_start.tv_sec));
2760 int cmd_cclparse(char* arg)
2763 struct ccl_rpn_node *rpn=NULL;
2766 rpn = ccl_find_str (bibset, arg, &error, &pos);
2769 printf ("%*s^ - ", 3+strlen(last_cmd)+1+pos, " ");
2770 printf ("%s\n", ccl_err_msg (error));
2776 ccl_pr_tree(rpn, stdout);
2780 ccl_rpn_delete(rpn);
2788 int cmd_set_otherinfo(char* args)
2790 char oid[101], otherinfoString[101];
2795 sscan_res = sscanf (args, "%d %100[^ ] %100s", &otherinfoNo, oid, otherinfoString);
2797 /* reset this otherinfo */
2798 if(otherinfoNo>=maxOtherInfosSupported) {
2799 printf("Error otherinfo index to large (%d>%d)\n",otherinfoNo,maxOtherInfosSupported);
2801 extraOtherInfos[otherinfoNo].oidval = -1;
2802 if(extraOtherInfos[otherinfoNo].value) free(extraOtherInfos[otherinfoNo].value);
2806 printf("Error in set_otherinfo command \n");
2810 if(otherinfoNo>=maxOtherInfosSupported) {
2811 printf("Error otherinfo index to large (%d>%d)\n",otherinfoNo,maxOtherInfosSupported);
2815 oidval = oid_getvalbyname (oid);
2817 printf("Error in set_otherinfo command unknown oid %s \n",oid);
2820 extraOtherInfos[otherinfoNo].oidval = oidval;
2821 if(extraOtherInfos[otherinfoNo].value) free(extraOtherInfos[otherinfoNo].value);
2822 extraOtherInfos[otherinfoNo].value = strdup(otherinfoString);
2827 int cmd_list_otherinfo(char* args)
2831 if(strlen(args)>0) {
2833 if( i >= maxOtherInfosSupported ) {
2834 printf("Error otherinfo index to large (%d>%d)\n",i,maxOtherInfosSupported);
2838 if(extraOtherInfos[i].oidval != -1)
2839 printf(" otherinfo %d %s %s\n",
2841 yaz_z3950_oid_value_to_str(
2842 (enum oid_value) extraOtherInfos[i].oidval,
2844 extraOtherInfos[i].value);
2847 for(i=0; i<maxOtherInfosSupported; ++i) {
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);
2862 int cmd_list_all(char* args) {
2865 /* connection options */
2867 printf("Connected to : %s\n",last_open_command);
2869 if(last_open_command)
2870 printf("Not connected to : %s\n",last_open_command);
2872 printf("Not connected : \n");
2875 if(yazProxy) printf("using proxy : %s\n",yazProxy);
2877 printf("auto_reconnect : %s\n",auto_reconnect?"on":"off");
2880 printf("Authentication : none\n");
2882 switch(auth->which) {
2883 case Z_IdAuthentication_idPass:
2884 printf("Authentication : IdPass\n");
2885 printf(" Login User : %s\n",auth->u.idPass->userId?auth->u.idPass->userId:"");
2886 printf(" Login Group : %s\n",auth->u.idPass->groupId?auth->u.idPass->groupId:"");
2887 printf(" Password : %s\n",auth->u.idPass->password?auth->u.idPass->password:"");
2889 case Z_IdAuthentication_open:
2890 printf("Authentication : psOpen\n");
2891 printf(" Open string : %s\n",auth->u.open);
2894 printf("Authentication : Unknown\n");
2897 if ( yazCharset ) printf("Character set : `%s'\n", (yazCharset) ? yazCharset:NULL);
2901 for (i = 0; i<num_databaseNames; i++) printf("%s ",databaseNames[i]);
2905 printf("CCL file : %s\n",ccl_fields);
2906 printf("Query type : %s\n",query_type_as_string(queryType));
2908 printf("Named Result Sets : %s\n",setnumber==-1?"off":"on");
2910 /* piggy back options */
2911 printf("ssub/lslb/mspn : %d/%d/%d\n",smallSetUpperBound,largeSetLowerBound,mediumSetPresentNumber);
2913 /* print present related options */
2914 printf("Format : %s\n",yaz_z3950_oid_value_to_str(recordsyntax,CLASS_RECSYN));
2915 printf("Schema : %s\n",yaz_z3950_oid_value_to_str(schema,CLASS_SCHEMA));
2916 printf("Elements : %s\n",elementSetNames?elementSetNames->u.generic:"");
2918 /* loging options */
2919 printf("APDU log : %s\n",apdu_file?"on":"off");
2920 printf("Record log : %s\n",marcdump?"on":"off");
2923 printf("Other Info: \n");
2924 cmd_list_otherinfo("");
2929 int cmd_clear_otherinfo(char* args)
2931 if(strlen(args)>0) {
2933 otherinfoNo = atoi(args);
2934 if( otherinfoNo >= maxOtherInfosSupported ) {
2935 printf("Error otherinfo index to large (%d>%d)\n",otherinfoNo,maxOtherInfosSupported);
2939 if(extraOtherInfos[otherinfoNo].oidval != -1) {
2940 /* only clear if set. */
2941 extraOtherInfos[otherinfoNo].oidval=-1;
2942 free(extraOtherInfos[otherinfoNo].value);
2947 for(i=0; i<maxOtherInfosSupported; ++i) {
2948 if (extraOtherInfos[i].oidval!=-1 ) {
2949 extraOtherInfos[i].oidval=-1;
2950 free(extraOtherInfos[i].value);
2957 static int cmd_help (char *line);
2959 typedef char *(*completerFunctionType)(const char *text, int state);
2963 int (*fun)(char *arg);
2965 completerFunctionType rl_completerfunction;
2966 int complete_filenames;
2967 char **local_tabcompletes;
2969 {"open", cmd_open, "('tcp'|'ssl')':<host>[':'<port>][/<db>]",NULL,0,NULL},
2970 {"quit", cmd_quit, "",NULL,0,NULL},
2971 {"find", cmd_find, "<query>",NULL,0,NULL},
2972 {"delete", cmd_delete, "<setname>",NULL,0,NULL},
2973 {"base", cmd_base, "<base-name>",NULL,0,NULL},
2974 {"show", cmd_show, "<rec#>['+'<#recs>['+'<setname>]]",NULL,0,NULL},
2975 {"scan", cmd_scan, "<term>",NULL,0,NULL},
2976 {"sort", cmd_sort, "<sortkey> <flag> <sortkey> <flag> ...",NULL,0,NULL},
2977 {"sort+", cmd_sort_newset, "<sortkey> <flag> <sortkey> <flag> ...",NULL,0,NULL},
2978 {"authentication", cmd_authentication, "<acctstring>",NULL,0,NULL},
2979 {"lslb", cmd_lslb, "<largeSetLowerBound>",NULL,0,NULL},
2980 {"ssub", cmd_ssub, "<smallSetUpperBound>",NULL,0,NULL},
2981 {"mspn", cmd_mspn, "<mediumSetPresentNumber>",NULL,0,NULL},
2982 {"status", cmd_status, "",NULL,0,NULL},
2983 {"setnames", cmd_setnames, "",NULL,0,NULL},
2984 {"cancel", cmd_cancel, "",NULL,0,NULL},
2985 {"format", cmd_format, "<recordsyntax>",complete_format,0,NULL},
2986 {"schema", cmd_schema, "<schema>",complete_schema,0,NULL},
2987 {"elements", cmd_elements, "<elementSetName>",NULL,0,NULL},
2988 {"close", cmd_close, "",NULL,0,NULL},
2989 {"attributeset", cmd_attributeset, "<attrset>",complete_attributeset,0,NULL},
2990 {"querytype", cmd_querytype, "<type>",complete_querytype,0,NULL},
2991 {"refid", cmd_refid, "<id>",NULL,0,NULL},
2992 {"itemorder", cmd_itemorder, "ill|item <itemno>",NULL,0,NULL},
2993 {"update", cmd_update, "<action> <recid> [<file>]",NULL,0,NULL},
2994 {"packagename", cmd_packagename, "<packagename>",NULL,0,NULL},
2995 {"proxy", cmd_proxy, "[('tcp'|'ssl')]<host>[':'<port>]",NULL,0,NULL},
2996 {"charset", cmd_charset, "<charset_name>",NULL,0,NULL},
2997 {"lang", cmd_lang, "<language_code>",NULL,0,NULL},
2998 {".", cmd_source, "<filename>",NULL,1,NULL},
2999 {"!", cmd_subshell, "Subshell command",NULL,1,NULL},
3000 {"set_apdufile", cmd_set_apdufile, "<filename>",NULL,1,NULL},
3001 {"set_marcdump", cmd_set_marcdump," <filename>",NULL,1,NULL},
3002 {"set_cclfile", cmd_set_cclfile," <filename>",NULL,1,NULL},
3003 {"set_auto_reconnect", cmd_set_auto_reconnect," on|off",complete_auto_reconnect,1,NULL},
3004 {"set_otherinfo", cmd_set_otherinfo,"<otherinfoinddex> <oid> <string>",NULL,0,NULL},
3005 {"register_oid", cmd_register_oid,"<name> <class> <oid>",NULL,0,NULL},
3006 {"push_command", cmd_push_command,"<command>",command_generator,0,NULL},
3007 {"register_tab", cmd_register_tab,"<commandname> <tab>",command_generator,0,NULL},
3008 {"cclparse", cmd_cclparse,"<ccl find command>",NULL,0,NULL},
3009 {"list_otherinfo",cmd_list_otherinfo,"[otherinfoinddex]",NULL,0,NULL},
3010 {"list_all",cmd_list_all,"",NULL,0,NULL},
3011 {"clear_otherinfo",cmd_clear_otherinfo,"",NULL,0,NULL},
3012 /* Server Admin Functions */
3013 {"adm-reindex", cmd_adm_reindex, "<database-name>",NULL,0,NULL},
3014 {"adm-truncate", cmd_adm_truncate, "('database'|'index')<object-name>",NULL,0,NULL},
3015 {"adm-create", cmd_adm_create, "",NULL,0,NULL},
3016 {"adm-drop", cmd_adm_drop, "('database'|'index')<object-name>",NULL,0,NULL},
3017 {"adm-import", cmd_adm_import, "<record-type> <dir> <pattern>",NULL,0,NULL},
3018 {"adm-refresh", cmd_adm_refresh, "",NULL,0,NULL},
3019 {"adm-commit", cmd_adm_commit, "",NULL,0,NULL},
3020 {"adm-shutdown", cmd_adm_shutdown, "",NULL,0,NULL},
3021 {"adm-startup", cmd_adm_startup, "",NULL,0,NULL},
3022 {"help", cmd_help, "", NULL,0,NULL},
3026 static int cmd_help (char *line)
3032 sscanf (line, "%20s", topic);
3035 printf("Commands:\n");
3036 for (i = 0; cmd[i].cmd; i++)
3037 if (*topic == 0 || strcmp (topic, cmd[i].cmd) == 0)
3038 printf(" %s %s\n", cmd[i].cmd, cmd[i].ad);
3039 if (strcmp (topic, "find") == 0)
3042 printf (" \"term\" Simple Term\n");
3043 printf (" @attr [attset] type=value op Attribute\n");
3044 printf (" @and opl opr And\n");
3045 printf (" @or opl opr Or\n");
3046 printf (" @not opl opr And-Not\n");
3047 printf (" @set set Result set\n");
3049 printf ("Bib-1 attribute types\n");
3051 printf ("4=Title 7=ISBN 8=ISSN 30=Date 62=Abstract 1003=Author 1016=Any\n");
3052 printf ("2=Relation: ");
3053 printf ("1< 2<= 3= 4>= 5> 6!= 102=Relevance\n");
3054 printf ("3=Position: ");
3055 printf ("1=First in Field 2=First in subfield 3=Any position\n");
3056 printf ("4=Structure: ");
3057 printf ("1=Phrase 2=Word 3=Key 4=Year 5=Date 6=WordList\n");
3058 printf ("5=Truncation: ");
3059 printf ("1=Right 2=Left 3=L&R 100=No 101=# 102=Re-1 103=Re-2\n");
3060 printf ("6=Completeness:");
3061 printf ("1=Incomplete subfield 2=Complete subfield 3=Complete field\n");
3066 int cmd_register_tab(char* arg) {
3068 char command[101], tabargument[101];
3073 if (sscanf (arg, "%100s %100s", command, tabargument) < 1) {
3077 /* locate the amdn in the list */
3078 for (i = 0; cmd[i].cmd; i++) {
3079 if (!strncmp(cmd[i].cmd, command, strlen(command))) {
3085 fprintf(stderr,"Unknown command %s\n",command);
3090 if(!cmd[i].local_tabcompletes)
3091 cmd[i].local_tabcompletes = (char **) calloc(1,sizeof(char**));
3095 tabslist = cmd[i].local_tabcompletes;
3096 for(;tabslist && *tabslist;tabslist++) {
3100 cmd[i].local_tabcompletes = (char **)
3101 realloc(cmd[i].local_tabcompletes,(num_of_tabs+2)*sizeof(char**));
3102 tabslist=cmd[i].local_tabcompletes;
3103 tabslist[num_of_tabs]=strdup(tabargument);
3104 tabslist[num_of_tabs+1]=NULL;
3109 void process_cmd_line(char* line)
3112 char word[32], arg[1024];
3114 #if HAVE_GETTIMEOFDAY
3115 gettimeofday (&tv_start, 0);
3118 if ((res = sscanf(line, "%31s %1023[^;]", word, arg)) <= 0)
3120 strcpy(word, last_cmd);
3125 strcpy(last_cmd, word);
3127 /* removed tailing spaces from the arg command */
3130 char* lastnonspace=NULL;
3139 *(++lastnonspace) = 0;
3143 for (i = 0; cmd[i].cmd; i++)
3144 if (!strncmp(cmd[i].cmd, word, strlen(word)))
3146 res = (*cmd[i].fun)(arg);
3150 if (!cmd[i].cmd) /* dump our help-screen */
3152 printf("Unknown command: %s.\n", word);
3153 printf("use help for list of commands\n");
3154 /* cmd_help (""); */
3158 if(apdu_file) fflush(apdu_file);
3161 wait_and_handle_responce();
3170 char *command_generator(const char *text, int state)
3176 for( ; cmd[idx].cmd; ++idx) {
3177 if (!strncmp(cmd[idx].cmd,text,strlen(text))) {
3178 ++idx; /* skip this entry on the next run */
3179 return strdup(cmd[idx-1].cmd);
3187 This function only known how to complete on the first word
3189 char ** readline_completer(char *text, int start, int end) {
3190 #if HAVE_READLINE_READLINE_H
3192 completerFunctionType completerToUse;
3195 #if HAVE_READLINE_RL_COMPLETION_MATCHES
3196 char** res=rl_completion_matches(text,
3199 char** res=completion_matches(text,
3200 (CPFunction*)command_generator);
3202 rl_attempted_completion_over = 1;
3205 char arg[1024],word[32];
3207 if ((res = sscanf(rl_line_buffer, "%31s %1023[^;]", word, arg)) <= 0) {
3208 rl_attempted_completion_over = 1;
3212 for (i = 0; cmd[i].cmd; i++) {
3213 if (!strncmp(cmd[i].cmd, word, strlen(word))) {
3218 if(!cmd[i].cmd) return NULL;
3221 curret_global_list = cmd[i].local_tabcompletes;
3223 completerToUse = cmd[i].rl_completerfunction;
3224 if(completerToUse==NULL) /* if no pr. command completer is defined use the default completer */
3225 completerToUse = default_completer;
3227 if(completerToUse) {
3228 #ifdef HAVE_READLINE_RL_COMPLETION_MATCHES
3230 rl_completion_matches(text,
3234 completion_matches(text,
3235 (CPFunction*)completerToUse);
3237 if(!cmd[i].complete_filenames)
3238 rl_attempted_completion_over = 1;
3241 if(!cmd[i].complete_filenames)
3242 rl_attempted_completion_over = 1;
3252 static void client(void)
3258 #if HAVE_GETTIMEOFDAY
3259 gettimeofday (&tv_start, 0);
3264 char *line_in = NULL;
3265 #if HAVE_READLINE_READLINE_H
3268 line_in=readline(C_PROMPT);
3271 #if HAVE_READLINE_HISTORY_H
3273 add_history(line_in);
3275 strncpy(line, line_in, 1023);
3284 if (!fgets(line, 1023, stdin))
3286 if ((end_p = strchr (line, '\n')))
3289 process_cmd_line(line);
3293 int main(int argc, char **argv)
3296 char *open_command = 0;
3297 char *auth_command = 0;
3302 if (!setlocale(LC_CTYPE, ""))
3303 fprintf (stderr, "setlocale failed\n");
3306 codeset = nl_langinfo(CODESET);
3309 while ((ret = options("k:c:a:m:v:p:u:t:", argv, argc, &arg)) != -2)
3316 open_command = (char *) xmalloc (strlen(arg)+6);
3317 strcpy (open_command, "open ");
3318 strcat (open_command, arg);
3322 kilobytes = atoi(arg);
3325 if (!(marcdump = fopen (arg, "a")))
3335 strncpy (ccl_fields, arg, sizeof(ccl_fields)-1);
3336 ccl_fields[sizeof(ccl_fields)-1] = '\0';
3339 if (!strcmp(arg, "-"))
3342 apdu_file=fopen(arg, "a");
3345 yazProxy=strdup(arg);
3350 auth_command = (char *) xmalloc (strlen(arg)+6);
3351 strcpy (auth_command, "auth ");
3352 strcat (auth_command, arg);
3356 yaz_log_init (yaz_log_mask_str(arg), "", NULL);
3359 fprintf (stderr, "Usage: %s [-m <marclog>] [ -a <apdulog>] "
3360 "[-c cclfields]\n [-p <proxy-addr>] [-u <auth>] "
3361 "[-k size] [<server-addr>]\n",
3369 #ifdef HAVE_GETTIMEOFDAY
3370 gettimeofday (&tv_start, 0);
3372 process_cmd_line (auth_command);
3373 #if HAVE_READLINE_HISTORY_H
3374 add_history(auth_command);
3376 xfree(auth_command);
3380 #ifdef HAVE_GETTIMEOFDAY
3381 gettimeofday (&tv_start, 0);
3383 process_cmd_line (open_command);
3384 #if HAVE_READLINE_HISTORY_H
3385 add_history(open_command);
3387 xfree(open_command);
3398 * vim600: sw=4 ts=8 fdm=marker
3399 * vim<600: sw=4 ts=8