2 * Copyright (c) 1995-2002, Index Data
3 * See the file LICENSE for details.
5 * $Id: client.c,v 1.169 2002-09-17 11:07:30 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 laiter */
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 printf ("Update request\n");
1544 update_oid.proto = PROTO_Z3950;
1545 update_oid.oclass = CLASS_EXTSERV;
1546 update_oid.value = VAL_DBUPDATE;
1547 oid_ent_to_oid (&update_oid, oid);
1548 req->packageType = odr_oiddup(out,oid);
1549 req->packageName = esPackageName;
1551 req->referenceId = set_refid (out);
1553 r = req->taskSpecificParameters = (Z_External *)
1554 odr_malloc (out, sizeof(*r));
1555 r->direct_reference = odr_oiddup(out,oid);
1556 r->indirect_reference = 0;
1558 r->which = Z_External_update;
1559 r->u.update = (Z_IUUpdate *) odr_malloc(out, sizeof(*r->u.update));
1560 r->u.update->which = Z_IUUpdate_esRequest;
1561 r->u.update->u.esRequest = (Z_IUUpdateEsRequest *)
1562 odr_malloc(out, sizeof(*r->u.update->u.esRequest));
1563 toKeep = r->u.update->u.esRequest->toKeep = (Z_IUOriginPartToKeep *)
1564 odr_malloc(out, sizeof(*r->u.update->u.esRequest->toKeep));
1565 toKeep->databaseName = databaseNames[0];
1567 toKeep->elementSetName = 0;
1568 toKeep->actionQualifier = 0;
1569 toKeep->action = (int *) odr_malloc(out, sizeof(*toKeep->action));
1570 *toKeep->action = Z_IUOriginPartToKeep_recordInsert;
1572 notToKeep = r->u.update->u.esRequest->notToKeep = (Z_IUSuppliedRecords *)
1573 odr_malloc(out, sizeof(*r->u.update->u.esRequest->notToKeep));
1575 notToKeep->elements = (Z_IUSuppliedRecords_elem **)
1576 odr_malloc(out, sizeof(*notToKeep->elements));
1577 notToKeep->elements[0] = (Z_IUSuppliedRecords_elem *)
1578 odr_malloc(out, sizeof(**notToKeep->elements));
1579 notToKeep->elements[0]->u.number = 0;
1580 notToKeep->elements[0]->supplementalId = 0;
1581 notToKeep->elements[0]->correlationInfo = 0;
1582 notToKeep->elements[0]->record = record_last;
1589 static int cmd_itemorder(char *arg)
1594 if (sscanf (arg, "%10s %d", type, &itemno) != 2)
1597 printf("Item order request\n");
1599 send_itemorder(type, itemno);
1603 static int cmd_find(char *arg)
1607 printf("Find what?\n");
1615 printf("Not connected yet\n");
1619 if (!send_searchRequest(arg))
1624 static int cmd_delete(char *arg)
1628 printf("Not connected yet\n");
1631 if (!send_deleteResultSetRequest(arg))
1636 static int cmd_ssub(char *arg)
1638 if (!(smallSetUpperBound = atoi(arg)))
1643 static int cmd_lslb(char *arg)
1645 if (!(largeSetLowerBound = atoi(arg)))
1650 static int cmd_mspn(char *arg)
1652 if (!(mediumSetPresentNumber = atoi(arg)))
1657 static int cmd_status(char *arg)
1659 printf("smallSetUpperBound: %d\n", smallSetUpperBound);
1660 printf("largeSetLowerBound: %d\n", largeSetLowerBound);
1661 printf("mediumSetPresentNumber: %d\n", mediumSetPresentNumber);
1665 static int cmd_setnames(char *arg)
1667 if (*arg == '1') /* enable ? */
1669 else if (*arg == '0') /* disable ? */
1671 else if (setnumber < 0) /* no args, toggle .. */
1677 printf("Set numbering enabled.\n");
1679 printf("Set numbering disabled.\n");
1683 /* PRESENT SERVICE ----------------------------- */
1685 static int send_presentRequest(char *arg)
1687 Z_APDU *apdu = zget_APDU(out, Z_APDU_presentRequest);
1688 Z_PresentRequest *req = apdu->u.presentRequest;
1689 Z_RecordComposition compo;
1694 char setstring[100];
1696 req->referenceId = set_refid (out);
1697 if ((p = strchr(arg, '+')))
1704 if (p && (p=strchr(p+1, '+')))
1706 strcpy (setstring, p+1);
1707 req->resultSetId = setstring;
1709 else if (setnumber >= 0)
1711 sprintf(setstring, "%d", setnumber);
1712 req->resultSetId = setstring;
1714 req->resultSetStartPoint = &setno;
1715 req->numberOfRecordsRequested = &nos;
1716 prefsyn.proto = protocol;
1717 prefsyn.oclass = CLASS_RECSYN;
1718 prefsyn.value = recordsyntax;
1719 req->preferredRecordSyntax =
1720 odr_oiddup (out, oid_ent_to_oid(&prefsyn, oid));
1722 if (schema != VAL_NONE)
1726 prefschema.proto = protocol;
1727 prefschema.oclass = CLASS_SCHEMA;
1728 prefschema.value = schema;
1730 req->recordComposition = &compo;
1731 compo.which = Z_RecordComp_complex;
1732 compo.u.complex = (Z_CompSpec *)
1733 odr_malloc(out, sizeof(*compo.u.complex));
1734 compo.u.complex->selectAlternativeSyntax = (bool_t *)
1735 odr_malloc(out, sizeof(bool_t));
1736 *compo.u.complex->selectAlternativeSyntax = 0;
1738 compo.u.complex->generic = (Z_Specification *)
1739 odr_malloc(out, sizeof(*compo.u.complex->generic));
1740 compo.u.complex->generic->schema = (Odr_oid *)
1741 odr_oiddup(out, oid_ent_to_oid(&prefschema, oid));
1742 if (!compo.u.complex->generic->schema)
1744 /* OID wasn't a schema! Try record syntax instead. */
1745 prefschema.oclass = CLASS_RECSYN;
1746 compo.u.complex->generic->schema = (Odr_oid *)
1747 odr_oiddup(out, oid_ent_to_oid(&prefschema, oid));
1749 if (!elementSetNames)
1750 compo.u.complex->generic->elementSpec = 0;
1753 compo.u.complex->generic->elementSpec = (Z_ElementSpec *)
1754 odr_malloc(out, sizeof(Z_ElementSpec));
1755 compo.u.complex->generic->elementSpec->which =
1756 Z_ElementSpec_elementSetName;
1757 compo.u.complex->generic->elementSpec->u.elementSetName =
1758 elementSetNames->u.generic;
1760 compo.u.complex->num_dbSpecific = 0;
1761 compo.u.complex->dbSpecific = 0;
1762 compo.u.complex->num_recordSyntax = 0;
1763 compo.u.complex->recordSyntax = 0;
1765 else if (elementSetNames)
1767 req->recordComposition = &compo;
1768 compo.which = Z_RecordComp_simple;
1769 compo.u.simple = elementSetNames;
1772 printf("Sent presentRequest (%d+%d).\n", setno, nos);
1776 static void close_session (void)
1782 nmem_destroy (session_mem);
1788 void process_close(Z_Close *req)
1790 Z_APDU *apdu = zget_APDU(out, Z_APDU_close);
1791 Z_Close *res = apdu->u.close;
1793 static char *reasons[] =
1798 "cost limit reached",
1800 "security violation",
1807 printf("Reason: %s, message: %s\n", reasons[*req->closeReason],
1808 req->diagnosticInformation ? req->diagnosticInformation : "NULL");
1813 *res->closeReason = Z_Close_finished;
1815 printf("Sent response.\n");
1820 static int cmd_show(char *arg)
1824 printf("Not connected yet\n");
1827 if (!send_presentRequest(arg))
1832 int cmd_quit(char *arg)
1834 printf("See you later, alligator.\n");
1840 int cmd_cancel(char *arg)
1842 Z_APDU *apdu = zget_APDU(out, Z_APDU_triggerResourceControlRequest);
1843 Z_TriggerResourceControlRequest *req =
1844 apdu->u.triggerResourceControlRequest;
1849 printf("Session not initialized yet\n");
1852 if (!ODR_MASK_GET(session->options, Z_Options_triggerResourceCtrl))
1854 printf("Target doesn't support cancel (trigger resource ctrl)\n");
1857 *req->requestedAction = Z_TriggerResourceCtrl_cancel;
1858 req->resultSetWanted = &rfalse;
1861 printf("Sent cancel request\n");
1865 int send_scanrequest(const char *query, int pp, int num, const char *term)
1867 Z_APDU *apdu = zget_APDU(out, Z_APDU_scanRequest);
1868 Z_ScanRequest *req = apdu->u.scanRequest;
1871 if (queryType == QueryType_CCL2RPN)
1875 struct ccl_rpn_node *rpn;
1877 rpn = ccl_find_str (bibset, query, &error, &pos);
1880 printf("CCL ERROR: %s\n", ccl_err_msg(error));
1883 bib1.proto = PROTO_Z3950;
1884 bib1.oclass = CLASS_ATTSET;
1885 bib1.value = VAL_BIB1;
1886 req->attributeSet = oid_ent_to_oid (&bib1, oid);
1887 if (!(req->termListAndStartPoint = ccl_scan_query (out, rpn)))
1889 printf("Couldn't convert CCL to Scan term\n");
1892 ccl_rpn_delete (rpn);
1896 YAZ_PQF_Parser pqf_parser = yaz_pqf_create ();
1898 if (!(req->termListAndStartPoint =
1899 yaz_pqf_scan(pqf_parser, out, &req->attributeSet, query)))
1901 const char *pqf_msg;
1903 int code = yaz_pqf_error (pqf_parser, &pqf_msg, &off);
1904 printf("%*s^\n", off+7, "");
1905 printf("Prefix query error: %s (code %d)\n", pqf_msg, code);
1906 yaz_pqf_destroy (pqf_parser);
1909 yaz_pqf_destroy (pqf_parser);
1913 if (req->termListAndStartPoint->term &&
1914 req->termListAndStartPoint->term->which == Z_Term_general &&
1915 req->termListAndStartPoint->term->u.general)
1917 req->termListAndStartPoint->term->u.general->buf =
1918 (unsigned char *) odr_strdup(out, term);
1919 req->termListAndStartPoint->term->u.general->len =
1920 req->termListAndStartPoint->term->u.general->size =
1924 req->referenceId = set_refid (out);
1925 req->num_databaseNames = num_databaseNames;
1926 req->databaseNames = databaseNames;
1927 req->numberOfTermsRequested = #
1928 req->preferredPositionInResponse = &pp;
1933 int send_sortrequest(char *arg, int newset)
1935 Z_APDU *apdu = zget_APDU(out, Z_APDU_sortRequest);
1936 Z_SortRequest *req = apdu->u.sortRequest;
1937 Z_SortKeySpecList *sksl = (Z_SortKeySpecList *)
1938 odr_malloc (out, sizeof(*sksl));
1942 sprintf (setstring, "%d", setnumber);
1944 sprintf (setstring, "default");
1946 req->referenceId = set_refid (out);
1948 req->num_inputResultSetNames = 1;
1949 req->inputResultSetNames = (Z_InternationalString **)
1950 odr_malloc (out, sizeof(*req->inputResultSetNames));
1951 req->inputResultSetNames[0] = odr_strdup (out, setstring);
1953 if (newset && setnumber >= 0)
1954 sprintf (setstring, "%d", ++setnumber);
1956 req->sortedResultSetName = odr_strdup (out, setstring);
1958 req->sortSequence = yaz_sort_spec (out, arg);
1959 if (!req->sortSequence)
1961 printf ("Missing sort specifications\n");
1968 void display_term(Z_TermInfo *t)
1970 if (t->term->which == Z_Term_general)
1972 printf("%.*s", t->term->u.general->len, t->term->u.general->buf);
1973 sprintf(last_scan_line, "%.*s", t->term->u.general->len,
1974 t->term->u.general->buf);
1977 printf("Term (not general)");
1978 if (t->globalOccurrences)
1979 printf (" (%d)\n", *t->globalOccurrences);
1984 void process_scanResponse(Z_ScanResponse *res)
1987 Z_Entry **entries = NULL;
1988 int num_entries = 0;
1990 printf("Received ScanResponse\n");
1991 print_refid (res->referenceId);
1992 printf("%d entries", *res->numberOfEntriesReturned);
1993 if (res->positionOfTerm)
1994 printf (", position=%d", *res->positionOfTerm);
1996 if (*res->scanStatus != Z_Scan_success)
1997 printf("Scan returned code %d\n", *res->scanStatus);
2000 if ((entries = res->entries->entries))
2001 num_entries = res->entries->num_entries;
2002 for (i = 0; i < num_entries; i++)
2004 int pos_term = res->positionOfTerm ? *res->positionOfTerm : -1;
2005 if (entries[i]->which == Z_Entry_termInfo)
2007 printf("%c ", i + 1 == pos_term ? '*' : ' ');
2008 display_term(entries[i]->u.termInfo);
2011 display_diagrecs(&entries[i]->u.surrogateDiagnostic, 1);
2013 if (res->entries->nonsurrogateDiagnostics)
2014 display_diagrecs (res->entries->nonsurrogateDiagnostics,
2015 res->entries->num_nonsurrogateDiagnostics);
2018 void process_sortResponse(Z_SortResponse *res)
2020 printf("Received SortResponse: status=");
2021 switch (*res->sortStatus)
2023 case Z_SortStatus_success:
2024 printf ("success"); break;
2025 case Z_SortStatus_partial_1:
2026 printf ("partial"); break;
2027 case Z_SortStatus_failure:
2028 printf ("failure"); break;
2030 printf ("unknown (%d)", *res->sortStatus);
2033 print_refid (res->referenceId);
2034 if (res->diagnostics)
2035 display_diagrecs(res->diagnostics,
2036 res->num_diagnostics);
2039 void process_deleteResultSetResponse (Z_DeleteResultSetResponse *res)
2041 printf("Got deleteResultSetResponse status=%d\n",
2042 *res->deleteOperationStatus);
2043 if (res->deleteListStatuses)
2046 for (i = 0; i < res->deleteListStatuses->num; i++)
2048 printf ("%s status=%d\n", res->deleteListStatuses->elements[i]->id,
2049 *res->deleteListStatuses->elements[i]->status);
2054 int cmd_sort_generic(char *arg, int newset)
2058 printf("Session not initialized yet\n");
2061 if (!ODR_MASK_GET(session->options, Z_Options_sort))
2063 printf("Target doesn't support sort\n");
2068 if (send_sortrequest(arg, newset) < 0)
2075 int cmd_sort(char *arg)
2077 return cmd_sort_generic (arg, 0);
2080 int cmd_sort_newset (char *arg)
2082 return cmd_sort_generic (arg, 1);
2085 int cmd_scan(char *arg)
2092 printf("Session not initialized yet\n");
2096 if (!ODR_MASK_GET(session->options, Z_Options_scan))
2098 printf("Target doesn't support scan\n");
2103 strcpy (last_scan_query, arg);
2104 if (send_scanrequest(arg, 1, 20, 0) < 0)
2109 if (send_scanrequest(last_scan_query, 1, 20, last_scan_line) < 0)
2115 int cmd_schema(char *arg)
2122 schema = oid_getvalbyname (arg);
2123 if (schema == VAL_NONE)
2125 printf ("unknown schema\n");
2131 int cmd_format(char *arg)
2135 printf("Usage: format <recordsyntax>\n");
2138 recordsyntax = oid_getvalbyname (arg);
2139 if (recordsyntax == VAL_NONE)
2141 printf ("unknown record syntax\n");
2147 int cmd_elements(char *arg)
2149 static Z_ElementSetNames esn;
2150 static char what[100];
2154 elementSetNames = 0;
2158 esn.which = Z_ElementSetNames_generic;
2159 esn.u.generic = what;
2160 elementSetNames = &esn;
2164 int cmd_attributeset(char *arg)
2170 printf("Usage: attributeset <setname>\n");
2173 sscanf(arg, "%s", what);
2174 if (p_query_attset (what))
2176 printf("Unknown attribute set name\n");
2182 int cmd_querytype (char *arg)
2184 if (!strcmp (arg, "ccl"))
2185 queryType = QueryType_CCL;
2186 else if (!strcmp (arg, "prefix") || !strcmp(arg, "rpn"))
2187 queryType = QueryType_Prefix;
2188 else if (!strcmp (arg, "ccl2rpn") || !strcmp (arg, "cclrpn"))
2189 queryType = QueryType_CCL2RPN;
2192 printf ("Querytype must be one of:\n");
2193 printf (" prefix - Prefix query\n");
2194 printf (" ccl - CCL query\n");
2195 printf (" ccl2rpn - CCL query converted to RPN\n");
2201 int cmd_refid (char *arg)
2207 refid = (char *) xmalloc (strlen(arg)+1);
2208 strcpy (refid, arg);
2213 int cmd_close(char *arg)
2220 apdu = zget_APDU(out, Z_APDU_close);
2221 req = apdu->u.close;
2222 *req->closeReason = Z_Close_finished;
2224 printf("Sent close request.\n");
2229 int cmd_packagename(char* arg)
2231 xfree (esPackageName);
2232 esPackageName = NULL;
2235 esPackageName = (char *) xmalloc (strlen(arg)+1);
2236 strcpy (esPackageName, arg);
2241 int cmd_proxy(char* arg)
2252 yazProxy = (char *) xmalloc (strlen(arg)+1);
2253 strcpy (yazProxy, arg);
2258 int cmd_charset(char* arg)
2260 char l1[30], l2[30];
2263 if (sscanf(arg, "%29s %29s", l1, l2) < 1)
2265 printf("Current character set is `%s'\n", (yazCharset) ? yazCharset:NULL);
2271 yazCharset = xstrdup(l1);
2274 odr_set_charset (out, l1, l2);
2275 odr_set_charset (in, l2, l1);
2280 int cmd_lang(char* arg)
2283 printf("Current language is `%s'\n", (yazLang)?yazLang:NULL);
2290 yazLang = (char *) xmalloc (strlen(arg)+1);
2291 strcpy (yazLang, arg);
2296 int cmd_source(char* arg)
2298 /* first should open the file and read one line at a time.. */
2300 char line[1024], *cp;
2303 char* args_end=(arg)+strlen(arg)-1;
2304 while(isspace(*args_end))
2309 REMOVE_TAILING_BLANKS(arg);
2312 fprintf(stderr,"Error in source command use a filename\n");
2316 includeFile = fopen (arg, "r");
2319 fprintf(stderr,"Unable to open file %s for reading\n",arg);
2323 while(!feof(includeFile)) {
2324 memset(line,0,sizeof(line));
2325 fgets(line,sizeof(line),includeFile);
2327 if(strlen(line) < 2) continue;
2328 if(line[0] == '#') continue;
2330 if ((cp = strrchr (line, '\n')))
2333 process_cmd_line(line);
2336 if(fclose(includeFile)<0) {
2337 perror("unable to close include file");
2343 int cmd_subshell(char* args)
2348 system(getenv("SHELL"));
2354 int cmd_set_apdufile(char* arg)
2356 REMOVE_TAILING_BLANKS(arg);
2358 if(apdu_file && apdu_file != stderr) { /* don't close stdout*/
2359 perror("unable to close apdu log file");
2367 if(!strcmp(arg,"-"))
2370 apdu_file=fopen(arg, "a");
2373 perror("unable to open apdu log file no apdu log loaded");
2375 odr_setprint(print, apdu_file);
2381 int cmd_set_cclfile(char* arg)
2385 REMOVE_TAILING_BLANKS(arg);
2387 bibset = ccl_qual_mk ();
2388 inf = fopen (arg, "r");
2391 ccl_qual_file (bibset, inf);
2394 strcpy(ccl_fields,arg);
2399 int cmd_set_auto_reconnect(char* arg)
2401 REMOVE_TAILING_BLANKS(arg);
2403 if(strlen(arg)==0) {
2404 auto_reconnect = ! auto_reconnect;
2405 } else if(strcmp(arg,"on")==0) {
2407 } else if(strcmp(arg,"off")==0) {
2410 printf("Error use on or off\n");
2415 printf("Set auto reconnect enabled.\n");
2417 printf("Set auto reconnect disabled.\n");
2422 int cmd_set_marcdump(char* arg)
2424 if(marcdump && marcdump != stderr) { /* don't close stdout*/
2425 perror("unable to close apdu log file");
2433 if(!strcmp(arg,"-"))
2436 marcdump=fopen(arg, "a");
2439 perror("unable to open apdu marcdump file no marcdump done\n");
2445 int cmd_set_proxy(char* arg)
2447 if(yazProxy) free(yazProxy);
2450 if(strlen(arg) > 1) {
2451 yazProxy=strdup(arg);
2457 this command takes 3 arge {name class oid}
2459 int cmd_register_oid(char* args) {
2464 {"appctx",CLASS_APPCTX},
2465 {"absyn",CLASS_ABSYN},
2466 {"attset",CLASS_ATTSET},
2467 {"transyn",CLASS_TRANSYN},
2468 {"diagset",CLASS_DIAGSET},
2469 {"recsyn",CLASS_RECSYN},
2470 {"resform",CLASS_RESFORM},
2471 {"accform",CLASS_ACCFORM},
2472 {"extserv",CLASS_EXTSERV},
2473 {"userinfo",CLASS_USERINFO},
2474 {"elemspec",CLASS_ELEMSPEC},
2475 {"varset",CLASS_VARSET},
2476 {"schema",CLASS_SCHEMA},
2477 {"tagset",CLASS_TAGSET},
2478 {"general",CLASS_GENERAL},
2481 char oname_str[101], oclass_str[101], oid_str[101];
2484 oid_class oidclass = CLASS_GENERAL;
2485 int val = 0, oid[OID_SIZE];
2486 struct oident * new_oident=NULL;
2488 if (sscanf (args, "%100[^ ] %100[^ ] %100s",
2489 oname_str,oclass_str, oid_str) < 1) {
2490 printf("Error in regristrate command \n");
2494 for (i = 0; oid_classes[i].className; i++) {
2495 if (!strcmp(oid_classes[i].className, oclass_str))
2497 oidclass=oid_classes[i].oclass;
2502 if(!(oid_classes[i].className)) {
2503 printf("Unknonwn oid class %s\n",oclass_str);
2511 while (isdigit (*name))
2513 val = val*10 + (*name - '0');
2526 new_oident=oid_addent (oid,PROTO_GENERAL,oidclass,oname_str,VAL_DYNAMIC);
2527 if(strcmp(new_oident->desc,oname_str)) {
2528 fprintf(stderr,"oid is already named as %s, regristration faild\n",
2534 int cmd_push_command(char* arg)
2536 #if HAVE_READLINE_HISTORY_H
2540 fprintf(stderr,"Not compiled with the readline/history module\n");
2545 void source_rcfile()
2547 /* Look for a $HOME/.yazclientrc and source it if it exists */
2548 struct stat statbuf;
2550 char* homedir=getenv("HOME");
2552 if(!homedir) return;
2554 sprintf(buffer,"%s/.yazclientrc",homedir);
2556 if(stat(buffer,&statbuf)==0) {
2560 if(stat(".yazclientrc",&statbuf)==0) {
2561 cmd_source(".yazclientrc");
2566 static void initialize(void)
2571 if (!(out = odr_createmem(ODR_ENCODE)) ||
2572 !(in = odr_createmem(ODR_DECODE)) ||
2573 !(print = odr_createmem(ODR_PRINT)))
2575 fprintf(stderr, "failed to allocate ODR streams\n");
2580 setvbuf(stdout, 0, _IONBF, 0);
2582 odr_setprint(print, apdu_file);
2584 bibset = ccl_qual_mk ();
2585 inf = fopen (ccl_fields, "r");
2588 ccl_qual_file (bibset, inf);
2591 cmd_base("Default");
2593 #if HAVE_READLINE_READLINE_H
2594 rl_attempted_completion_function = (CPPFunction*)readline_completer;
2598 for(i=0; i<maxOtherInfosSupported; ++i) {
2599 extraOtherInfos[i].oidval = -1;
2606 #if HAVE_GETTIMEOFDAY
2607 struct timeval tv_start, tv_end;
2610 void wait_and_handle_responce()
2615 int netbufferlen = 0;
2623 if ((res = cs_get(conn, &netbuffer, &netbufferlen)) < 0)
2625 printf("Target closed connection\n");
2631 printf("Target closed connection.\n");
2635 odr_reset(in); /* release APDU from last round */
2637 odr_setbuf(in, netbuffer, res, 0);
2638 if (!z_APDU(in, &apdu, 0, 0))
2640 odr_perror(in, "Decoding incoming APDU");
2641 fprintf(stderr, "[Near %d]\n", odr_offset(in));
2642 fprintf(stderr, "Packet dump:\n---------\n");
2643 odr_dumpBER(stderr, netbuffer, res);
2644 fprintf(stderr, "---------\n");
2646 z_APDU(print, &apdu, 0, 0);
2650 if (apdu_file && !z_APDU(print, &apdu, 0, 0))
2652 odr_perror(print, "Failed to print incoming APDU");
2658 case Z_APDU_initResponse:
2659 process_initResponse(apdu->u.initResponse);
2661 case Z_APDU_searchResponse:
2662 process_searchResponse(apdu->u.searchResponse);
2664 case Z_APDU_scanResponse:
2665 process_scanResponse(apdu->u.scanResponse);
2667 case Z_APDU_presentResponse:
2668 print_refid (apdu->u.presentResponse->referenceId);
2670 *apdu->u.presentResponse->numberOfRecordsReturned;
2671 if (apdu->u.presentResponse->records)
2672 display_records(apdu->u.presentResponse->records);
2674 printf("No records.\n");
2675 printf ("nextResultSetPosition = %d\n",
2676 *apdu->u.presentResponse->nextResultSetPosition);
2678 case Z_APDU_sortResponse:
2679 process_sortResponse(apdu->u.sortResponse);
2681 case Z_APDU_extendedServicesResponse:
2682 printf("Got extended services response\n");
2683 process_ESResponse(apdu->u.extendedServicesResponse);
2686 printf("Target has closed the association.\n");
2687 process_close(apdu->u.close);
2689 case Z_APDU_resourceControlRequest:
2690 process_resourceControlRequest
2691 (apdu->u.resourceControlRequest);
2693 case Z_APDU_deleteResultSetResponse:
2694 process_deleteResultSetResponse(apdu->u.
2695 deleteResultSetResponse);
2698 printf("Received unknown APDU type (%d).\n",
2703 while (conn && cs_more(conn));
2704 #if HAVE_GETTIMEOFDAY
2705 gettimeofday (&tv_end, 0);
2707 printf ("S/U S/U=%ld/%ld %ld/%ld",
2708 (long) tv_start.tv_sec,
2709 (long) tv_start.tv_usec,
2710 (long) tv_end.tv_sec,
2711 (long) tv_end.tv_usec);
2713 printf ("Elapsed: %.6f\n",
2714 (double) tv_end.tv_usec / 1e6 + tv_end.tv_sec -
2715 ((double) tv_start.tv_usec / 1e6 + tv_start.tv_sec));
2722 int cmd_cclparse(char* arg)
2725 struct ccl_rpn_node *rpn=NULL;
2728 rpn = ccl_find_str (bibset, arg, &error, &pos);
2731 printf ("%*s^ - ", 3+strlen(last_cmd)+1+pos, " ");
2732 printf ("%s\n", ccl_err_msg (error));
2738 ccl_pr_tree(rpn, stdout);
2742 ccl_rpn_delete(rpn);
2750 int cmd_set_otherinfo(char* args)
2752 char oid[101], otherinfoString[101];
2757 sscan_res = sscanf (args, "%d %100[^ ] %100s", &otherinfoNo, oid, otherinfoString);
2759 /* reset this otherinfo */
2760 if(otherinfoNo>=maxOtherInfosSupported) {
2761 printf("Error otherinfo index to large (%d>%d)\n",otherinfoNo,maxOtherInfosSupported);
2763 extraOtherInfos[otherinfoNo].oidval = -1;
2764 if(extraOtherInfos[otherinfoNo].value) free(extraOtherInfos[otherinfoNo].value);
2768 printf("Error in set_otherinfo command \n");
2772 if(otherinfoNo>=maxOtherInfosSupported) {
2773 printf("Error otherinfo index to large (%d>%d)\n",otherinfoNo,maxOtherInfosSupported);
2777 oidval = oid_getvalbyname (oid);
2779 printf("Error in set_otherinfo command unknown oid %s \n",oid);
2782 extraOtherInfos[otherinfoNo].oidval = oidval;
2783 if(extraOtherInfos[otherinfoNo].value) free(extraOtherInfos[otherinfoNo].value);
2784 extraOtherInfos[otherinfoNo].value = strdup(otherinfoString);
2789 int cmd_list_otherinfo(char* args)
2793 if(strlen(args)>0) {
2795 if( i >= maxOtherInfosSupported ) {
2796 printf("Error otherinfo index to large (%d>%d)\n",i,maxOtherInfosSupported);
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);
2804 for(i=0; i<maxOtherInfosSupported; ++i) {
2805 if(extraOtherInfos[i].oidval != -1)
2806 printf(" otherinfo %d %s %s\n",i,yaz_z3950_oid_value_to_str(extraOtherInfos[i].oidval,CLASS_RECSYN), extraOtherInfos[i].value);
2814 int cmd_list_all(char* args) {
2817 /* connection options */
2819 printf("Connected to : %s\n",last_open_command);
2821 if(last_open_command)
2822 printf("Not connected to : %s\n",last_open_command);
2824 printf("Not connected : \n");
2827 if(yazProxy) printf("using proxy : %s\n",yazProxy);
2829 printf("auto_reconnect : %s\n",auto_reconnect?"on":"off");
2832 printf("Authentication : none\n");
2834 switch(auth->which) {
2835 case Z_IdAuthentication_idPass:
2836 printf("Authentication : IdPass\n");
2837 printf(" Login User : %s\n",auth->u.idPass->userId?auth->u.idPass->userId:"");
2838 printf(" Login Group : %s\n",auth->u.idPass->groupId?auth->u.idPass->groupId:"");
2839 printf(" Password : %s\n",auth->u.idPass->password?auth->u.idPass->password:"");
2841 case Z_IdAuthentication_open:
2842 printf("Authentication : psOpen\n");
2843 printf(" Open string : %s\n",auth->u.open);
2846 printf("Authentication : Unknown\n");
2849 if ( yazCharset ) printf("Character set : `%s'\n", (yazCharset) ? yazCharset:NULL);
2853 for (i = 0; i<num_databaseNames; i++) printf("%s ",databaseNames[i]);
2857 printf("CCL file : %s\n",ccl_fields);
2858 printf("Query type : %s\n",query_type_as_string(queryType));
2860 printf("Named Result Sets : %s\n",setnumber==-1?"off":"on");
2862 /* piggy back options */
2863 printf("ssub/lslb/mspn : %d/%d/%d\n",smallSetUpperBound,largeSetLowerBound,mediumSetPresentNumber);
2865 /* print present related options */
2866 printf("Format : %s\n",yaz_z3950_oid_value_to_str(recordsyntax,CLASS_RECSYN));
2867 printf("Schema : %s\n",yaz_z3950_oid_value_to_str(schema,CLASS_SCHEMA));
2868 printf("Elements : %s\n",elementSetNames?elementSetNames->u.generic:"");
2870 /* loging options */
2871 printf("APDU log : %s\n",apdu_file?"on":"off");
2872 printf("Record log : %s\n",marcdump?"on":"off");
2875 printf("Other Info: \n");
2876 cmd_list_otherinfo("");
2881 int cmd_clear_otherinfo(char* args)
2883 if(strlen(args)>0) {
2885 otherinfoNo = atoi(args);
2886 if( otherinfoNo >= maxOtherInfosSupported ) {
2887 printf("Error otherinfo index to large (%d>%d)\n",otherinfoNo,maxOtherInfosSupported);
2891 if(extraOtherInfos[otherinfoNo].oidval != -1) {
2892 /* only clear if set. */
2893 extraOtherInfos[otherinfoNo].oidval=-1;
2894 free(extraOtherInfos[otherinfoNo].value);
2899 for(i=0; i<maxOtherInfosSupported; ++i) {
2900 if (extraOtherInfos[i].oidval!=-1 ) {
2901 extraOtherInfos[i].oidval=-1;
2902 free(extraOtherInfos[i].value);
2909 static int cmd_help (char *line);
2911 typedef char *(*completerFunctionType)(const char *text, int state);
2915 int (*fun)(char *arg);
2917 completerFunctionType rl_completerfunction;
2918 int complete_filenames;
2919 char **local_tabcompletes;
2921 {"open", cmd_open, "('tcp'|'ssl')':<host>[':'<port>][/<db>]",NULL,0,NULL},
2922 {"quit", cmd_quit, "",NULL,0,NULL},
2923 {"find", cmd_find, "<query>",NULL,0,NULL},
2924 {"delete", cmd_delete, "<setname>",NULL,0,NULL},
2925 {"base", cmd_base, "<base-name>",NULL,0,NULL},
2926 {"show", cmd_show, "<rec#>['+'<#recs>['+'<setname>]]",NULL,0,NULL},
2927 {"scan", cmd_scan, "<term>",NULL,0,NULL},
2928 {"sort", cmd_sort, "<sortkey> <flag> <sortkey> <flag> ...",NULL,0,NULL},
2929 {"sort+", cmd_sort_newset, "<sortkey> <flag> <sortkey> <flag> ...",NULL,0,NULL},
2930 {"authentication", cmd_authentication, "<acctstring>",NULL,0,NULL},
2931 {"lslb", cmd_lslb, "<largeSetLowerBound>",NULL,0,NULL},
2932 {"ssub", cmd_ssub, "<smallSetUpperBound>",NULL,0,NULL},
2933 {"mspn", cmd_mspn, "<mediumSetPresentNumber>",NULL,0,NULL},
2934 {"status", cmd_status, "",NULL,0,NULL},
2935 {"setnames", cmd_setnames, "",NULL,0,NULL},
2936 {"cancel", cmd_cancel, "",NULL,0,NULL},
2937 {"format", cmd_format, "<recordsyntax>",complete_format,0,NULL},
2938 {"schema", cmd_schema, "<schema>",complete_schema,0,NULL},
2939 {"elements", cmd_elements, "<elementSetName>",NULL,0,NULL},
2940 {"close", cmd_close, "",NULL,0,NULL},
2941 {"attributeset", cmd_attributeset, "<attrset>",complete_attributeset,0,NULL},
2942 {"querytype", cmd_querytype, "<type>",complete_querytype,0,NULL},
2943 {"refid", cmd_refid, "<id>",NULL,0,NULL},
2944 {"itemorder", cmd_itemorder, "ill|item <itemno>",NULL,0,NULL},
2945 {"update", cmd_update, "<item>",NULL,0,NULL},
2946 {"packagename", cmd_packagename, "<packagename>",NULL,0,NULL},
2947 {"proxy", cmd_proxy, "[('tcp'|'ssl')]<host>[':'<port>]",NULL,0,NULL},
2948 {"charset", cmd_charset, "<charset_name>",NULL,0,NULL},
2949 {"lang", cmd_lang, "<language_code>",NULL,0,NULL},
2950 {".", cmd_source, "<filename>",NULL,1,NULL},
2951 {"!", cmd_subshell, "Subshell command",NULL,1,NULL},
2952 {"set_apdufile", cmd_set_apdufile, "<filename>",NULL,1,NULL},
2953 {"set_marcdump", cmd_set_marcdump," <filename>",NULL,1,NULL},
2954 {"set_cclfile", cmd_set_cclfile," <filename>",NULL,1,NULL},
2955 {"set_auto_reconnect", cmd_set_auto_reconnect," on|off",complete_auto_reconnect,1,NULL},
2956 {"set_otherinfo", cmd_set_otherinfo,"<otherinfoinddex> <oid> <string>",NULL,0,NULL},
2957 {"register_oid", cmd_register_oid,"<name> <class> <oid>",NULL,0,NULL},
2958 {"push_command", cmd_push_command,"<command>",command_generator,0,NULL},
2959 {"register_tab", cmd_register_tab,"<commandname> <tab>",command_generator,0,NULL},
2960 {"cclparse", cmd_cclparse,"<ccl find command>",NULL,0,NULL},
2961 {"list_otherinfo",cmd_list_otherinfo,"[otherinfoinddex]",NULL,0,NULL},
2962 {"list_all",cmd_list_all,"",NULL,0,NULL},
2963 {"clear_otherinfo",cmd_clear_otherinfo,"",NULL,0,NULL},
2964 /* Server Admin Functions */
2965 {"adm-reindex", cmd_adm_reindex, "<database-name>",NULL,0,NULL},
2966 {"adm-truncate", cmd_adm_truncate, "('database'|'index')<object-name>",NULL,0,NULL},
2967 {"adm-create", cmd_adm_create, "",NULL,0,NULL},
2968 {"adm-drop", cmd_adm_drop, "('database'|'index')<object-name>",NULL,0,NULL},
2969 {"adm-import", cmd_adm_import, "<record-type> <dir> <pattern>",NULL,0,NULL},
2970 {"adm-refresh", cmd_adm_refresh, "",NULL,0,NULL},
2971 {"adm-commit", cmd_adm_commit, "",NULL,0,NULL},
2972 {"adm-shutdown", cmd_adm_shutdown, "",NULL,0,NULL},
2973 {"adm-startup", cmd_adm_startup, "",NULL,0,NULL},
2974 {"help", cmd_help, "", NULL,0,NULL},
2978 static int cmd_help (char *line)
2984 sscanf (line, "%20s", topic);
2987 printf("Commands:\n");
2988 for (i = 0; cmd[i].cmd; i++)
2989 if (*topic == 0 || strcmp (topic, cmd[i].cmd) == 0)
2990 printf(" %s %s\n", cmd[i].cmd, cmd[i].ad);
2991 if (strcmp (topic, "find") == 0)
2994 printf (" \"term\" Simple Term\n");
2995 printf (" @attr [attset] type=value op Attribute\n");
2996 printf (" @and opl opr And\n");
2997 printf (" @or opl opr Or\n");
2998 printf (" @not opl opr And-Not\n");
2999 printf (" @set set Result set\n");
3001 printf ("Bib-1 attribute types\n");
3003 printf ("4=Title 7=ISBN 8=ISSN 30=Date 62=Abstract 1003=Author 1016=Any\n");
3004 printf ("2=Relation: ");
3005 printf ("1< 2<= 3= 4>= 5> 6!= 102=Relevance\n");
3006 printf ("3=Position: ");
3007 printf ("1=First in Field 2=First in subfield 3=Any position\n");
3008 printf ("4=Structure: ");
3009 printf ("1=Phrase 2=Word 3=Key 4=Year 5=Date 6=WordList\n");
3010 printf ("5=Truncation: ");
3011 printf ("1=Right 2=Left 3=L&R 100=No 101=# 102=Re-1 103=Re-2\n");
3012 printf ("6=Completeness:");
3013 printf ("1=Incomplete subfield 2=Complete subfield 3=Complete field\n");
3018 int cmd_register_tab(char* arg) {
3020 char command[101], tabargument[101];
3025 if (sscanf (arg, "%100s %100s", command, tabargument) < 1) {
3029 /* locate the amdn in the list */
3030 for (i = 0; cmd[i].cmd; i++) {
3031 if (!strncmp(cmd[i].cmd, command, strlen(command))) {
3037 fprintf(stderr,"Unknown command %s\n",command);
3043 if(!cmd[i].local_tabcompletes) {
3044 cmd[i].local_tabcompletes = calloc(1,sizeof(char**));
3049 tabslist = cmd[i].local_tabcompletes;
3050 for(;tabslist && *tabslist;tabslist++) {
3054 cmd[i].local_tabcompletes=realloc(cmd[i].local_tabcompletes,(num_of_tabs+2)*sizeof(char**));
3055 tabslist=cmd[i].local_tabcompletes;
3056 tabslist[num_of_tabs]=strdup(tabargument);
3057 tabslist[num_of_tabs+1]=NULL;
3062 void process_cmd_line(char* line)
3065 char word[32], arg[1024];
3067 #if HAVE_GETTIMEOFDAY
3068 gettimeofday (&tv_start, 0);
3071 if ((res = sscanf(line, "%31s %1023[^;]", word, arg)) <= 0)
3073 strcpy(word, last_cmd);
3078 strcpy(last_cmd, word);
3080 /* removed tailing spaces from the arg command */
3083 char* lastnonspace=NULL;
3092 *(++lastnonspace) = 0;
3096 for (i = 0; cmd[i].cmd; i++)
3097 if (!strncmp(cmd[i].cmd, word, strlen(word)))
3099 res = (*cmd[i].fun)(arg);
3103 if (!cmd[i].cmd) /* dump our help-screen */
3105 printf("Unknown command: %s.\n", word);
3106 printf("use help for list of commands\n");
3107 /* cmd_help (""); */
3111 if(apdu_file) fflush(apdu_file);
3114 wait_and_handle_responce();
3123 char *command_generator(const char *text, int state)
3129 for( ; cmd[idx].cmd; ++idx) {
3130 if (!strncmp(cmd[idx].cmd,text,strlen(text))) {
3131 ++idx; /* skip this entry on the next run */
3132 return strdup(cmd[idx-1].cmd);
3140 This function only known how to complete on the first word
3142 char ** readline_completer(char *text, int start, int end) {
3143 #if HAVE_READLINE_READLINE_H
3145 completerFunctionType completerToUse;
3148 #if HAVE_READLINE_RL_COMPLETION_MATCHES
3149 char** res=rl_completion_matches(text,
3152 char** res=completion_matches(text,
3153 (CPFunction*)command_generator);
3155 rl_attempted_completion_over = 1;
3158 char arg[1024],word[32];
3160 if ((res = sscanf(rl_line_buffer, "%31s %1023[^;]", word, arg)) <= 0) {
3161 rl_attempted_completion_over = 1;
3165 for (i = 0; cmd[i].cmd; i++) {
3166 if (!strncmp(cmd[i].cmd, word, strlen(word))) {
3171 if(!cmd[i].cmd) return NULL;
3174 curret_global_list = cmd[i].local_tabcompletes;
3176 completerToUse = cmd[i].rl_completerfunction;
3177 if(completerToUse==NULL) /* if no pr. command completer is defined use the default completer */
3178 completerToUse = default_completer;
3180 if(completerToUse) {
3181 #ifdef HAVE_READLINE_RL_COMPLETION_MATCHES
3183 rl_completion_matches(text,
3187 completion_matches(text,
3188 (CPFunction*)completerToUse);
3190 if(!cmd[i].complete_filenames)
3191 rl_attempted_completion_over = 1;
3194 if(!cmd[i].complete_filenames)
3195 rl_attempted_completion_over = 1;
3205 static void client(void)
3211 #if HAVE_GETTIMEOFDAY
3212 gettimeofday (&tv_start, 0);
3217 char *line_in = NULL;
3218 #if HAVE_READLINE_READLINE_H
3221 line_in=readline(C_PROMPT);
3224 #if HAVE_READLINE_HISTORY_H
3226 add_history(line_in);
3228 strncpy(line, line_in, 1023);
3237 if (!fgets(line, 1023, stdin))
3239 if ((end_p = strchr (line, '\n')))
3242 process_cmd_line(line);
3246 int main(int argc, char **argv)
3249 char *open_command = 0;
3250 char *auth_command = 0;
3254 while ((ret = options("k:c:a:m:v:p:u:", argv, argc, &arg)) != -2)
3261 open_command = (char *) xmalloc (strlen(arg)+6);
3262 strcpy (open_command, "open ");
3263 strcat (open_command, arg);
3267 kilobytes = atoi(arg);
3270 if (!(marcdump = fopen (arg, "a")))
3277 strncpy (ccl_fields, arg, sizeof(ccl_fields)-1);
3278 ccl_fields[sizeof(ccl_fields)-1] = '\0';
3281 if (!strcmp(arg, "-"))
3284 apdu_file=fopen(arg, "a");
3287 yazProxy=strdup(arg);
3292 auth_command = (char *) xmalloc (strlen(arg)+6);
3293 strcpy (auth_command, "auth ");
3294 strcat (auth_command, arg);
3298 yaz_log_init (yaz_log_mask_str(arg), "", NULL);
3301 fprintf (stderr, "Usage: %s [-m <marclog>] [ -a <apdulog>] "
3302 "[-c cclfields]\n [-p <proxy-addr>] [-u <auth>] "
3303 "[-k size] [<server-addr>]\n",
3311 #ifdef HAVE_GETTIMEOFDAY
3312 gettimeofday (&tv_start, 0);
3314 process_cmd_line (auth_command);
3315 #if HAVE_READLINE_HISTORY_H
3316 add_history(auth_command);
3318 xfree(auth_command);
3322 #ifdef HAVE_GETTIMEOFDAY
3323 gettimeofday (&tv_start, 0);
3325 process_cmd_line (open_command);
3326 #if HAVE_READLINE_HISTORY_H
3327 add_history(open_command);
3329 xfree(open_command);
3340 * vim600: sw=4 ts=8 fdm=marker
3341 * vim<600: sw=4 ts=8