2 * Copyright (c) 1995-2002, Index Data
3 * See the file LICENSE for details.
5 * $Id: client.c,v 1.165 2002-08-30 09:06:42 adam Exp $
12 #include <yaz/yaz-util.h>
14 #include <yaz/comstack.h>
16 #include <yaz/proto.h>
17 #include <yaz/marcdisp.h>
18 #include <yaz/diagbib1.h>
19 #include <yaz/otherinfo.h>
20 #include <yaz/charneg.h>
22 #include <yaz/pquery.h>
23 #include <yaz/sortspec.h>
27 #include <yaz/yaz-ccl.h>
29 #if HAVE_READLINE_READLINE_H
30 #include <readline/readline.h>
33 #if HAVE_READLINE_HISTORY_H
34 #include <readline/history.h>
41 #include "tabcomplete.h"
43 #define C_PROMPT "Z> "
45 static ODR out, in, print; /* encoding and decoding streams */
46 static FILE *apdu_file = 0;
47 static COMSTACK conn = 0; /* our z-association */
48 static Z_IdAuthentication *auth = 0; /* our current auth definition */
49 char *databaseNames[128];
50 int num_databaseNames = 0;
51 static Z_External *record_last = 0;
52 static int setnumber = -1; /* current result set number */
53 static int smallSetUpperBound = 0;
54 static int largeSetLowerBound = 1;
55 static int mediumSetPresentNumber = 0;
56 static Z_ElementSetNames *elementSetNames = 0;
57 static int setno = 1; /* current set offset */
58 static enum oid_proto protocol = PROTO_Z3950; /* current app protocol */
59 static enum oid_value recordsyntax = VAL_USMARC;
60 static enum oid_value schema = VAL_NONE;
61 static int sent_close = 0;
62 static NMEM session_mem = NULL; /* memory handle for init-response */
63 static Z_InitResponse *session = 0; /* session parameters */
64 static char last_scan_line[512] = "0";
65 static char last_scan_query[512] = "0";
66 static char ccl_fields[512] = "default.bib";
67 static char* esPackageName = 0;
68 static char* yazProxy = 0;
69 static int kilobytes = 1024;
70 static char* yazCharset = 0;
71 static char* yazLang = 0;
74 static char last_cmd[32] = "?";
75 static FILE *marcdump = 0;
76 static char *refid = NULL;
77 static char *last_open_command = NULL;
78 static int auto_reconnect = 0;
86 static QueryType queryType = QueryType_Prefix;
88 static CCL_bibset bibset; /* CCL bibset handle */
90 #if HAVE_READLINE_COMPLETION_OVER
93 /* readline doesn't have this var. Define it ourselves. */
94 int rl_attempted_completion_over = 0;
97 /* set this one to 1, to avoid decode of unknown MARCs */
98 #define AVOID_MARC_DECODE 1
100 /* nice helper macro as extensive tabbing gives spaces at the en of the args lines */
101 #define REMOVE_TAILING_BLANKS(a) {\
102 char* args_end=(a)+strlen(a)-1; \
103 while(isspace(*args_end)) {*args_end=0;--args_end;}; \
106 #define maxOtherInfosSupported 10
110 } extraOtherInfos[maxOtherInfosSupported];
113 void process_cmd_line(char* line);
114 char ** readline_completer(char *text, int start, int end);
115 char *command_generator(const char *text, int state);
116 char** curret_global_list=NULL;
117 int cmd_register_tab(char* arg);
119 ODR getODROutputStream()
124 const char* query_type_as_string(QueryType q)
127 case QueryType_Prefix: return "prefix (RPN sent to server)";
128 case QueryType_CCL: return "CCL (CCL sent to server) ";
129 case QueryType_CCL2RPN: return "CCL -> RPN (RPN sent to server)";
131 return "unknown Query type internal yaz-client error";
136 void do_hex_dump(char* buf,int len)
140 for( i=0; i<len ; i=i+16 )
143 for(x=0 ; i+x<len && x<16; ++x)
145 printf("%2.2X ",(unsigned int)((unsigned char)buf[i+x]));
154 void add_otherInfos(Z_APDU *a)
156 Z_OtherInformation **oi;
160 for(i=0; i<maxOtherInfosSupported; ++i)
162 if(extraOtherInfos[i].oidval != -1)
163 yaz_oi_set_string_oidval(oi, out, extraOtherInfos[i].oidval, 1, extraOtherInfos[i].value);
167 void send_apdu(Z_APDU *a)
176 z_APDU(print, &a, 0, 0);
179 if (!z_APDU(out, &a, 0, 0))
181 odr_perror(out, "Encoding APDU");
184 buf = odr_getbuf(out, &len, 0);
185 /* printf ("sending APDU of size %d\n", len); */
186 if (cs_put(conn, buf, len) < 0)
188 fprintf(stderr, "cs_put: %s", cs_errmsg(cs_errno(conn)));
192 do_hex_dump(buf,len);
193 odr_reset(out); /* release the APDU structure */
196 static void print_stringn(const unsigned char *buf, size_t len)
199 for (i = 0; i<len; i++)
200 if ((buf[i] <= 126 && buf[i] >= 32) || strchr ("\n\r\t\f", buf[i]))
201 printf ("%c", buf[i]);
203 printf ("\\X%02X", buf[i]);
206 static void print_refid (Z_ReferenceId *id)
210 printf ("Reference Id: ");
211 print_stringn (id->buf, id->len);
216 static Z_ReferenceId *set_refid (ODR out)
221 id = (Z_ReferenceId *) odr_malloc (out, sizeof(*id));
222 id->size = id->len = strlen(refid);
223 id->buf = (unsigned char *) odr_malloc (out, id->len);
224 memcpy (id->buf, refid, id->len);
228 /* INIT SERVICE ------------------------------- */
230 static void send_initRequest(const char* type_and_host)
232 Z_APDU *apdu = zget_APDU(out, Z_APDU_initRequest);
233 Z_InitRequest *req = apdu->u.initRequest;
235 ODR_MASK_SET(req->options, Z_Options_search);
236 ODR_MASK_SET(req->options, Z_Options_present);
237 ODR_MASK_SET(req->options, Z_Options_namedResultSets);
238 ODR_MASK_SET(req->options, Z_Options_triggerResourceCtrl);
239 ODR_MASK_SET(req->options, Z_Options_scan);
240 ODR_MASK_SET(req->options, Z_Options_sort);
241 ODR_MASK_SET(req->options, Z_Options_extendedServices);
242 ODR_MASK_SET(req->options, Z_Options_delSet);
244 ODR_MASK_SET(req->protocolVersion, Z_ProtocolVersion_1);
245 ODR_MASK_SET(req->protocolVersion, Z_ProtocolVersion_2);
246 ODR_MASK_SET(req->protocolVersion, Z_ProtocolVersion_3);
248 *req->maximumRecordSize = 1024*kilobytes;
249 *req->preferredMessageSize = 1024*kilobytes;
251 req->idAuthentication = auth;
253 req->referenceId = set_refid (out);
256 yaz_oi_set_string_oidval(&req->otherInfo, out, VAL_PROXY,
259 if (yazCharset || yazLang) {
260 Z_OtherInformation **p;
261 Z_OtherInformationUnit *p0;
263 yaz_oi_APDU(apdu, &p);
265 if ((p0=yaz_oi_update(p, out, NULL, 0, 0))) {
266 ODR_MASK_SET(req->options, Z_Options_negotiationModel);
268 p0->which = Z_OtherInfo_externallyDefinedInfo;
269 p0->information.externallyDefinedInfo =
270 yaz_set_proposal_charneg(out,
271 (const char**)&yazCharset, (yazCharset)?1:0,
272 (const char**)&yazLang, (yazLang)?1:0, 1);
277 printf("Sent initrequest.\n");
280 static int process_initResponse(Z_InitResponse *res)
282 /* save session parameters for later use */
283 session_mem = odr_extract_mem(in);
287 printf("Connection rejected by target.\n");
289 printf("Connection accepted by target.\n");
290 if (res->implementationId)
291 printf("ID : %s\n", res->implementationId);
292 if (res->implementationName)
293 printf("Name : %s\n", res->implementationName);
294 if (res->implementationVersion)
295 printf("Version: %s\n", res->implementationVersion);
296 if (res->userInformationField)
298 printf("UserInformationfield:\n");
299 if (!z_External(print, (Z_External**)&res-> userInformationField,
302 odr_perror(print, "Printing userinfo\n");
305 if (res->userInformationField->which == Z_External_octet)
307 printf("Guessing visiblestring:\n");
308 printf("'%s'\n", res->userInformationField->u. octet_aligned->buf);
313 if (ODR_MASK_GET(res->options, Z_Options_search))
315 if (ODR_MASK_GET(res->options, Z_Options_present))
317 if (ODR_MASK_GET(res->options, Z_Options_delSet))
319 if (ODR_MASK_GET(res->options, Z_Options_resourceReport))
320 printf (" resourceReport");
321 if (ODR_MASK_GET(res->options, Z_Options_resourceCtrl))
322 printf (" resourceCtrl");
323 if (ODR_MASK_GET(res->options, Z_Options_accessCtrl))
324 printf (" accessCtrl");
325 if (ODR_MASK_GET(res->options, Z_Options_scan))
327 if (ODR_MASK_GET(res->options, Z_Options_sort))
329 if (ODR_MASK_GET(res->options, Z_Options_extendedServices))
330 printf (" extendedServices");
331 if (ODR_MASK_GET(res->options, Z_Options_level_1Segmentation))
332 printf (" level1Segmentation");
333 if (ODR_MASK_GET(res->options, Z_Options_level_2Segmentation))
334 printf (" level2Segmentation");
335 if (ODR_MASK_GET(res->options, Z_Options_concurrentOperations))
336 printf (" concurrentOperations");
337 if (ODR_MASK_GET(res->options, Z_Options_namedResultSets))
339 printf (" namedResultSets");
342 if (ODR_MASK_GET(res->options, Z_Options_encapsulation))
343 printf (" encapsulation");
344 if (ODR_MASK_GET(res->options, Z_Options_resultCount))
345 printf (" resultCount");
346 if (ODR_MASK_GET(res->options, Z_Options_negotiationModel))
347 printf (" negotiationModel");
348 if (ODR_MASK_GET(res->options, Z_Options_duplicateDetection))
349 printf (" duplicateDetection");
350 if (ODR_MASK_GET(res->options, Z_Options_queryType104))
351 printf (" queryType104");
354 if (ODR_MASK_GET(res->options, Z_Options_negotiationModel)) {
356 Z_CharSetandLanguageNegotiation *p =
357 yaz_get_charneg_record(res->otherInfo);
361 char *charset=NULL, *lang=NULL;
364 yaz_get_response_charneg(session_mem, p, &charset, &lang,
367 printf("Accepted character set : %s\n", charset);
368 printf("Accepted code language : %s\n", lang ? lang : "none");
369 printf("Accepted records in ...: %d\n", selected );
376 static int cmd_base(char *arg)
383 printf("Usage: base <database> <database> ...\n");
386 for (i = 0; i<num_databaseNames; i++)
387 xfree (databaseNames[i]);
388 num_databaseNames = 0;
392 if (!(cp = strchr(arg, ' ')))
393 cp = arg + strlen(arg);
396 databaseNames[num_databaseNames] = (char *)xmalloc (1 + cp - arg);
397 memcpy (databaseNames[num_databaseNames], arg, cp - arg);
398 databaseNames[num_databaseNames][cp - arg] = '\0';
400 for (cp1 = databaseNames[num_databaseNames]; *cp1 ; cp1++)
412 void cmd_open_remember_last_open_command(char* arg, char* new_open_command)
414 if(last_open_command != arg)
416 if(last_open_command) xfree(last_open_command);
417 last_open_command = xstrdup(new_open_command);
421 int cmd_open(char *arg)
424 char type_and_host[101], base[101];
428 printf("Already connected.\n");
434 nmem_destroy (session_mem);
439 if (strncmp (arg, "unix:", 5) == 0)
442 conn = cs_create_host(arg, 1, &add);
443 cmd_open_remember_last_open_command(arg,arg);
448 if (sscanf (arg, "%100[^/]/%100s", type_and_host, base) < 1)
451 cmd_open_remember_last_open_command(arg,type_and_host);
453 conn = cs_create_host(yazProxy, 1, &add);
455 conn = cs_create_host(type_and_host, 1, &add);
459 printf ("Couldn't create comstack\n");
462 printf("Connecting...");
464 if (cs_connect(conn, add) < 0)
466 printf ("error = %s\n", cs_strerror(conn));
467 if (conn->cerrno == CSYSERR)
475 send_initRequest(type_and_host);
488 if(!( auto_reconnect && last_open_command) ) return ;
490 open_command = (char *) xmalloc (strlen(last_open_command)+6);
491 strcpy (open_command, "open ");
493 strcat (open_command, last_open_command);
495 process_cmd_line(open_command);
500 int cmd_authentication(char *arg)
502 static Z_IdAuthentication au;
503 static char user[40], group[40], pass[40];
504 static Z_IdPass idPass;
509 printf("Auth field set to null\n");
513 r = sscanf (arg, "%39s %39s %39s", user, group, pass);
516 printf("Auth field set to null\n");
522 au.which = Z_IdAuthentication_open;
528 au.which = Z_IdAuthentication_idPass;
529 au.u.idPass = &idPass;
530 idPass.groupId = NULL;
531 idPass.userId = user;
532 idPass.password = group;
537 au.which = Z_IdAuthentication_idPass;
538 au.u.idPass = &idPass;
539 idPass.groupId = group;
540 idPass.userId = user;
541 idPass.password = pass;
546 /* SEARCH SERVICE ------------------------------ */
547 static void display_record(Z_External *r);
549 static void display_variant(Z_Variant *v, int level)
553 for (i = 0; i < v->num_triples; i++)
555 printf("%*sclass=%d,type=%d", level * 4, "", *v->triples[i]->zclass,
556 *v->triples[i]->type);
557 if (v->triples[i]->which == Z_Triple_internationalString)
558 printf(",value=%s\n", v->triples[i]->value.internationalString);
564 static void display_grs1(Z_GenericRecord *r, int level)
572 for (i = 0; i < r->num_elements; i++)
576 printf("%*s", level * 4, "");
580 printf("%d,", *t->tagType);
583 if (t->tagValue->which == Z_StringOrNumeric_numeric)
584 printf("%d) ", *t->tagValue->u.numeric);
586 printf("%s) ", t->tagValue->u.string);
587 if (t->content->which == Z_ElementData_subtree)
589 if (!t->content->u.subtree)
590 printf (" (no subtree)\n");
594 display_grs1(t->content->u.subtree, level+1);
597 else if (t->content->which == Z_ElementData_string)
598 printf("%s\n", t->content->u.string);
599 else if (t->content->which == Z_ElementData_numeric)
600 printf("%d\n", *t->content->u.numeric);
601 else if (t->content->which == Z_ElementData_oid)
603 int *ip = t->content->u.oid;
606 if ((oent = oid_getentbyoid(t->content->u.oid)))
607 printf("OID: %s\n", oent->desc);
611 while (ip && *ip >= 0)
612 printf(" %d", *(ip++));
616 else if (t->content->which == Z_ElementData_noDataRequested)
617 printf("[No data requested]\n");
618 else if (t->content->which == Z_ElementData_elementEmpty)
619 printf("[Element empty]\n");
620 else if (t->content->which == Z_ElementData_elementNotThere)
621 printf("[Element not there]\n");
622 else if (t->content->which == Z_ElementData_date)
623 printf("Date: %s\n", t->content->u.date);
624 else if (t->content->which == Z_ElementData_ext)
626 printf ("External\n");
627 display_record (t->content->u.ext);
630 printf("? type = %d\n",t->content->which);
631 if (t->appliedVariant)
632 display_variant(t->appliedVariant, level+1);
633 if (t->metaData && t->metaData->supportedVariants)
637 printf("%*s---- variant list\n", (level+1)*4, "");
638 for (c = 0; c < t->metaData->num_supportedVariants; c++)
640 printf("%*svariant #%d\n", (level+1)*4, "", c);
641 display_variant(t->metaData->supportedVariants[c], level + 2);
648 static void print_record(const unsigned char *buf, size_t len)
651 print_stringn (buf, len);
652 /* add newline if not already added ... */
653 if (i <= 0 || buf[i-1] != '\n')
657 static void display_record(Z_External *r)
659 oident *ent = oid_getentbyoid(r->direct_reference);
663 * Tell the user what we got.
665 if (r->direct_reference)
667 printf("Record type: ");
669 printf("%s\n", ent->desc);
670 else if (!odr_oid(print, &r->direct_reference, 0, 0))
672 odr_perror(print, "print oid");
676 /* Check if this is a known, ASN.1 type tucked away in an octet string */
677 if (ent && r->which == Z_External_octet)
679 Z_ext_typeent *type = z_ext_getentbyref(ent->value);
685 * Call the given decoder to process the record.
687 odr_setbuf(in, (char*)r->u.octet_aligned->buf,
688 r->u.octet_aligned->len, 0);
689 if (!(*type->fun)(in, (char **)&rr, 0, 0))
691 odr_perror(in, "Decoding constructed record.");
692 fprintf(stderr, "[Near %d]\n", odr_offset(in));
693 fprintf(stderr, "Packet dump:\n---------\n");
694 odr_dumpBER(stderr, (char*)r->u.octet_aligned->buf,r->u.octet_aligned->len);
695 fprintf(stderr, "---------\n");
697 /* note just ignores the error ant print the bytes form the octet_aligned laiter */
700 * Note: we throw away the original, BER-encoded record here.
701 * Do something else with it if you want to keep it.
703 r->u.sutrs = (Z_SUTRS *) rr; /* we don't actually check the type here. */
704 r->which = type->what;
708 if (ent && ent->oclass != CLASS_RECSYN)
710 if (ent && ent->value == VAL_SOIF)
711 print_record((const unsigned char *) r->u.octet_aligned->buf,
712 r->u.octet_aligned->len);
713 else if (r->which == Z_External_octet && r->u.octet_aligned->len)
715 const char *octet_buf = (char*)r->u.octet_aligned->buf;
716 if (ent->value == VAL_TEXT_XML || ent->value == VAL_APPLICATION_XML ||
717 ent->value == VAL_HTML)
719 print_record((const unsigned char *) octet_buf,
720 r->u.octet_aligned->len);
722 else if (ent->value == VAL_POSTSCRIPT)
724 int size = r->u.octet_aligned->len;
727 print_record((const unsigned char *) octet_buf, size);
732 #if AVOID_MARC_DECODE
733 /* primitive check for a marc OID 5.1-29 except 16 */
734 ent->oidsuffix[0] == 5 && ent->oidsuffix[1] < 30 &&
735 ent->oidsuffix[1] != 16
741 if (marc_display_exl (octet_buf, NULL, 0 /* debug */,
742 r->u.octet_aligned->len) <= 0)
744 printf ("bad MARC. Dumping as it is:\n");
745 print_record((const unsigned char*) octet_buf,
746 r->u.octet_aligned->len);
751 print_record((const unsigned char*) octet_buf,
752 r->u.octet_aligned->len);
756 fwrite (octet_buf, 1, r->u.octet_aligned->len, marcdump);
758 else if (ent && ent->value == VAL_SUTRS)
760 if (r->which != Z_External_sutrs)
762 printf("Expecting single SUTRS type for SUTRS.\n");
765 print_record(r->u.sutrs->buf, r->u.sutrs->len);
767 else if (ent && ent->value == VAL_GRS1)
769 if (r->which != Z_External_grs1)
771 printf("Expecting single GRS type for GRS.\n");
774 display_grs1(r->u.grs1, 0);
778 printf("Unknown record representation.\n");
779 if (!z_External(print, &r, 0, 0))
781 odr_perror(print, "Printing external");
787 static void display_diagrecs(Z_DiagRec **pp, int num)
791 Z_DefaultDiagFormat *r;
793 printf("Diagnostic message(s) from database:\n");
794 for (i = 0; i<num; i++)
796 Z_DiagRec *p = pp[i];
797 if (p->which != Z_DiagRec_defaultFormat)
799 printf("Diagnostic record not in default format.\n");
803 r = p->u.defaultFormat;
804 if (!(ent = oid_getentbyoid(r->diagnosticSetId)) ||
805 ent->oclass != CLASS_DIAGSET || ent->value != VAL_BIB1)
806 printf("Missing or unknown diagset\n");
807 printf(" [%d] %s", *r->condition, diagbib1_str(*r->condition));
810 case Z_DefaultDiagFormat_v2Addinfo:
811 printf (" -- v2 addinfo '%s'\n", r->u.v2Addinfo);
813 case Z_DefaultDiagFormat_v3Addinfo:
814 printf (" -- v3 addinfo '%s'\n", r->u.v3Addinfo);
821 static void display_nameplusrecord(Z_NamePlusRecord *p)
824 printf("[%s]", p->databaseName);
825 if (p->which == Z_NamePlusRecord_surrogateDiagnostic)
826 display_diagrecs(&p->u.surrogateDiagnostic, 1);
827 else if (p->which == Z_NamePlusRecord_databaseRecord)
828 display_record(p->u.databaseRecord);
831 static void display_records(Z_Records *p)
835 if (p->which == Z_Records_NSD)
837 Z_DiagRec dr, *dr_p = &dr;
838 dr.which = Z_DiagRec_defaultFormat;
839 dr.u.defaultFormat = p->u.nonSurrogateDiagnostic;
840 display_diagrecs (&dr_p, 1);
842 else if (p->which == Z_Records_multipleNSD)
843 display_diagrecs (p->u.multipleNonSurDiagnostics->diagRecs,
844 p->u.multipleNonSurDiagnostics->num_diagRecs);
847 printf("Records: %d\n", p->u.databaseOrSurDiagnostics->num_records);
848 for (i = 0; i < p->u.databaseOrSurDiagnostics->num_records; i++)
849 display_nameplusrecord(p->u.databaseOrSurDiagnostics->records[i]);
853 static int send_deleteResultSetRequest(char *arg)
858 Z_APDU *apdu = zget_APDU(out, Z_APDU_deleteResultSetRequest);
859 Z_DeleteResultSetRequest *req = apdu->u.deleteResultSetRequest;
861 req->referenceId = set_refid (out);
863 req->num_resultSetList =
864 sscanf (arg, "%30s %30s %30s %30s %30s %30s %30s %30s",
865 names[0], names[1], names[2], names[3],
866 names[4], names[5], names[6], names[7]);
868 req->deleteFunction = (int *)
869 odr_malloc (out, sizeof(*req->deleteFunction));
870 if (req->num_resultSetList > 0)
872 *req->deleteFunction = Z_DeleteRequest_list;
873 req->resultSetList = (char **)
874 odr_malloc (out, sizeof(*req->resultSetList)*
875 req->num_resultSetList);
876 for (i = 0; i<req->num_resultSetList; i++)
877 req->resultSetList[i] = names[i];
881 *req->deleteFunction = Z_DeleteRequest_all;
882 req->resultSetList = 0;
886 printf("Sent deleteResultSetRequest.\n");
890 static int send_searchRequest(char *arg)
892 Z_APDU *apdu = zget_APDU(out, Z_APDU_searchRequest);
893 Z_SearchRequest *req = apdu->u.searchRequest;
896 struct ccl_rpn_node *rpn = NULL;
899 Z_RPNQuery *RPNquery;
902 if (queryType == QueryType_CCL2RPN)
904 rpn = ccl_find_str(bibset, arg, &error, &pos);
907 printf("CCL ERROR: %s\n", ccl_err_msg(error));
911 req->referenceId = set_refid (out);
912 if (!strcmp(arg, "@big")) /* strictly for troublemaking */
914 static unsigned char big[2100];
917 /* send a very big referenceid to test transport stack etc. */
918 memset(big, 'A', 2100);
919 bigo.len = bigo.size = 2100;
921 req->referenceId = &bigo;
926 sprintf(setstring, "%d", ++setnumber);
927 req->resultSetName = setstring;
929 *req->smallSetUpperBound = smallSetUpperBound;
930 *req->largeSetLowerBound = largeSetLowerBound;
931 *req->mediumSetPresentNumber = mediumSetPresentNumber;
932 if (smallSetUpperBound > 0 || (largeSetLowerBound > 1 &&
933 mediumSetPresentNumber > 0))
937 prefsyn.proto = protocol;
938 prefsyn.oclass = CLASS_RECSYN;
939 prefsyn.value = recordsyntax;
940 req->preferredRecordSyntax =
941 odr_oiddup(out, oid_ent_to_oid(&prefsyn, oid));
942 req->smallSetElementSetNames =
943 req->mediumSetElementSetNames = elementSetNames;
945 req->num_databaseNames = num_databaseNames;
946 req->databaseNames = databaseNames;
952 case QueryType_Prefix:
953 query.which = Z_Query_type_1;
954 RPNquery = p_query_rpn (out, protocol, arg);
957 printf("Prefix query error\n");
960 query.u.type_1 = RPNquery;
963 query.which = Z_Query_type_2;
964 query.u.type_2 = &ccl_query;
965 ccl_query.buf = (unsigned char*) arg;
966 ccl_query.len = strlen(arg);
968 case QueryType_CCL2RPN:
969 query.which = Z_Query_type_1;
970 RPNquery = ccl_rpn_query(out, rpn);
973 printf ("Couldn't convert from CCL to RPN\n");
976 query.u.type_1 = RPNquery;
977 ccl_rpn_delete (rpn);
980 printf ("Unsupported query type\n");
985 printf("Sent searchRequest.\n");
989 /* display Query Expression as part of searchResult-1 */
990 static void display_queryExpression (Z_QueryExpression *qe)
994 if (qe->which == Z_QueryExpression_term)
996 if (qe->u.term->queryTerm)
998 Z_Term *term = qe->u.term->queryTerm;
1001 case Z_Term_general:
1002 printf (" %.*s", term->u.general->len, term->u.general->buf);
1004 case Z_Term_characterString:
1005 printf (" %s", term->u.characterString);
1007 case Z_Term_numeric:
1008 printf (" %d", *term->u.numeric);
1018 /* see if we can find USR:SearchResult-1 */
1019 static void display_searchResult (Z_OtherInformation *o)
1024 for (i = 0; i < o->num_elements; i++)
1026 if (o->list[i]->which == Z_OtherInfo_externallyDefinedInfo)
1028 Z_External *ext = o->list[i]->information.externallyDefinedInfo;
1030 if (ext->which == Z_External_searchResult1)
1033 Z_SearchInfoReport *sr = ext->u.searchResult1;
1034 printf ("SearchResult-1:");
1035 for (j = 0; j < sr->num; j++)
1037 if (!sr->elements[j]->subqueryExpression)
1039 display_queryExpression (
1040 sr->elements[j]->subqueryExpression);
1041 display_queryExpression (
1042 sr->elements[j]->subqueryInterpretation);
1043 display_queryExpression (
1044 sr->elements[j]->subqueryRecommendation);
1045 if (sr->elements[j]->subqueryCount)
1046 printf ("(%d)", *sr->elements[j]->subqueryCount);
1054 static int process_searchResponse(Z_SearchResponse *res)
1056 printf ("Received SearchResponse.\n");
1057 print_refid (res->referenceId);
1058 if (*res->searchStatus)
1059 printf("Search was a success.\n");
1061 printf("Search was a bloomin' failure.\n");
1062 printf("Number of hits: %d", *res->resultCount);
1064 printf (", setno %d", setnumber);
1066 display_searchResult (res->additionalSearchInfo);
1067 printf("records returned: %d\n",
1068 *res->numberOfRecordsReturned);
1069 setno += *res->numberOfRecordsReturned;
1071 display_records(res->records);
1075 static void print_level(int iLevel)
1078 for (i = 0; i < iLevel * 4; i++)
1082 static void print_int(int iLevel, const char *pTag, int *pInt)
1086 print_level(iLevel);
1087 printf("%s: %d\n", pTag, *pInt);
1091 static void print_string(int iLevel, const char *pTag, const char *pString)
1093 if (pString != NULL)
1095 print_level(iLevel);
1096 printf("%s: %s\n", pTag, pString);
1100 static void print_oid(int iLevel, const char *pTag, Odr_oid *pOid)
1106 print_level(iLevel);
1107 printf("%s:", pTag);
1108 for (; *pInt != -1; pInt++)
1109 printf(" %d", *pInt);
1114 static void print_referenceId(int iLevel, Z_ReferenceId *referenceId)
1116 if (referenceId != NULL)
1120 print_level(iLevel);
1121 printf("Ref Id (%d, %d): ", referenceId->len, referenceId->size);
1122 for (i = 0; i < referenceId->len; i++)
1123 printf("%c", referenceId->buf[i]);
1128 static void print_string_or_numeric(int iLevel, const char *pTag, Z_StringOrNumeric *pStringNumeric)
1130 if (pStringNumeric != NULL)
1132 switch (pStringNumeric->which)
1134 case Z_StringOrNumeric_string:
1135 print_string(iLevel, pTag, pStringNumeric->u.string);
1138 case Z_StringOrNumeric_numeric:
1139 print_int(iLevel, pTag, pStringNumeric->u.numeric);
1143 print_level(iLevel);
1144 printf("%s: valid type for Z_StringOrNumeric\n", pTag);
1150 static void print_universe_report_duplicate(int iLevel, Z_UniverseReportDuplicate *pUniverseReportDuplicate)
1152 if (pUniverseReportDuplicate != NULL)
1154 print_level(iLevel);
1155 printf("Universe Report Duplicate: \n");
1157 print_string_or_numeric(iLevel, "Hit No",
1158 pUniverseReportDuplicate->hitno);
1163 print_universe_report_hits(int iLevel,
1164 Z_UniverseReportHits *pUniverseReportHits)
1166 if (pUniverseReportHits != NULL)
1168 print_level(iLevel);
1169 printf("Universe Report Hits: \n");
1171 print_string_or_numeric(iLevel, "Database",
1172 pUniverseReportHits->database);
1173 print_string_or_numeric(iLevel, "Hits", pUniverseReportHits->hits);
1177 static void print_universe_report(int iLevel, Z_UniverseReport *pUniverseReport)
1179 if (pUniverseReport != NULL)
1181 print_level(iLevel);
1182 printf("Universe Report: \n");
1184 print_int(iLevel, "Total Hits", pUniverseReport->totalHits);
1185 switch (pUniverseReport->which)
1187 case Z_UniverseReport_databaseHits:
1188 print_universe_report_hits(iLevel, pUniverseReport->u.databaseHits);
1191 case Z_UniverseReport_duplicate:
1192 print_universe_report_duplicate(iLevel, 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(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 printf ("Update request\n");
1530 update_oid.proto = PROTO_Z3950;
1531 update_oid.oclass = CLASS_EXTSERV;
1532 update_oid.value = VAL_DBUPDATE;
1533 oid_ent_to_oid (&update_oid, oid);
1534 req->packageType = odr_oiddup(out,oid);
1535 req->packageName = esPackageName;
1537 req->referenceId = set_refid (out);
1539 r = req->taskSpecificParameters = (Z_External *)
1540 odr_malloc (out, sizeof(*r));
1541 r->direct_reference = odr_oiddup(out,oid);
1542 r->indirect_reference = 0;
1544 r->which = Z_External_update;
1545 r->u.update = (Z_IUUpdate *) odr_malloc(out, sizeof(*r->u.update));
1546 r->u.update->which = Z_IUUpdate_esRequest;
1547 r->u.update->u.esRequest = (Z_IUUpdateEsRequest *)
1548 odr_malloc(out, sizeof(*r->u.update->u.esRequest));
1549 toKeep = r->u.update->u.esRequest->toKeep = (Z_IUOriginPartToKeep *)
1550 odr_malloc(out, sizeof(*r->u.update->u.esRequest->toKeep));
1551 toKeep->databaseName = databaseNames[0];
1553 toKeep->elementSetName = 0;
1554 toKeep->actionQualifier = 0;
1555 toKeep->action = (int *) odr_malloc(out, sizeof(*toKeep->action));
1556 *toKeep->action = Z_IUOriginPartToKeep_recordInsert;
1558 notToKeep = r->u.update->u.esRequest->notToKeep = (Z_IUSuppliedRecords *)
1559 odr_malloc(out, sizeof(*r->u.update->u.esRequest->notToKeep));
1561 notToKeep->elements = (Z_IUSuppliedRecords_elem **)
1562 odr_malloc(out, sizeof(*notToKeep->elements));
1563 notToKeep->elements[0] = (Z_IUSuppliedRecords_elem *)
1564 odr_malloc(out, sizeof(**notToKeep->elements));
1565 notToKeep->elements[0]->u.number = 0;
1566 notToKeep->elements[0]->supplementalId = 0;
1567 notToKeep->elements[0]->correlationInfo = 0;
1568 notToKeep->elements[0]->record = record_last;
1575 static int cmd_itemorder(char *arg)
1580 if (sscanf (arg, "%10s %d", type, &itemno) != 2)
1583 printf("Item order request\n");
1585 send_itemorder(type, itemno);
1589 static int cmd_find(char *arg)
1593 printf("Find what?\n");
1601 printf("Not connected yet\n");
1605 if (!send_searchRequest(arg))
1610 static int cmd_delete(char *arg)
1614 printf("Not connected yet\n");
1617 if (!send_deleteResultSetRequest(arg))
1622 static int cmd_ssub(char *arg)
1624 if (!(smallSetUpperBound = atoi(arg)))
1629 static int cmd_lslb(char *arg)
1631 if (!(largeSetLowerBound = atoi(arg)))
1636 static int cmd_mspn(char *arg)
1638 if (!(mediumSetPresentNumber = atoi(arg)))
1643 static int cmd_status(char *arg)
1645 printf("smallSetUpperBound: %d\n", smallSetUpperBound);
1646 printf("largeSetLowerBound: %d\n", largeSetLowerBound);
1647 printf("mediumSetPresentNumber: %d\n", mediumSetPresentNumber);
1651 static int cmd_setnames(char *arg)
1653 if (*arg == '1') /* enable ? */
1655 else if (*arg == '0') /* disable ? */
1657 else if (setnumber < 0) /* no args, toggle .. */
1663 printf("Set numbering enabled.\n");
1665 printf("Set numbering disabled.\n");
1669 /* PRESENT SERVICE ----------------------------- */
1671 static int send_presentRequest(char *arg)
1673 Z_APDU *apdu = zget_APDU(out, Z_APDU_presentRequest);
1674 Z_PresentRequest *req = apdu->u.presentRequest;
1675 Z_RecordComposition compo;
1680 char setstring[100];
1682 req->referenceId = set_refid (out);
1683 if ((p = strchr(arg, '+')))
1690 if (p && (p=strchr(p+1, '+')))
1692 strcpy (setstring, p+1);
1693 req->resultSetId = setstring;
1695 else if (setnumber >= 0)
1697 sprintf(setstring, "%d", setnumber);
1698 req->resultSetId = setstring;
1700 req->resultSetStartPoint = &setno;
1701 req->numberOfRecordsRequested = &nos;
1702 prefsyn.proto = protocol;
1703 prefsyn.oclass = CLASS_RECSYN;
1704 prefsyn.value = recordsyntax;
1705 req->preferredRecordSyntax =
1706 odr_oiddup (out, oid_ent_to_oid(&prefsyn, oid));
1708 if (schema != VAL_NONE)
1712 prefschema.proto = protocol;
1713 prefschema.oclass = CLASS_SCHEMA;
1714 prefschema.value = schema;
1716 req->recordComposition = &compo;
1717 compo.which = Z_RecordComp_complex;
1718 compo.u.complex = (Z_CompSpec *)
1719 odr_malloc(out, sizeof(*compo.u.complex));
1720 compo.u.complex->selectAlternativeSyntax = (bool_t *)
1721 odr_malloc(out, sizeof(bool_t));
1722 *compo.u.complex->selectAlternativeSyntax = 0;
1724 compo.u.complex->generic = (Z_Specification *)
1725 odr_malloc(out, sizeof(*compo.u.complex->generic));
1726 compo.u.complex->generic->schema = (Odr_oid *)
1727 odr_oiddup(out, oid_ent_to_oid(&prefschema, oid));
1728 if (!compo.u.complex->generic->schema)
1730 /* OID wasn't a schema! Try record syntax instead. */
1731 prefschema.oclass = CLASS_RECSYN;
1732 compo.u.complex->generic->schema = (Odr_oid *)
1733 odr_oiddup(out, oid_ent_to_oid(&prefschema, oid));
1735 if (!elementSetNames)
1736 compo.u.complex->generic->elementSpec = 0;
1739 compo.u.complex->generic->elementSpec = (Z_ElementSpec *)
1740 odr_malloc(out, sizeof(Z_ElementSpec));
1741 compo.u.complex->generic->elementSpec->which =
1742 Z_ElementSpec_elementSetName;
1743 compo.u.complex->generic->elementSpec->u.elementSetName =
1744 elementSetNames->u.generic;
1746 compo.u.complex->num_dbSpecific = 0;
1747 compo.u.complex->dbSpecific = 0;
1748 compo.u.complex->num_recordSyntax = 0;
1749 compo.u.complex->recordSyntax = 0;
1751 else if (elementSetNames)
1753 req->recordComposition = &compo;
1754 compo.which = Z_RecordComp_simple;
1755 compo.u.simple = elementSetNames;
1758 printf("Sent presentRequest (%d+%d).\n", setno, nos);
1762 static void close_session (void)
1768 nmem_destroy (session_mem);
1774 void process_close(Z_Close *req)
1776 Z_APDU *apdu = zget_APDU(out, Z_APDU_close);
1777 Z_Close *res = apdu->u.close;
1779 static char *reasons[] =
1784 "cost limit reached",
1786 "security violation",
1793 printf("Reason: %s, message: %s\n", reasons[*req->closeReason],
1794 req->diagnosticInformation ? req->diagnosticInformation : "NULL");
1799 *res->closeReason = Z_Close_finished;
1801 printf("Sent response.\n");
1806 static int cmd_show(char *arg)
1810 printf("Not connected yet\n");
1813 if (!send_presentRequest(arg))
1818 int cmd_quit(char *arg)
1820 printf("See you later, alligator.\n");
1826 int cmd_cancel(char *arg)
1828 Z_APDU *apdu = zget_APDU(out, Z_APDU_triggerResourceControlRequest);
1829 Z_TriggerResourceControlRequest *req =
1830 apdu->u.triggerResourceControlRequest;
1835 printf("Session not initialized yet\n");
1838 if (!ODR_MASK_GET(session->options, Z_Options_triggerResourceCtrl))
1840 printf("Target doesn't support cancel (trigger resource ctrl)\n");
1843 *req->requestedAction = Z_TriggerResourceCtrl_cancel;
1844 req->resultSetWanted = &rfalse;
1847 printf("Sent cancel request\n");
1851 int send_scanrequest(const char *query, int pp, int num, const char *term)
1853 Z_APDU *apdu = zget_APDU(out, Z_APDU_scanRequest);
1854 Z_ScanRequest *req = apdu->u.scanRequest;
1858 if (queryType == QueryType_CCL2RPN)
1862 struct ccl_rpn_node *rpn;
1864 rpn = ccl_find_str (bibset, query, &error, &pos);
1867 printf("CCL ERROR: %s\n", ccl_err_msg(error));
1871 bib1.proto = PROTO_Z3950;
1872 bib1.oclass = CLASS_ATTSET;
1873 bib1.value = VAL_BIB1;
1874 req->attributeSet = oid_ent_to_oid (&bib1, oid);
1875 if (!(req->termListAndStartPoint = ccl_scan_query (out, rpn)))
1877 printf("Couldn't convert CCL to Scan term\n");
1880 ccl_rpn_delete (rpn);
1882 if (use_rpn && !(req->termListAndStartPoint =
1883 p_query_scan(out, protocol, &req->attributeSet, query)))
1885 printf("Prefix query error\n");
1890 if (req->termListAndStartPoint->term &&
1891 req->termListAndStartPoint->term->which == Z_Term_general &&
1892 req->termListAndStartPoint->term->u.general)
1894 req->termListAndStartPoint->term->u.general->buf =
1895 (unsigned char *) odr_strdup(out, term);
1896 req->termListAndStartPoint->term->u.general->len =
1897 req->termListAndStartPoint->term->u.general->size =
1901 req->referenceId = set_refid (out);
1902 req->num_databaseNames = num_databaseNames;
1903 req->databaseNames = databaseNames;
1904 req->numberOfTermsRequested = #
1905 req->preferredPositionInResponse = &pp;
1910 int send_sortrequest(char *arg, int newset)
1912 Z_APDU *apdu = zget_APDU(out, Z_APDU_sortRequest);
1913 Z_SortRequest *req = apdu->u.sortRequest;
1914 Z_SortKeySpecList *sksl = (Z_SortKeySpecList *)
1915 odr_malloc (out, sizeof(*sksl));
1919 sprintf (setstring, "%d", setnumber);
1921 sprintf (setstring, "default");
1923 req->referenceId = set_refid (out);
1925 req->num_inputResultSetNames = 1;
1926 req->inputResultSetNames = (Z_InternationalString **)
1927 odr_malloc (out, sizeof(*req->inputResultSetNames));
1928 req->inputResultSetNames[0] = odr_strdup (out, setstring);
1930 if (newset && setnumber >= 0)
1931 sprintf (setstring, "%d", ++setnumber);
1933 req->sortedResultSetName = odr_strdup (out, setstring);
1935 req->sortSequence = yaz_sort_spec (out, arg);
1936 if (!req->sortSequence)
1938 printf ("Missing sort specifications\n");
1945 void display_term(Z_TermInfo *t)
1947 if (t->term->which == Z_Term_general)
1949 printf("%.*s", t->term->u.general->len, t->term->u.general->buf);
1950 sprintf(last_scan_line, "%.*s", t->term->u.general->len,
1951 t->term->u.general->buf);
1954 printf("Term (not general)");
1955 if (t->globalOccurrences)
1956 printf (" (%d)\n", *t->globalOccurrences);
1961 void process_scanResponse(Z_ScanResponse *res)
1964 Z_Entry **entries = NULL;
1965 int num_entries = 0;
1967 printf("Received ScanResponse\n");
1968 print_refid (res->referenceId);
1969 printf("%d entries", *res->numberOfEntriesReturned);
1970 if (res->positionOfTerm)
1971 printf (", position=%d", *res->positionOfTerm);
1973 if (*res->scanStatus != Z_Scan_success)
1974 printf("Scan returned code %d\n", *res->scanStatus);
1977 if ((entries = res->entries->entries))
1978 num_entries = res->entries->num_entries;
1979 for (i = 0; i < num_entries; i++)
1981 int pos_term = res->positionOfTerm ? *res->positionOfTerm : -1;
1982 if (entries[i]->which == Z_Entry_termInfo)
1984 printf("%c ", i + 1 == pos_term ? '*' : ' ');
1985 display_term(entries[i]->u.termInfo);
1988 display_diagrecs(&entries[i]->u.surrogateDiagnostic, 1);
1990 if (res->entries->nonsurrogateDiagnostics)
1991 display_diagrecs (res->entries->nonsurrogateDiagnostics,
1992 res->entries->num_nonsurrogateDiagnostics);
1995 void process_sortResponse(Z_SortResponse *res)
1997 printf("Received SortResponse: status=");
1998 switch (*res->sortStatus)
2000 case Z_SortStatus_success:
2001 printf ("success"); break;
2002 case Z_SortStatus_partial_1:
2003 printf ("partial"); break;
2004 case Z_SortStatus_failure:
2005 printf ("failure"); break;
2007 printf ("unknown (%d)", *res->sortStatus);
2010 print_refid (res->referenceId);
2011 if (res->diagnostics)
2012 display_diagrecs(res->diagnostics,
2013 res->num_diagnostics);
2016 void process_deleteResultSetResponse (Z_DeleteResultSetResponse *res)
2018 printf("Got deleteResultSetResponse status=%d\n",
2019 *res->deleteOperationStatus);
2020 if (res->deleteListStatuses)
2023 for (i = 0; i < res->deleteListStatuses->num; i++)
2025 printf ("%s status=%d\n", res->deleteListStatuses->elements[i]->id,
2026 *res->deleteListStatuses->elements[i]->status);
2031 int cmd_sort_generic(char *arg, int newset)
2035 printf("Session not initialized yet\n");
2038 if (!ODR_MASK_GET(session->options, Z_Options_sort))
2040 printf("Target doesn't support sort\n");
2045 if (send_sortrequest(arg, newset) < 0)
2052 int cmd_sort(char *arg)
2054 return cmd_sort_generic (arg, 0);
2057 int cmd_sort_newset (char *arg)
2059 return cmd_sort_generic (arg, 1);
2062 int cmd_scan(char *arg)
2069 printf("Session not initialized yet\n");
2073 if (!ODR_MASK_GET(session->options, Z_Options_scan))
2075 printf("Target doesn't support scan\n");
2080 strcpy (last_scan_query, arg);
2081 if (send_scanrequest(arg, 1, 20, 0) < 0)
2086 if (send_scanrequest(last_scan_query, 1, 20, last_scan_line) < 0)
2092 int cmd_schema(char *arg)
2099 schema = oid_getvalbyname (arg);
2100 if (schema == VAL_NONE)
2102 printf ("unknown schema\n");
2108 int cmd_format(char *arg)
2112 printf("Usage: format <recordsyntax>\n");
2115 recordsyntax = oid_getvalbyname (arg);
2116 if (recordsyntax == VAL_NONE)
2118 printf ("unknown record syntax\n");
2124 int cmd_elements(char *arg)
2126 static Z_ElementSetNames esn;
2127 static char what[100];
2131 elementSetNames = 0;
2135 esn.which = Z_ElementSetNames_generic;
2136 esn.u.generic = what;
2137 elementSetNames = &esn;
2141 int cmd_attributeset(char *arg)
2147 printf("Usage: attributeset <setname>\n");
2150 sscanf(arg, "%s", what);
2151 if (p_query_attset (what))
2153 printf("Unknown attribute set name\n");
2159 int cmd_querytype (char *arg)
2161 if (!strcmp (arg, "ccl"))
2162 queryType = QueryType_CCL;
2163 else if (!strcmp (arg, "prefix") || !strcmp(arg, "rpn"))
2164 queryType = QueryType_Prefix;
2165 else if (!strcmp (arg, "ccl2rpn") || !strcmp (arg, "cclrpn"))
2166 queryType = QueryType_CCL2RPN;
2169 printf ("Querytype must be one of:\n");
2170 printf (" prefix - Prefix query\n");
2171 printf (" ccl - CCL query\n");
2172 printf (" ccl2rpn - CCL query converted to RPN\n");
2178 int cmd_refid (char *arg)
2184 refid = (char *) xmalloc (strlen(arg)+1);
2185 strcpy (refid, arg);
2190 int cmd_close(char *arg)
2197 apdu = zget_APDU(out, Z_APDU_close);
2198 req = apdu->u.close;
2199 *req->closeReason = Z_Close_finished;
2201 printf("Sent close request.\n");
2206 int cmd_packagename(char* arg)
2208 xfree (esPackageName);
2209 esPackageName = NULL;
2212 esPackageName = (char *) xmalloc (strlen(arg)+1);
2213 strcpy (esPackageName, arg);
2218 int cmd_proxy(char* arg)
2229 yazProxy = (char *) xmalloc (strlen(arg)+1);
2230 strcpy (yazProxy, arg);
2235 int cmd_charset(char* arg)
2237 char l1[30], l2[30];
2240 if (sscanf(arg, "%29s %29s", l1, l2) < 1)
2242 printf("Current character set is `%s'\n", (yazCharset) ? yazCharset:NULL);
2248 yazCharset = xstrdup(l1);
2251 odr_set_charset (out, l1, l2);
2252 odr_set_charset (in, l2, l1);
2257 int cmd_lang(char* arg)
2260 printf("Current language is `%s'\n", (yazLang)?yazLang:NULL);
2267 yazLang = (char *) xmalloc (strlen(arg)+1);
2268 strcpy (yazLang, arg);
2273 int cmd_source(char* arg)
2275 /* first should open the file and read one line at a time.. */
2277 char line[1024], *cp;
2280 char* args_end=(arg)+strlen(arg)-1;
2281 while(isspace(*args_end))
2286 REMOVE_TAILING_BLANKS(arg);
2289 fprintf(stderr,"Error in source command use a filename\n");
2293 includeFile = fopen (arg, "r");
2296 fprintf(stderr,"Unable to open file %s for reading\n",arg);
2300 while(!feof(includeFile)) {
2301 memset(line,0,sizeof(line));
2302 fgets(line,sizeof(line),includeFile);
2304 if(strlen(line) < 2) continue;
2305 if(line[0] == '#') continue;
2307 if ((cp = strrchr (line, '\n')))
2310 process_cmd_line(line);
2313 if(fclose(includeFile)<0) {
2314 perror("unable to close include file");
2320 int cmd_subshell(char* args)
2325 system(getenv("SHELL"));
2331 int cmd_set_apdufile(char* arg)
2333 REMOVE_TAILING_BLANKS(arg);
2335 if(apdu_file && apdu_file != stderr) { /* don't close stdout*/
2336 perror("unable to close apdu log file");
2344 if(!strcmp(arg,"-"))
2347 apdu_file=fopen(arg, "a");
2350 perror("unable to open apdu log file no apdu log loaded");
2352 odr_setprint(print, apdu_file);
2358 int cmd_set_cclfile(char* arg)
2362 REMOVE_TAILING_BLANKS(arg);
2364 bibset = ccl_qual_mk ();
2365 inf = fopen (arg, "r");
2368 ccl_qual_file (bibset, inf);
2372 strcpy(ccl_fields,arg);
2377 int cmd_set_auto_reconnect(char* arg)
2379 REMOVE_TAILING_BLANKS(arg);
2381 if(strlen(arg)==0) {
2382 auto_reconnect = ! auto_reconnect;
2383 } else if(strcmp(arg,"on")==0) {
2385 } else if(strcmp(arg,"off")==0) {
2388 printf("Error use on or off\n");
2393 printf("Set auto reconnect enabled.\n");
2395 printf("Set auto reconnect disabled.\n");
2400 int cmd_set_marcdump(char* arg)
2402 if(marcdump && marcdump != stderr) { /* don't close stdout*/
2403 perror("unable to close apdu log file");
2411 if(!strcmp(arg,"-"))
2414 marcdump=fopen(arg, "a");
2417 perror("unable to open apdu marcdump file no marcdump done\n");
2423 int cmd_set_proxy(char* arg) {
2424 if(yazProxy) free(yazProxy);
2427 if(strlen(arg) > 1) {
2428 yazProxy=strdup(arg);
2434 this command takes 3 arge {name class oid}
2436 int cmd_register_oid(char* args) {
2441 {"appctx",CLASS_APPCTX},
2442 {"absyn",CLASS_ABSYN},
2443 {"attset",CLASS_ATTSET},
2444 {"transyn",CLASS_TRANSYN},
2445 {"diagset",CLASS_DIAGSET},
2446 {"recsyn",CLASS_RECSYN},
2447 {"resform",CLASS_RESFORM},
2448 {"accform",CLASS_ACCFORM},
2449 {"extserv",CLASS_EXTSERV},
2450 {"userinfo",CLASS_USERINFO},
2451 {"elemspec",CLASS_ELEMSPEC},
2452 {"varset",CLASS_VARSET},
2453 {"schema",CLASS_SCHEMA},
2454 {"tagset",CLASS_TAGSET},
2455 {"general",CLASS_GENERAL},
2458 char oname_str[101], oclass_str[101], oid_str[101];
2461 oid_class oidclass = CLASS_GENERAL;
2462 int val = 0, oid[OID_SIZE];
2463 struct oident * new_oident=NULL;
2465 if (sscanf (args, "%100[^ ] %100[^ ] %100s",
2466 oname_str,oclass_str, oid_str) < 1) {
2467 printf("Error in regristrate command \n");
2471 for (i = 0; oid_classes[i].className; i++) {
2472 if (!strcmp(oid_classes[i].className, oclass_str))
2474 oidclass=oid_classes[i].oclass;
2479 if(!(oid_classes[i].className)) {
2480 printf("Unknonwn oid class %s\n",oclass_str);
2488 while (isdigit (*name))
2490 val = val*10 + (*name - '0');
2503 new_oident=oid_addent (oid,PROTO_GENERAL,oidclass,oname_str,VAL_DYNAMIC);
2504 if(strcmp(new_oident->desc,oname_str)) {
2505 fprintf(stderr,"oid is already named as %s, regristration faild\n",
2511 int cmd_push_command(char* arg)
2513 #if HAVE_READLINE_HISTORY_H
2517 fprintf(stderr,"Not compiled with the readline/history module\n");
2522 void source_rcfile()
2524 /* Look for a $HOME/.yazclientrc and source it if it exists */
2525 struct stat statbuf;
2527 char* homedir=getenv("HOME");
2529 if(!homedir) return;
2531 sprintf(buffer,"%s/.yazclientrc",homedir);
2533 if(stat(buffer,&statbuf)==0) {
2537 if(stat(".yazclientrc",&statbuf)==0) {
2538 cmd_source(".yazclientrc");
2543 static void initialize(void)
2548 if (!(out = odr_createmem(ODR_ENCODE)) ||
2549 !(in = odr_createmem(ODR_DECODE)) ||
2550 !(print = odr_createmem(ODR_PRINT)))
2552 fprintf(stderr, "failed to allocate ODR streams\n");
2557 setvbuf(stdout, 0, _IONBF, 0);
2559 odr_setprint(print, apdu_file);
2561 bibset = ccl_qual_mk ();
2562 inf = fopen (ccl_fields, "r");
2565 ccl_qual_file (bibset, inf);
2568 cmd_base("Default");
2570 #if HAVE_READLINE_READLINE_H
2571 rl_attempted_completion_function = (CPPFunction*)readline_completer;
2575 for(i=0; i<maxOtherInfosSupported; ++i) {
2576 extraOtherInfos[i].oidval = -1;
2583 #if HAVE_GETTIMEOFDAY
2584 struct timeval tv_start, tv_end;
2587 void wait_and_handle_responce()
2592 int netbufferlen = 0;
2600 if ((res = cs_get(conn, &netbuffer, &netbufferlen)) < 0)
2602 printf("Target closed connection\n");
2608 printf("Target closed connection.\n");
2612 odr_reset(in); /* release APDU from last round */
2614 odr_setbuf(in, netbuffer, res, 0);
2615 if (!z_APDU(in, &apdu, 0, 0))
2617 odr_perror(in, "Decoding incoming APDU");
2618 fprintf(stderr, "[Near %d]\n", odr_offset(in));
2619 fprintf(stderr, "Packet dump:\n---------\n");
2620 odr_dumpBER(stderr, netbuffer, res);
2621 fprintf(stderr, "---------\n");
2623 z_APDU(print, &apdu, 0, 0);
2627 if (apdu_file && !z_APDU(print, &apdu, 0, 0))
2629 odr_perror(print, "Failed to print incoming APDU");
2635 case Z_APDU_initResponse:
2636 process_initResponse(apdu->u.initResponse);
2638 case Z_APDU_searchResponse:
2639 process_searchResponse(apdu->u.searchResponse);
2641 case Z_APDU_scanResponse:
2642 process_scanResponse(apdu->u.scanResponse);
2644 case Z_APDU_presentResponse:
2645 print_refid (apdu->u.presentResponse->referenceId);
2647 *apdu->u.presentResponse->numberOfRecordsReturned;
2648 if (apdu->u.presentResponse->records)
2649 display_records(apdu->u.presentResponse->records);
2651 printf("No records.\n");
2652 printf ("nextResultSetPosition = %d\n",
2653 *apdu->u.presentResponse->nextResultSetPosition);
2655 case Z_APDU_sortResponse:
2656 process_sortResponse(apdu->u.sortResponse);
2658 case Z_APDU_extendedServicesResponse:
2659 printf("Got extended services response\n");
2660 process_ESResponse(apdu->u.extendedServicesResponse);
2663 printf("Target has closed the association.\n");
2664 process_close(apdu->u.close);
2666 case Z_APDU_resourceControlRequest:
2667 process_resourceControlRequest
2668 (apdu->u.resourceControlRequest);
2670 case Z_APDU_deleteResultSetResponse:
2671 process_deleteResultSetResponse(apdu->u.
2672 deleteResultSetResponse);
2675 printf("Received unknown APDU type (%d).\n",
2680 while (conn && cs_more(conn));
2681 #if HAVE_GETTIMEOFDAY
2682 gettimeofday (&tv_end, 0);
2684 printf ("S/U S/U=%ld/%ld %ld/%ld",
2685 (long) tv_start.tv_sec,
2686 (long) tv_start.tv_usec,
2687 (long) tv_end.tv_sec,
2688 (long) tv_end.tv_usec);
2690 printf ("Elapsed: %.6f\n",
2691 (double) tv_end.tv_usec / 1e6 + tv_end.tv_sec -
2692 ((double) tv_start.tv_usec / 1e6 + tv_start.tv_sec));
2699 int cmd_cclparse(char* arg)
2702 struct ccl_rpn_node *rpn=NULL;
2705 rpn = ccl_find_str (bibset, arg, &error, &pos);
2708 printf ("%*s^ - ", 3+strlen(last_cmd)+1+pos, " ");
2709 printf ("%s\n", ccl_err_msg (error));
2715 ccl_pr_tree(rpn, stdout);
2719 ccl_rpn_delete(rpn);
2727 int cmd_set_otherinfo(char* args)
2729 char oid[101], otherinfoString[101];
2734 sscan_res = sscanf (args, "%d %100[^ ] %100s", &otherinfoNo, oid, otherinfoString);
2736 /* reset this otherinfo */
2737 if(otherinfoNo>=maxOtherInfosSupported) {
2738 printf("Error otherinfo index to large (%d>%d)\n",otherinfoNo,maxOtherInfosSupported);
2740 extraOtherInfos[otherinfoNo].oidval = -1;
2741 if(extraOtherInfos[otherinfoNo].value) free(extraOtherInfos[otherinfoNo].value);
2745 printf("Error in set_otherinfo command \n");
2749 if(otherinfoNo>=maxOtherInfosSupported) {
2750 printf("Error otherinfo index to large (%d>%d)\n",otherinfoNo,maxOtherInfosSupported);
2754 oidval = oid_getvalbyname (oid);
2756 printf("Error in set_otherinfo command unknown oid %s \n",oid);
2759 extraOtherInfos[otherinfoNo].oidval = oidval;
2760 if(extraOtherInfos[otherinfoNo].value) free(extraOtherInfos[otherinfoNo].value);
2761 extraOtherInfos[otherinfoNo].value = strdup(otherinfoString);
2766 int cmd_list_otherinfo(char* args)
2770 if(strlen(args)>0) {
2772 if( i >= maxOtherInfosSupported ) {
2773 printf("Error otherinfo index to large (%d>%d)\n",i,maxOtherInfosSupported);
2777 if(extraOtherInfos[i].oidval != -1)
2778 printf(" otherinfo %d %s %s\n",i,yaz_z3950_oid_value_to_str(extraOtherInfos[i].oidval,CLASS_RECSYN), extraOtherInfos[i].value);
2781 for(i=0; i<maxOtherInfosSupported; ++i) {
2782 if(extraOtherInfos[i].oidval != -1)
2783 printf(" otherinfo %d %s %s\n",i,yaz_z3950_oid_value_to_str(extraOtherInfos[i].oidval,CLASS_RECSYN), extraOtherInfos[i].value);
2791 int cmd_list_all(char* args) {
2794 /* connection options */
2796 printf("Connected to : %s\n",last_open_command);
2798 if(last_open_command)
2799 printf("Not connected to : %s\n",last_open_command);
2801 printf("Not connected : \n");
2804 if(yazProxy) printf("using proxy : %s\n",yazProxy);
2806 printf("auto_reconnect : %s\n",auto_reconnect?"on":"off");
2809 printf("Authentication : none\n");
2811 switch(auth->which) {
2812 case Z_IdAuthentication_idPass:
2813 printf("Authentication : IdPass\n");
2814 printf(" Login User : %s\n",auth->u.idPass->userId?auth->u.idPass->userId:"");
2815 printf(" Login Group : %s\n",auth->u.idPass->groupId?auth->u.idPass->groupId:"");
2816 printf(" Password : %s\n",auth->u.idPass->password?auth->u.idPass->password:"");
2818 case Z_IdAuthentication_open:
2819 printf("Authentication : psOpen\n");
2820 printf(" Open string : %s\n",auth->u.open);
2823 printf("Authentication : Unknown\n");
2826 if ( yazCharset ) printf("Character set : `%s'\n", (yazCharset) ? yazCharset:NULL);
2830 for (i = 0; i<num_databaseNames; i++) printf("%s ",databaseNames[i]);
2834 printf("CCL file : %s\n",ccl_fields);
2835 printf("Query type : %s\n",query_type_as_string(queryType));
2837 printf("Named Result Sets : %s\n",setnumber==-1?"off":"on");
2839 /* piggy back options */
2840 printf("ssub/lslb/mspn : %d/%d/%d\n",smallSetUpperBound,largeSetLowerBound,mediumSetPresentNumber);
2842 /* print present related options */
2843 printf("Format : %s\n",yaz_z3950_oid_value_to_str(recordsyntax,CLASS_RECSYN));
2844 printf("Schema : %s\n",yaz_z3950_oid_value_to_str(schema,CLASS_SCHEMA));
2845 printf("Elements : %s\n",elementSetNames?elementSetNames->u.generic:"");
2847 /* loging options */
2848 printf("APDU log : %s\n",apdu_file?"on":"off");
2849 printf("Record log : %s\n",marcdump?"on":"off");
2852 printf("Other Info: \n");
2853 cmd_list_otherinfo("");
2858 int cmd_clear_otherinfo(char* args)
2860 if(strlen(args)>0) {
2862 otherinfoNo = atoi(args);
2863 if( otherinfoNo >= maxOtherInfosSupported ) {
2864 printf("Error otherinfo index to large (%d>%d)\n",otherinfoNo,maxOtherInfosSupported);
2868 if(extraOtherInfos[otherinfoNo].oidval != -1) {
2869 /* only clear if set. */
2870 extraOtherInfos[otherinfoNo].oidval=-1;
2871 free(extraOtherInfos[otherinfoNo].value);
2876 for(i=0; i<maxOtherInfosSupported; ++i) {
2877 if (extraOtherInfos[i].oidval!=-1 ) {
2878 extraOtherInfos[i].oidval=-1;
2879 free(extraOtherInfos[i].value);
2886 static int cmd_help (char *line);
2888 typedef char *(*completerFunctionType)(const char *text, int state);
2892 int (*fun)(char *arg);
2894 completerFunctionType rl_completerfunction;
2895 int complete_filenames;
2896 char **local_tabcompletes;
2898 {"open", cmd_open, "('tcp'|'ssl')':<host>[':'<port>][/<db>]",NULL,0,NULL},
2899 {"quit", cmd_quit, "",NULL,0,NULL},
2900 {"find", cmd_find, "<query>",NULL,0,NULL},
2901 {"delete", cmd_delete, "<setname>",NULL,0,NULL},
2902 {"base", cmd_base, "<base-name>",NULL,0,NULL},
2903 {"show", cmd_show, "<rec#>['+'<#recs>['+'<setname>]]",NULL,0,NULL},
2904 {"scan", cmd_scan, "<term>",NULL,0,NULL},
2905 {"sort", cmd_sort, "<sortkey> <flag> <sortkey> <flag> ...",NULL,0,NULL},
2906 {"sort+", cmd_sort_newset, "<sortkey> <flag> <sortkey> <flag> ...",NULL,0,NULL},
2907 {"authentication", cmd_authentication, "<acctstring>",NULL,0,NULL},
2908 {"lslb", cmd_lslb, "<largeSetLowerBound>",NULL,0,NULL},
2909 {"ssub", cmd_ssub, "<smallSetUpperBound>",NULL,0,NULL},
2910 {"mspn", cmd_mspn, "<mediumSetPresentNumber>",NULL,0,NULL},
2911 {"status", cmd_status, "",NULL,0,NULL},
2912 {"setnames", cmd_setnames, "",NULL,0,NULL},
2913 {"cancel", cmd_cancel, "",NULL,0,NULL},
2914 {"format", cmd_format, "<recordsyntax>",complete_format,0,NULL},
2915 {"schema", cmd_schema, "<schema>",complete_schema,0,NULL},
2916 {"elements", cmd_elements, "<elementSetName>",NULL,0,NULL},
2917 {"close", cmd_close, "",NULL,0,NULL},
2918 {"attributeset", cmd_attributeset, "<attrset>",complete_attributeset,0,NULL},
2919 {"querytype", cmd_querytype, "<type>",complete_querytype,0,NULL},
2920 {"refid", cmd_refid, "<id>",NULL,0,NULL},
2921 {"itemorder", cmd_itemorder, "ill|item <itemno>",NULL,0,NULL},
2922 {"update", cmd_update, "<item>",NULL,0,NULL},
2923 {"packagename", cmd_packagename, "<packagename>",NULL,0,NULL},
2924 {"proxy", cmd_proxy, "[('tcp'|'ssl')]<host>[':'<port>]",NULL,0,NULL},
2925 {"charset", cmd_charset, "<charset_name>",NULL,0,NULL},
2926 {"lang", cmd_lang, "<language_code>",NULL,0,NULL},
2927 {".", cmd_source, "<filename>",NULL,1,NULL},
2928 {"!", cmd_subshell, "Subshell command",NULL,1,NULL},
2929 {"set_apdufile", cmd_set_apdufile, "<filename>",NULL,1,NULL},
2930 {"set_marcdump", cmd_set_marcdump," <filename>",NULL,1,NULL},
2931 {"set_cclfile", cmd_set_cclfile," <filename>",NULL,1,NULL},
2932 {"set_auto_reconnect", cmd_set_auto_reconnect," on|off",complete_auto_reconnect,1,NULL},
2933 {"set_otherinfo", cmd_set_otherinfo,"<otherinfoinddex> <oid> <string>",NULL,0,NULL},
2934 {"register_oid", cmd_register_oid,"<name> <class> <oid>",NULL,0,NULL},
2935 {"push_command", cmd_push_command,"<command>",command_generator,0,NULL},
2936 {"register_tab", cmd_register_tab,"<commandname> <tab>",command_generator,0,NULL},
2937 {"cclparse", cmd_cclparse,"<ccl find command>",NULL,0,NULL},
2938 {"list_otherinfo",cmd_list_otherinfo,"[otherinfoinddex]",NULL,0,NULL},
2939 {"list_all",cmd_list_all,"",NULL,0,NULL},
2940 {"clear_otherinfo",cmd_clear_otherinfo,"",NULL,0,NULL},
2941 /* Server Admin Functions */
2942 {"adm-reindex", cmd_adm_reindex, "<database-name>",NULL,0,NULL},
2943 {"adm-truncate", cmd_adm_truncate, "('database'|'index')<object-name>",NULL,0,NULL},
2944 {"adm-create", cmd_adm_create, "",NULL,0,NULL},
2945 {"adm-drop", cmd_adm_drop, "('database'|'index')<object-name>",NULL,0,NULL},
2946 {"adm-import", cmd_adm_import, "<record-type> <dir> <pattern>",NULL,0,NULL},
2947 {"adm-refresh", cmd_adm_refresh, "",NULL,0,NULL},
2948 {"adm-commit", cmd_adm_commit, "",NULL,0,NULL},
2949 {"adm-shutdown", cmd_adm_shutdown, "",NULL,0,NULL},
2950 {"adm-startup", cmd_adm_startup, "",NULL,0,NULL},
2951 {"help", cmd_help, "", NULL,0,NULL},
2955 static int cmd_help (char *line)
2961 sscanf (line, "%20s", topic);
2964 printf("Commands:\n");
2965 for (i = 0; cmd[i].cmd; i++)
2966 if (*topic == 0 || strcmp (topic, cmd[i].cmd) == 0)
2967 printf(" %s %s\n", cmd[i].cmd, cmd[i].ad);
2968 if (strcmp (topic, "find") == 0)
2971 printf (" \"term\" Simple Term\n");
2972 printf (" @attr [attset] type=value op Attribute\n");
2973 printf (" @and opl opr And\n");
2974 printf (" @or opl opr Or\n");
2975 printf (" @not opl opr And-Not\n");
2976 printf (" @set set Result set\n");
2978 printf ("Bib-1 attribute types\n");
2980 printf ("4=Title 7=ISBN 8=ISSN 30=Date 62=Abstract 1003=Author 1016=Any\n");
2981 printf ("2=Relation: ");
2982 printf ("1< 2<= 3= 4>= 5> 6!= 102=Relevance\n");
2983 printf ("3=Position: ");
2984 printf ("1=First in Field 2=First in subfield 3=Any position\n");
2985 printf ("4=Structure: ");
2986 printf ("1=Phrase 2=Word 3=Key 4=Year 5=Date 6=WordList\n");
2987 printf ("5=Truncation: ");
2988 printf ("1=Right 2=Left 3=L&R 100=No 101=# 102=Re-1 103=Re-2\n");
2989 printf ("6=Completeness:");
2990 printf ("1=Incomplete subfield 2=Complete subfield 3=Complete field\n");
2995 int cmd_register_tab(char* arg) {
2997 char command[101], tabargument[101];
3002 if (sscanf (arg, "%100s %100s", command, tabargument) < 1) {
3006 /* locate the amdn in the list */
3007 for (i = 0; cmd[i].cmd; i++) {
3008 if (!strncmp(cmd[i].cmd, command, strlen(command))) {
3014 fprintf(stderr,"Unknown command %s\n",command);
3020 if(!cmd[i].local_tabcompletes) {
3021 cmd[i].local_tabcompletes = calloc(1,sizeof(char**));
3026 tabslist = cmd[i].local_tabcompletes;
3027 for(;tabslist && *tabslist;tabslist++) {
3031 cmd[i].local_tabcompletes=realloc(cmd[i].local_tabcompletes,(num_of_tabs+2)*sizeof(char**));
3032 tabslist=cmd[i].local_tabcompletes;
3033 tabslist[num_of_tabs]=strdup(tabargument);
3034 tabslist[num_of_tabs+1]=NULL;
3039 void process_cmd_line(char* line)
3042 char word[32], arg[1024];
3044 #if HAVE_GETTIMEOFDAY
3045 gettimeofday (&tv_start, 0);
3048 if ((res = sscanf(line, "%31s %1023[^;]", word, arg)) <= 0)
3050 strcpy(word, last_cmd);
3055 strcpy(last_cmd, word);
3057 /* removed tailing spaces from the arg command */
3060 char* lastnonspace=NULL;
3069 *(++lastnonspace) = 0;
3073 for (i = 0; cmd[i].cmd; i++)
3074 if (!strncmp(cmd[i].cmd, word, strlen(word)))
3076 res = (*cmd[i].fun)(arg);
3080 if (!cmd[i].cmd) /* dump our help-screen */
3082 printf("Unknown command: %s.\n", word);
3083 printf("use help for list of commands\n");
3084 /* cmd_help (""); */
3088 if(apdu_file) fflush(apdu_file);
3091 wait_and_handle_responce();
3100 char *command_generator(const char *text, int state)
3106 for( ; cmd[idx].cmd; ++idx) {
3107 if (!strncmp(cmd[idx].cmd,text,strlen(text))) {
3108 ++idx; /* skip this entry on the next run */
3109 return strdup(cmd[idx-1].cmd);
3117 This function only known how to complete on the first word
3119 char ** readline_completer(char *text, int start, int end) {
3120 #if HAVE_READLINE_READLINE_H
3122 completerFunctionType completerToUse;
3125 #if HAVE_READLINE_RL_COMPLETION_MATCHES
3126 char** res=rl_completion_matches(text,
3129 char** res=completion_matches(text,
3130 (CPFunction*)command_generator);
3132 rl_attempted_completion_over = 1;
3135 char arg[1024],word[32];
3137 if ((res = sscanf(rl_line_buffer, "%31s %1023[^;]", word, arg)) <= 0) {
3138 rl_attempted_completion_over = 1;
3142 for (i = 0; cmd[i].cmd; i++) {
3143 if (!strncmp(cmd[i].cmd, word, strlen(word))) {
3148 if(!cmd[i].cmd) return NULL;
3151 curret_global_list = cmd[i].local_tabcompletes;
3153 completerToUse = cmd[i].rl_completerfunction;
3154 if(completerToUse==NULL) /* if no pr. command completer is defined use the default completer */
3155 completerToUse = default_completer;
3157 if(completerToUse) {
3158 #ifdef HAVE_READLINE_RL_COMPLETION_MATCHES
3160 rl_completion_matches(text,
3164 completion_matches(text,
3165 (CPFunction*)completerToUse);
3167 if(!cmd[i].complete_filenames)
3168 rl_attempted_completion_over = 1;
3171 if(!cmd[i].complete_filenames)
3172 rl_attempted_completion_over = 1;
3182 static void client(void)
3188 #if HAVE_GETTIMEOFDAY
3189 gettimeofday (&tv_start, 0);
3194 char *line_in = NULL;
3195 #if HAVE_READLINE_READLINE_H
3198 line_in=readline(C_PROMPT);
3201 #if HAVE_READLINE_HISTORY_H
3203 add_history(line_in);
3205 strncpy(line, line_in, 1023);
3214 if (!fgets(line, 1023, stdin))
3216 if ((end_p = strchr (line, '\n')))
3219 process_cmd_line(line);
3223 int main(int argc, char **argv)
3226 char *open_command = 0;
3227 char *auth_command = 0;
3231 while ((ret = options("k:c:a:m:v:p:u:", argv, argc, &arg)) != -2)
3238 open_command = (char *) xmalloc (strlen(arg)+6);
3239 strcpy (open_command, "open ");
3240 strcat (open_command, arg);
3244 kilobytes = atoi(arg);
3247 if (!(marcdump = fopen (arg, "a")))
3254 strncpy (ccl_fields, arg, sizeof(ccl_fields)-1);
3255 ccl_fields[sizeof(ccl_fields)-1] = '\0';
3258 if (!strcmp(arg, "-"))
3261 apdu_file=fopen(arg, "a");
3264 yazProxy=strdup(arg);
3269 auth_command = (char *) xmalloc (strlen(arg)+6);
3270 strcpy (auth_command, "auth ");
3271 strcat (auth_command, arg);
3275 yaz_log_init (yaz_log_mask_str(arg), "", NULL);
3278 fprintf (stderr, "Usage: %s [-m <marclog>] [ -a <apdulog>] "
3279 "[-c cclfields]\n [-p <proxy-addr>] [-u <auth>] "
3280 "[-k size] [<server-addr>]\n",
3288 #ifdef HAVE_GETTIMEOFDAY
3289 gettimeofday (&tv_start, 0);
3291 process_cmd_line (auth_command);
3292 #if HAVE_READLINE_HISTORY_H
3293 add_history(auth_command);
3295 xfree(auth_command);
3299 #ifdef HAVE_GETTIMEOFDAY
3300 gettimeofday (&tv_start, 0);
3302 process_cmd_line (open_command);
3303 #if HAVE_READLINE_HISTORY_H
3304 add_history(open_command);
3306 xfree(open_command);