2 * Copyright (c) 1995-2002, Index Data
3 * See the file LICENSE for details.
5 * $Id: client.c,v 1.170 2002-09-17 21:19:38 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,
695 r->u.octet_aligned->len);
696 fprintf(stderr, "---------\n");
698 /* note just ignores the error ant print the bytes form the octet_aligned later */
701 * Note: we throw away the original, BER-encoded record here.
702 * Do something else with it if you want to keep it.
704 r->u.sutrs = (Z_SUTRS *) rr; /* we don't actually check the type here. */
705 r->which = type->what;
709 if (ent && ent->oclass != CLASS_RECSYN)
711 if (ent && ent->value == VAL_SOIF)
712 print_record((const unsigned char *) r->u.octet_aligned->buf,
713 r->u.octet_aligned->len);
714 else if (r->which == Z_External_octet && r->u.octet_aligned->len)
716 const char *octet_buf = (char*)r->u.octet_aligned->buf;
717 if (ent->value == VAL_TEXT_XML || ent->value == VAL_APPLICATION_XML ||
718 ent->value == VAL_HTML)
720 print_record((const unsigned char *) octet_buf,
721 r->u.octet_aligned->len);
723 else if (ent->value == VAL_POSTSCRIPT)
725 int size = r->u.octet_aligned->len;
728 print_record((const unsigned char *) octet_buf, size);
733 #if AVOID_MARC_DECODE
734 /* primitive check for a marc OID 5.1-29 except 16 */
735 ent->oidsuffix[0] == 5 && ent->oidsuffix[1] < 30 &&
736 ent->oidsuffix[1] != 16
742 if (marc_display_exl (octet_buf, NULL, 0 /* debug */,
743 r->u.octet_aligned->len) <= 0)
745 printf ("bad MARC. Dumping as it is:\n");
746 print_record((const unsigned char*) octet_buf,
747 r->u.octet_aligned->len);
752 print_record((const unsigned char*) octet_buf,
753 r->u.octet_aligned->len);
757 fwrite (octet_buf, 1, r->u.octet_aligned->len, marcdump);
759 else if (ent && ent->value == VAL_SUTRS)
761 if (r->which != Z_External_sutrs)
763 printf("Expecting single SUTRS type for SUTRS.\n");
766 print_record(r->u.sutrs->buf, r->u.sutrs->len);
768 else if (ent && ent->value == VAL_GRS1)
770 if (r->which != Z_External_grs1)
772 printf("Expecting single GRS type for GRS.\n");
775 display_grs1(r->u.grs1, 0);
779 printf("Unknown record representation.\n");
780 if (!z_External(print, &r, 0, 0))
782 odr_perror(print, "Printing external");
788 static void display_diagrecs(Z_DiagRec **pp, int num)
792 Z_DefaultDiagFormat *r;
794 printf("Diagnostic message(s) from database:\n");
795 for (i = 0; i<num; i++)
797 Z_DiagRec *p = pp[i];
798 if (p->which != Z_DiagRec_defaultFormat)
800 printf("Diagnostic record not in default format.\n");
804 r = p->u.defaultFormat;
805 if (!(ent = oid_getentbyoid(r->diagnosticSetId)) ||
806 ent->oclass != CLASS_DIAGSET || ent->value != VAL_BIB1)
807 printf("Missing or unknown diagset\n");
808 printf(" [%d] %s", *r->condition, diagbib1_str(*r->condition));
811 case Z_DefaultDiagFormat_v2Addinfo:
812 printf (" -- v2 addinfo '%s'\n", r->u.v2Addinfo);
814 case Z_DefaultDiagFormat_v3Addinfo:
815 printf (" -- v3 addinfo '%s'\n", r->u.v3Addinfo);
822 static void display_nameplusrecord(Z_NamePlusRecord *p)
825 printf("[%s]", p->databaseName);
826 if (p->which == Z_NamePlusRecord_surrogateDiagnostic)
827 display_diagrecs(&p->u.surrogateDiagnostic, 1);
828 else if (p->which == Z_NamePlusRecord_databaseRecord)
829 display_record(p->u.databaseRecord);
832 static void display_records(Z_Records *p)
836 if (p->which == Z_Records_NSD)
838 Z_DiagRec dr, *dr_p = &dr;
839 dr.which = Z_DiagRec_defaultFormat;
840 dr.u.defaultFormat = p->u.nonSurrogateDiagnostic;
841 display_diagrecs (&dr_p, 1);
843 else if (p->which == Z_Records_multipleNSD)
844 display_diagrecs (p->u.multipleNonSurDiagnostics->diagRecs,
845 p->u.multipleNonSurDiagnostics->num_diagRecs);
848 printf("Records: %d\n", p->u.databaseOrSurDiagnostics->num_records);
849 for (i = 0; i < p->u.databaseOrSurDiagnostics->num_records; i++)
850 display_nameplusrecord(p->u.databaseOrSurDiagnostics->records[i]);
854 static int send_deleteResultSetRequest(char *arg)
859 Z_APDU *apdu = zget_APDU(out, Z_APDU_deleteResultSetRequest);
860 Z_DeleteResultSetRequest *req = apdu->u.deleteResultSetRequest;
862 req->referenceId = set_refid (out);
864 req->num_resultSetList =
865 sscanf (arg, "%30s %30s %30s %30s %30s %30s %30s %30s",
866 names[0], names[1], names[2], names[3],
867 names[4], names[5], names[6], names[7]);
869 req->deleteFunction = (int *)
870 odr_malloc (out, sizeof(*req->deleteFunction));
871 if (req->num_resultSetList > 0)
873 *req->deleteFunction = Z_DeleteRequest_list;
874 req->resultSetList = (char **)
875 odr_malloc (out, sizeof(*req->resultSetList)*
876 req->num_resultSetList);
877 for (i = 0; i<req->num_resultSetList; i++)
878 req->resultSetList[i] = names[i];
882 *req->deleteFunction = Z_DeleteRequest_all;
883 req->resultSetList = 0;
887 printf("Sent deleteResultSetRequest.\n");
891 static int send_searchRequest(char *arg)
893 Z_APDU *apdu = zget_APDU(out, Z_APDU_searchRequest);
894 Z_SearchRequest *req = apdu->u.searchRequest;
897 struct ccl_rpn_node *rpn = NULL;
900 Z_RPNQuery *RPNquery;
902 YAZ_PQF_Parser pqf_parser;
904 if (queryType == QueryType_CCL2RPN)
906 rpn = ccl_find_str(bibset, arg, &error, &pos);
909 printf("CCL ERROR: %s\n", ccl_err_msg(error));
913 req->referenceId = set_refid (out);
914 if (!strcmp(arg, "@big")) /* strictly for troublemaking */
916 static unsigned char big[2100];
919 /* send a very big referenceid to test transport stack etc. */
920 memset(big, 'A', 2100);
921 bigo.len = bigo.size = 2100;
923 req->referenceId = &bigo;
928 sprintf(setstring, "%d", ++setnumber);
929 req->resultSetName = setstring;
931 *req->smallSetUpperBound = smallSetUpperBound;
932 *req->largeSetLowerBound = largeSetLowerBound;
933 *req->mediumSetPresentNumber = mediumSetPresentNumber;
934 if (smallSetUpperBound > 0 || (largeSetLowerBound > 1 &&
935 mediumSetPresentNumber > 0))
939 prefsyn.proto = protocol;
940 prefsyn.oclass = CLASS_RECSYN;
941 prefsyn.value = recordsyntax;
942 req->preferredRecordSyntax =
943 odr_oiddup(out, oid_ent_to_oid(&prefsyn, oid));
944 req->smallSetElementSetNames =
945 req->mediumSetElementSetNames = elementSetNames;
947 req->num_databaseNames = num_databaseNames;
948 req->databaseNames = databaseNames;
954 case QueryType_Prefix:
955 query.which = Z_Query_type_1;
956 pqf_parser = yaz_pqf_create ();
957 RPNquery = yaz_pqf_parse (pqf_parser, out, arg);
962 int code = yaz_pqf_error (pqf_parser, &pqf_msg, &off);
963 printf("%*s^\n", off+4, "");
964 printf("Prefix query error: %s (code %d)\n", pqf_msg, code);
966 yaz_pqf_destroy (pqf_parser);
969 yaz_pqf_destroy (pqf_parser);
970 query.u.type_1 = RPNquery;
973 query.which = Z_Query_type_2;
974 query.u.type_2 = &ccl_query;
975 ccl_query.buf = (unsigned char*) arg;
976 ccl_query.len = strlen(arg);
978 case QueryType_CCL2RPN:
979 query.which = Z_Query_type_1;
980 RPNquery = ccl_rpn_query(out, rpn);
983 printf ("Couldn't convert from CCL to RPN\n");
986 query.u.type_1 = RPNquery;
987 ccl_rpn_delete (rpn);
990 printf ("Unsupported query type\n");
995 printf("Sent searchRequest.\n");
999 /* display Query Expression as part of searchResult-1 */
1000 static void display_queryExpression (Z_QueryExpression *qe)
1004 if (qe->which == Z_QueryExpression_term)
1006 if (qe->u.term->queryTerm)
1008 Z_Term *term = qe->u.term->queryTerm;
1009 switch (term->which)
1011 case Z_Term_general:
1012 printf (" %.*s", term->u.general->len, term->u.general->buf);
1014 case Z_Term_characterString:
1015 printf (" %s", term->u.characterString);
1017 case Z_Term_numeric:
1018 printf (" %d", *term->u.numeric);
1028 /* see if we can find USR:SearchResult-1 */
1029 static void display_searchResult (Z_OtherInformation *o)
1034 for (i = 0; i < o->num_elements; i++)
1036 if (o->list[i]->which == Z_OtherInfo_externallyDefinedInfo)
1038 Z_External *ext = o->list[i]->information.externallyDefinedInfo;
1040 if (ext->which == Z_External_searchResult1)
1043 Z_SearchInfoReport *sr = ext->u.searchResult1;
1044 printf ("SearchResult-1:");
1045 for (j = 0; j < sr->num; j++)
1047 if (!sr->elements[j]->subqueryExpression)
1049 display_queryExpression (
1050 sr->elements[j]->subqueryExpression);
1051 display_queryExpression (
1052 sr->elements[j]->subqueryInterpretation);
1053 display_queryExpression (
1054 sr->elements[j]->subqueryRecommendation);
1055 if (sr->elements[j]->subqueryCount)
1056 printf ("(%d)", *sr->elements[j]->subqueryCount);
1064 static int process_searchResponse(Z_SearchResponse *res)
1066 printf ("Received SearchResponse.\n");
1067 print_refid (res->referenceId);
1068 if (*res->searchStatus)
1069 printf("Search was a success.\n");
1071 printf("Search was a bloomin' failure.\n");
1072 printf("Number of hits: %d", *res->resultCount);
1074 printf (", setno %d", setnumber);
1076 display_searchResult (res->additionalSearchInfo);
1077 printf("records returned: %d\n",
1078 *res->numberOfRecordsReturned);
1079 setno += *res->numberOfRecordsReturned;
1081 display_records(res->records);
1085 static void print_level(int iLevel)
1088 for (i = 0; i < iLevel * 4; i++)
1092 static void print_int(int iLevel, const char *pTag, int *pInt)
1096 print_level(iLevel);
1097 printf("%s: %d\n", pTag, *pInt);
1101 static void print_string(int iLevel, const char *pTag, const char *pString)
1103 if (pString != NULL)
1105 print_level(iLevel);
1106 printf("%s: %s\n", pTag, pString);
1110 static void print_oid(int iLevel, const char *pTag, Odr_oid *pOid)
1116 print_level(iLevel);
1117 printf("%s:", pTag);
1118 for (; *pInt != -1; pInt++)
1119 printf(" %d", *pInt);
1124 static void print_referenceId(int iLevel, Z_ReferenceId *referenceId)
1126 if (referenceId != NULL)
1130 print_level(iLevel);
1131 printf("Ref Id (%d, %d): ", referenceId->len, referenceId->size);
1132 for (i = 0; i < referenceId->len; i++)
1133 printf("%c", referenceId->buf[i]);
1138 static void print_string_or_numeric(int iLevel, const char *pTag, Z_StringOrNumeric *pStringNumeric)
1140 if (pStringNumeric != NULL)
1142 switch (pStringNumeric->which)
1144 case Z_StringOrNumeric_string:
1145 print_string(iLevel, pTag, pStringNumeric->u.string);
1148 case Z_StringOrNumeric_numeric:
1149 print_int(iLevel, pTag, pStringNumeric->u.numeric);
1153 print_level(iLevel);
1154 printf("%s: valid type for Z_StringOrNumeric\n", pTag);
1160 static void print_universe_report_duplicate(
1162 Z_UniverseReportDuplicate *pUniverseReportDuplicate)
1164 if (pUniverseReportDuplicate != NULL)
1166 print_level(iLevel);
1167 printf("Universe Report Duplicate: \n");
1169 print_string_or_numeric(iLevel, "Hit No",
1170 pUniverseReportDuplicate->hitno);
1174 static void print_universe_report_hits(
1176 Z_UniverseReportHits *pUniverseReportHits)
1178 if (pUniverseReportHits != NULL)
1180 print_level(iLevel);
1181 printf("Universe Report Hits: \n");
1183 print_string_or_numeric(iLevel, "Database",
1184 pUniverseReportHits->database);
1185 print_string_or_numeric(iLevel, "Hits", pUniverseReportHits->hits);
1189 static void print_universe_report(int iLevel, Z_UniverseReport *pUniverseReport)
1191 if (pUniverseReport != NULL)
1193 print_level(iLevel);
1194 printf("Universe Report: \n");
1196 print_int(iLevel, "Total Hits", pUniverseReport->totalHits);
1197 switch (pUniverseReport->which)
1199 case Z_UniverseReport_databaseHits:
1200 print_universe_report_hits(iLevel,
1201 pUniverseReport->u.databaseHits);
1204 case Z_UniverseReport_duplicate:
1205 print_universe_report_duplicate(iLevel,
1206 pUniverseReport->u.duplicate);
1210 print_level(iLevel);
1211 printf("Type: %d\n", pUniverseReport->which);
1217 static void print_external(int iLevel, Z_External *pExternal)
1219 if (pExternal != NULL)
1221 print_level(iLevel);
1222 printf("External: \n");
1224 print_oid(iLevel, "Direct Reference", pExternal->direct_reference);
1225 print_int(iLevel, "InDirect Reference", pExternal->indirect_reference);
1226 print_string(iLevel, "Descriptor", pExternal->descriptor);
1227 switch (pExternal->which)
1229 case Z_External_universeReport:
1230 print_universe_report(iLevel, pExternal->u.universeReport);
1234 print_level(iLevel);
1235 printf("Type: %d\n", pExternal->which);
1241 static int process_resourceControlRequest (Z_ResourceControlRequest *req)
1243 printf ("Received ResourceControlRequest.\n");
1244 print_referenceId(1, req->referenceId);
1245 print_int(1, "Suspended Flag", req->suspendedFlag);
1246 print_int(1, "Partial Results Available", req->partialResultsAvailable);
1247 print_int(1, "Response Required", req->responseRequired);
1248 print_int(1, "Triggered Request Flag", req->triggeredRequestFlag);
1249 print_external(1, req->resourceReport);
1253 void process_ESResponse(Z_ExtendedServicesResponse *res)
1256 switch (*res->operationStatus)
1258 case Z_ExtendedServicesResponse_done:
1261 case Z_ExtendedServicesResponse_accepted:
1262 printf ("accepted\n");
1264 case Z_ExtendedServicesResponse_failure:
1265 printf ("failure\n");
1266 display_diagrecs(res->diagnostics, res->num_diagnostics);
1269 printf ("unknown\n");
1271 if ( (*res->operationStatus != Z_ExtendedServicesResponse_failure) &&
1272 (res->num_diagnostics != 0) ) {
1273 display_diagrecs(res->diagnostics, res->num_diagnostics);
1275 print_refid (res->referenceId);
1276 if (res->taskPackage &&
1277 res->taskPackage->which == Z_External_extendedService)
1279 Z_TaskPackage *taskPackage = res->taskPackage->u.extendedService;
1280 Odr_oct *id = taskPackage->targetReference;
1281 Z_External *ext = taskPackage->taskSpecificParameters;
1285 printf ("Target Reference: ");
1286 print_stringn (id->buf, id->len);
1289 if (ext->which == Z_External_update)
1291 Z_IUUpdateTaskPackage *utp = ext->u.update->u.taskPackage;
1292 if (utp && utp->targetPart)
1294 Z_IUTargetPart *targetPart = utp->targetPart;
1297 for (i = 0; i<targetPart->num_taskPackageRecords; i++)
1300 Z_IUTaskPackageRecordStructure *tpr =
1301 targetPart->taskPackageRecords[i];
1302 printf ("task package record %d\n", i+1);
1303 if (tpr->which == Z_IUTaskPackageRecordStructure_record)
1305 display_record (tpr->u.record);
1309 printf ("other type\n");
1317 const char *get_ill_element (void *clientData, const char *element)
1322 static Z_External *create_external_itemRequest()
1324 struct ill_get_ctl ctl;
1325 ILL_ItemRequest *req;
1327 int item_request_size = 0;
1328 char *item_request_buf = 0;
1332 ctl.f = get_ill_element;
1334 req = ill_get_ItemRequest(&ctl, "ill", 0);
1336 printf ("ill_get_ItemRequest failed\n");
1338 if (!ill_ItemRequest (out, &req, 0, 0))
1342 ill_ItemRequest(print, &req, 0, 0);
1345 item_request_buf = odr_getbuf (out, &item_request_size, 0);
1346 if (item_request_buf)
1347 odr_setbuf (out, item_request_buf, item_request_size, 1);
1348 printf ("Couldn't encode ItemRequest, size %d\n", item_request_size);
1355 item_request_buf = odr_getbuf (out, &item_request_size, 0);
1356 oid.proto = PROTO_GENERAL;
1357 oid.oclass = CLASS_GENERAL;
1358 oid.value = VAL_ISO_ILL_1;
1360 r = (Z_External *) odr_malloc (out, sizeof(*r));
1361 r->direct_reference = odr_oiddup(out,oid_getoidbyent(&oid));
1362 r->indirect_reference = 0;
1364 r->which = Z_External_single;
1366 r->u.single_ASN1_type = (Odr_oct *)
1367 odr_malloc (out, sizeof(*r->u.single_ASN1_type));
1368 r->u.single_ASN1_type->buf = (unsigned char *)
1369 odr_malloc (out, item_request_size);
1370 r->u.single_ASN1_type->len = item_request_size;
1371 r->u.single_ASN1_type->size = item_request_size;
1372 memcpy (r->u.single_ASN1_type->buf, item_request_buf,
1375 do_hex_dump(item_request_buf,item_request_size);
1380 static Z_External *create_external_ILL_APDU(int which)
1382 struct ill_get_ctl ctl;
1385 int ill_request_size = 0;
1386 char *ill_request_buf = 0;
1390 ctl.f = get_ill_element;
1392 ill_apdu = ill_get_APDU(&ctl, "ill", 0);
1394 if (!ill_APDU (out, &ill_apdu, 0, 0))
1398 printf ("-------------------\n");
1399 ill_APDU(print, &ill_apdu, 0, 0);
1401 printf ("-------------------\n");
1403 ill_request_buf = odr_getbuf (out, &ill_request_size, 0);
1404 if (ill_request_buf)
1405 odr_setbuf (out, ill_request_buf, ill_request_size, 1);
1406 printf ("Couldn't encode ILL-Request, size %d\n", ill_request_size);
1412 ill_request_buf = odr_getbuf (out, &ill_request_size, 0);
1414 oid.proto = PROTO_GENERAL;
1415 oid.oclass = CLASS_GENERAL;
1416 oid.value = VAL_ISO_ILL_1;
1418 r = (Z_External *) odr_malloc (out, sizeof(*r));
1419 r->direct_reference = odr_oiddup(out,oid_getoidbyent(&oid));
1420 r->indirect_reference = 0;
1422 r->which = Z_External_single;
1424 r->u.single_ASN1_type = (Odr_oct *)
1425 odr_malloc (out, sizeof(*r->u.single_ASN1_type));
1426 r->u.single_ASN1_type->buf = (unsigned char *)
1427 odr_malloc (out, ill_request_size);
1428 r->u.single_ASN1_type->len = ill_request_size;
1429 r->u.single_ASN1_type->size = ill_request_size;
1430 memcpy (r->u.single_ASN1_type->buf, ill_request_buf, ill_request_size);
1431 /* printf ("len = %d\n", ill_request_size); */
1432 /* do_hex_dump(ill_request_buf,ill_request_size); */
1433 /* printf("--- end of extenal\n"); */
1440 static Z_External *create_ItemOrderExternal(const char *type, int itemno)
1442 Z_External *r = (Z_External *) odr_malloc(out, sizeof(Z_External));
1443 oident ItemOrderRequest;
1445 ItemOrderRequest.proto = PROTO_Z3950;
1446 ItemOrderRequest.oclass = CLASS_EXTSERV;
1447 ItemOrderRequest.value = VAL_ITEMORDER;
1449 r->direct_reference = odr_oiddup(out,oid_getoidbyent(&ItemOrderRequest));
1450 r->indirect_reference = 0;
1453 r->which = Z_External_itemOrder;
1455 r->u.itemOrder = (Z_ItemOrder *) odr_malloc(out,sizeof(Z_ItemOrder));
1456 memset(r->u.itemOrder, 0, sizeof(Z_ItemOrder));
1457 r->u.itemOrder->which=Z_IOItemOrder_esRequest;
1459 r->u.itemOrder->u.esRequest = (Z_IORequest *)
1460 odr_malloc(out,sizeof(Z_IORequest));
1461 memset(r->u.itemOrder->u.esRequest, 0, sizeof(Z_IORequest));
1463 r->u.itemOrder->u.esRequest->toKeep = (Z_IOOriginPartToKeep *)
1464 odr_malloc(out,sizeof(Z_IOOriginPartToKeep));
1465 memset(r->u.itemOrder->u.esRequest->toKeep, 0, sizeof(Z_IOOriginPartToKeep));
1466 r->u.itemOrder->u.esRequest->notToKeep = (Z_IOOriginPartNotToKeep *)
1467 odr_malloc(out,sizeof(Z_IOOriginPartNotToKeep));
1468 memset(r->u.itemOrder->u.esRequest->notToKeep, 0, sizeof(Z_IOOriginPartNotToKeep));
1470 r->u.itemOrder->u.esRequest->toKeep->supplDescription = NULL;
1471 r->u.itemOrder->u.esRequest->toKeep->contact = NULL;
1472 r->u.itemOrder->u.esRequest->toKeep->addlBilling = NULL;
1474 r->u.itemOrder->u.esRequest->notToKeep->resultSetItem =
1475 (Z_IOResultSetItem *) odr_malloc(out, sizeof(Z_IOResultSetItem));
1476 memset(r->u.itemOrder->u.esRequest->notToKeep->resultSetItem, 0, sizeof(Z_IOResultSetItem));
1477 r->u.itemOrder->u.esRequest->notToKeep->resultSetItem->resultSetId = "1";
1479 r->u.itemOrder->u.esRequest->notToKeep->resultSetItem->item =
1480 (int *) odr_malloc(out, sizeof(int));
1481 *r->u.itemOrder->u.esRequest->notToKeep->resultSetItem->item = itemno;
1483 if (!strcmp (type, "item") || !strcmp(type, "2"))
1485 printf ("using item-request\n");
1486 r->u.itemOrder->u.esRequest->notToKeep->itemRequest =
1487 create_external_itemRequest();
1489 else if (!strcmp(type, "ill") || !strcmp(type, "1"))
1491 printf ("using ILL-request\n");
1492 r->u.itemOrder->u.esRequest->notToKeep->itemRequest =
1493 create_external_ILL_APDU(ILL_APDU_ILL_Request);
1495 else if (!strcmp(type, "xml") || !strcmp(type, "3"))
1497 const char *xml_buf =
1499 " <type>request</type>\n"
1500 " <libraryNo>000200</libraryNo>\n"
1501 " <borrowerTicketNo> 1212 </borrowerTicketNo>\n"
1503 r->u.itemOrder->u.esRequest->notToKeep->itemRequest =
1504 z_ext_record (out, VAL_TEXT_XML, xml_buf, strlen(xml_buf));
1507 r->u.itemOrder->u.esRequest->notToKeep->itemRequest = 0;
1512 static int send_itemorder(const char *type, int itemno)
1514 Z_APDU *apdu = zget_APDU(out, Z_APDU_extendedServicesRequest);
1515 Z_ExtendedServicesRequest *req = apdu->u.extendedServicesRequest;
1516 oident ItemOrderRequest;
1518 ItemOrderRequest.proto = PROTO_Z3950;
1519 ItemOrderRequest.oclass = CLASS_EXTSERV;
1520 ItemOrderRequest.value = VAL_ITEMORDER;
1521 req->packageType = odr_oiddup(out,oid_getoidbyent(&ItemOrderRequest));
1522 req->packageName = esPackageName;
1524 req->taskSpecificParameters = create_ItemOrderExternal(type, itemno);
1530 static int cmd_update(char *arg)
1532 Z_APDU *apdu = zget_APDU(out, Z_APDU_extendedServicesRequest );
1533 Z_ExtendedServicesRequest *req = apdu->u.extendedServicesRequest;
1536 Z_IUOriginPartToKeep *toKeep;
1537 Z_IUSuppliedRecords *notToKeep;
1539 char action[20], recid[20], fname[80];
1541 Z_External *record_this = 0;
1546 sscanf (arg, "%19s %19s %79s", action, recid, fname);
1548 if (!strcmp (action, "insert"))
1549 action_no = Z_IUOriginPartToKeep_recordInsert;
1550 else if (!strcmp (action, "replace"))
1551 action_no = Z_IUOriginPartToKeep_recordReplace;
1552 else if (!strcmp (action, "delete"))
1553 action_no = Z_IUOriginPartToKeep_recordDelete;
1554 else if (!strcmp (action, "update"))
1555 action_no = Z_IUOriginPartToKeep_specialUpdate;
1558 printf ("Bad action: %s\n", action);
1559 printf ("Possible values: insert, replace, delete, update\n");
1567 stat (fname, &status);
1568 if (S_ISREG(status.st_mode) && (inf = fopen(fname, "r")))
1570 size_t len = status.st_size;
1571 char *buf = xmalloc (len);
1573 fread (buf, 1, len, inf);
1577 record_this = z_ext_record (out, VAL_TEXT_XML, buf, len);
1583 printf ("File %s doesn't exist\n", fname);
1591 printf ("No last record (update ignored)\n");
1594 record_this = record_last;
1597 update_oid.proto = PROTO_Z3950;
1598 update_oid.oclass = CLASS_EXTSERV;
1599 update_oid.value = VAL_DBUPDATE;
1600 oid_ent_to_oid (&update_oid, oid);
1601 req->packageType = odr_oiddup(out,oid);
1602 req->packageName = esPackageName;
1604 req->referenceId = set_refid (out);
1606 r = req->taskSpecificParameters = (Z_External *)
1607 odr_malloc (out, sizeof(*r));
1608 r->direct_reference = odr_oiddup(out,oid);
1609 r->indirect_reference = 0;
1611 r->which = Z_External_update;
1612 r->u.update = (Z_IUUpdate *) odr_malloc(out, sizeof(*r->u.update));
1613 r->u.update->which = Z_IUUpdate_esRequest;
1614 r->u.update->u.esRequest = (Z_IUUpdateEsRequest *)
1615 odr_malloc(out, sizeof(*r->u.update->u.esRequest));
1616 toKeep = r->u.update->u.esRequest->toKeep = (Z_IUOriginPartToKeep *)
1617 odr_malloc(out, sizeof(*r->u.update->u.esRequest->toKeep));
1618 toKeep->databaseName = databaseNames[0];
1620 toKeep->elementSetName = 0;
1621 toKeep->actionQualifier = 0;
1622 toKeep->action = (int *) odr_malloc(out, sizeof(*toKeep->action));
1623 *toKeep->action = action_no;
1625 notToKeep = r->u.update->u.esRequest->notToKeep = (Z_IUSuppliedRecords *)
1626 odr_malloc(out, sizeof(*r->u.update->u.esRequest->notToKeep));
1628 notToKeep->elements = (Z_IUSuppliedRecords_elem **)
1629 odr_malloc(out, sizeof(*notToKeep->elements));
1630 notToKeep->elements[0] = (Z_IUSuppliedRecords_elem *)
1631 odr_malloc(out, sizeof(**notToKeep->elements));
1632 notToKeep->elements[0]->which = Z_IUSuppliedRecords_elem_opaque;
1635 notToKeep->elements[0]->u.opaque = odr_malloc (out, sizeof(Odr_oct));
1636 notToKeep->elements[0]->u.opaque->buf = recid;
1637 notToKeep->elements[0]->u.opaque->size = strlen(recid);
1638 notToKeep->elements[0]->u.opaque->len = strlen(recid);
1641 notToKeep->elements[0]->u.opaque = 0;
1642 notToKeep->elements[0]->supplementalId = 0;
1643 notToKeep->elements[0]->correlationInfo = 0;
1644 notToKeep->elements[0]->record = record_this;
1651 static int cmd_itemorder(char *arg)
1656 if (sscanf (arg, "%10s %d", type, &itemno) != 2)
1659 printf("Item order request\n");
1661 send_itemorder(type, itemno);
1665 static int cmd_find(char *arg)
1669 printf("Find what?\n");
1677 printf("Not connected yet\n");
1681 if (!send_searchRequest(arg))
1686 static int cmd_delete(char *arg)
1690 printf("Not connected yet\n");
1693 if (!send_deleteResultSetRequest(arg))
1698 static int cmd_ssub(char *arg)
1700 if (!(smallSetUpperBound = atoi(arg)))
1705 static int cmd_lslb(char *arg)
1707 if (!(largeSetLowerBound = atoi(arg)))
1712 static int cmd_mspn(char *arg)
1714 if (!(mediumSetPresentNumber = atoi(arg)))
1719 static int cmd_status(char *arg)
1721 printf("smallSetUpperBound: %d\n", smallSetUpperBound);
1722 printf("largeSetLowerBound: %d\n", largeSetLowerBound);
1723 printf("mediumSetPresentNumber: %d\n", mediumSetPresentNumber);
1727 static int cmd_setnames(char *arg)
1729 if (*arg == '1') /* enable ? */
1731 else if (*arg == '0') /* disable ? */
1733 else if (setnumber < 0) /* no args, toggle .. */
1739 printf("Set numbering enabled.\n");
1741 printf("Set numbering disabled.\n");
1745 /* PRESENT SERVICE ----------------------------- */
1747 static int send_presentRequest(char *arg)
1749 Z_APDU *apdu = zget_APDU(out, Z_APDU_presentRequest);
1750 Z_PresentRequest *req = apdu->u.presentRequest;
1751 Z_RecordComposition compo;
1756 char setstring[100];
1758 req->referenceId = set_refid (out);
1759 if ((p = strchr(arg, '+')))
1766 if (p && (p=strchr(p+1, '+')))
1768 strcpy (setstring, p+1);
1769 req->resultSetId = setstring;
1771 else if (setnumber >= 0)
1773 sprintf(setstring, "%d", setnumber);
1774 req->resultSetId = setstring;
1776 req->resultSetStartPoint = &setno;
1777 req->numberOfRecordsRequested = &nos;
1778 prefsyn.proto = protocol;
1779 prefsyn.oclass = CLASS_RECSYN;
1780 prefsyn.value = recordsyntax;
1781 req->preferredRecordSyntax =
1782 odr_oiddup (out, oid_ent_to_oid(&prefsyn, oid));
1784 if (schema != VAL_NONE)
1788 prefschema.proto = protocol;
1789 prefschema.oclass = CLASS_SCHEMA;
1790 prefschema.value = schema;
1792 req->recordComposition = &compo;
1793 compo.which = Z_RecordComp_complex;
1794 compo.u.complex = (Z_CompSpec *)
1795 odr_malloc(out, sizeof(*compo.u.complex));
1796 compo.u.complex->selectAlternativeSyntax = (bool_t *)
1797 odr_malloc(out, sizeof(bool_t));
1798 *compo.u.complex->selectAlternativeSyntax = 0;
1800 compo.u.complex->generic = (Z_Specification *)
1801 odr_malloc(out, sizeof(*compo.u.complex->generic));
1802 compo.u.complex->generic->schema = (Odr_oid *)
1803 odr_oiddup(out, oid_ent_to_oid(&prefschema, oid));
1804 if (!compo.u.complex->generic->schema)
1806 /* OID wasn't a schema! Try record syntax instead. */
1807 prefschema.oclass = CLASS_RECSYN;
1808 compo.u.complex->generic->schema = (Odr_oid *)
1809 odr_oiddup(out, oid_ent_to_oid(&prefschema, oid));
1811 if (!elementSetNames)
1812 compo.u.complex->generic->elementSpec = 0;
1815 compo.u.complex->generic->elementSpec = (Z_ElementSpec *)
1816 odr_malloc(out, sizeof(Z_ElementSpec));
1817 compo.u.complex->generic->elementSpec->which =
1818 Z_ElementSpec_elementSetName;
1819 compo.u.complex->generic->elementSpec->u.elementSetName =
1820 elementSetNames->u.generic;
1822 compo.u.complex->num_dbSpecific = 0;
1823 compo.u.complex->dbSpecific = 0;
1824 compo.u.complex->num_recordSyntax = 0;
1825 compo.u.complex->recordSyntax = 0;
1827 else if (elementSetNames)
1829 req->recordComposition = &compo;
1830 compo.which = Z_RecordComp_simple;
1831 compo.u.simple = elementSetNames;
1834 printf("Sent presentRequest (%d+%d).\n", setno, nos);
1838 static void close_session (void)
1844 nmem_destroy (session_mem);
1850 void process_close(Z_Close *req)
1852 Z_APDU *apdu = zget_APDU(out, Z_APDU_close);
1853 Z_Close *res = apdu->u.close;
1855 static char *reasons[] =
1860 "cost limit reached",
1862 "security violation",
1869 printf("Reason: %s, message: %s\n", reasons[*req->closeReason],
1870 req->diagnosticInformation ? req->diagnosticInformation : "NULL");
1875 *res->closeReason = Z_Close_finished;
1877 printf("Sent response.\n");
1882 static int cmd_show(char *arg)
1886 printf("Not connected yet\n");
1889 if (!send_presentRequest(arg))
1894 int cmd_quit(char *arg)
1896 printf("See you later, alligator.\n");
1902 int cmd_cancel(char *arg)
1904 Z_APDU *apdu = zget_APDU(out, Z_APDU_triggerResourceControlRequest);
1905 Z_TriggerResourceControlRequest *req =
1906 apdu->u.triggerResourceControlRequest;
1911 printf("Session not initialized yet\n");
1914 if (!ODR_MASK_GET(session->options, Z_Options_triggerResourceCtrl))
1916 printf("Target doesn't support cancel (trigger resource ctrl)\n");
1919 *req->requestedAction = Z_TriggerResourceCtrl_cancel;
1920 req->resultSetWanted = &rfalse;
1923 printf("Sent cancel request\n");
1927 int send_scanrequest(const char *query, int pp, int num, const char *term)
1929 Z_APDU *apdu = zget_APDU(out, Z_APDU_scanRequest);
1930 Z_ScanRequest *req = apdu->u.scanRequest;
1933 if (queryType == QueryType_CCL2RPN)
1937 struct ccl_rpn_node *rpn;
1939 rpn = ccl_find_str (bibset, query, &error, &pos);
1942 printf("CCL ERROR: %s\n", ccl_err_msg(error));
1945 bib1.proto = PROTO_Z3950;
1946 bib1.oclass = CLASS_ATTSET;
1947 bib1.value = VAL_BIB1;
1948 req->attributeSet = oid_ent_to_oid (&bib1, oid);
1949 if (!(req->termListAndStartPoint = ccl_scan_query (out, rpn)))
1951 printf("Couldn't convert CCL to Scan term\n");
1954 ccl_rpn_delete (rpn);
1958 YAZ_PQF_Parser pqf_parser = yaz_pqf_create ();
1960 if (!(req->termListAndStartPoint =
1961 yaz_pqf_scan(pqf_parser, out, &req->attributeSet, query)))
1963 const char *pqf_msg;
1965 int code = yaz_pqf_error (pqf_parser, &pqf_msg, &off);
1966 printf("%*s^\n", off+7, "");
1967 printf("Prefix query error: %s (code %d)\n", pqf_msg, code);
1968 yaz_pqf_destroy (pqf_parser);
1971 yaz_pqf_destroy (pqf_parser);
1975 if (req->termListAndStartPoint->term &&
1976 req->termListAndStartPoint->term->which == Z_Term_general &&
1977 req->termListAndStartPoint->term->u.general)
1979 req->termListAndStartPoint->term->u.general->buf =
1980 (unsigned char *) odr_strdup(out, term);
1981 req->termListAndStartPoint->term->u.general->len =
1982 req->termListAndStartPoint->term->u.general->size =
1986 req->referenceId = set_refid (out);
1987 req->num_databaseNames = num_databaseNames;
1988 req->databaseNames = databaseNames;
1989 req->numberOfTermsRequested = #
1990 req->preferredPositionInResponse = &pp;
1995 int send_sortrequest(char *arg, int newset)
1997 Z_APDU *apdu = zget_APDU(out, Z_APDU_sortRequest);
1998 Z_SortRequest *req = apdu->u.sortRequest;
1999 Z_SortKeySpecList *sksl = (Z_SortKeySpecList *)
2000 odr_malloc (out, sizeof(*sksl));
2004 sprintf (setstring, "%d", setnumber);
2006 sprintf (setstring, "default");
2008 req->referenceId = set_refid (out);
2010 req->num_inputResultSetNames = 1;
2011 req->inputResultSetNames = (Z_InternationalString **)
2012 odr_malloc (out, sizeof(*req->inputResultSetNames));
2013 req->inputResultSetNames[0] = odr_strdup (out, setstring);
2015 if (newset && setnumber >= 0)
2016 sprintf (setstring, "%d", ++setnumber);
2018 req->sortedResultSetName = odr_strdup (out, setstring);
2020 req->sortSequence = yaz_sort_spec (out, arg);
2021 if (!req->sortSequence)
2023 printf ("Missing sort specifications\n");
2030 void display_term(Z_TermInfo *t)
2032 if (t->term->which == Z_Term_general)
2034 printf("%.*s", t->term->u.general->len, t->term->u.general->buf);
2035 sprintf(last_scan_line, "%.*s", t->term->u.general->len,
2036 t->term->u.general->buf);
2039 printf("Term (not general)");
2040 if (t->globalOccurrences)
2041 printf (" (%d)\n", *t->globalOccurrences);
2046 void process_scanResponse(Z_ScanResponse *res)
2049 Z_Entry **entries = NULL;
2050 int num_entries = 0;
2052 printf("Received ScanResponse\n");
2053 print_refid (res->referenceId);
2054 printf("%d entries", *res->numberOfEntriesReturned);
2055 if (res->positionOfTerm)
2056 printf (", position=%d", *res->positionOfTerm);
2058 if (*res->scanStatus != Z_Scan_success)
2059 printf("Scan returned code %d\n", *res->scanStatus);
2062 if ((entries = res->entries->entries))
2063 num_entries = res->entries->num_entries;
2064 for (i = 0; i < num_entries; i++)
2066 int pos_term = res->positionOfTerm ? *res->positionOfTerm : -1;
2067 if (entries[i]->which == Z_Entry_termInfo)
2069 printf("%c ", i + 1 == pos_term ? '*' : ' ');
2070 display_term(entries[i]->u.termInfo);
2073 display_diagrecs(&entries[i]->u.surrogateDiagnostic, 1);
2075 if (res->entries->nonsurrogateDiagnostics)
2076 display_diagrecs (res->entries->nonsurrogateDiagnostics,
2077 res->entries->num_nonsurrogateDiagnostics);
2080 void process_sortResponse(Z_SortResponse *res)
2082 printf("Received SortResponse: status=");
2083 switch (*res->sortStatus)
2085 case Z_SortStatus_success:
2086 printf ("success"); break;
2087 case Z_SortStatus_partial_1:
2088 printf ("partial"); break;
2089 case Z_SortStatus_failure:
2090 printf ("failure"); break;
2092 printf ("unknown (%d)", *res->sortStatus);
2095 print_refid (res->referenceId);
2096 if (res->diagnostics)
2097 display_diagrecs(res->diagnostics,
2098 res->num_diagnostics);
2101 void process_deleteResultSetResponse (Z_DeleteResultSetResponse *res)
2103 printf("Got deleteResultSetResponse status=%d\n",
2104 *res->deleteOperationStatus);
2105 if (res->deleteListStatuses)
2108 for (i = 0; i < res->deleteListStatuses->num; i++)
2110 printf ("%s status=%d\n", res->deleteListStatuses->elements[i]->id,
2111 *res->deleteListStatuses->elements[i]->status);
2116 int cmd_sort_generic(char *arg, int newset)
2120 printf("Session not initialized yet\n");
2123 if (!ODR_MASK_GET(session->options, Z_Options_sort))
2125 printf("Target doesn't support sort\n");
2130 if (send_sortrequest(arg, newset) < 0)
2137 int cmd_sort(char *arg)
2139 return cmd_sort_generic (arg, 0);
2142 int cmd_sort_newset (char *arg)
2144 return cmd_sort_generic (arg, 1);
2147 int cmd_scan(char *arg)
2154 printf("Session not initialized yet\n");
2158 if (!ODR_MASK_GET(session->options, Z_Options_scan))
2160 printf("Target doesn't support scan\n");
2165 strcpy (last_scan_query, arg);
2166 if (send_scanrequest(arg, 1, 20, 0) < 0)
2171 if (send_scanrequest(last_scan_query, 1, 20, last_scan_line) < 0)
2177 int cmd_schema(char *arg)
2184 schema = oid_getvalbyname (arg);
2185 if (schema == VAL_NONE)
2187 printf ("unknown schema\n");
2193 int cmd_format(char *arg)
2197 printf("Usage: format <recordsyntax>\n");
2200 recordsyntax = oid_getvalbyname (arg);
2201 if (recordsyntax == VAL_NONE)
2203 printf ("unknown record syntax\n");
2209 int cmd_elements(char *arg)
2211 static Z_ElementSetNames esn;
2212 static char what[100];
2216 elementSetNames = 0;
2220 esn.which = Z_ElementSetNames_generic;
2221 esn.u.generic = what;
2222 elementSetNames = &esn;
2226 int cmd_attributeset(char *arg)
2232 printf("Usage: attributeset <setname>\n");
2235 sscanf(arg, "%s", what);
2236 if (p_query_attset (what))
2238 printf("Unknown attribute set name\n");
2244 int cmd_querytype (char *arg)
2246 if (!strcmp (arg, "ccl"))
2247 queryType = QueryType_CCL;
2248 else if (!strcmp (arg, "prefix") || !strcmp(arg, "rpn"))
2249 queryType = QueryType_Prefix;
2250 else if (!strcmp (arg, "ccl2rpn") || !strcmp (arg, "cclrpn"))
2251 queryType = QueryType_CCL2RPN;
2254 printf ("Querytype must be one of:\n");
2255 printf (" prefix - Prefix query\n");
2256 printf (" ccl - CCL query\n");
2257 printf (" ccl2rpn - CCL query converted to RPN\n");
2263 int cmd_refid (char *arg)
2269 refid = (char *) xmalloc (strlen(arg)+1);
2270 strcpy (refid, arg);
2275 int cmd_close(char *arg)
2282 apdu = zget_APDU(out, Z_APDU_close);
2283 req = apdu->u.close;
2284 *req->closeReason = Z_Close_finished;
2286 printf("Sent close request.\n");
2291 int cmd_packagename(char* arg)
2293 xfree (esPackageName);
2294 esPackageName = NULL;
2297 esPackageName = (char *) xmalloc (strlen(arg)+1);
2298 strcpy (esPackageName, arg);
2303 int cmd_proxy(char* arg)
2314 yazProxy = (char *) xmalloc (strlen(arg)+1);
2315 strcpy (yazProxy, arg);
2320 int cmd_charset(char* arg)
2322 char l1[30], l2[30];
2325 if (sscanf(arg, "%29s %29s", l1, l2) < 1)
2327 printf("Current character set is `%s'\n", (yazCharset) ? yazCharset:NULL);
2333 yazCharset = xstrdup(l1);
2336 odr_set_charset (out, l1, l2);
2337 odr_set_charset (in, l2, l1);
2342 int cmd_lang(char* arg)
2345 printf("Current language is `%s'\n", (yazLang)?yazLang:NULL);
2352 yazLang = (char *) xmalloc (strlen(arg)+1);
2353 strcpy (yazLang, arg);
2358 int cmd_source(char* arg)
2360 /* first should open the file and read one line at a time.. */
2362 char line[1024], *cp;
2365 char* args_end=(arg)+strlen(arg)-1;
2366 while(isspace(*args_end))
2371 REMOVE_TAILING_BLANKS(arg);
2374 fprintf(stderr,"Error in source command use a filename\n");
2378 includeFile = fopen (arg, "r");
2381 fprintf(stderr,"Unable to open file %s for reading\n",arg);
2385 while(!feof(includeFile)) {
2386 memset(line,0,sizeof(line));
2387 fgets(line,sizeof(line),includeFile);
2389 if(strlen(line) < 2) continue;
2390 if(line[0] == '#') continue;
2392 if ((cp = strrchr (line, '\n')))
2395 process_cmd_line(line);
2398 if(fclose(includeFile)<0) {
2399 perror("unable to close include file");
2405 int cmd_subshell(char* args)
2410 system(getenv("SHELL"));
2416 int cmd_set_apdufile(char* arg)
2418 REMOVE_TAILING_BLANKS(arg);
2420 if(apdu_file && apdu_file != stderr) { /* don't close stdout*/
2421 perror("unable to close apdu log file");
2429 if(!strcmp(arg,"-"))
2432 apdu_file=fopen(arg, "a");
2435 perror("unable to open apdu log file no apdu log loaded");
2437 odr_setprint(print, apdu_file);
2443 int cmd_set_cclfile(char* arg)
2447 REMOVE_TAILING_BLANKS(arg);
2449 bibset = ccl_qual_mk ();
2450 inf = fopen (arg, "r");
2453 ccl_qual_file (bibset, inf);
2456 strcpy(ccl_fields,arg);
2461 int cmd_set_auto_reconnect(char* arg)
2463 REMOVE_TAILING_BLANKS(arg);
2465 if(strlen(arg)==0) {
2466 auto_reconnect = ! auto_reconnect;
2467 } else if(strcmp(arg,"on")==0) {
2469 } else if(strcmp(arg,"off")==0) {
2472 printf("Error use on or off\n");
2477 printf("Set auto reconnect enabled.\n");
2479 printf("Set auto reconnect disabled.\n");
2484 int cmd_set_marcdump(char* arg)
2486 if(marcdump && marcdump != stderr) { /* don't close stdout*/
2487 perror("unable to close apdu log file");
2495 if(!strcmp(arg,"-"))
2498 marcdump=fopen(arg, "a");
2501 perror("unable to open apdu marcdump file no marcdump done\n");
2507 int cmd_set_proxy(char* arg)
2509 if(yazProxy) free(yazProxy);
2512 if(strlen(arg) > 1) {
2513 yazProxy=strdup(arg);
2519 this command takes 3 arge {name class oid}
2521 int cmd_register_oid(char* args) {
2526 {"appctx",CLASS_APPCTX},
2527 {"absyn",CLASS_ABSYN},
2528 {"attset",CLASS_ATTSET},
2529 {"transyn",CLASS_TRANSYN},
2530 {"diagset",CLASS_DIAGSET},
2531 {"recsyn",CLASS_RECSYN},
2532 {"resform",CLASS_RESFORM},
2533 {"accform",CLASS_ACCFORM},
2534 {"extserv",CLASS_EXTSERV},
2535 {"userinfo",CLASS_USERINFO},
2536 {"elemspec",CLASS_ELEMSPEC},
2537 {"varset",CLASS_VARSET},
2538 {"schema",CLASS_SCHEMA},
2539 {"tagset",CLASS_TAGSET},
2540 {"general",CLASS_GENERAL},
2543 char oname_str[101], oclass_str[101], oid_str[101];
2546 oid_class oidclass = CLASS_GENERAL;
2547 int val = 0, oid[OID_SIZE];
2548 struct oident * new_oident=NULL;
2550 if (sscanf (args, "%100[^ ] %100[^ ] %100s",
2551 oname_str,oclass_str, oid_str) < 1) {
2552 printf("Error in regristrate command \n");
2556 for (i = 0; oid_classes[i].className; i++) {
2557 if (!strcmp(oid_classes[i].className, oclass_str))
2559 oidclass=oid_classes[i].oclass;
2564 if(!(oid_classes[i].className)) {
2565 printf("Unknonwn oid class %s\n",oclass_str);
2573 while (isdigit (*name))
2575 val = val*10 + (*name - '0');
2588 new_oident=oid_addent (oid,PROTO_GENERAL,oidclass,oname_str,VAL_DYNAMIC);
2589 if(strcmp(new_oident->desc,oname_str)) {
2590 fprintf(stderr,"oid is already named as %s, regristration faild\n",
2596 int cmd_push_command(char* arg)
2598 #if HAVE_READLINE_HISTORY_H
2602 fprintf(stderr,"Not compiled with the readline/history module\n");
2607 void source_rcfile()
2609 /* Look for a $HOME/.yazclientrc and source it if it exists */
2610 struct stat statbuf;
2612 char* homedir=getenv("HOME");
2614 if(!homedir) return;
2616 sprintf(buffer,"%s/.yazclientrc",homedir);
2618 if(stat(buffer,&statbuf)==0) {
2622 if(stat(".yazclientrc",&statbuf)==0) {
2623 cmd_source(".yazclientrc");
2628 static void initialize(void)
2633 if (!(out = odr_createmem(ODR_ENCODE)) ||
2634 !(in = odr_createmem(ODR_DECODE)) ||
2635 !(print = odr_createmem(ODR_PRINT)))
2637 fprintf(stderr, "failed to allocate ODR streams\n");
2642 setvbuf(stdout, 0, _IONBF, 0);
2644 odr_setprint(print, apdu_file);
2646 bibset = ccl_qual_mk ();
2647 inf = fopen (ccl_fields, "r");
2650 ccl_qual_file (bibset, inf);
2653 cmd_base("Default");
2655 #if HAVE_READLINE_READLINE_H
2656 rl_attempted_completion_function = (CPPFunction*)readline_completer;
2660 for(i=0; i<maxOtherInfosSupported; ++i) {
2661 extraOtherInfos[i].oidval = -1;
2668 #if HAVE_GETTIMEOFDAY
2669 struct timeval tv_start, tv_end;
2672 void wait_and_handle_responce()
2677 int netbufferlen = 0;
2685 if ((res = cs_get(conn, &netbuffer, &netbufferlen)) < 0)
2687 printf("Target closed connection\n");
2693 printf("Target closed connection.\n");
2697 odr_reset(in); /* release APDU from last round */
2699 odr_setbuf(in, netbuffer, res, 0);
2700 if (!z_APDU(in, &apdu, 0, 0))
2702 odr_perror(in, "Decoding incoming APDU");
2703 fprintf(stderr, "[Near %d]\n", odr_offset(in));
2704 fprintf(stderr, "Packet dump:\n---------\n");
2705 odr_dumpBER(stderr, netbuffer, res);
2706 fprintf(stderr, "---------\n");
2708 z_APDU(print, &apdu, 0, 0);
2712 if (apdu_file && !z_APDU(print, &apdu, 0, 0))
2714 odr_perror(print, "Failed to print incoming APDU");
2720 case Z_APDU_initResponse:
2721 process_initResponse(apdu->u.initResponse);
2723 case Z_APDU_searchResponse:
2724 process_searchResponse(apdu->u.searchResponse);
2726 case Z_APDU_scanResponse:
2727 process_scanResponse(apdu->u.scanResponse);
2729 case Z_APDU_presentResponse:
2730 print_refid (apdu->u.presentResponse->referenceId);
2732 *apdu->u.presentResponse->numberOfRecordsReturned;
2733 if (apdu->u.presentResponse->records)
2734 display_records(apdu->u.presentResponse->records);
2736 printf("No records.\n");
2737 printf ("nextResultSetPosition = %d\n",
2738 *apdu->u.presentResponse->nextResultSetPosition);
2740 case Z_APDU_sortResponse:
2741 process_sortResponse(apdu->u.sortResponse);
2743 case Z_APDU_extendedServicesResponse:
2744 printf("Got extended services response\n");
2745 process_ESResponse(apdu->u.extendedServicesResponse);
2748 printf("Target has closed the association.\n");
2749 process_close(apdu->u.close);
2751 case Z_APDU_resourceControlRequest:
2752 process_resourceControlRequest
2753 (apdu->u.resourceControlRequest);
2755 case Z_APDU_deleteResultSetResponse:
2756 process_deleteResultSetResponse(apdu->u.
2757 deleteResultSetResponse);
2760 printf("Received unknown APDU type (%d).\n",
2765 while (conn && cs_more(conn));
2766 #if HAVE_GETTIMEOFDAY
2767 gettimeofday (&tv_end, 0);
2769 printf ("S/U S/U=%ld/%ld %ld/%ld",
2770 (long) tv_start.tv_sec,
2771 (long) tv_start.tv_usec,
2772 (long) tv_end.tv_sec,
2773 (long) tv_end.tv_usec);
2775 printf ("Elapsed: %.6f\n",
2776 (double) tv_end.tv_usec / 1e6 + tv_end.tv_sec -
2777 ((double) tv_start.tv_usec / 1e6 + tv_start.tv_sec));
2784 int cmd_cclparse(char* arg)
2787 struct ccl_rpn_node *rpn=NULL;
2790 rpn = ccl_find_str (bibset, arg, &error, &pos);
2793 printf ("%*s^ - ", 3+strlen(last_cmd)+1+pos, " ");
2794 printf ("%s\n", ccl_err_msg (error));
2800 ccl_pr_tree(rpn, stdout);
2804 ccl_rpn_delete(rpn);
2812 int cmd_set_otherinfo(char* args)
2814 char oid[101], otherinfoString[101];
2819 sscan_res = sscanf (args, "%d %100[^ ] %100s", &otherinfoNo, oid, otherinfoString);
2821 /* reset this otherinfo */
2822 if(otherinfoNo>=maxOtherInfosSupported) {
2823 printf("Error otherinfo index to large (%d>%d)\n",otherinfoNo,maxOtherInfosSupported);
2825 extraOtherInfos[otherinfoNo].oidval = -1;
2826 if(extraOtherInfos[otherinfoNo].value) free(extraOtherInfos[otherinfoNo].value);
2830 printf("Error in set_otherinfo command \n");
2834 if(otherinfoNo>=maxOtherInfosSupported) {
2835 printf("Error otherinfo index to large (%d>%d)\n",otherinfoNo,maxOtherInfosSupported);
2839 oidval = oid_getvalbyname (oid);
2841 printf("Error in set_otherinfo command unknown oid %s \n",oid);
2844 extraOtherInfos[otherinfoNo].oidval = oidval;
2845 if(extraOtherInfos[otherinfoNo].value) free(extraOtherInfos[otherinfoNo].value);
2846 extraOtherInfos[otherinfoNo].value = strdup(otherinfoString);
2851 int cmd_list_otherinfo(char* args)
2855 if(strlen(args)>0) {
2857 if( i >= maxOtherInfosSupported ) {
2858 printf("Error otherinfo index to large (%d>%d)\n",i,maxOtherInfosSupported);
2862 if(extraOtherInfos[i].oidval != -1)
2863 printf(" otherinfo %d %s %s\n",i,yaz_z3950_oid_value_to_str(extraOtherInfos[i].oidval,CLASS_RECSYN), extraOtherInfos[i].value);
2866 for(i=0; i<maxOtherInfosSupported; ++i) {
2867 if(extraOtherInfos[i].oidval != -1)
2868 printf(" otherinfo %d %s %s\n",i,yaz_z3950_oid_value_to_str(extraOtherInfos[i].oidval,CLASS_RECSYN), extraOtherInfos[i].value);
2876 int cmd_list_all(char* args) {
2879 /* connection options */
2881 printf("Connected to : %s\n",last_open_command);
2883 if(last_open_command)
2884 printf("Not connected to : %s\n",last_open_command);
2886 printf("Not connected : \n");
2889 if(yazProxy) printf("using proxy : %s\n",yazProxy);
2891 printf("auto_reconnect : %s\n",auto_reconnect?"on":"off");
2894 printf("Authentication : none\n");
2896 switch(auth->which) {
2897 case Z_IdAuthentication_idPass:
2898 printf("Authentication : IdPass\n");
2899 printf(" Login User : %s\n",auth->u.idPass->userId?auth->u.idPass->userId:"");
2900 printf(" Login Group : %s\n",auth->u.idPass->groupId?auth->u.idPass->groupId:"");
2901 printf(" Password : %s\n",auth->u.idPass->password?auth->u.idPass->password:"");
2903 case Z_IdAuthentication_open:
2904 printf("Authentication : psOpen\n");
2905 printf(" Open string : %s\n",auth->u.open);
2908 printf("Authentication : Unknown\n");
2911 if ( yazCharset ) printf("Character set : `%s'\n", (yazCharset) ? yazCharset:NULL);
2915 for (i = 0; i<num_databaseNames; i++) printf("%s ",databaseNames[i]);
2919 printf("CCL file : %s\n",ccl_fields);
2920 printf("Query type : %s\n",query_type_as_string(queryType));
2922 printf("Named Result Sets : %s\n",setnumber==-1?"off":"on");
2924 /* piggy back options */
2925 printf("ssub/lslb/mspn : %d/%d/%d\n",smallSetUpperBound,largeSetLowerBound,mediumSetPresentNumber);
2927 /* print present related options */
2928 printf("Format : %s\n",yaz_z3950_oid_value_to_str(recordsyntax,CLASS_RECSYN));
2929 printf("Schema : %s\n",yaz_z3950_oid_value_to_str(schema,CLASS_SCHEMA));
2930 printf("Elements : %s\n",elementSetNames?elementSetNames->u.generic:"");
2932 /* loging options */
2933 printf("APDU log : %s\n",apdu_file?"on":"off");
2934 printf("Record log : %s\n",marcdump?"on":"off");
2937 printf("Other Info: \n");
2938 cmd_list_otherinfo("");
2943 int cmd_clear_otherinfo(char* args)
2945 if(strlen(args)>0) {
2947 otherinfoNo = atoi(args);
2948 if( otherinfoNo >= maxOtherInfosSupported ) {
2949 printf("Error otherinfo index to large (%d>%d)\n",otherinfoNo,maxOtherInfosSupported);
2953 if(extraOtherInfos[otherinfoNo].oidval != -1) {
2954 /* only clear if set. */
2955 extraOtherInfos[otherinfoNo].oidval=-1;
2956 free(extraOtherInfos[otherinfoNo].value);
2961 for(i=0; i<maxOtherInfosSupported; ++i) {
2962 if (extraOtherInfos[i].oidval!=-1 ) {
2963 extraOtherInfos[i].oidval=-1;
2964 free(extraOtherInfos[i].value);
2971 static int cmd_help (char *line);
2973 typedef char *(*completerFunctionType)(const char *text, int state);
2977 int (*fun)(char *arg);
2979 completerFunctionType rl_completerfunction;
2980 int complete_filenames;
2981 char **local_tabcompletes;
2983 {"open", cmd_open, "('tcp'|'ssl')':<host>[':'<port>][/<db>]",NULL,0,NULL},
2984 {"quit", cmd_quit, "",NULL,0,NULL},
2985 {"find", cmd_find, "<query>",NULL,0,NULL},
2986 {"delete", cmd_delete, "<setname>",NULL,0,NULL},
2987 {"base", cmd_base, "<base-name>",NULL,0,NULL},
2988 {"show", cmd_show, "<rec#>['+'<#recs>['+'<setname>]]",NULL,0,NULL},
2989 {"scan", cmd_scan, "<term>",NULL,0,NULL},
2990 {"sort", cmd_sort, "<sortkey> <flag> <sortkey> <flag> ...",NULL,0,NULL},
2991 {"sort+", cmd_sort_newset, "<sortkey> <flag> <sortkey> <flag> ...",NULL,0,NULL},
2992 {"authentication", cmd_authentication, "<acctstring>",NULL,0,NULL},
2993 {"lslb", cmd_lslb, "<largeSetLowerBound>",NULL,0,NULL},
2994 {"ssub", cmd_ssub, "<smallSetUpperBound>",NULL,0,NULL},
2995 {"mspn", cmd_mspn, "<mediumSetPresentNumber>",NULL,0,NULL},
2996 {"status", cmd_status, "",NULL,0,NULL},
2997 {"setnames", cmd_setnames, "",NULL,0,NULL},
2998 {"cancel", cmd_cancel, "",NULL,0,NULL},
2999 {"format", cmd_format, "<recordsyntax>",complete_format,0,NULL},
3000 {"schema", cmd_schema, "<schema>",complete_schema,0,NULL},
3001 {"elements", cmd_elements, "<elementSetName>",NULL,0,NULL},
3002 {"close", cmd_close, "",NULL,0,NULL},
3003 {"attributeset", cmd_attributeset, "<attrset>",complete_attributeset,0,NULL},
3004 {"querytype", cmd_querytype, "<type>",complete_querytype,0,NULL},
3005 {"refid", cmd_refid, "<id>",NULL,0,NULL},
3006 {"itemorder", cmd_itemorder, "ill|item <itemno>",NULL,0,NULL},
3007 {"update", cmd_update, "<action> <recid> [<file>]",NULL,0,NULL},
3008 {"packagename", cmd_packagename, "<packagename>",NULL,0,NULL},
3009 {"proxy", cmd_proxy, "[('tcp'|'ssl')]<host>[':'<port>]",NULL,0,NULL},
3010 {"charset", cmd_charset, "<charset_name>",NULL,0,NULL},
3011 {"lang", cmd_lang, "<language_code>",NULL,0,NULL},
3012 {".", cmd_source, "<filename>",NULL,1,NULL},
3013 {"!", cmd_subshell, "Subshell command",NULL,1,NULL},
3014 {"set_apdufile", cmd_set_apdufile, "<filename>",NULL,1,NULL},
3015 {"set_marcdump", cmd_set_marcdump," <filename>",NULL,1,NULL},
3016 {"set_cclfile", cmd_set_cclfile," <filename>",NULL,1,NULL},
3017 {"set_auto_reconnect", cmd_set_auto_reconnect," on|off",complete_auto_reconnect,1,NULL},
3018 {"set_otherinfo", cmd_set_otherinfo,"<otherinfoinddex> <oid> <string>",NULL,0,NULL},
3019 {"register_oid", cmd_register_oid,"<name> <class> <oid>",NULL,0,NULL},
3020 {"push_command", cmd_push_command,"<command>",command_generator,0,NULL},
3021 {"register_tab", cmd_register_tab,"<commandname> <tab>",command_generator,0,NULL},
3022 {"cclparse", cmd_cclparse,"<ccl find command>",NULL,0,NULL},
3023 {"list_otherinfo",cmd_list_otherinfo,"[otherinfoinddex]",NULL,0,NULL},
3024 {"list_all",cmd_list_all,"",NULL,0,NULL},
3025 {"clear_otherinfo",cmd_clear_otherinfo,"",NULL,0,NULL},
3026 /* Server Admin Functions */
3027 {"adm-reindex", cmd_adm_reindex, "<database-name>",NULL,0,NULL},
3028 {"adm-truncate", cmd_adm_truncate, "('database'|'index')<object-name>",NULL,0,NULL},
3029 {"adm-create", cmd_adm_create, "",NULL,0,NULL},
3030 {"adm-drop", cmd_adm_drop, "('database'|'index')<object-name>",NULL,0,NULL},
3031 {"adm-import", cmd_adm_import, "<record-type> <dir> <pattern>",NULL,0,NULL},
3032 {"adm-refresh", cmd_adm_refresh, "",NULL,0,NULL},
3033 {"adm-commit", cmd_adm_commit, "",NULL,0,NULL},
3034 {"adm-shutdown", cmd_adm_shutdown, "",NULL,0,NULL},
3035 {"adm-startup", cmd_adm_startup, "",NULL,0,NULL},
3036 {"help", cmd_help, "", NULL,0,NULL},
3040 static int cmd_help (char *line)
3046 sscanf (line, "%20s", topic);
3049 printf("Commands:\n");
3050 for (i = 0; cmd[i].cmd; i++)
3051 if (*topic == 0 || strcmp (topic, cmd[i].cmd) == 0)
3052 printf(" %s %s\n", cmd[i].cmd, cmd[i].ad);
3053 if (strcmp (topic, "find") == 0)
3056 printf (" \"term\" Simple Term\n");
3057 printf (" @attr [attset] type=value op Attribute\n");
3058 printf (" @and opl opr And\n");
3059 printf (" @or opl opr Or\n");
3060 printf (" @not opl opr And-Not\n");
3061 printf (" @set set Result set\n");
3063 printf ("Bib-1 attribute types\n");
3065 printf ("4=Title 7=ISBN 8=ISSN 30=Date 62=Abstract 1003=Author 1016=Any\n");
3066 printf ("2=Relation: ");
3067 printf ("1< 2<= 3= 4>= 5> 6!= 102=Relevance\n");
3068 printf ("3=Position: ");
3069 printf ("1=First in Field 2=First in subfield 3=Any position\n");
3070 printf ("4=Structure: ");
3071 printf ("1=Phrase 2=Word 3=Key 4=Year 5=Date 6=WordList\n");
3072 printf ("5=Truncation: ");
3073 printf ("1=Right 2=Left 3=L&R 100=No 101=# 102=Re-1 103=Re-2\n");
3074 printf ("6=Completeness:");
3075 printf ("1=Incomplete subfield 2=Complete subfield 3=Complete field\n");
3080 int cmd_register_tab(char* arg) {
3082 char command[101], tabargument[101];
3087 if (sscanf (arg, "%100s %100s", command, tabargument) < 1) {
3091 /* locate the amdn in the list */
3092 for (i = 0; cmd[i].cmd; i++) {
3093 if (!strncmp(cmd[i].cmd, command, strlen(command))) {
3099 fprintf(stderr,"Unknown command %s\n",command);
3104 if(!cmd[i].local_tabcompletes) {
3105 cmd[i].local_tabcompletes = calloc(1,sizeof(char**));
3110 tabslist = cmd[i].local_tabcompletes;
3111 for(;tabslist && *tabslist;tabslist++) {
3115 cmd[i].local_tabcompletes =
3116 realloc(cmd[i].local_tabcompletes,(num_of_tabs+2)*sizeof(char**));
3117 tabslist=cmd[i].local_tabcompletes;
3118 tabslist[num_of_tabs]=strdup(tabargument);
3119 tabslist[num_of_tabs+1]=NULL;
3124 void process_cmd_line(char* line)
3127 char word[32], arg[1024];
3129 #if HAVE_GETTIMEOFDAY
3130 gettimeofday (&tv_start, 0);
3133 if ((res = sscanf(line, "%31s %1023[^;]", word, arg)) <= 0)
3135 strcpy(word, last_cmd);
3140 strcpy(last_cmd, word);
3142 /* removed tailing spaces from the arg command */
3145 char* lastnonspace=NULL;
3154 *(++lastnonspace) = 0;
3158 for (i = 0; cmd[i].cmd; i++)
3159 if (!strncmp(cmd[i].cmd, word, strlen(word)))
3161 res = (*cmd[i].fun)(arg);
3165 if (!cmd[i].cmd) /* dump our help-screen */
3167 printf("Unknown command: %s.\n", word);
3168 printf("use help for list of commands\n");
3169 /* cmd_help (""); */
3173 if(apdu_file) fflush(apdu_file);
3176 wait_and_handle_responce();
3185 char *command_generator(const char *text, int state)
3191 for( ; cmd[idx].cmd; ++idx) {
3192 if (!strncmp(cmd[idx].cmd,text,strlen(text))) {
3193 ++idx; /* skip this entry on the next run */
3194 return strdup(cmd[idx-1].cmd);
3202 This function only known how to complete on the first word
3204 char ** readline_completer(char *text, int start, int end) {
3205 #if HAVE_READLINE_READLINE_H
3207 completerFunctionType completerToUse;
3210 #if HAVE_READLINE_RL_COMPLETION_MATCHES
3211 char** res=rl_completion_matches(text,
3214 char** res=completion_matches(text,
3215 (CPFunction*)command_generator);
3217 rl_attempted_completion_over = 1;
3220 char arg[1024],word[32];
3222 if ((res = sscanf(rl_line_buffer, "%31s %1023[^;]", word, arg)) <= 0) {
3223 rl_attempted_completion_over = 1;
3227 for (i = 0; cmd[i].cmd; i++) {
3228 if (!strncmp(cmd[i].cmd, word, strlen(word))) {
3233 if(!cmd[i].cmd) return NULL;
3236 curret_global_list = cmd[i].local_tabcompletes;
3238 completerToUse = cmd[i].rl_completerfunction;
3239 if(completerToUse==NULL) /* if no pr. command completer is defined use the default completer */
3240 completerToUse = default_completer;
3242 if(completerToUse) {
3243 #ifdef HAVE_READLINE_RL_COMPLETION_MATCHES
3245 rl_completion_matches(text,
3249 completion_matches(text,
3250 (CPFunction*)completerToUse);
3252 if(!cmd[i].complete_filenames)
3253 rl_attempted_completion_over = 1;
3256 if(!cmd[i].complete_filenames)
3257 rl_attempted_completion_over = 1;
3267 static void client(void)
3273 #if HAVE_GETTIMEOFDAY
3274 gettimeofday (&tv_start, 0);
3279 char *line_in = NULL;
3280 #if HAVE_READLINE_READLINE_H
3283 line_in=readline(C_PROMPT);
3286 #if HAVE_READLINE_HISTORY_H
3288 add_history(line_in);
3290 strncpy(line, line_in, 1023);
3299 if (!fgets(line, 1023, stdin))
3301 if ((end_p = strchr (line, '\n')))
3304 process_cmd_line(line);
3308 int main(int argc, char **argv)
3311 char *open_command = 0;
3312 char *auth_command = 0;
3316 while ((ret = options("k:c:a:m:v:p:u:", argv, argc, &arg)) != -2)
3323 open_command = (char *) xmalloc (strlen(arg)+6);
3324 strcpy (open_command, "open ");
3325 strcat (open_command, arg);
3329 kilobytes = atoi(arg);
3332 if (!(marcdump = fopen (arg, "a")))
3339 strncpy (ccl_fields, arg, sizeof(ccl_fields)-1);
3340 ccl_fields[sizeof(ccl_fields)-1] = '\0';
3343 if (!strcmp(arg, "-"))
3346 apdu_file=fopen(arg, "a");
3349 yazProxy=strdup(arg);
3354 auth_command = (char *) xmalloc (strlen(arg)+6);
3355 strcpy (auth_command, "auth ");
3356 strcat (auth_command, arg);
3360 yaz_log_init (yaz_log_mask_str(arg), "", NULL);
3363 fprintf (stderr, "Usage: %s [-m <marclog>] [ -a <apdulog>] "
3364 "[-c cclfields]\n [-p <proxy-addr>] [-u <auth>] "
3365 "[-k size] [<server-addr>]\n",
3373 #ifdef HAVE_GETTIMEOFDAY
3374 gettimeofday (&tv_start, 0);
3376 process_cmd_line (auth_command);
3377 #if HAVE_READLINE_HISTORY_H
3378 add_history(auth_command);
3380 xfree(auth_command);
3384 #ifdef HAVE_GETTIMEOFDAY
3385 gettimeofday (&tv_start, 0);
3387 process_cmd_line (open_command);
3388 #if HAVE_READLINE_HISTORY_H
3389 add_history(open_command);
3391 xfree(open_command);
3402 * vim600: sw=4 ts=8 fdm=marker
3403 * vim<600: sw=4 ts=8