2 * Copyright (c) 1995-2002, Index Data
3 * See the file LICENSE for details.
5 * $Id: client.c,v 1.168 2002-09-15 20:41:01 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;
901 YAZ_PQF_Parser pqf_parser;
903 if (queryType == QueryType_CCL2RPN)
905 rpn = ccl_find_str(bibset, arg, &error, &pos);
908 printf("CCL ERROR: %s\n", ccl_err_msg(error));
912 req->referenceId = set_refid (out);
913 if (!strcmp(arg, "@big")) /* strictly for troublemaking */
915 static unsigned char big[2100];
918 /* send a very big referenceid to test transport stack etc. */
919 memset(big, 'A', 2100);
920 bigo.len = bigo.size = 2100;
922 req->referenceId = &bigo;
927 sprintf(setstring, "%d", ++setnumber);
928 req->resultSetName = setstring;
930 *req->smallSetUpperBound = smallSetUpperBound;
931 *req->largeSetLowerBound = largeSetLowerBound;
932 *req->mediumSetPresentNumber = mediumSetPresentNumber;
933 if (smallSetUpperBound > 0 || (largeSetLowerBound > 1 &&
934 mediumSetPresentNumber > 0))
938 prefsyn.proto = protocol;
939 prefsyn.oclass = CLASS_RECSYN;
940 prefsyn.value = recordsyntax;
941 req->preferredRecordSyntax =
942 odr_oiddup(out, oid_ent_to_oid(&prefsyn, oid));
943 req->smallSetElementSetNames =
944 req->mediumSetElementSetNames = elementSetNames;
946 req->num_databaseNames = num_databaseNames;
947 req->databaseNames = databaseNames;
953 case QueryType_Prefix:
954 query.which = Z_Query_type_1;
955 pqf_parser = yaz_pqf_create ();
956 RPNquery = yaz_pqf_parse (pqf_parser, out, arg);
961 int code = yaz_pqf_error (pqf_parser, &pqf_msg, &off);
962 printf("%*s^\n", off+4, "");
963 printf("Prefix query error: %s (code %d)\n", pqf_msg, code);
965 yaz_pqf_destroy (pqf_parser);
968 yaz_pqf_destroy (pqf_parser);
969 query.u.type_1 = RPNquery;
972 query.which = Z_Query_type_2;
973 query.u.type_2 = &ccl_query;
974 ccl_query.buf = (unsigned char*) arg;
975 ccl_query.len = strlen(arg);
977 case QueryType_CCL2RPN:
978 query.which = Z_Query_type_1;
979 RPNquery = ccl_rpn_query(out, rpn);
982 printf ("Couldn't convert from CCL to RPN\n");
985 query.u.type_1 = RPNquery;
986 ccl_rpn_delete (rpn);
989 printf ("Unsupported query type\n");
994 printf("Sent searchRequest.\n");
998 /* display Query Expression as part of searchResult-1 */
999 static void display_queryExpression (Z_QueryExpression *qe)
1003 if (qe->which == Z_QueryExpression_term)
1005 if (qe->u.term->queryTerm)
1007 Z_Term *term = qe->u.term->queryTerm;
1008 switch (term->which)
1010 case Z_Term_general:
1011 printf (" %.*s", term->u.general->len, term->u.general->buf);
1013 case Z_Term_characterString:
1014 printf (" %s", term->u.characterString);
1016 case Z_Term_numeric:
1017 printf (" %d", *term->u.numeric);
1027 /* see if we can find USR:SearchResult-1 */
1028 static void display_searchResult (Z_OtherInformation *o)
1033 for (i = 0; i < o->num_elements; i++)
1035 if (o->list[i]->which == Z_OtherInfo_externallyDefinedInfo)
1037 Z_External *ext = o->list[i]->information.externallyDefinedInfo;
1039 if (ext->which == Z_External_searchResult1)
1042 Z_SearchInfoReport *sr = ext->u.searchResult1;
1043 printf ("SearchResult-1:");
1044 for (j = 0; j < sr->num; j++)
1046 if (!sr->elements[j]->subqueryExpression)
1048 display_queryExpression (
1049 sr->elements[j]->subqueryExpression);
1050 display_queryExpression (
1051 sr->elements[j]->subqueryInterpretation);
1052 display_queryExpression (
1053 sr->elements[j]->subqueryRecommendation);
1054 if (sr->elements[j]->subqueryCount)
1055 printf ("(%d)", *sr->elements[j]->subqueryCount);
1063 static int process_searchResponse(Z_SearchResponse *res)
1065 printf ("Received SearchResponse.\n");
1066 print_refid (res->referenceId);
1067 if (*res->searchStatus)
1068 printf("Search was a success.\n");
1070 printf("Search was a bloomin' failure.\n");
1071 printf("Number of hits: %d", *res->resultCount);
1073 printf (", setno %d", setnumber);
1075 display_searchResult (res->additionalSearchInfo);
1076 printf("records returned: %d\n",
1077 *res->numberOfRecordsReturned);
1078 setno += *res->numberOfRecordsReturned;
1080 display_records(res->records);
1084 static void print_level(int iLevel)
1087 for (i = 0; i < iLevel * 4; i++)
1091 static void print_int(int iLevel, const char *pTag, int *pInt)
1095 print_level(iLevel);
1096 printf("%s: %d\n", pTag, *pInt);
1100 static void print_string(int iLevel, const char *pTag, const char *pString)
1102 if (pString != NULL)
1104 print_level(iLevel);
1105 printf("%s: %s\n", pTag, pString);
1109 static void print_oid(int iLevel, const char *pTag, Odr_oid *pOid)
1115 print_level(iLevel);
1116 printf("%s:", pTag);
1117 for (; *pInt != -1; pInt++)
1118 printf(" %d", *pInt);
1123 static void print_referenceId(int iLevel, Z_ReferenceId *referenceId)
1125 if (referenceId != NULL)
1129 print_level(iLevel);
1130 printf("Ref Id (%d, %d): ", referenceId->len, referenceId->size);
1131 for (i = 0; i < referenceId->len; i++)
1132 printf("%c", referenceId->buf[i]);
1137 static void print_string_or_numeric(int iLevel, const char *pTag, Z_StringOrNumeric *pStringNumeric)
1139 if (pStringNumeric != NULL)
1141 switch (pStringNumeric->which)
1143 case Z_StringOrNumeric_string:
1144 print_string(iLevel, pTag, pStringNumeric->u.string);
1147 case Z_StringOrNumeric_numeric:
1148 print_int(iLevel, pTag, pStringNumeric->u.numeric);
1152 print_level(iLevel);
1153 printf("%s: valid type for Z_StringOrNumeric\n", pTag);
1159 static void print_universe_report_duplicate(int iLevel, Z_UniverseReportDuplicate *pUniverseReportDuplicate)
1161 if (pUniverseReportDuplicate != NULL)
1163 print_level(iLevel);
1164 printf("Universe Report Duplicate: \n");
1166 print_string_or_numeric(iLevel, "Hit No",
1167 pUniverseReportDuplicate->hitno);
1172 print_universe_report_hits(int iLevel,
1173 Z_UniverseReportHits *pUniverseReportHits)
1175 if (pUniverseReportHits != NULL)
1177 print_level(iLevel);
1178 printf("Universe Report Hits: \n");
1180 print_string_or_numeric(iLevel, "Database",
1181 pUniverseReportHits->database);
1182 print_string_or_numeric(iLevel, "Hits", pUniverseReportHits->hits);
1186 static void print_universe_report(int iLevel, Z_UniverseReport *pUniverseReport)
1188 if (pUniverseReport != NULL)
1190 print_level(iLevel);
1191 printf("Universe Report: \n");
1193 print_int(iLevel, "Total Hits", pUniverseReport->totalHits);
1194 switch (pUniverseReport->which)
1196 case Z_UniverseReport_databaseHits:
1197 print_universe_report_hits(iLevel, pUniverseReport->u.databaseHits);
1200 case Z_UniverseReport_duplicate:
1201 print_universe_report_duplicate(iLevel, pUniverseReport->u.duplicate);
1205 print_level(iLevel);
1206 printf("Type: %d\n", pUniverseReport->which);
1212 static void print_external(int iLevel, Z_External *pExternal)
1214 if (pExternal != NULL)
1216 print_level(iLevel);
1217 printf("External: \n");
1219 print_oid(iLevel, "Direct Reference", pExternal->direct_reference);
1220 print_int(iLevel, "InDirect Reference", pExternal->indirect_reference);
1221 print_string(iLevel, "Descriptor", pExternal->descriptor);
1222 switch (pExternal->which)
1224 case Z_External_universeReport:
1225 print_universe_report(iLevel, pExternal->u.universeReport);
1229 print_level(iLevel);
1230 printf("Type: %d\n", pExternal->which);
1236 static int process_resourceControlRequest (Z_ResourceControlRequest *req)
1238 printf ("Received ResourceControlRequest.\n");
1239 print_referenceId(1, req->referenceId);
1240 print_int(1, "Suspended Flag", req->suspendedFlag);
1241 print_int(1, "Partial Results Available", req->partialResultsAvailable);
1242 print_int(1, "Response Required", req->responseRequired);
1243 print_int(1, "Triggered Request Flag", req->triggeredRequestFlag);
1244 print_external(1, req->resourceReport);
1248 void process_ESResponse(Z_ExtendedServicesResponse *res)
1251 switch (*res->operationStatus)
1253 case Z_ExtendedServicesResponse_done:
1256 case Z_ExtendedServicesResponse_accepted:
1257 printf ("accepted\n");
1259 case Z_ExtendedServicesResponse_failure:
1260 printf ("failure\n");
1261 display_diagrecs(res->diagnostics, res->num_diagnostics);
1264 printf ("unknown\n");
1266 if ( (*res->operationStatus != Z_ExtendedServicesResponse_failure) &&
1267 (res->num_diagnostics != 0) ) {
1268 display_diagrecs(res->diagnostics, res->num_diagnostics);
1270 print_refid (res->referenceId);
1271 if (res->taskPackage &&
1272 res->taskPackage->which == Z_External_extendedService)
1274 Z_TaskPackage *taskPackage = res->taskPackage->u.extendedService;
1275 Odr_oct *id = taskPackage->targetReference;
1276 Z_External *ext = taskPackage->taskSpecificParameters;
1280 printf ("Target Reference: ");
1281 print_stringn (id->buf, id->len);
1284 if (ext->which == Z_External_update)
1286 Z_IUUpdateTaskPackage *utp = ext->u.update->u.taskPackage;
1287 if (utp && utp->targetPart)
1289 Z_IUTargetPart *targetPart = utp->targetPart;
1292 for (i = 0; i<targetPart->num_taskPackageRecords; i++)
1295 Z_IUTaskPackageRecordStructure *tpr =
1296 targetPart->taskPackageRecords[i];
1297 printf ("task package record %d\n", i+1);
1298 if (tpr->which == Z_IUTaskPackageRecordStructure_record)
1300 display_record (tpr->u.record);
1304 printf ("other type\n");
1312 const char *get_ill_element (void *clientData, const char *element)
1317 static Z_External *create_external_itemRequest()
1319 struct ill_get_ctl ctl;
1320 ILL_ItemRequest *req;
1322 int item_request_size = 0;
1323 char *item_request_buf = 0;
1327 ctl.f = get_ill_element;
1329 req = ill_get_ItemRequest(&ctl, "ill", 0);
1331 printf ("ill_get_ItemRequest failed\n");
1333 if (!ill_ItemRequest (out, &req, 0, 0))
1337 ill_ItemRequest(print, &req, 0, 0);
1340 item_request_buf = odr_getbuf (out, &item_request_size, 0);
1341 if (item_request_buf)
1342 odr_setbuf (out, item_request_buf, item_request_size, 1);
1343 printf ("Couldn't encode ItemRequest, size %d\n", item_request_size);
1350 item_request_buf = odr_getbuf (out, &item_request_size, 0);
1351 oid.proto = PROTO_GENERAL;
1352 oid.oclass = CLASS_GENERAL;
1353 oid.value = VAL_ISO_ILL_1;
1355 r = (Z_External *) odr_malloc (out, sizeof(*r));
1356 r->direct_reference = odr_oiddup(out,oid_getoidbyent(&oid));
1357 r->indirect_reference = 0;
1359 r->which = Z_External_single;
1361 r->u.single_ASN1_type = (Odr_oct *)
1362 odr_malloc (out, sizeof(*r->u.single_ASN1_type));
1363 r->u.single_ASN1_type->buf = (unsigned char *)
1364 odr_malloc (out, item_request_size);
1365 r->u.single_ASN1_type->len = item_request_size;
1366 r->u.single_ASN1_type->size = item_request_size;
1367 memcpy (r->u.single_ASN1_type->buf, item_request_buf,
1370 do_hex_dump(item_request_buf,item_request_size);
1375 static Z_External *create_external_ILL_APDU(int which)
1377 struct ill_get_ctl ctl;
1380 int ill_request_size = 0;
1381 char *ill_request_buf = 0;
1385 ctl.f = get_ill_element;
1387 ill_apdu = ill_get_APDU(&ctl, "ill", 0);
1389 if (!ill_APDU (out, &ill_apdu, 0, 0))
1393 printf ("-------------------\n");
1394 ill_APDU(print, &ill_apdu, 0, 0);
1396 printf ("-------------------\n");
1398 ill_request_buf = odr_getbuf (out, &ill_request_size, 0);
1399 if (ill_request_buf)
1400 odr_setbuf (out, ill_request_buf, ill_request_size, 1);
1401 printf ("Couldn't encode ILL-Request, size %d\n", ill_request_size);
1407 ill_request_buf = odr_getbuf (out, &ill_request_size, 0);
1409 oid.proto = PROTO_GENERAL;
1410 oid.oclass = CLASS_GENERAL;
1411 oid.value = VAL_ISO_ILL_1;
1413 r = (Z_External *) odr_malloc (out, sizeof(*r));
1414 r->direct_reference = odr_oiddup(out,oid_getoidbyent(&oid));
1415 r->indirect_reference = 0;
1417 r->which = Z_External_single;
1419 r->u.single_ASN1_type = (Odr_oct *)
1420 odr_malloc (out, sizeof(*r->u.single_ASN1_type));
1421 r->u.single_ASN1_type->buf = (unsigned char *)
1422 odr_malloc (out, ill_request_size);
1423 r->u.single_ASN1_type->len = ill_request_size;
1424 r->u.single_ASN1_type->size = ill_request_size;
1425 memcpy (r->u.single_ASN1_type->buf, ill_request_buf, ill_request_size);
1426 /* printf ("len = %d\n", ill_request_size); */
1427 /* do_hex_dump(ill_request_buf,ill_request_size); */
1428 /* printf("--- end of extenal\n"); */
1435 static Z_External *create_ItemOrderExternal(const char *type, int itemno)
1437 Z_External *r = (Z_External *) odr_malloc(out, sizeof(Z_External));
1438 oident ItemOrderRequest;
1440 ItemOrderRequest.proto = PROTO_Z3950;
1441 ItemOrderRequest.oclass = CLASS_EXTSERV;
1442 ItemOrderRequest.value = VAL_ITEMORDER;
1444 r->direct_reference = odr_oiddup(out,oid_getoidbyent(&ItemOrderRequest));
1445 r->indirect_reference = 0;
1448 r->which = Z_External_itemOrder;
1450 r->u.itemOrder = (Z_ItemOrder *) odr_malloc(out,sizeof(Z_ItemOrder));
1451 memset(r->u.itemOrder, 0, sizeof(Z_ItemOrder));
1452 r->u.itemOrder->which=Z_IOItemOrder_esRequest;
1454 r->u.itemOrder->u.esRequest = (Z_IORequest *)
1455 odr_malloc(out,sizeof(Z_IORequest));
1456 memset(r->u.itemOrder->u.esRequest, 0, sizeof(Z_IORequest));
1458 r->u.itemOrder->u.esRequest->toKeep = (Z_IOOriginPartToKeep *)
1459 odr_malloc(out,sizeof(Z_IOOriginPartToKeep));
1460 memset(r->u.itemOrder->u.esRequest->toKeep, 0, sizeof(Z_IOOriginPartToKeep));
1461 r->u.itemOrder->u.esRequest->notToKeep = (Z_IOOriginPartNotToKeep *)
1462 odr_malloc(out,sizeof(Z_IOOriginPartNotToKeep));
1463 memset(r->u.itemOrder->u.esRequest->notToKeep, 0, sizeof(Z_IOOriginPartNotToKeep));
1465 r->u.itemOrder->u.esRequest->toKeep->supplDescription = NULL;
1466 r->u.itemOrder->u.esRequest->toKeep->contact = NULL;
1467 r->u.itemOrder->u.esRequest->toKeep->addlBilling = NULL;
1469 r->u.itemOrder->u.esRequest->notToKeep->resultSetItem =
1470 (Z_IOResultSetItem *) odr_malloc(out, sizeof(Z_IOResultSetItem));
1471 memset(r->u.itemOrder->u.esRequest->notToKeep->resultSetItem, 0, sizeof(Z_IOResultSetItem));
1472 r->u.itemOrder->u.esRequest->notToKeep->resultSetItem->resultSetId = "1";
1474 r->u.itemOrder->u.esRequest->notToKeep->resultSetItem->item =
1475 (int *) odr_malloc(out, sizeof(int));
1476 *r->u.itemOrder->u.esRequest->notToKeep->resultSetItem->item = itemno;
1478 if (!strcmp (type, "item") || !strcmp(type, "2"))
1480 printf ("using item-request\n");
1481 r->u.itemOrder->u.esRequest->notToKeep->itemRequest =
1482 create_external_itemRequest();
1484 else if (!strcmp(type, "ill") || !strcmp(type, "1"))
1486 printf ("using ILL-request\n");
1487 r->u.itemOrder->u.esRequest->notToKeep->itemRequest =
1488 create_external_ILL_APDU(ILL_APDU_ILL_Request);
1490 else if (!strcmp(type, "xml") || !strcmp(type, "3"))
1492 const char *xml_buf =
1494 " <type>request</type>\n"
1495 " <libraryNo>000200</libraryNo>\n"
1496 " <borrowerTicketNo> 1212 </borrowerTicketNo>\n"
1498 r->u.itemOrder->u.esRequest->notToKeep->itemRequest =
1499 z_ext_record (out, VAL_TEXT_XML, xml_buf, strlen(xml_buf));
1502 r->u.itemOrder->u.esRequest->notToKeep->itemRequest = 0;
1507 static int send_itemorder(const char *type, int itemno)
1509 Z_APDU *apdu = zget_APDU(out, Z_APDU_extendedServicesRequest);
1510 Z_ExtendedServicesRequest *req = apdu->u.extendedServicesRequest;
1511 oident ItemOrderRequest;
1513 ItemOrderRequest.proto = PROTO_Z3950;
1514 ItemOrderRequest.oclass = CLASS_EXTSERV;
1515 ItemOrderRequest.value = VAL_ITEMORDER;
1516 req->packageType = odr_oiddup(out,oid_getoidbyent(&ItemOrderRequest));
1517 req->packageName = esPackageName;
1519 req->taskSpecificParameters = create_ItemOrderExternal(type, itemno);
1525 static int cmd_update(char *arg)
1527 Z_APDU *apdu = zget_APDU(out, Z_APDU_extendedServicesRequest );
1528 Z_ExtendedServicesRequest *req = apdu->u.extendedServicesRequest;
1531 Z_IUOriginPartToKeep *toKeep;
1532 Z_IUSuppliedRecords *notToKeep;
1534 printf ("Update request\n");
1539 update_oid.proto = PROTO_Z3950;
1540 update_oid.oclass = CLASS_EXTSERV;
1541 update_oid.value = VAL_DBUPDATE;
1542 oid_ent_to_oid (&update_oid, oid);
1543 req->packageType = odr_oiddup(out,oid);
1544 req->packageName = esPackageName;
1546 req->referenceId = set_refid (out);
1548 r = req->taskSpecificParameters = (Z_External *)
1549 odr_malloc (out, sizeof(*r));
1550 r->direct_reference = odr_oiddup(out,oid);
1551 r->indirect_reference = 0;
1553 r->which = Z_External_update;
1554 r->u.update = (Z_IUUpdate *) odr_malloc(out, sizeof(*r->u.update));
1555 r->u.update->which = Z_IUUpdate_esRequest;
1556 r->u.update->u.esRequest = (Z_IUUpdateEsRequest *)
1557 odr_malloc(out, sizeof(*r->u.update->u.esRequest));
1558 toKeep = r->u.update->u.esRequest->toKeep = (Z_IUOriginPartToKeep *)
1559 odr_malloc(out, sizeof(*r->u.update->u.esRequest->toKeep));
1560 toKeep->databaseName = databaseNames[0];
1562 toKeep->elementSetName = 0;
1563 toKeep->actionQualifier = 0;
1564 toKeep->action = (int *) odr_malloc(out, sizeof(*toKeep->action));
1565 *toKeep->action = Z_IUOriginPartToKeep_recordInsert;
1567 notToKeep = r->u.update->u.esRequest->notToKeep = (Z_IUSuppliedRecords *)
1568 odr_malloc(out, sizeof(*r->u.update->u.esRequest->notToKeep));
1570 notToKeep->elements = (Z_IUSuppliedRecords_elem **)
1571 odr_malloc(out, sizeof(*notToKeep->elements));
1572 notToKeep->elements[0] = (Z_IUSuppliedRecords_elem *)
1573 odr_malloc(out, sizeof(**notToKeep->elements));
1574 notToKeep->elements[0]->u.number = 0;
1575 notToKeep->elements[0]->supplementalId = 0;
1576 notToKeep->elements[0]->correlationInfo = 0;
1577 notToKeep->elements[0]->record = record_last;
1584 static int cmd_itemorder(char *arg)
1589 if (sscanf (arg, "%10s %d", type, &itemno) != 2)
1592 printf("Item order request\n");
1594 send_itemorder(type, itemno);
1598 static int cmd_find(char *arg)
1602 printf("Find what?\n");
1610 printf("Not connected yet\n");
1614 if (!send_searchRequest(arg))
1619 static int cmd_delete(char *arg)
1623 printf("Not connected yet\n");
1626 if (!send_deleteResultSetRequest(arg))
1631 static int cmd_ssub(char *arg)
1633 if (!(smallSetUpperBound = atoi(arg)))
1638 static int cmd_lslb(char *arg)
1640 if (!(largeSetLowerBound = atoi(arg)))
1645 static int cmd_mspn(char *arg)
1647 if (!(mediumSetPresentNumber = atoi(arg)))
1652 static int cmd_status(char *arg)
1654 printf("smallSetUpperBound: %d\n", smallSetUpperBound);
1655 printf("largeSetLowerBound: %d\n", largeSetLowerBound);
1656 printf("mediumSetPresentNumber: %d\n", mediumSetPresentNumber);
1660 static int cmd_setnames(char *arg)
1662 if (*arg == '1') /* enable ? */
1664 else if (*arg == '0') /* disable ? */
1666 else if (setnumber < 0) /* no args, toggle .. */
1672 printf("Set numbering enabled.\n");
1674 printf("Set numbering disabled.\n");
1678 /* PRESENT SERVICE ----------------------------- */
1680 static int send_presentRequest(char *arg)
1682 Z_APDU *apdu = zget_APDU(out, Z_APDU_presentRequest);
1683 Z_PresentRequest *req = apdu->u.presentRequest;
1684 Z_RecordComposition compo;
1689 char setstring[100];
1691 req->referenceId = set_refid (out);
1692 if ((p = strchr(arg, '+')))
1699 if (p && (p=strchr(p+1, '+')))
1701 strcpy (setstring, p+1);
1702 req->resultSetId = setstring;
1704 else if (setnumber >= 0)
1706 sprintf(setstring, "%d", setnumber);
1707 req->resultSetId = setstring;
1709 req->resultSetStartPoint = &setno;
1710 req->numberOfRecordsRequested = &nos;
1711 prefsyn.proto = protocol;
1712 prefsyn.oclass = CLASS_RECSYN;
1713 prefsyn.value = recordsyntax;
1714 req->preferredRecordSyntax =
1715 odr_oiddup (out, oid_ent_to_oid(&prefsyn, oid));
1717 if (schema != VAL_NONE)
1721 prefschema.proto = protocol;
1722 prefschema.oclass = CLASS_SCHEMA;
1723 prefschema.value = schema;
1725 req->recordComposition = &compo;
1726 compo.which = Z_RecordComp_complex;
1727 compo.u.complex = (Z_CompSpec *)
1728 odr_malloc(out, sizeof(*compo.u.complex));
1729 compo.u.complex->selectAlternativeSyntax = (bool_t *)
1730 odr_malloc(out, sizeof(bool_t));
1731 *compo.u.complex->selectAlternativeSyntax = 0;
1733 compo.u.complex->generic = (Z_Specification *)
1734 odr_malloc(out, sizeof(*compo.u.complex->generic));
1735 compo.u.complex->generic->schema = (Odr_oid *)
1736 odr_oiddup(out, oid_ent_to_oid(&prefschema, oid));
1737 if (!compo.u.complex->generic->schema)
1739 /* OID wasn't a schema! Try record syntax instead. */
1740 prefschema.oclass = CLASS_RECSYN;
1741 compo.u.complex->generic->schema = (Odr_oid *)
1742 odr_oiddup(out, oid_ent_to_oid(&prefschema, oid));
1744 if (!elementSetNames)
1745 compo.u.complex->generic->elementSpec = 0;
1748 compo.u.complex->generic->elementSpec = (Z_ElementSpec *)
1749 odr_malloc(out, sizeof(Z_ElementSpec));
1750 compo.u.complex->generic->elementSpec->which =
1751 Z_ElementSpec_elementSetName;
1752 compo.u.complex->generic->elementSpec->u.elementSetName =
1753 elementSetNames->u.generic;
1755 compo.u.complex->num_dbSpecific = 0;
1756 compo.u.complex->dbSpecific = 0;
1757 compo.u.complex->num_recordSyntax = 0;
1758 compo.u.complex->recordSyntax = 0;
1760 else if (elementSetNames)
1762 req->recordComposition = &compo;
1763 compo.which = Z_RecordComp_simple;
1764 compo.u.simple = elementSetNames;
1767 printf("Sent presentRequest (%d+%d).\n", setno, nos);
1771 static void close_session (void)
1777 nmem_destroy (session_mem);
1783 void process_close(Z_Close *req)
1785 Z_APDU *apdu = zget_APDU(out, Z_APDU_close);
1786 Z_Close *res = apdu->u.close;
1788 static char *reasons[] =
1793 "cost limit reached",
1795 "security violation",
1802 printf("Reason: %s, message: %s\n", reasons[*req->closeReason],
1803 req->diagnosticInformation ? req->diagnosticInformation : "NULL");
1808 *res->closeReason = Z_Close_finished;
1810 printf("Sent response.\n");
1815 static int cmd_show(char *arg)
1819 printf("Not connected yet\n");
1822 if (!send_presentRequest(arg))
1827 int cmd_quit(char *arg)
1829 printf("See you later, alligator.\n");
1835 int cmd_cancel(char *arg)
1837 Z_APDU *apdu = zget_APDU(out, Z_APDU_triggerResourceControlRequest);
1838 Z_TriggerResourceControlRequest *req =
1839 apdu->u.triggerResourceControlRequest;
1844 printf("Session not initialized yet\n");
1847 if (!ODR_MASK_GET(session->options, Z_Options_triggerResourceCtrl))
1849 printf("Target doesn't support cancel (trigger resource ctrl)\n");
1852 *req->requestedAction = Z_TriggerResourceCtrl_cancel;
1853 req->resultSetWanted = &rfalse;
1856 printf("Sent cancel request\n");
1860 int send_scanrequest(const char *query, int pp, int num, const char *term)
1862 Z_APDU *apdu = zget_APDU(out, Z_APDU_scanRequest);
1863 Z_ScanRequest *req = apdu->u.scanRequest;
1866 if (queryType == QueryType_CCL2RPN)
1870 struct ccl_rpn_node *rpn;
1872 rpn = ccl_find_str (bibset, query, &error, &pos);
1875 printf("CCL ERROR: %s\n", ccl_err_msg(error));
1878 bib1.proto = PROTO_Z3950;
1879 bib1.oclass = CLASS_ATTSET;
1880 bib1.value = VAL_BIB1;
1881 req->attributeSet = oid_ent_to_oid (&bib1, oid);
1882 if (!(req->termListAndStartPoint = ccl_scan_query (out, rpn)))
1884 printf("Couldn't convert CCL to Scan term\n");
1887 ccl_rpn_delete (rpn);
1891 YAZ_PQF_Parser pqf_parser = yaz_pqf_create ();
1893 if (!(req->termListAndStartPoint =
1894 yaz_pqf_scan(pqf_parser, out, &req->attributeSet, query)))
1896 const char *pqf_msg;
1898 int code = yaz_pqf_error (pqf_parser, &pqf_msg, &off);
1899 printf("%*s^\n", off+7, "");
1900 printf("Prefix query error: %s (code %d)\n", pqf_msg, code);
1901 yaz_pqf_destroy (pqf_parser);
1904 yaz_pqf_destroy (pqf_parser);
1908 if (req->termListAndStartPoint->term &&
1909 req->termListAndStartPoint->term->which == Z_Term_general &&
1910 req->termListAndStartPoint->term->u.general)
1912 req->termListAndStartPoint->term->u.general->buf =
1913 (unsigned char *) odr_strdup(out, term);
1914 req->termListAndStartPoint->term->u.general->len =
1915 req->termListAndStartPoint->term->u.general->size =
1919 req->referenceId = set_refid (out);
1920 req->num_databaseNames = num_databaseNames;
1921 req->databaseNames = databaseNames;
1922 req->numberOfTermsRequested = #
1923 req->preferredPositionInResponse = &pp;
1928 int send_sortrequest(char *arg, int newset)
1930 Z_APDU *apdu = zget_APDU(out, Z_APDU_sortRequest);
1931 Z_SortRequest *req = apdu->u.sortRequest;
1932 Z_SortKeySpecList *sksl = (Z_SortKeySpecList *)
1933 odr_malloc (out, sizeof(*sksl));
1937 sprintf (setstring, "%d", setnumber);
1939 sprintf (setstring, "default");
1941 req->referenceId = set_refid (out);
1943 req->num_inputResultSetNames = 1;
1944 req->inputResultSetNames = (Z_InternationalString **)
1945 odr_malloc (out, sizeof(*req->inputResultSetNames));
1946 req->inputResultSetNames[0] = odr_strdup (out, setstring);
1948 if (newset && setnumber >= 0)
1949 sprintf (setstring, "%d", ++setnumber);
1951 req->sortedResultSetName = odr_strdup (out, setstring);
1953 req->sortSequence = yaz_sort_spec (out, arg);
1954 if (!req->sortSequence)
1956 printf ("Missing sort specifications\n");
1963 void display_term(Z_TermInfo *t)
1965 if (t->term->which == Z_Term_general)
1967 printf("%.*s", t->term->u.general->len, t->term->u.general->buf);
1968 sprintf(last_scan_line, "%.*s", t->term->u.general->len,
1969 t->term->u.general->buf);
1972 printf("Term (not general)");
1973 if (t->globalOccurrences)
1974 printf (" (%d)\n", *t->globalOccurrences);
1979 void process_scanResponse(Z_ScanResponse *res)
1982 Z_Entry **entries = NULL;
1983 int num_entries = 0;
1985 printf("Received ScanResponse\n");
1986 print_refid (res->referenceId);
1987 printf("%d entries", *res->numberOfEntriesReturned);
1988 if (res->positionOfTerm)
1989 printf (", position=%d", *res->positionOfTerm);
1991 if (*res->scanStatus != Z_Scan_success)
1992 printf("Scan returned code %d\n", *res->scanStatus);
1995 if ((entries = res->entries->entries))
1996 num_entries = res->entries->num_entries;
1997 for (i = 0; i < num_entries; i++)
1999 int pos_term = res->positionOfTerm ? *res->positionOfTerm : -1;
2000 if (entries[i]->which == Z_Entry_termInfo)
2002 printf("%c ", i + 1 == pos_term ? '*' : ' ');
2003 display_term(entries[i]->u.termInfo);
2006 display_diagrecs(&entries[i]->u.surrogateDiagnostic, 1);
2008 if (res->entries->nonsurrogateDiagnostics)
2009 display_diagrecs (res->entries->nonsurrogateDiagnostics,
2010 res->entries->num_nonsurrogateDiagnostics);
2013 void process_sortResponse(Z_SortResponse *res)
2015 printf("Received SortResponse: status=");
2016 switch (*res->sortStatus)
2018 case Z_SortStatus_success:
2019 printf ("success"); break;
2020 case Z_SortStatus_partial_1:
2021 printf ("partial"); break;
2022 case Z_SortStatus_failure:
2023 printf ("failure"); break;
2025 printf ("unknown (%d)", *res->sortStatus);
2028 print_refid (res->referenceId);
2029 if (res->diagnostics)
2030 display_diagrecs(res->diagnostics,
2031 res->num_diagnostics);
2034 void process_deleteResultSetResponse (Z_DeleteResultSetResponse *res)
2036 printf("Got deleteResultSetResponse status=%d\n",
2037 *res->deleteOperationStatus);
2038 if (res->deleteListStatuses)
2041 for (i = 0; i < res->deleteListStatuses->num; i++)
2043 printf ("%s status=%d\n", res->deleteListStatuses->elements[i]->id,
2044 *res->deleteListStatuses->elements[i]->status);
2049 int cmd_sort_generic(char *arg, int newset)
2053 printf("Session not initialized yet\n");
2056 if (!ODR_MASK_GET(session->options, Z_Options_sort))
2058 printf("Target doesn't support sort\n");
2063 if (send_sortrequest(arg, newset) < 0)
2070 int cmd_sort(char *arg)
2072 return cmd_sort_generic (arg, 0);
2075 int cmd_sort_newset (char *arg)
2077 return cmd_sort_generic (arg, 1);
2080 int cmd_scan(char *arg)
2087 printf("Session not initialized yet\n");
2091 if (!ODR_MASK_GET(session->options, Z_Options_scan))
2093 printf("Target doesn't support scan\n");
2098 strcpy (last_scan_query, arg);
2099 if (send_scanrequest(arg, 1, 20, 0) < 0)
2104 if (send_scanrequest(last_scan_query, 1, 20, last_scan_line) < 0)
2110 int cmd_schema(char *arg)
2117 schema = oid_getvalbyname (arg);
2118 if (schema == VAL_NONE)
2120 printf ("unknown schema\n");
2126 int cmd_format(char *arg)
2130 printf("Usage: format <recordsyntax>\n");
2133 recordsyntax = oid_getvalbyname (arg);
2134 if (recordsyntax == VAL_NONE)
2136 printf ("unknown record syntax\n");
2142 int cmd_elements(char *arg)
2144 static Z_ElementSetNames esn;
2145 static char what[100];
2149 elementSetNames = 0;
2153 esn.which = Z_ElementSetNames_generic;
2154 esn.u.generic = what;
2155 elementSetNames = &esn;
2159 int cmd_attributeset(char *arg)
2165 printf("Usage: attributeset <setname>\n");
2168 sscanf(arg, "%s", what);
2169 if (p_query_attset (what))
2171 printf("Unknown attribute set name\n");
2177 int cmd_querytype (char *arg)
2179 if (!strcmp (arg, "ccl"))
2180 queryType = QueryType_CCL;
2181 else if (!strcmp (arg, "prefix") || !strcmp(arg, "rpn"))
2182 queryType = QueryType_Prefix;
2183 else if (!strcmp (arg, "ccl2rpn") || !strcmp (arg, "cclrpn"))
2184 queryType = QueryType_CCL2RPN;
2187 printf ("Querytype must be one of:\n");
2188 printf (" prefix - Prefix query\n");
2189 printf (" ccl - CCL query\n");
2190 printf (" ccl2rpn - CCL query converted to RPN\n");
2196 int cmd_refid (char *arg)
2202 refid = (char *) xmalloc (strlen(arg)+1);
2203 strcpy (refid, arg);
2208 int cmd_close(char *arg)
2215 apdu = zget_APDU(out, Z_APDU_close);
2216 req = apdu->u.close;
2217 *req->closeReason = Z_Close_finished;
2219 printf("Sent close request.\n");
2224 int cmd_packagename(char* arg)
2226 xfree (esPackageName);
2227 esPackageName = NULL;
2230 esPackageName = (char *) xmalloc (strlen(arg)+1);
2231 strcpy (esPackageName, arg);
2236 int cmd_proxy(char* arg)
2247 yazProxy = (char *) xmalloc (strlen(arg)+1);
2248 strcpy (yazProxy, arg);
2253 int cmd_charset(char* arg)
2255 char l1[30], l2[30];
2258 if (sscanf(arg, "%29s %29s", l1, l2) < 1)
2260 printf("Current character set is `%s'\n", (yazCharset) ? yazCharset:NULL);
2266 yazCharset = xstrdup(l1);
2269 odr_set_charset (out, l1, l2);
2270 odr_set_charset (in, l2, l1);
2275 int cmd_lang(char* arg)
2278 printf("Current language is `%s'\n", (yazLang)?yazLang:NULL);
2285 yazLang = (char *) xmalloc (strlen(arg)+1);
2286 strcpy (yazLang, arg);
2291 int cmd_source(char* arg)
2293 /* first should open the file and read one line at a time.. */
2295 char line[1024], *cp;
2298 char* args_end=(arg)+strlen(arg)-1;
2299 while(isspace(*args_end))
2304 REMOVE_TAILING_BLANKS(arg);
2307 fprintf(stderr,"Error in source command use a filename\n");
2311 includeFile = fopen (arg, "r");
2314 fprintf(stderr,"Unable to open file %s for reading\n",arg);
2318 while(!feof(includeFile)) {
2319 memset(line,0,sizeof(line));
2320 fgets(line,sizeof(line),includeFile);
2322 if(strlen(line) < 2) continue;
2323 if(line[0] == '#') continue;
2325 if ((cp = strrchr (line, '\n')))
2328 process_cmd_line(line);
2331 if(fclose(includeFile)<0) {
2332 perror("unable to close include file");
2338 int cmd_subshell(char* args)
2343 system(getenv("SHELL"));
2349 int cmd_set_apdufile(char* arg)
2351 REMOVE_TAILING_BLANKS(arg);
2353 if(apdu_file && apdu_file != stderr) { /* don't close stdout*/
2354 perror("unable to close apdu log file");
2362 if(!strcmp(arg,"-"))
2365 apdu_file=fopen(arg, "a");
2368 perror("unable to open apdu log file no apdu log loaded");
2370 odr_setprint(print, apdu_file);
2376 int cmd_set_cclfile(char* arg)
2380 REMOVE_TAILING_BLANKS(arg);
2382 bibset = ccl_qual_mk ();
2383 inf = fopen (arg, "r");
2386 ccl_qual_file (bibset, inf);
2390 strcpy(ccl_fields,arg);
2395 int cmd_set_auto_reconnect(char* arg)
2397 REMOVE_TAILING_BLANKS(arg);
2399 if(strlen(arg)==0) {
2400 auto_reconnect = ! auto_reconnect;
2401 } else if(strcmp(arg,"on")==0) {
2403 } else if(strcmp(arg,"off")==0) {
2406 printf("Error use on or off\n");
2411 printf("Set auto reconnect enabled.\n");
2413 printf("Set auto reconnect disabled.\n");
2418 int cmd_set_marcdump(char* arg)
2420 if(marcdump && marcdump != stderr) { /* don't close stdout*/
2421 perror("unable to close apdu log file");
2429 if(!strcmp(arg,"-"))
2432 marcdump=fopen(arg, "a");
2435 perror("unable to open apdu marcdump file no marcdump done\n");
2441 int cmd_set_proxy(char* arg) {
2442 if(yazProxy) free(yazProxy);
2445 if(strlen(arg) > 1) {
2446 yazProxy=strdup(arg);
2452 this command takes 3 arge {name class oid}
2454 int cmd_register_oid(char* args) {
2459 {"appctx",CLASS_APPCTX},
2460 {"absyn",CLASS_ABSYN},
2461 {"attset",CLASS_ATTSET},
2462 {"transyn",CLASS_TRANSYN},
2463 {"diagset",CLASS_DIAGSET},
2464 {"recsyn",CLASS_RECSYN},
2465 {"resform",CLASS_RESFORM},
2466 {"accform",CLASS_ACCFORM},
2467 {"extserv",CLASS_EXTSERV},
2468 {"userinfo",CLASS_USERINFO},
2469 {"elemspec",CLASS_ELEMSPEC},
2470 {"varset",CLASS_VARSET},
2471 {"schema",CLASS_SCHEMA},
2472 {"tagset",CLASS_TAGSET},
2473 {"general",CLASS_GENERAL},
2476 char oname_str[101], oclass_str[101], oid_str[101];
2479 oid_class oidclass = CLASS_GENERAL;
2480 int val = 0, oid[OID_SIZE];
2481 struct oident * new_oident=NULL;
2483 if (sscanf (args, "%100[^ ] %100[^ ] %100s",
2484 oname_str,oclass_str, oid_str) < 1) {
2485 printf("Error in regristrate command \n");
2489 for (i = 0; oid_classes[i].className; i++) {
2490 if (!strcmp(oid_classes[i].className, oclass_str))
2492 oidclass=oid_classes[i].oclass;
2497 if(!(oid_classes[i].className)) {
2498 printf("Unknonwn oid class %s\n",oclass_str);
2506 while (isdigit (*name))
2508 val = val*10 + (*name - '0');
2521 new_oident=oid_addent (oid,PROTO_GENERAL,oidclass,oname_str,VAL_DYNAMIC);
2522 if(strcmp(new_oident->desc,oname_str)) {
2523 fprintf(stderr,"oid is already named as %s, regristration faild\n",
2529 int cmd_push_command(char* arg)
2531 #if HAVE_READLINE_HISTORY_H
2535 fprintf(stderr,"Not compiled with the readline/history module\n");
2540 void source_rcfile()
2542 /* Look for a $HOME/.yazclientrc and source it if it exists */
2543 struct stat statbuf;
2545 char* homedir=getenv("HOME");
2547 if(!homedir) return;
2549 sprintf(buffer,"%s/.yazclientrc",homedir);
2551 if(stat(buffer,&statbuf)==0) {
2555 if(stat(".yazclientrc",&statbuf)==0) {
2556 cmd_source(".yazclientrc");
2561 static void initialize(void)
2566 if (!(out = odr_createmem(ODR_ENCODE)) ||
2567 !(in = odr_createmem(ODR_DECODE)) ||
2568 !(print = odr_createmem(ODR_PRINT)))
2570 fprintf(stderr, "failed to allocate ODR streams\n");
2575 setvbuf(stdout, 0, _IONBF, 0);
2577 odr_setprint(print, apdu_file);
2579 bibset = ccl_qual_mk ();
2580 inf = fopen (ccl_fields, "r");
2583 ccl_qual_file (bibset, inf);
2586 cmd_base("Default");
2588 #if HAVE_READLINE_READLINE_H
2589 rl_attempted_completion_function = (CPPFunction*)readline_completer;
2593 for(i=0; i<maxOtherInfosSupported; ++i) {
2594 extraOtherInfos[i].oidval = -1;
2601 #if HAVE_GETTIMEOFDAY
2602 struct timeval tv_start, tv_end;
2605 void wait_and_handle_responce()
2610 int netbufferlen = 0;
2618 if ((res = cs_get(conn, &netbuffer, &netbufferlen)) < 0)
2620 printf("Target closed connection\n");
2626 printf("Target closed connection.\n");
2630 odr_reset(in); /* release APDU from last round */
2632 odr_setbuf(in, netbuffer, res, 0);
2633 if (!z_APDU(in, &apdu, 0, 0))
2635 odr_perror(in, "Decoding incoming APDU");
2636 fprintf(stderr, "[Near %d]\n", odr_offset(in));
2637 fprintf(stderr, "Packet dump:\n---------\n");
2638 odr_dumpBER(stderr, netbuffer, res);
2639 fprintf(stderr, "---------\n");
2641 z_APDU(print, &apdu, 0, 0);
2645 if (apdu_file && !z_APDU(print, &apdu, 0, 0))
2647 odr_perror(print, "Failed to print incoming APDU");
2653 case Z_APDU_initResponse:
2654 process_initResponse(apdu->u.initResponse);
2656 case Z_APDU_searchResponse:
2657 process_searchResponse(apdu->u.searchResponse);
2659 case Z_APDU_scanResponse:
2660 process_scanResponse(apdu->u.scanResponse);
2662 case Z_APDU_presentResponse:
2663 print_refid (apdu->u.presentResponse->referenceId);
2665 *apdu->u.presentResponse->numberOfRecordsReturned;
2666 if (apdu->u.presentResponse->records)
2667 display_records(apdu->u.presentResponse->records);
2669 printf("No records.\n");
2670 printf ("nextResultSetPosition = %d\n",
2671 *apdu->u.presentResponse->nextResultSetPosition);
2673 case Z_APDU_sortResponse:
2674 process_sortResponse(apdu->u.sortResponse);
2676 case Z_APDU_extendedServicesResponse:
2677 printf("Got extended services response\n");
2678 process_ESResponse(apdu->u.extendedServicesResponse);
2681 printf("Target has closed the association.\n");
2682 process_close(apdu->u.close);
2684 case Z_APDU_resourceControlRequest:
2685 process_resourceControlRequest
2686 (apdu->u.resourceControlRequest);
2688 case Z_APDU_deleteResultSetResponse:
2689 process_deleteResultSetResponse(apdu->u.
2690 deleteResultSetResponse);
2693 printf("Received unknown APDU type (%d).\n",
2698 while (conn && cs_more(conn));
2699 #if HAVE_GETTIMEOFDAY
2700 gettimeofday (&tv_end, 0);
2702 printf ("S/U S/U=%ld/%ld %ld/%ld",
2703 (long) tv_start.tv_sec,
2704 (long) tv_start.tv_usec,
2705 (long) tv_end.tv_sec,
2706 (long) tv_end.tv_usec);
2708 printf ("Elapsed: %.6f\n",
2709 (double) tv_end.tv_usec / 1e6 + tv_end.tv_sec -
2710 ((double) tv_start.tv_usec / 1e6 + tv_start.tv_sec));
2717 int cmd_cclparse(char* arg)
2720 struct ccl_rpn_node *rpn=NULL;
2723 rpn = ccl_find_str (bibset, arg, &error, &pos);
2726 printf ("%*s^ - ", 3+strlen(last_cmd)+1+pos, " ");
2727 printf ("%s\n", ccl_err_msg (error));
2733 ccl_pr_tree(rpn, stdout);
2737 ccl_rpn_delete(rpn);
2745 int cmd_set_otherinfo(char* args)
2747 char oid[101], otherinfoString[101];
2752 sscan_res = sscanf (args, "%d %100[^ ] %100s", &otherinfoNo, oid, otherinfoString);
2754 /* reset this otherinfo */
2755 if(otherinfoNo>=maxOtherInfosSupported) {
2756 printf("Error otherinfo index to large (%d>%d)\n",otherinfoNo,maxOtherInfosSupported);
2758 extraOtherInfos[otherinfoNo].oidval = -1;
2759 if(extraOtherInfos[otherinfoNo].value) free(extraOtherInfos[otherinfoNo].value);
2763 printf("Error in set_otherinfo command \n");
2767 if(otherinfoNo>=maxOtherInfosSupported) {
2768 printf("Error otherinfo index to large (%d>%d)\n",otherinfoNo,maxOtherInfosSupported);
2772 oidval = oid_getvalbyname (oid);
2774 printf("Error in set_otherinfo command unknown oid %s \n",oid);
2777 extraOtherInfos[otherinfoNo].oidval = oidval;
2778 if(extraOtherInfos[otherinfoNo].value) free(extraOtherInfos[otherinfoNo].value);
2779 extraOtherInfos[otherinfoNo].value = strdup(otherinfoString);
2784 int cmd_list_otherinfo(char* args)
2788 if(strlen(args)>0) {
2790 if( i >= maxOtherInfosSupported ) {
2791 printf("Error otherinfo index to large (%d>%d)\n",i,maxOtherInfosSupported);
2795 if(extraOtherInfos[i].oidval != -1)
2796 printf(" otherinfo %d %s %s\n",i,yaz_z3950_oid_value_to_str(extraOtherInfos[i].oidval,CLASS_RECSYN), extraOtherInfos[i].value);
2799 for(i=0; i<maxOtherInfosSupported; ++i) {
2800 if(extraOtherInfos[i].oidval != -1)
2801 printf(" otherinfo %d %s %s\n",i,yaz_z3950_oid_value_to_str(extraOtherInfos[i].oidval,CLASS_RECSYN), extraOtherInfos[i].value);
2809 int cmd_list_all(char* args) {
2812 /* connection options */
2814 printf("Connected to : %s\n",last_open_command);
2816 if(last_open_command)
2817 printf("Not connected to : %s\n",last_open_command);
2819 printf("Not connected : \n");
2822 if(yazProxy) printf("using proxy : %s\n",yazProxy);
2824 printf("auto_reconnect : %s\n",auto_reconnect?"on":"off");
2827 printf("Authentication : none\n");
2829 switch(auth->which) {
2830 case Z_IdAuthentication_idPass:
2831 printf("Authentication : IdPass\n");
2832 printf(" Login User : %s\n",auth->u.idPass->userId?auth->u.idPass->userId:"");
2833 printf(" Login Group : %s\n",auth->u.idPass->groupId?auth->u.idPass->groupId:"");
2834 printf(" Password : %s\n",auth->u.idPass->password?auth->u.idPass->password:"");
2836 case Z_IdAuthentication_open:
2837 printf("Authentication : psOpen\n");
2838 printf(" Open string : %s\n",auth->u.open);
2841 printf("Authentication : Unknown\n");
2844 if ( yazCharset ) printf("Character set : `%s'\n", (yazCharset) ? yazCharset:NULL);
2848 for (i = 0; i<num_databaseNames; i++) printf("%s ",databaseNames[i]);
2852 printf("CCL file : %s\n",ccl_fields);
2853 printf("Query type : %s\n",query_type_as_string(queryType));
2855 printf("Named Result Sets : %s\n",setnumber==-1?"off":"on");
2857 /* piggy back options */
2858 printf("ssub/lslb/mspn : %d/%d/%d\n",smallSetUpperBound,largeSetLowerBound,mediumSetPresentNumber);
2860 /* print present related options */
2861 printf("Format : %s\n",yaz_z3950_oid_value_to_str(recordsyntax,CLASS_RECSYN));
2862 printf("Schema : %s\n",yaz_z3950_oid_value_to_str(schema,CLASS_SCHEMA));
2863 printf("Elements : %s\n",elementSetNames?elementSetNames->u.generic:"");
2865 /* loging options */
2866 printf("APDU log : %s\n",apdu_file?"on":"off");
2867 printf("Record log : %s\n",marcdump?"on":"off");
2870 printf("Other Info: \n");
2871 cmd_list_otherinfo("");
2876 int cmd_clear_otherinfo(char* args)
2878 if(strlen(args)>0) {
2880 otherinfoNo = atoi(args);
2881 if( otherinfoNo >= maxOtherInfosSupported ) {
2882 printf("Error otherinfo index to large (%d>%d)\n",otherinfoNo,maxOtherInfosSupported);
2886 if(extraOtherInfos[otherinfoNo].oidval != -1) {
2887 /* only clear if set. */
2888 extraOtherInfos[otherinfoNo].oidval=-1;
2889 free(extraOtherInfos[otherinfoNo].value);
2894 for(i=0; i<maxOtherInfosSupported; ++i) {
2895 if (extraOtherInfos[i].oidval!=-1 ) {
2896 extraOtherInfos[i].oidval=-1;
2897 free(extraOtherInfos[i].value);
2904 static int cmd_help (char *line);
2906 typedef char *(*completerFunctionType)(const char *text, int state);
2910 int (*fun)(char *arg);
2912 completerFunctionType rl_completerfunction;
2913 int complete_filenames;
2914 char **local_tabcompletes;
2916 {"open", cmd_open, "('tcp'|'ssl')':<host>[':'<port>][/<db>]",NULL,0,NULL},
2917 {"quit", cmd_quit, "",NULL,0,NULL},
2918 {"find", cmd_find, "<query>",NULL,0,NULL},
2919 {"delete", cmd_delete, "<setname>",NULL,0,NULL},
2920 {"base", cmd_base, "<base-name>",NULL,0,NULL},
2921 {"show", cmd_show, "<rec#>['+'<#recs>['+'<setname>]]",NULL,0,NULL},
2922 {"scan", cmd_scan, "<term>",NULL,0,NULL},
2923 {"sort", cmd_sort, "<sortkey> <flag> <sortkey> <flag> ...",NULL,0,NULL},
2924 {"sort+", cmd_sort_newset, "<sortkey> <flag> <sortkey> <flag> ...",NULL,0,NULL},
2925 {"authentication", cmd_authentication, "<acctstring>",NULL,0,NULL},
2926 {"lslb", cmd_lslb, "<largeSetLowerBound>",NULL,0,NULL},
2927 {"ssub", cmd_ssub, "<smallSetUpperBound>",NULL,0,NULL},
2928 {"mspn", cmd_mspn, "<mediumSetPresentNumber>",NULL,0,NULL},
2929 {"status", cmd_status, "",NULL,0,NULL},
2930 {"setnames", cmd_setnames, "",NULL,0,NULL},
2931 {"cancel", cmd_cancel, "",NULL,0,NULL},
2932 {"format", cmd_format, "<recordsyntax>",complete_format,0,NULL},
2933 {"schema", cmd_schema, "<schema>",complete_schema,0,NULL},
2934 {"elements", cmd_elements, "<elementSetName>",NULL,0,NULL},
2935 {"close", cmd_close, "",NULL,0,NULL},
2936 {"attributeset", cmd_attributeset, "<attrset>",complete_attributeset,0,NULL},
2937 {"querytype", cmd_querytype, "<type>",complete_querytype,0,NULL},
2938 {"refid", cmd_refid, "<id>",NULL,0,NULL},
2939 {"itemorder", cmd_itemorder, "ill|item <itemno>",NULL,0,NULL},
2940 {"update", cmd_update, "<item>",NULL,0,NULL},
2941 {"packagename", cmd_packagename, "<packagename>",NULL,0,NULL},
2942 {"proxy", cmd_proxy, "[('tcp'|'ssl')]<host>[':'<port>]",NULL,0,NULL},
2943 {"charset", cmd_charset, "<charset_name>",NULL,0,NULL},
2944 {"lang", cmd_lang, "<language_code>",NULL,0,NULL},
2945 {".", cmd_source, "<filename>",NULL,1,NULL},
2946 {"!", cmd_subshell, "Subshell command",NULL,1,NULL},
2947 {"set_apdufile", cmd_set_apdufile, "<filename>",NULL,1,NULL},
2948 {"set_marcdump", cmd_set_marcdump," <filename>",NULL,1,NULL},
2949 {"set_cclfile", cmd_set_cclfile," <filename>",NULL,1,NULL},
2950 {"set_auto_reconnect", cmd_set_auto_reconnect," on|off",complete_auto_reconnect,1,NULL},
2951 {"set_otherinfo", cmd_set_otherinfo,"<otherinfoinddex> <oid> <string>",NULL,0,NULL},
2952 {"register_oid", cmd_register_oid,"<name> <class> <oid>",NULL,0,NULL},
2953 {"push_command", cmd_push_command,"<command>",command_generator,0,NULL},
2954 {"register_tab", cmd_register_tab,"<commandname> <tab>",command_generator,0,NULL},
2955 {"cclparse", cmd_cclparse,"<ccl find command>",NULL,0,NULL},
2956 {"list_otherinfo",cmd_list_otherinfo,"[otherinfoinddex]",NULL,0,NULL},
2957 {"list_all",cmd_list_all,"",NULL,0,NULL},
2958 {"clear_otherinfo",cmd_clear_otherinfo,"",NULL,0,NULL},
2959 /* Server Admin Functions */
2960 {"adm-reindex", cmd_adm_reindex, "<database-name>",NULL,0,NULL},
2961 {"adm-truncate", cmd_adm_truncate, "('database'|'index')<object-name>",NULL,0,NULL},
2962 {"adm-create", cmd_adm_create, "",NULL,0,NULL},
2963 {"adm-drop", cmd_adm_drop, "('database'|'index')<object-name>",NULL,0,NULL},
2964 {"adm-import", cmd_adm_import, "<record-type> <dir> <pattern>",NULL,0,NULL},
2965 {"adm-refresh", cmd_adm_refresh, "",NULL,0,NULL},
2966 {"adm-commit", cmd_adm_commit, "",NULL,0,NULL},
2967 {"adm-shutdown", cmd_adm_shutdown, "",NULL,0,NULL},
2968 {"adm-startup", cmd_adm_startup, "",NULL,0,NULL},
2969 {"help", cmd_help, "", NULL,0,NULL},
2973 static int cmd_help (char *line)
2979 sscanf (line, "%20s", topic);
2982 printf("Commands:\n");
2983 for (i = 0; cmd[i].cmd; i++)
2984 if (*topic == 0 || strcmp (topic, cmd[i].cmd) == 0)
2985 printf(" %s %s\n", cmd[i].cmd, cmd[i].ad);
2986 if (strcmp (topic, "find") == 0)
2989 printf (" \"term\" Simple Term\n");
2990 printf (" @attr [attset] type=value op Attribute\n");
2991 printf (" @and opl opr And\n");
2992 printf (" @or opl opr Or\n");
2993 printf (" @not opl opr And-Not\n");
2994 printf (" @set set Result set\n");
2996 printf ("Bib-1 attribute types\n");
2998 printf ("4=Title 7=ISBN 8=ISSN 30=Date 62=Abstract 1003=Author 1016=Any\n");
2999 printf ("2=Relation: ");
3000 printf ("1< 2<= 3= 4>= 5> 6!= 102=Relevance\n");
3001 printf ("3=Position: ");
3002 printf ("1=First in Field 2=First in subfield 3=Any position\n");
3003 printf ("4=Structure: ");
3004 printf ("1=Phrase 2=Word 3=Key 4=Year 5=Date 6=WordList\n");
3005 printf ("5=Truncation: ");
3006 printf ("1=Right 2=Left 3=L&R 100=No 101=# 102=Re-1 103=Re-2\n");
3007 printf ("6=Completeness:");
3008 printf ("1=Incomplete subfield 2=Complete subfield 3=Complete field\n");
3013 int cmd_register_tab(char* arg) {
3015 char command[101], tabargument[101];
3020 if (sscanf (arg, "%100s %100s", command, tabargument) < 1) {
3024 /* locate the amdn in the list */
3025 for (i = 0; cmd[i].cmd; i++) {
3026 if (!strncmp(cmd[i].cmd, command, strlen(command))) {
3032 fprintf(stderr,"Unknown command %s\n",command);
3038 if(!cmd[i].local_tabcompletes) {
3039 cmd[i].local_tabcompletes = calloc(1,sizeof(char**));
3044 tabslist = cmd[i].local_tabcompletes;
3045 for(;tabslist && *tabslist;tabslist++) {
3049 cmd[i].local_tabcompletes=realloc(cmd[i].local_tabcompletes,(num_of_tabs+2)*sizeof(char**));
3050 tabslist=cmd[i].local_tabcompletes;
3051 tabslist[num_of_tabs]=strdup(tabargument);
3052 tabslist[num_of_tabs+1]=NULL;
3057 void process_cmd_line(char* line)
3060 char word[32], arg[1024];
3062 #if HAVE_GETTIMEOFDAY
3063 gettimeofday (&tv_start, 0);
3066 if ((res = sscanf(line, "%31s %1023[^;]", word, arg)) <= 0)
3068 strcpy(word, last_cmd);
3073 strcpy(last_cmd, word);
3075 /* removed tailing spaces from the arg command */
3078 char* lastnonspace=NULL;
3087 *(++lastnonspace) = 0;
3091 for (i = 0; cmd[i].cmd; i++)
3092 if (!strncmp(cmd[i].cmd, word, strlen(word)))
3094 res = (*cmd[i].fun)(arg);
3098 if (!cmd[i].cmd) /* dump our help-screen */
3100 printf("Unknown command: %s.\n", word);
3101 printf("use help for list of commands\n");
3102 /* cmd_help (""); */
3106 if(apdu_file) fflush(apdu_file);
3109 wait_and_handle_responce();
3118 char *command_generator(const char *text, int state)
3124 for( ; cmd[idx].cmd; ++idx) {
3125 if (!strncmp(cmd[idx].cmd,text,strlen(text))) {
3126 ++idx; /* skip this entry on the next run */
3127 return strdup(cmd[idx-1].cmd);
3135 This function only known how to complete on the first word
3137 char ** readline_completer(char *text, int start, int end) {
3138 #if HAVE_READLINE_READLINE_H
3140 completerFunctionType completerToUse;
3143 #if HAVE_READLINE_RL_COMPLETION_MATCHES
3144 char** res=rl_completion_matches(text,
3147 char** res=completion_matches(text,
3148 (CPFunction*)command_generator);
3150 rl_attempted_completion_over = 1;
3153 char arg[1024],word[32];
3155 if ((res = sscanf(rl_line_buffer, "%31s %1023[^;]", word, arg)) <= 0) {
3156 rl_attempted_completion_over = 1;
3160 for (i = 0; cmd[i].cmd; i++) {
3161 if (!strncmp(cmd[i].cmd, word, strlen(word))) {
3166 if(!cmd[i].cmd) return NULL;
3169 curret_global_list = cmd[i].local_tabcompletes;
3171 completerToUse = cmd[i].rl_completerfunction;
3172 if(completerToUse==NULL) /* if no pr. command completer is defined use the default completer */
3173 completerToUse = default_completer;
3175 if(completerToUse) {
3176 #ifdef HAVE_READLINE_RL_COMPLETION_MATCHES
3178 rl_completion_matches(text,
3182 completion_matches(text,
3183 (CPFunction*)completerToUse);
3185 if(!cmd[i].complete_filenames)
3186 rl_attempted_completion_over = 1;
3189 if(!cmd[i].complete_filenames)
3190 rl_attempted_completion_over = 1;
3200 static void client(void)
3206 #if HAVE_GETTIMEOFDAY
3207 gettimeofday (&tv_start, 0);
3212 char *line_in = NULL;
3213 #if HAVE_READLINE_READLINE_H
3216 line_in=readline(C_PROMPT);
3219 #if HAVE_READLINE_HISTORY_H
3221 add_history(line_in);
3223 strncpy(line, line_in, 1023);
3232 if (!fgets(line, 1023, stdin))
3234 if ((end_p = strchr (line, '\n')))
3237 process_cmd_line(line);
3241 int main(int argc, char **argv)
3244 char *open_command = 0;
3245 char *auth_command = 0;
3249 while ((ret = options("k:c:a:m:v:p:u:", argv, argc, &arg)) != -2)
3256 open_command = (char *) xmalloc (strlen(arg)+6);
3257 strcpy (open_command, "open ");
3258 strcat (open_command, arg);
3262 kilobytes = atoi(arg);
3265 if (!(marcdump = fopen (arg, "a")))
3272 strncpy (ccl_fields, arg, sizeof(ccl_fields)-1);
3273 ccl_fields[sizeof(ccl_fields)-1] = '\0';
3276 if (!strcmp(arg, "-"))
3279 apdu_file=fopen(arg, "a");
3282 yazProxy=strdup(arg);
3287 auth_command = (char *) xmalloc (strlen(arg)+6);
3288 strcpy (auth_command, "auth ");
3289 strcat (auth_command, arg);
3293 yaz_log_init (yaz_log_mask_str(arg), "", NULL);
3296 fprintf (stderr, "Usage: %s [-m <marclog>] [ -a <apdulog>] "
3297 "[-c cclfields]\n [-p <proxy-addr>] [-u <auth>] "
3298 "[-k size] [<server-addr>]\n",
3306 #ifdef HAVE_GETTIMEOFDAY
3307 gettimeofday (&tv_start, 0);
3309 process_cmd_line (auth_command);
3310 #if HAVE_READLINE_HISTORY_H
3311 add_history(auth_command);
3313 xfree(auth_command);
3317 #ifdef HAVE_GETTIMEOFDAY
3318 gettimeofday (&tv_start, 0);
3320 process_cmd_line (open_command);
3321 #if HAVE_READLINE_HISTORY_H
3322 add_history(open_command);
3324 xfree(open_command);