2 * Copyright (c) 1995-2002, Index Data
3 * See the file LICENSE for details.
5 * $Id: client.c,v 1.152 2002-05-18 09:52:37 oleg Exp $
12 #include <yaz/yaz-util.h>
14 #include <yaz/tcpip.h>
16 #include <yaz/xmosi.h>
19 #include <yaz/proto.h>
20 #include <yaz/marcdisp.h>
21 #include <yaz/diagbib1.h>
22 #include <yaz/otherinfo.h>
23 #include <yaz/charneg.h>
25 #include <yaz/pquery.h>
26 #include <yaz/sortspec.h>
33 #include <yaz/yaz-ccl.h>
36 #if HAVE_READLINE_READLINE_H
37 #include <readline/readline.h>
39 #if HAVE_READLINE_HISTORY_H
40 #include <readline/history.h>
47 #include "tabcomplete.h"
49 #define C_PROMPT "Z> "
51 static ODR out, in, print; /* encoding and decoding streams */
52 static FILE *apdu_file = 0;
53 static COMSTACK conn = 0; /* our z-association */
54 static Z_IdAuthentication *auth = 0; /* our current auth definition */
55 char *databaseNames[128];
56 int num_databaseNames = 0;
57 static Z_External *record_last = 0;
58 static int setnumber = -1; /* current result set number */
59 static int smallSetUpperBound = 0;
60 static int largeSetLowerBound = 1;
61 static int mediumSetPresentNumber = 0;
62 static Z_ElementSetNames *elementSetNames = 0;
63 static int setno = 1; /* current set offset */
64 static enum oid_proto protocol = PROTO_Z3950; /* current app protocol */
65 static enum oid_value recordsyntax = VAL_USMARC;
66 static enum oid_value schema = VAL_NONE;
67 static int sent_close = 0;
68 static NMEM session_mem = NULL; /* memory handle for init-response */
69 static Z_InitResponse *session = 0; /* session parameters */
70 static char last_scan_line[512] = "0";
71 static char last_scan_query[512] = "0";
72 static char ccl_fields[512] = "default.bib";
73 static char* esPackageName = 0;
74 static char* yazProxy = 0;
75 static int kilobytes = 1024;
76 static char* yazCharset = 0;
77 static char* yazLang = 0;
79 static char last_cmd[32] = "?";
80 static FILE *marcdump = 0;
81 static char *refid = NULL;
89 static QueryType queryType = QueryType_Prefix;
92 static CCL_bibset bibset; /* CCL bibset handle */
95 #if HAVE_READLINE_COMPLETION_OVER
98 /* readline doesn't have this var. Define it ourselves. */
99 int rl_attempted_completion_over = 0;
102 /* set this one to 1, to avoid decode of unknown MARCs */
103 #define AVOID_MARC_DECODE 1
105 /* nice helper macro as extensive tabbing gives spaces at the en of the args lines */
106 #define REMOVE_TAILING_BLANKS(a) {\
107 char* args_end=(a)+strlen(a)-1; \
108 while(isspace(*args_end)) {*args_end=0;--args_end;}; \
112 void process_cmd_line(char* line);
113 char ** readline_completer(char *text, int start, int end);
114 char *command_generator(const char *text, int state);
117 ODR getODROutputStream()
122 void send_apdu(Z_APDU *a)
129 z_APDU(print, &a, 0, 0);
132 if (!z_APDU(out, &a, 0, 0))
134 odr_perror(out, "Encoding APDU");
137 buf = odr_getbuf(out, &len, 0);
138 /* printf ("sending APDU of size %d\n", len); */
139 if (cs_put(conn, buf, len) < 0)
141 fprintf(stderr, "cs_put: %s", cs_errmsg(cs_errno(conn)));
144 odr_reset(out); /* release the APDU structure */
147 static void print_stringn(const unsigned char *buf, size_t len)
150 for (i = 0; i<len; i++)
151 if ((buf[i] <= 126 && buf[i] >= 32) || strchr ("\n\r\t\f", buf[i]))
152 printf ("%c", buf[i]);
154 printf ("\\X%02X", buf[i]);
157 static void print_refid (Z_ReferenceId *id)
161 printf ("Reference Id: ");
162 print_stringn (id->buf, id->len);
167 static Z_ReferenceId *set_refid (ODR out)
172 id = (Z_ReferenceId *) odr_malloc (out, sizeof(*id));
173 id->size = id->len = strlen(refid);
174 id->buf = (unsigned char *) odr_malloc (out, id->len);
175 memcpy (id->buf, refid, id->len);
179 /* INIT SERVICE ------------------------------- */
181 static void send_initRequest(const char* type_and_host)
183 Z_APDU *apdu = zget_APDU(out, Z_APDU_initRequest);
184 Z_InitRequest *req = apdu->u.initRequest;
186 ODR_MASK_SET(req->options, Z_Options_search);
187 ODR_MASK_SET(req->options, Z_Options_present);
188 ODR_MASK_SET(req->options, Z_Options_namedResultSets);
189 ODR_MASK_SET(req->options, Z_Options_triggerResourceCtrl);
190 ODR_MASK_SET(req->options, Z_Options_scan);
191 ODR_MASK_SET(req->options, Z_Options_sort);
192 ODR_MASK_SET(req->options, Z_Options_extendedServices);
193 ODR_MASK_SET(req->options, Z_Options_delSet);
195 ODR_MASK_SET(req->protocolVersion, Z_ProtocolVersion_1);
196 ODR_MASK_SET(req->protocolVersion, Z_ProtocolVersion_2);
197 ODR_MASK_SET(req->protocolVersion, Z_ProtocolVersion_3);
199 *req->maximumRecordSize = 1024*kilobytes;
200 *req->preferredMessageSize = 1024*kilobytes;
202 req->idAuthentication = auth;
204 req->referenceId = set_refid (out);
207 yaz_oi_set_string_oidval(&req->otherInfo, out, VAL_PROXY,
210 if (yazCharset || yazLang) {
211 Z_OtherInformation **p;
212 Z_OtherInformationUnit *p0;
214 yaz_oi_APDU(apdu, &p);
216 if (p0=yaz_oi_update(p, out, NULL, 0, 0)) {
217 ODR_MASK_SET(req->options, Z_Options_negotiationModel);
219 p0->which = Z_OtherInfo_externallyDefinedInfo;
220 p0->information.externallyDefinedInfo =
221 yaz_set_charset_and_lang(out, CLASS_NEGOT, VAL_CHARNEG3,
222 (const char**)&yazCharset, (yazCharset)?1:0,
223 (const char**)&yazLang, (yazLang)?1:0);
228 printf("Sent initrequest.\n");
231 static int process_initResponse(Z_InitResponse *res)
233 /* save session parameters for later use */
234 session_mem = odr_extract_mem(in);
238 printf("Connection rejected by target.\n");
240 printf("Connection accepted by target.\n");
241 if (res->implementationId)
242 printf("ID : %s\n", res->implementationId);
243 if (res->implementationName)
244 printf("Name : %s\n", res->implementationName);
245 if (res->implementationVersion)
246 printf("Version: %s\n", res->implementationVersion);
247 if (res->userInformationField)
249 printf("UserInformationfield:\n");
250 if (!z_External(print, (Z_External**)&res-> userInformationField,
253 odr_perror(print, "Printing userinfo\n");
256 if (res->userInformationField->which == Z_External_octet)
258 printf("Guessing visiblestring:\n");
259 printf("'%s'\n", res->userInformationField->u. octet_aligned->buf);
264 if (ODR_MASK_GET(res->options, Z_Options_search))
266 if (ODR_MASK_GET(res->options, Z_Options_present))
268 if (ODR_MASK_GET(res->options, Z_Options_delSet))
270 if (ODR_MASK_GET(res->options, Z_Options_resourceReport))
271 printf (" resourceReport");
272 if (ODR_MASK_GET(res->options, Z_Options_resourceCtrl))
273 printf (" resourceCtrl");
274 if (ODR_MASK_GET(res->options, Z_Options_accessCtrl))
275 printf (" accessCtrl");
276 if (ODR_MASK_GET(res->options, Z_Options_scan))
278 if (ODR_MASK_GET(res->options, Z_Options_sort))
280 if (ODR_MASK_GET(res->options, Z_Options_extendedServices))
281 printf (" extendedServices");
282 if (ODR_MASK_GET(res->options, Z_Options_level_1Segmentation))
283 printf (" level1Segmentation");
284 if (ODR_MASK_GET(res->options, Z_Options_level_2Segmentation))
285 printf (" level2Segmentation");
286 if (ODR_MASK_GET(res->options, Z_Options_concurrentOperations))
287 printf (" concurrentOperations");
288 if (ODR_MASK_GET(res->options, Z_Options_namedResultSets))
290 printf (" namedResultSets");
293 if (ODR_MASK_GET(res->options, Z_Options_encapsulation))
294 printf (" encapsulation");
295 if (ODR_MASK_GET(res->options, Z_Options_resultCount))
296 printf (" resultCount");
297 if (ODR_MASK_GET(res->options, Z_Options_negotiationModel))
298 printf (" negotiationModel");
299 if (ODR_MASK_GET(res->options, Z_Options_duplicateDetection))
300 printf (" duplicateDetection");
301 if (ODR_MASK_GET(res->options, Z_Options_queryType104))
302 printf (" queryType104");
308 static int cmd_base(char *arg)
315 printf("Usage: base <database> <database> ...\n");
318 for (i = 0; i<num_databaseNames; i++)
319 xfree (databaseNames[i]);
320 num_databaseNames = 0;
323 if (!(cp = strchr(arg, ' ')))
324 cp = arg + strlen(arg);
327 databaseNames[num_databaseNames] = (char *)xmalloc (1 + cp - arg);
328 memcpy (databaseNames[num_databaseNames], arg, cp - arg);
329 databaseNames[num_databaseNames++][cp - arg] = '\0';
337 int cmd_open(char *arg)
340 char type_and_host[101], base[101];
345 printf("Already connected.\n");
351 nmem_destroy (session_mem);
357 if (sscanf (arg, "%100[^/]/%100s", type_and_host, base) < 1)
361 conn = cs_create_host(yazProxy, 1, &add);
363 conn = cs_create_host(type_and_host, 1, &add);
367 printf ("Couldn't create comstack\n");
370 printf("Connecting...");
372 if (cs_connect(conn, add) < 0)
374 printf ("error = %s\n", cs_strerror(conn));
375 if (conn->cerrno == CSYSERR)
383 send_initRequest(type_and_host);
389 int cmd_authentication(char *arg)
391 static Z_IdAuthentication au;
392 static char user[40], group[40], pass[40];
393 static Z_IdPass idPass;
398 printf("Auth field set to null\n");
402 r = sscanf (arg, "%39s %39s %39s", user, group, pass);
405 printf("Auth field set to null\n");
411 au.which = Z_IdAuthentication_open;
417 au.which = Z_IdAuthentication_idPass;
418 au.u.idPass = &idPass;
419 idPass.groupId = group;
420 idPass.userId = user;
421 idPass.password = pass;
426 /* SEARCH SERVICE ------------------------------ */
428 static void display_variant(Z_Variant *v, int level)
432 for (i = 0; i < v->num_triples; i++)
434 printf("%*sclass=%d,type=%d", level * 4, "", *v->triples[i]->zclass,
435 *v->triples[i]->type);
436 if (v->triples[i]->which == Z_Triple_internationalString)
437 printf(",value=%s\n", v->triples[i]->value.internationalString);
443 static void display_grs1(Z_GenericRecord *r, int level)
449 for (i = 0; i < r->num_elements; i++)
453 printf("%*s", level * 4, "");
457 printf("%d,", *t->tagType);
460 if (t->tagValue->which == Z_StringOrNumeric_numeric)
461 printf("%d) ", *t->tagValue->u.numeric);
463 printf("%s) ", t->tagValue->u.string);
464 if (t->content->which == Z_ElementData_subtree)
467 display_grs1(t->content->u.subtree, level+1);
469 else if (t->content->which == Z_ElementData_string)
470 printf("%s\n", t->content->u.string);
471 else if (t->content->which == Z_ElementData_numeric)
472 printf("%d\n", *t->content->u.numeric);
473 else if (t->content->which == Z_ElementData_oid)
475 int *ip = t->content->u.oid;
478 if ((oent = oid_getentbyoid(t->content->u.oid)))
479 printf("OID: %s\n", oent->desc);
483 while (ip && *ip >= 0)
484 printf(" %d", *(ip++));
488 else if (t->content->which == Z_ElementData_noDataRequested)
489 printf("[No data requested]\n");
490 else if (t->content->which == Z_ElementData_elementEmpty)
491 printf("[Element empty]\n");
492 else if (t->content->which == Z_ElementData_elementNotThere)
493 printf("[Element not there]\n");
496 if (t->appliedVariant)
497 display_variant(t->appliedVariant, level+1);
498 if (t->metaData && t->metaData->supportedVariants)
502 printf("%*s---- variant list\n", (level+1)*4, "");
503 for (c = 0; c < t->metaData->num_supportedVariants; c++)
505 printf("%*svariant #%d\n", (level+1)*4, "", c);
506 display_variant(t->metaData->supportedVariants[c], level + 2);
513 static void print_record(const unsigned char *buf, size_t len)
516 print_stringn (buf, len);
517 /* add newline if not already added ... */
518 if (i <= 0 || buf[i-1] != '\n')
522 static void display_record(Z_External *r)
524 oident *ent = oid_getentbyoid(r->direct_reference);
528 * Tell the user what we got.
530 if (r->direct_reference)
532 printf("Record type: ");
534 printf("%s\n", ent->desc);
535 else if (!odr_oid(print, &r->direct_reference, 0, 0))
537 odr_perror(print, "print oid");
541 /* Check if this is a known, ASN.1 type tucked away in an octet string */
542 if (ent && r->which == Z_External_octet)
544 Z_ext_typeent *type = z_ext_getentbyref(ent->value);
550 * Call the given decoder to process the record.
552 odr_setbuf(in, (char*)r->u.octet_aligned->buf,
553 r->u.octet_aligned->len, 0);
554 if (!(*type->fun)(in, (char **)&rr, 0, 0))
556 odr_perror(in, "Decoding constructed record.");
557 fprintf(stderr, "[Near %d]\n", odr_offset(in));
558 fprintf(stderr, "Packet dump:\n---------\n");
559 odr_dumpBER(stderr, (char*)r->u.octet_aligned->buf,
560 r->u.octet_aligned->len);
561 fprintf(stderr, "---------\n");
565 * Note: we throw away the original, BER-encoded record here.
566 * Do something else with it if you want to keep it.
568 r->u.sutrs = (Z_SUTRS *) rr; /* we don't actually check the type here. */
569 r->which = type->what;
572 if (ent && ent->value == VAL_SOIF)
573 print_record((const unsigned char *) r->u.octet_aligned->buf,
574 r->u.octet_aligned->len);
575 else if (r->which == Z_External_octet && r->u.octet_aligned->len)
577 const char *octet_buf = (char*)r->u.octet_aligned->buf;
578 if (ent->value == VAL_TEXT_XML || ent->value == VAL_APPLICATION_XML ||
579 ent->value == VAL_HTML)
581 print_record((const unsigned char *) octet_buf,
582 r->u.octet_aligned->len);
584 else if (ent->value == VAL_POSTSCRIPT)
586 int size = r->u.octet_aligned->len;
589 print_record((const unsigned char *) octet_buf, size);
594 #if AVOID_MARC_DECODE
595 /* primitive check for a marc OID 5.1-29 except 16 */
596 ent->oidsuffix[0] == 5 && ent->oidsuffix[1] < 30 &&
597 ent->oidsuffix[1] != 16
603 if (marc_display_exl (octet_buf, NULL, 0 /* debug */,
604 r->u.octet_aligned->len) <= 0)
606 printf ("bad MARC. Dumping as it is:\n");
607 print_record((const unsigned char*) octet_buf,
608 r->u.octet_aligned->len);
613 print_record((const unsigned char*) octet_buf,
614 r->u.octet_aligned->len);
618 fwrite (octet_buf, 1, r->u.octet_aligned->len, marcdump);
620 else if (ent && ent->value == VAL_SUTRS)
622 if (r->which != Z_External_sutrs)
624 printf("Expecting single SUTRS type for SUTRS.\n");
627 print_record(r->u.sutrs->buf, r->u.sutrs->len);
629 else if (ent && ent->value == VAL_GRS1)
631 if (r->which != Z_External_grs1)
633 printf("Expecting single GRS type for GRS.\n");
636 display_grs1(r->u.grs1, 0);
640 printf("Unknown record representation.\n");
641 if (!z_External(print, &r, 0, 0))
643 odr_perror(print, "Printing external");
649 static void display_diagrecs(Z_DiagRec **pp, int num)
653 Z_DefaultDiagFormat *r;
655 printf("Diagnostic message(s) from database:\n");
656 for (i = 0; i<num; i++)
658 Z_DiagRec *p = pp[i];
659 if (p->which != Z_DiagRec_defaultFormat)
661 printf("Diagnostic record not in default format.\n");
665 r = p->u.defaultFormat;
666 if (!(ent = oid_getentbyoid(r->diagnosticSetId)) ||
667 ent->oclass != CLASS_DIAGSET || ent->value != VAL_BIB1)
668 printf("Missing or unknown diagset\n");
669 printf(" [%d] %s", *r->condition, diagbib1_str(*r->condition));
672 case Z_DefaultDiagFormat_v2Addinfo:
673 printf (" -- v2 addinfo '%s'\n", r->u.v2Addinfo);
675 case Z_DefaultDiagFormat_v3Addinfo:
676 printf (" -- v3 addinfo '%s'\n", r->u.v3Addinfo);
683 static void display_nameplusrecord(Z_NamePlusRecord *p)
686 printf("[%s]", p->databaseName);
687 if (p->which == Z_NamePlusRecord_surrogateDiagnostic)
688 display_diagrecs(&p->u.surrogateDiagnostic, 1);
689 else if (p->which == Z_NamePlusRecord_databaseRecord)
690 display_record(p->u.databaseRecord);
693 static void display_records(Z_Records *p)
697 if (p->which == Z_Records_NSD)
699 Z_DiagRec dr, *dr_p = &dr;
700 dr.which = Z_DiagRec_defaultFormat;
701 dr.u.defaultFormat = p->u.nonSurrogateDiagnostic;
702 display_diagrecs (&dr_p, 1);
704 else if (p->which == Z_Records_multipleNSD)
705 display_diagrecs (p->u.multipleNonSurDiagnostics->diagRecs,
706 p->u.multipleNonSurDiagnostics->num_diagRecs);
709 printf("Records: %d\n", p->u.databaseOrSurDiagnostics->num_records);
710 for (i = 0; i < p->u.databaseOrSurDiagnostics->num_records; i++)
711 display_nameplusrecord(p->u.databaseOrSurDiagnostics->records[i]);
715 static int send_deleteResultSetRequest(char *arg)
720 Z_APDU *apdu = zget_APDU(out, Z_APDU_deleteResultSetRequest);
721 Z_DeleteResultSetRequest *req = apdu->u.deleteResultSetRequest;
723 req->referenceId = set_refid (out);
725 req->num_resultSetList =
726 sscanf (arg, "%30s %30s %30s %30s %30s %30s %30s %30s",
727 names[0], names[1], names[2], names[3],
728 names[4], names[5], names[6], names[7]);
730 req->deleteFunction = (int *)
731 odr_malloc (out, sizeof(*req->deleteFunction));
732 if (req->num_resultSetList > 0)
734 *req->deleteFunction = Z_DeleteRequest_list;
735 req->resultSetList = (char **)
736 odr_malloc (out, sizeof(*req->resultSetList)*
737 req->num_resultSetList);
738 for (i = 0; i<req->num_resultSetList; i++)
739 req->resultSetList[i] = names[i];
743 *req->deleteFunction = Z_DeleteRequest_all;
744 req->resultSetList = 0;
748 printf("Sent deleteResultSetRequest.\n");
752 static int send_searchRequest(char *arg)
754 Z_APDU *apdu = zget_APDU(out, Z_APDU_searchRequest);
755 Z_SearchRequest *req = apdu->u.searchRequest;
759 struct ccl_rpn_node *rpn = NULL;
763 Z_RPNQuery *RPNquery;
767 if (queryType == QueryType_CCL2RPN)
769 rpn = ccl_find_str(bibset, arg, &error, &pos);
772 printf("CCL ERROR: %s\n", ccl_err_msg(error));
777 req->referenceId = set_refid (out);
778 if (!strcmp(arg, "@big")) /* strictly for troublemaking */
780 static unsigned char big[2100];
783 /* send a very big referenceid to test transport stack etc. */
784 memset(big, 'A', 2100);
785 bigo.len = bigo.size = 2100;
787 req->referenceId = &bigo;
792 sprintf(setstring, "%d", ++setnumber);
793 req->resultSetName = setstring;
795 *req->smallSetUpperBound = smallSetUpperBound;
796 *req->largeSetLowerBound = largeSetLowerBound;
797 *req->mediumSetPresentNumber = mediumSetPresentNumber;
798 if (smallSetUpperBound > 0 || (largeSetLowerBound > 1 &&
799 mediumSetPresentNumber > 0))
803 prefsyn.proto = protocol;
804 prefsyn.oclass = CLASS_RECSYN;
805 prefsyn.value = recordsyntax;
806 req->preferredRecordSyntax =
807 odr_oiddup(out, oid_ent_to_oid(&prefsyn, oid));
808 req->smallSetElementSetNames =
809 req->mediumSetElementSetNames = elementSetNames;
811 req->num_databaseNames = num_databaseNames;
812 req->databaseNames = databaseNames;
818 case QueryType_Prefix:
819 query.which = Z_Query_type_1;
820 RPNquery = p_query_rpn (out, protocol, arg);
823 printf("Prefix query error\n");
826 query.u.type_1 = RPNquery;
829 query.which = Z_Query_type_2;
830 query.u.type_2 = &ccl_query;
831 ccl_query.buf = (unsigned char*) arg;
832 ccl_query.len = strlen(arg);
835 case QueryType_CCL2RPN:
836 query.which = Z_Query_type_1;
837 RPNquery = ccl_rpn_query(out, rpn);
840 printf ("Couldn't convert from CCL to RPN\n");
843 query.u.type_1 = RPNquery;
844 ccl_rpn_delete (rpn);
848 printf ("Unsupported query type\n");
853 printf("Sent searchRequest.\n");
857 /* display Query Expression as part of searchResult-1 */
858 static void display_queryExpression (Z_QueryExpression *qe)
862 if (qe->which == Z_QueryExpression_term)
864 if (qe->u.term->queryTerm)
866 Z_Term *term = qe->u.term->queryTerm;
867 if (term->which == Z_Term_general)
868 printf (" %.*s", term->u.general->len, term->u.general->buf);
874 /* see if we can find USR:SearchResult-1 */
875 static void display_searchResult (Z_OtherInformation *o)
880 for (i = 0; i < o->num_elements; i++)
882 if (o->list[i]->which == Z_OtherInfo_externallyDefinedInfo)
884 Z_External *ext = o->list[i]->information.externallyDefinedInfo;
886 if (ext->which == Z_External_searchResult1)
889 Z_SearchInfoReport *sr = ext->u.searchResult1;
890 printf ("SearchResult-1:");
891 for (j = 0; j < sr->num; j++)
893 if (!sr->elements[j]->subqueryExpression)
895 display_queryExpression (
896 sr->elements[j]->subqueryExpression);
897 display_queryExpression (
898 sr->elements[j]->subqueryInterpretation);
899 display_queryExpression (
900 sr->elements[j]->subqueryRecommendation);
901 if (sr->elements[j]->subqueryCount)
902 printf ("(%d)", *sr->elements[j]->subqueryCount);
910 static int process_searchResponse(Z_SearchResponse *res)
912 printf ("Received SearchResponse.\n");
913 print_refid (res->referenceId);
914 if (*res->searchStatus)
915 printf("Search was a success.\n");
917 printf("Search was a bloomin' failure.\n");
918 printf("Number of hits: %d", *res->resultCount);
920 printf (", setno %d", setnumber);
922 display_searchResult (res->additionalSearchInfo);
923 printf("records returned: %d\n",
924 *res->numberOfRecordsReturned);
925 setno += *res->numberOfRecordsReturned;
927 display_records(res->records);
931 static void print_level(int iLevel)
934 for (i = 0; i < iLevel * 4; i++)
938 static void print_int(int iLevel, const char *pTag, int *pInt)
943 printf("%s: %d\n", pTag, *pInt);
947 static void print_string(int iLevel, const char *pTag, const char *pString)
952 printf("%s: %s\n", pTag, pString);
956 static void print_oid(int iLevel, const char *pTag, Odr_oid *pOid)
964 for (; *pInt != -1; pInt++)
965 printf(" %d", *pInt);
970 static void print_referenceId(int iLevel, Z_ReferenceId *referenceId)
972 if (referenceId != NULL)
977 printf("Ref Id (%d, %d): ", referenceId->len, referenceId->size);
978 for (i = 0; i < referenceId->len; i++)
979 printf("%c", referenceId->buf[i]);
984 static void print_string_or_numeric(int iLevel, const char *pTag, Z_StringOrNumeric *pStringNumeric)
986 if (pStringNumeric != NULL)
988 switch (pStringNumeric->which)
990 case Z_StringOrNumeric_string:
991 print_string(iLevel, pTag, pStringNumeric->u.string);
994 case Z_StringOrNumeric_numeric:
995 print_int(iLevel, pTag, pStringNumeric->u.numeric);
1000 printf("%s: valid type for Z_StringOrNumeric\n", pTag);
1006 static void print_universe_report_duplicate(int iLevel, Z_UniverseReportDuplicate *pUniverseReportDuplicate)
1008 if (pUniverseReportDuplicate != NULL)
1010 print_level(iLevel);
1011 printf("Universe Report Duplicate: \n");
1013 print_string_or_numeric(iLevel, "Hit No",
1014 pUniverseReportDuplicate->hitno);
1019 print_universe_report_hits(int iLevel,
1020 Z_UniverseReportHits *pUniverseReportHits)
1022 if (pUniverseReportHits != NULL)
1024 print_level(iLevel);
1025 printf("Universe Report Hits: \n");
1027 print_string_or_numeric(iLevel, "Database",
1028 pUniverseReportHits->database);
1029 print_string_or_numeric(iLevel, "Hits", pUniverseReportHits->hits);
1033 static void print_universe_report(int iLevel, Z_UniverseReport *pUniverseReport)
1035 if (pUniverseReport != NULL)
1037 print_level(iLevel);
1038 printf("Universe Report: \n");
1040 print_int(iLevel, "Total Hits", pUniverseReport->totalHits);
1041 switch (pUniverseReport->which)
1043 case Z_UniverseReport_databaseHits:
1044 print_universe_report_hits(iLevel, pUniverseReport->u.databaseHits);
1047 case Z_UniverseReport_duplicate:
1048 print_universe_report_duplicate(iLevel, pUniverseReport->u.duplicate);
1052 print_level(iLevel);
1053 printf("Type: %d\n", pUniverseReport->which);
1059 static void print_external(int iLevel, Z_External *pExternal)
1061 if (pExternal != NULL)
1063 print_level(iLevel);
1064 printf("External: \n");
1066 print_oid(iLevel, "Direct Reference", pExternal->direct_reference);
1067 print_int(iLevel, "InDirect Reference", pExternal->indirect_reference);
1068 print_string(iLevel, "Descriptor", pExternal->descriptor);
1069 switch (pExternal->which)
1071 case Z_External_universeReport:
1072 print_universe_report(iLevel, pExternal->u.universeReport);
1076 print_level(iLevel);
1077 printf("Type: %d\n", pExternal->which);
1083 static int process_resourceControlRequest (Z_ResourceControlRequest *req)
1085 printf ("Received ResourceControlRequest.\n");
1086 print_referenceId(1, req->referenceId);
1087 print_int(1, "Suspended Flag", req->suspendedFlag);
1088 print_int(1, "Partial Results Available", req->partialResultsAvailable);
1089 print_int(1, "Response Required", req->responseRequired);
1090 print_int(1, "Triggered Request Flag", req->triggeredRequestFlag);
1091 print_external(1, req->resourceReport);
1095 void process_ESResponse(Z_ExtendedServicesResponse *res)
1098 switch (*res->operationStatus)
1100 case Z_ExtendedServicesResponse_done:
1103 case Z_ExtendedServicesResponse_accepted:
1104 printf ("accepted\n");
1106 case Z_ExtendedServicesResponse_failure:
1107 printf ("failure\n");
1108 display_diagrecs(res->diagnostics, res->num_diagnostics);
1111 printf ("unknown\n");
1113 if ( (*res->operationStatus != Z_ExtendedServicesResponse_failure) &&
1114 (res->num_diagnostics != 0) ) {
1115 display_diagrecs(res->diagnostics, res->num_diagnostics);
1117 print_refid (res->referenceId);
1118 if (res->taskPackage &&
1119 res->taskPackage->which == Z_External_extendedService)
1121 Z_TaskPackage *taskPackage = res->taskPackage->u.extendedService;
1122 Odr_oct *id = taskPackage->targetReference;
1123 Z_External *ext = taskPackage->taskSpecificParameters;
1127 printf ("Target Reference: ");
1128 print_stringn (id->buf, id->len);
1131 if (ext->which == Z_External_update)
1133 Z_IUUpdateTaskPackage *utp = ext->u.update->u.taskPackage;
1134 if (utp && utp->targetPart)
1136 Z_IUTargetPart *targetPart = utp->targetPart;
1139 for (i = 0; i<targetPart->num_taskPackageRecords; i++)
1142 Z_IUTaskPackageRecordStructure *tpr =
1143 targetPart->taskPackageRecords[i];
1144 printf ("task package record %d\n", i+1);
1145 if (tpr->which == Z_IUTaskPackageRecordStructure_record)
1147 display_record (tpr->u.record);
1151 printf ("other type\n");
1161 const char *get_ill_element (void *clientData, const char *element)
1166 static Z_External *create_external_itemRequest()
1168 struct ill_get_ctl ctl;
1169 ILL_ItemRequest *req;
1171 int item_request_size = 0;
1172 char *item_request_buf = 0;
1176 ctl.f = get_ill_element;
1178 req = ill_get_ItemRequest(&ctl, "ill", 0);
1180 printf ("ill_get_ItemRequest failed\n");
1182 if (!ill_ItemRequest (out, &req, 0, 0))
1186 ill_ItemRequest(print, &req, 0, 0);
1189 item_request_buf = odr_getbuf (out, &item_request_size, 0);
1190 if (item_request_buf)
1191 odr_setbuf (out, item_request_buf, item_request_size, 1);
1192 printf ("Couldn't encode ItemRequest, size %d\n", item_request_size);
1199 item_request_buf = odr_getbuf (out, &item_request_size, 0);
1200 oid.proto = PROTO_GENERAL;
1201 oid.oclass = CLASS_GENERAL;
1202 oid.value = VAL_ISO_ILL_1;
1204 r = (Z_External *) odr_malloc (out, sizeof(*r));
1205 r->direct_reference = odr_oiddup(out,oid_getoidbyent(&oid));
1206 r->indirect_reference = 0;
1208 r->which = Z_External_single;
1210 r->u.single_ASN1_type = (Odr_oct *)
1211 odr_malloc (out, sizeof(*r->u.single_ASN1_type));
1212 r->u.single_ASN1_type->buf = (unsigned char *)
1213 odr_malloc (out, item_request_size);
1214 r->u.single_ASN1_type->len = item_request_size;
1215 r->u.single_ASN1_type->size = item_request_size;
1216 memcpy (r->u.single_ASN1_type->buf, item_request_buf,
1218 printf ("len = %d\n", item_request_size);
1224 #ifdef YAZ_MODULE_ill
1225 static Z_External *create_external_ILL_APDU(int which)
1227 struct ill_get_ctl ctl;
1230 int ill_request_size = 0;
1231 char *ill_request_buf = 0;
1235 ctl.f = get_ill_element;
1237 ill_apdu = ill_get_APDU(&ctl, "ill", 0);
1239 if (!ill_APDU (out, &ill_apdu, 0, 0))
1243 printf ("-------------------\n");
1244 ill_APDU(print, &ill_apdu, 0, 0);
1246 printf ("-------------------\n");
1248 ill_request_buf = odr_getbuf (out, &ill_request_size, 0);
1249 if (ill_request_buf)
1250 odr_setbuf (out, ill_request_buf, ill_request_size, 1);
1251 printf ("Couldn't encode ILL-Request, size %d\n", ill_request_size);
1257 ill_request_buf = odr_getbuf (out, &ill_request_size, 0);
1259 oid.proto = PROTO_GENERAL;
1260 oid.oclass = CLASS_GENERAL;
1261 oid.value = VAL_ISO_ILL_1;
1263 r = (Z_External *) odr_malloc (out, sizeof(*r));
1264 r->direct_reference = odr_oiddup(out,oid_getoidbyent(&oid));
1265 r->indirect_reference = 0;
1267 r->which = Z_External_single;
1269 r->u.single_ASN1_type = (Odr_oct *)
1270 odr_malloc (out, sizeof(*r->u.single_ASN1_type));
1271 r->u.single_ASN1_type->buf = (unsigned char *)
1272 odr_malloc (out, ill_request_size);
1273 r->u.single_ASN1_type->len = ill_request_size;
1274 r->u.single_ASN1_type->size = ill_request_size;
1275 memcpy (r->u.single_ASN1_type->buf, ill_request_buf, ill_request_size);
1276 printf ("len = %d\n", ill_request_size);
1283 static Z_External *create_ItemOrderExternal(const char *type, int itemno)
1285 Z_External *r = (Z_External *) odr_malloc(out, sizeof(Z_External));
1286 oident ItemOrderRequest;
1288 ItemOrderRequest.proto = PROTO_Z3950;
1289 ItemOrderRequest.oclass = CLASS_EXTSERV;
1290 ItemOrderRequest.value = VAL_ITEMORDER;
1292 r->direct_reference = odr_oiddup(out,oid_getoidbyent(&ItemOrderRequest));
1293 r->indirect_reference = 0;
1296 r->which = Z_External_itemOrder;
1298 r->u.itemOrder = (Z_ItemOrder *) odr_malloc(out,sizeof(Z_ItemOrder));
1299 memset(r->u.itemOrder, 0, sizeof(Z_ItemOrder));
1300 r->u.itemOrder->which=Z_IOItemOrder_esRequest;
1302 r->u.itemOrder->u.esRequest = (Z_IORequest *)
1303 odr_malloc(out,sizeof(Z_IORequest));
1304 memset(r->u.itemOrder->u.esRequest, 0, sizeof(Z_IORequest));
1306 r->u.itemOrder->u.esRequest->toKeep = (Z_IOOriginPartToKeep *)
1307 odr_malloc(out,sizeof(Z_IOOriginPartToKeep));
1308 memset(r->u.itemOrder->u.esRequest->toKeep, 0, sizeof(Z_IOOriginPartToKeep));
1309 r->u.itemOrder->u.esRequest->notToKeep = (Z_IOOriginPartNotToKeep *)
1310 odr_malloc(out,sizeof(Z_IOOriginPartNotToKeep));
1311 memset(r->u.itemOrder->u.esRequest->notToKeep, 0, sizeof(Z_IOOriginPartNotToKeep));
1313 r->u.itemOrder->u.esRequest->toKeep->supplDescription = NULL;
1314 r->u.itemOrder->u.esRequest->toKeep->contact = NULL;
1315 r->u.itemOrder->u.esRequest->toKeep->addlBilling = NULL;
1317 r->u.itemOrder->u.esRequest->notToKeep->resultSetItem =
1318 (Z_IOResultSetItem *) odr_malloc(out, sizeof(Z_IOResultSetItem));
1319 memset(r->u.itemOrder->u.esRequest->notToKeep->resultSetItem, 0, sizeof(Z_IOResultSetItem));
1320 r->u.itemOrder->u.esRequest->notToKeep->resultSetItem->resultSetId = "1";
1322 r->u.itemOrder->u.esRequest->notToKeep->resultSetItem->item =
1323 (int *) odr_malloc(out, sizeof(int));
1324 *r->u.itemOrder->u.esRequest->notToKeep->resultSetItem->item = itemno;
1327 if (!strcmp (type, "item") || !strcmp(type, "2"))
1329 printf ("using item-request\n");
1330 r->u.itemOrder->u.esRequest->notToKeep->itemRequest =
1331 create_external_itemRequest();
1333 else if (!strcmp(type, "ill") || !strcmp(type, "1"))
1335 printf ("using ILL-request\n");
1336 r->u.itemOrder->u.esRequest->notToKeep->itemRequest =
1337 create_external_ILL_APDU(ILL_APDU_ILL_Request);
1339 else if (!strcmp(type, "xml") || !strcmp(type, "3"))
1341 const char *xml_buf =
1343 " <type>request</type>\n"
1344 " <libraryNo>000200</libraryNo>\n"
1345 " <borrowerTicketNo> 1212 </borrowerTicketNo>\n"
1347 r->u.itemOrder->u.esRequest->notToKeep->itemRequest =
1348 z_ext_record (out, VAL_TEXT_XML, xml_buf, strlen(xml_buf));
1351 r->u.itemOrder->u.esRequest->notToKeep->itemRequest = 0;
1354 r->u.itemOrder->u.esRequest->notToKeep->itemRequest = 0;
1359 static int send_itemorder(const char *type, int itemno)
1361 Z_APDU *apdu = zget_APDU(out, Z_APDU_extendedServicesRequest);
1362 Z_ExtendedServicesRequest *req = apdu->u.extendedServicesRequest;
1363 oident ItemOrderRequest;
1365 ItemOrderRequest.proto = PROTO_Z3950;
1366 ItemOrderRequest.oclass = CLASS_EXTSERV;
1367 ItemOrderRequest.value = VAL_ITEMORDER;
1368 req->packageType = odr_oiddup(out,oid_getoidbyent(&ItemOrderRequest));
1369 req->packageName = esPackageName;
1371 req->taskSpecificParameters = create_ItemOrderExternal(type, itemno);
1377 static int cmd_update(char *arg)
1379 Z_APDU *apdu = zget_APDU(out, Z_APDU_extendedServicesRequest );
1380 Z_ExtendedServicesRequest *req = apdu->u.extendedServicesRequest;
1383 Z_IUOriginPartToKeep *toKeep;
1384 Z_IUSuppliedRecords *notToKeep;
1386 printf ("Update request\n");
1391 update_oid.proto = PROTO_Z3950;
1392 update_oid.oclass = CLASS_EXTSERV;
1393 update_oid.value = VAL_DBUPDATE;
1394 oid_ent_to_oid (&update_oid, oid);
1395 req->packageType = odr_oiddup(out,oid);
1396 req->packageName = esPackageName;
1398 req->referenceId = set_refid (out);
1400 r = req->taskSpecificParameters = (Z_External *)
1401 odr_malloc (out, sizeof(*r));
1402 r->direct_reference = odr_oiddup(out,oid);
1403 r->indirect_reference = 0;
1405 r->which = Z_External_update;
1406 r->u.update = (Z_IUUpdate *) odr_malloc(out, sizeof(*r->u.update));
1407 r->u.update->which = Z_IUUpdate_esRequest;
1408 r->u.update->u.esRequest = (Z_IUUpdateEsRequest *)
1409 odr_malloc(out, sizeof(*r->u.update->u.esRequest));
1410 toKeep = r->u.update->u.esRequest->toKeep = (Z_IUOriginPartToKeep *)
1411 odr_malloc(out, sizeof(*r->u.update->u.esRequest->toKeep));
1412 toKeep->databaseName = databaseNames[0];
1414 toKeep->elementSetName = 0;
1415 toKeep->actionQualifier = 0;
1416 toKeep->action = (int *) odr_malloc(out, sizeof(*toKeep->action));
1417 *toKeep->action = Z_IUOriginPartToKeep_recordInsert;
1419 notToKeep = r->u.update->u.esRequest->notToKeep = (Z_IUSuppliedRecords *)
1420 odr_malloc(out, sizeof(*r->u.update->u.esRequest->notToKeep));
1422 notToKeep->elements = (Z_IUSuppliedRecords_elem **)
1423 odr_malloc(out, sizeof(*notToKeep->elements));
1424 notToKeep->elements[0] = (Z_IUSuppliedRecords_elem *)
1425 odr_malloc(out, sizeof(**notToKeep->elements));
1426 notToKeep->elements[0]->u.number = 0;
1427 notToKeep->elements[0]->supplementalId = 0;
1428 notToKeep->elements[0]->correlationInfo = 0;
1429 notToKeep->elements[0]->record = record_last;
1436 static int cmd_itemorder(char *arg)
1441 if (sscanf (arg, "%10s %d", type, &itemno) != 2)
1444 printf("Item order request\n");
1446 send_itemorder(type, itemno);
1450 static int cmd_find(char *arg)
1454 printf("Find what?\n");
1459 printf("Not connected yet\n");
1462 if (!send_searchRequest(arg))
1467 static int cmd_delete(char *arg)
1471 printf("Not connected yet\n");
1474 if (!send_deleteResultSetRequest(arg))
1479 static int cmd_ssub(char *arg)
1481 if (!(smallSetUpperBound = atoi(arg)))
1486 static int cmd_lslb(char *arg)
1488 if (!(largeSetLowerBound = atoi(arg)))
1493 static int cmd_mspn(char *arg)
1495 if (!(mediumSetPresentNumber = atoi(arg)))
1500 static int cmd_status(char *arg)
1502 printf("smallSetUpperBound: %d\n", smallSetUpperBound);
1503 printf("largeSetLowerBound: %d\n", largeSetLowerBound);
1504 printf("mediumSetPresentNumber: %d\n", mediumSetPresentNumber);
1508 static int cmd_setnames(char *arg)
1510 if (*arg == '1') /* enable ? */
1512 else if (*arg == '0') /* disable ? */
1514 else if (setnumber < 0) /* no args, toggle .. */
1520 printf("Set numbering enabled.\n");
1522 printf("Set numbering disabled.\n");
1526 /* PRESENT SERVICE ----------------------------- */
1528 static int send_presentRequest(char *arg)
1530 Z_APDU *apdu = zget_APDU(out, Z_APDU_presentRequest);
1531 Z_PresentRequest *req = apdu->u.presentRequest;
1532 Z_RecordComposition compo;
1537 char setstring[100];
1539 req->referenceId = set_refid (out);
1540 if ((p = strchr(arg, '+')))
1547 if (p && (p=strchr(p+1, '+')))
1549 strcpy (setstring, p+1);
1550 req->resultSetId = setstring;
1552 else if (setnumber >= 0)
1554 sprintf(setstring, "%d", setnumber);
1555 req->resultSetId = setstring;
1557 req->resultSetStartPoint = &setno;
1558 req->numberOfRecordsRequested = &nos;
1559 prefsyn.proto = protocol;
1560 prefsyn.oclass = CLASS_RECSYN;
1561 prefsyn.value = recordsyntax;
1562 req->preferredRecordSyntax =
1563 odr_oiddup (out, oid_ent_to_oid(&prefsyn, oid));
1565 if (schema != VAL_NONE)
1569 prefschema.proto = protocol;
1570 prefschema.oclass = CLASS_SCHEMA;
1571 prefschema.value = schema;
1573 req->recordComposition = &compo;
1574 compo.which = Z_RecordComp_complex;
1575 compo.u.complex = (Z_CompSpec *)
1576 odr_malloc(out, sizeof(*compo.u.complex));
1577 compo.u.complex->selectAlternativeSyntax = (bool_t *)
1578 odr_malloc(out, sizeof(bool_t));
1579 *compo.u.complex->selectAlternativeSyntax = 0;
1581 compo.u.complex->generic = (Z_Specification *)
1582 odr_malloc(out, sizeof(*compo.u.complex->generic));
1583 compo.u.complex->generic->schema = (Odr_oid *)
1584 odr_oiddup(out, oid_ent_to_oid(&prefschema, oid));
1585 if (!compo.u.complex->generic->schema)
1587 /* OID wasn't a schema! Try record syntax instead. */
1588 prefschema.oclass = CLASS_RECSYN;
1589 compo.u.complex->generic->schema = (Odr_oid *)
1590 odr_oiddup(out, oid_ent_to_oid(&prefschema, oid));
1592 if (!elementSetNames)
1593 compo.u.complex->generic->elementSpec = 0;
1596 compo.u.complex->generic->elementSpec = (Z_ElementSpec *)
1597 odr_malloc(out, sizeof(Z_ElementSpec));
1598 compo.u.complex->generic->elementSpec->which =
1599 Z_ElementSpec_elementSetName;
1600 compo.u.complex->generic->elementSpec->u.elementSetName =
1601 elementSetNames->u.generic;
1603 compo.u.complex->num_dbSpecific = 0;
1604 compo.u.complex->dbSpecific = 0;
1605 compo.u.complex->num_recordSyntax = 0;
1606 compo.u.complex->recordSyntax = 0;
1608 else if (elementSetNames)
1610 req->recordComposition = &compo;
1611 compo.which = Z_RecordComp_simple;
1612 compo.u.simple = elementSetNames;
1615 printf("Sent presentRequest (%d+%d).\n", setno, nos);
1619 static void close_session (void)
1625 nmem_destroy (session_mem);
1631 void process_close(Z_Close *req)
1633 Z_APDU *apdu = zget_APDU(out, Z_APDU_close);
1634 Z_Close *res = apdu->u.close;
1636 static char *reasons[] =
1641 "cost limit reached",
1643 "security violation",
1650 printf("Reason: %s, message: %s\n", reasons[*req->closeReason],
1651 req->diagnosticInformation ? req->diagnosticInformation : "NULL");
1656 *res->closeReason = Z_Close_finished;
1658 printf("Sent response.\n");
1663 static int cmd_show(char *arg)
1667 printf("Not connected yet\n");
1670 if (!send_presentRequest(arg))
1675 int cmd_quit(char *arg)
1677 printf("See you later, alligator.\n");
1683 int cmd_cancel(char *arg)
1685 Z_APDU *apdu = zget_APDU(out, Z_APDU_triggerResourceControlRequest);
1686 Z_TriggerResourceControlRequest *req =
1687 apdu->u.triggerResourceControlRequest;
1692 printf("Session not initialized yet\n");
1695 if (!ODR_MASK_GET(session->options, Z_Options_triggerResourceCtrl))
1697 printf("Target doesn't support cancel (trigger resource ctrl)\n");
1700 *req->requestedAction = Z_TriggerResourceCtrl_cancel;
1701 req->resultSetWanted = &rfalse;
1704 printf("Sent cancel request\n");
1708 int send_scanrequest(const char *query, int pp, int num, const char *term)
1710 Z_APDU *apdu = zget_APDU(out, Z_APDU_scanRequest);
1711 Z_ScanRequest *req = apdu->u.scanRequest;
1716 if (queryType == QueryType_CCL2RPN)
1720 struct ccl_rpn_node *rpn;
1722 rpn = ccl_find_str (bibset, query, &error, &pos);
1725 printf("CCL ERROR: %s\n", ccl_err_msg(error));
1729 bib1.proto = PROTO_Z3950;
1730 bib1.oclass = CLASS_ATTSET;
1731 bib1.value = VAL_BIB1;
1732 req->attributeSet = oid_ent_to_oid (&bib1, oid);
1733 if (!(req->termListAndStartPoint = ccl_scan_query (out, rpn)))
1735 printf("Couldn't convert CCL to Scan term\n");
1738 ccl_rpn_delete (rpn);
1741 if (use_rpn && !(req->termListAndStartPoint =
1742 p_query_scan(out, protocol, &req->attributeSet, query)))
1744 printf("Prefix query error\n");
1749 if (req->termListAndStartPoint->term &&
1750 req->termListAndStartPoint->term->which == Z_Term_general &&
1751 req->termListAndStartPoint->term->u.general)
1753 req->termListAndStartPoint->term->u.general->buf =
1754 (unsigned char *) odr_strdup(out, term);
1755 req->termListAndStartPoint->term->u.general->len =
1756 req->termListAndStartPoint->term->u.general->size =
1760 req->referenceId = set_refid (out);
1761 req->num_databaseNames = num_databaseNames;
1762 req->databaseNames = databaseNames;
1763 req->numberOfTermsRequested = #
1764 req->preferredPositionInResponse = &pp;
1769 int send_sortrequest(char *arg, int newset)
1771 Z_APDU *apdu = zget_APDU(out, Z_APDU_sortRequest);
1772 Z_SortRequest *req = apdu->u.sortRequest;
1773 Z_SortKeySpecList *sksl = (Z_SortKeySpecList *)
1774 odr_malloc (out, sizeof(*sksl));
1778 sprintf (setstring, "%d", setnumber);
1780 sprintf (setstring, "default");
1782 req->referenceId = set_refid (out);
1784 req->num_inputResultSetNames = 1;
1785 req->inputResultSetNames = (Z_InternationalString **)
1786 odr_malloc (out, sizeof(*req->inputResultSetNames));
1787 req->inputResultSetNames[0] = odr_strdup (out, setstring);
1789 if (newset && setnumber >= 0)
1790 sprintf (setstring, "%d", ++setnumber);
1792 req->sortedResultSetName = odr_strdup (out, setstring);
1794 req->sortSequence = yaz_sort_spec (out, arg);
1795 if (!req->sortSequence)
1797 printf ("Missing sort specifications\n");
1804 void display_term(Z_TermInfo *t)
1806 if (t->term->which == Z_Term_general)
1808 printf("%.*s", t->term->u.general->len, t->term->u.general->buf);
1809 sprintf(last_scan_line, "%.*s", t->term->u.general->len,
1810 t->term->u.general->buf);
1813 printf("Term (not general)");
1814 if (t->globalOccurrences)
1815 printf (" (%d)\n", *t->globalOccurrences);
1820 void process_scanResponse(Z_ScanResponse *res)
1823 Z_Entry **entries = NULL;
1824 int num_entries = 0;
1826 printf("Received ScanResponse\n");
1827 print_refid (res->referenceId);
1828 printf("%d entries", *res->numberOfEntriesReturned);
1829 if (res->positionOfTerm)
1830 printf (", position=%d", *res->positionOfTerm);
1832 if (*res->scanStatus != Z_Scan_success)
1833 printf("Scan returned code %d\n", *res->scanStatus);
1836 if ((entries = res->entries->entries))
1837 num_entries = res->entries->num_entries;
1838 for (i = 0; i < num_entries; i++)
1840 int pos_term = res->positionOfTerm ? *res->positionOfTerm : -1;
1841 if (entries[i]->which == Z_Entry_termInfo)
1843 printf("%c ", i + 1 == pos_term ? '*' : ' ');
1844 display_term(entries[i]->u.termInfo);
1847 display_diagrecs(&entries[i]->u.surrogateDiagnostic, 1);
1849 if (res->entries->nonsurrogateDiagnostics)
1850 display_diagrecs (res->entries->nonsurrogateDiagnostics,
1851 res->entries->num_nonsurrogateDiagnostics);
1854 void process_sortResponse(Z_SortResponse *res)
1856 printf("Received SortResponse: status=");
1857 switch (*res->sortStatus)
1859 case Z_SortStatus_success:
1860 printf ("success"); break;
1861 case Z_SortStatus_partial_1:
1862 printf ("partial"); break;
1863 case Z_SortStatus_failure:
1864 printf ("failure"); break;
1866 printf ("unknown (%d)", *res->sortStatus);
1869 print_refid (res->referenceId);
1870 if (res->diagnostics)
1871 display_diagrecs(res->diagnostics,
1872 res->num_diagnostics);
1875 void process_deleteResultSetResponse (Z_DeleteResultSetResponse *res)
1877 printf("Got deleteResultSetResponse status=%d\n",
1878 *res->deleteOperationStatus);
1879 if (res->deleteListStatuses)
1882 for (i = 0; i < res->deleteListStatuses->num; i++)
1884 printf ("%s status=%d\n", res->deleteListStatuses->elements[i]->id,
1885 *res->deleteListStatuses->elements[i]->status);
1890 int cmd_sort_generic(char *arg, int newset)
1894 printf("Session not initialized yet\n");
1897 if (!ODR_MASK_GET(session->options, Z_Options_sort))
1899 printf("Target doesn't support sort\n");
1904 if (send_sortrequest(arg, newset) < 0)
1911 int cmd_sort(char *arg)
1913 return cmd_sort_generic (arg, 0);
1916 int cmd_sort_newset (char *arg)
1918 return cmd_sort_generic (arg, 1);
1921 int cmd_scan(char *arg)
1925 printf("Session not initialized yet\n");
1928 if (!ODR_MASK_GET(session->options, Z_Options_scan))
1930 printf("Target doesn't support scan\n");
1935 strcpy (last_scan_query, arg);
1936 if (send_scanrequest(arg, 1, 20, 0) < 0)
1941 if (send_scanrequest(last_scan_query, 1, 20, last_scan_line) < 0)
1947 int cmd_schema(char *arg)
1954 schema = oid_getvalbyname (arg);
1955 if (schema == VAL_NONE)
1957 printf ("unknown schema\n");
1963 int cmd_format(char *arg)
1967 printf("Usage: format <recordsyntax>\n");
1970 recordsyntax = oid_getvalbyname (arg);
1971 if (recordsyntax == VAL_NONE)
1973 printf ("unknown record syntax\n");
1979 int cmd_elements(char *arg)
1981 static Z_ElementSetNames esn;
1982 static char what[100];
1986 elementSetNames = 0;
1990 esn.which = Z_ElementSetNames_generic;
1991 esn.u.generic = what;
1992 elementSetNames = &esn;
1996 int cmd_attributeset(char *arg)
2002 printf("Usage: attributeset <setname>\n");
2005 sscanf(arg, "%s", what);
2006 if (p_query_attset (what))
2008 printf("Unknown attribute set name\n");
2014 int cmd_querytype (char *arg)
2016 if (!strcmp (arg, "ccl"))
2017 queryType = QueryType_CCL;
2018 else if (!strcmp (arg, "prefix") || !strcmp(arg, "rpn"))
2019 queryType = QueryType_Prefix;
2021 else if (!strcmp (arg, "ccl2rpn") || !strcmp (arg, "cclrpn"))
2022 queryType = QueryType_CCL2RPN;
2026 printf ("Querytype must be one of:\n");
2027 printf (" prefix - Prefix query\n");
2028 printf (" ccl - CCL query\n");
2030 printf (" ccl2rpn - CCL query converted to RPN\n");
2037 int cmd_refid (char *arg)
2043 refid = (char *) xmalloc (strlen(arg)+1);
2044 strcpy (refid, arg);
2049 int cmd_close(char *arg)
2056 apdu = zget_APDU(out, Z_APDU_close);
2057 req = apdu->u.close;
2058 *req->closeReason = Z_Close_finished;
2060 printf("Sent close request.\n");
2065 int cmd_packagename(char* arg)
2067 xfree (esPackageName);
2068 esPackageName = NULL;
2071 esPackageName = (char *) xmalloc (strlen(arg)+1);
2072 strcpy (esPackageName, arg);
2077 int cmd_proxy(char* arg)
2080 printf("Current proxy is `%s'\n", (yazCharset)?yazProxy:NULL);
2087 yazProxy = (char *) xmalloc (strlen(arg)+1);
2088 strcpy (yazProxy, arg);
2093 int cmd_charset(char* arg)
2096 printf("Current character set is `%s'\n", (yazCharset)?yazCharset:NULL);
2103 yazCharset = (char *) xmalloc (strlen(arg)+1);
2104 strcpy (yazCharset, arg);
2109 int cmd_lang(char* arg)
2112 printf("Current language is `%s'\n", (yazLang)?yazLang:NULL);
2119 yazLang = (char *) xmalloc (strlen(arg)+1);
2120 strcpy (yazLang, arg);
2125 int cmd_source(char* arg)
2127 /* first should open the file and read one line at a time.. */
2129 char line[1024], *cp;
2132 char* args_end=(arg)+strlen(arg)-1;
2133 while(isspace(*args_end))
2138 REMOVE_TAILING_BLANKS(arg);
2141 fprintf(stderr,"Error in source command use a filename\n");
2145 includeFile = fopen (arg, "r");
2148 fprintf(stderr,"Unable to open file %s for reading\n",arg);
2152 while(!feof(includeFile)) {
2153 memset(line,0,sizeof(line));
2154 fgets(line,sizeof(line),includeFile);
2156 if(strlen(line) < 2) continue;
2157 if(line[0] == '#') continue;
2159 if ((cp = strrchr (line, '\n')))
2162 process_cmd_line(line);
2165 if(fclose(includeFile)<0) {
2166 perror("unable to close include file");
2172 int cmd_subshell(char* args)
2177 system(getenv("SHELL"));
2183 int cmd_set_apdufile(char* arg)
2185 REMOVE_TAILING_BLANKS(arg);
2187 if(apdu_file && apdu_file != stderr) { /* don't close stdout*/
2188 perror("unable to close apdu log file");
2196 if(!strcmp(arg,"-"))
2199 apdu_file=fopen(arg, "a");
2202 perror("unable to open apdu log file no apdu log loaded");
2204 odr_setprint(print, apdu_file);
2210 int cmd_set_cclfields(char* arg)
2215 REMOVE_TAILING_BLANKS(arg);
2217 bibset = ccl_qual_mk ();
2218 inf = fopen (arg, "r");
2221 ccl_qual_file (bibset, inf);
2225 fprintf(stderr,"Not compiled with the yaz ccl module\n");
2231 int cmd_set_marcdump(char* arg)
2233 if(marcdump && marcdump != stderr) { /* don't close stdout*/
2234 perror("unable to close apdu log file");
2242 if(!strcmp(arg,"-"))
2245 marcdump=fopen(arg, "a");
2248 perror("unable to open apdu marcdump file no marcdump done\n");
2254 int cmd_set_proxy(char* arg) {
2255 if(yazProxy) free(yazProxy);
2258 if(strlen(arg) > 1) {
2259 yazProxy=strdup(arg);
2265 this command takes 3 arge {name class oid}
2267 int cmd_register_oid(char* args) {
2272 {"appctx",CLASS_APPCTX},
2273 {"absyn",CLASS_ABSYN},
2274 {"attset",CLASS_ATTSET},
2275 {"transyn",CLASS_TRANSYN},
2276 {"diagset",CLASS_DIAGSET},
2277 {"recsyn",CLASS_RECSYN},
2278 {"resform",CLASS_RESFORM},
2279 {"accform",CLASS_ACCFORM},
2280 {"extserv",CLASS_EXTSERV},
2281 {"userinfo",CLASS_USERINFO},
2282 {"elemspec",CLASS_ELEMSPEC},
2283 {"varset",CLASS_VARSET},
2284 {"schema",CLASS_SCHEMA},
2285 {"tagset",CLASS_TAGSET},
2286 {"general",CLASS_GENERAL},
2289 char oname_str[101], oclass_str[101], oid_str[101];
2292 oid_class oidclass = CLASS_GENERAL;
2293 int val = 0, oid[OID_SIZE];
2294 struct oident * new_oident=NULL;
2296 if (sscanf (args, "%100[^ ] %100[^ ] %100s",
2297 oname_str,oclass_str, oid_str) < 1) {
2298 printf("Error in regristrate command \n");
2302 for (i = 0; oid_classes[i].className; i++) {
2303 if (!strcmp(oid_classes[i].className, oclass_str))
2305 oidclass=oid_classes[i].oclass;
2310 if(!(oid_classes[i].className)) {
2311 printf("Unknonwn oid class %s\n",oclass_str);
2319 while (isdigit (*name))
2321 val = val*10 + (*name - '0');
2334 new_oident=oid_addent (oid,PROTO_GENERAL,oidclass,oname_str,VAL_DYNAMIC);
2335 if(strcmp(new_oident->desc,oname_str)) {
2336 fprintf(stderr,"oid is already named as %s, regristration faild\n",
2342 int cmd_push_command(char* arg) {
2343 #if HAVE_READLINE_HISTORY_H
2347 fprintf(stderr,"Not compiled with the readline/history module\n");
2352 void source_rcfile() {
2353 /* Look for a $HOME/.yazclientrc and source it if it exists */
2354 struct stat statbuf;
2356 char* homedir=getenv("HOME");
2357 if(!homedir) return;
2359 sprintf(buffer,"%s/.yazclientrc",homedir);
2361 if(stat(buffer,&statbuf)==0) {
2365 if(stat(".yazclientrc",&statbuf)==0) {
2366 cmd_source(".yazclientrc");
2371 static void initialize(void)
2376 if (!(out = odr_createmem(ODR_ENCODE)) ||
2377 !(in = odr_createmem(ODR_DECODE)) ||
2378 !(print = odr_createmem(ODR_PRINT)))
2380 fprintf(stderr, "failed to allocate ODR streams\n");
2385 setvbuf(stdout, 0, _IONBF, 0);
2387 odr_setprint(print, apdu_file);
2390 bibset = ccl_qual_mk ();
2391 inf = fopen (ccl_fields, "r");
2394 ccl_qual_file (bibset, inf);
2398 cmd_base("Default");
2400 #if HAVE_READLINE_READLINE_H
2401 rl_attempted_completion_function = (CPPFunction*)readline_completer;
2408 #if HAVE_GETTIMEOFDAY
2409 struct timeval tv_start, tv_end;
2412 void wait_and_handle_responce()
2417 int netbufferlen = 0;
2425 if ((res = cs_get(conn, &netbuffer, &netbufferlen)) < 0)
2427 printf("Target closed connection\n");
2433 printf("Target closed connection.\n");
2437 odr_reset(in); /* release APDU from last round */
2439 odr_setbuf(in, netbuffer, res, 0);
2440 if (!z_APDU(in, &apdu, 0, 0))
2442 odr_perror(in, "Decoding incoming APDU");
2443 fprintf(stderr, "[Near %d]\n", odr_offset(in));
2444 fprintf(stderr, "Packet dump:\n---------\n");
2445 odr_dumpBER(stderr, netbuffer, res);
2446 fprintf(stderr, "---------\n");
2448 z_APDU(print, &apdu, 0, 0);
2452 if (apdu_file && !z_APDU(print, &apdu, 0, 0))
2454 odr_perror(print, "Failed to print incoming APDU");
2460 case Z_APDU_initResponse:
2461 process_initResponse(apdu->u.initResponse);
2463 case Z_APDU_searchResponse:
2464 process_searchResponse(apdu->u.searchResponse);
2466 case Z_APDU_scanResponse:
2467 process_scanResponse(apdu->u.scanResponse);
2469 case Z_APDU_presentResponse:
2470 print_refid (apdu->u.presentResponse->referenceId);
2472 *apdu->u.presentResponse->numberOfRecordsReturned;
2473 if (apdu->u.presentResponse->records)
2474 display_records(apdu->u.presentResponse->records);
2476 printf("No records.\n");
2477 printf ("nextResultSetPosition = %d\n",
2478 *apdu->u.presentResponse->nextResultSetPosition);
2480 case Z_APDU_sortResponse:
2481 process_sortResponse(apdu->u.sortResponse);
2483 case Z_APDU_extendedServicesResponse:
2484 printf("Got extended services response\n");
2485 process_ESResponse(apdu->u.extendedServicesResponse);
2488 printf("Target has closed the association.\n");
2489 process_close(apdu->u.close);
2491 case Z_APDU_resourceControlRequest:
2492 process_resourceControlRequest
2493 (apdu->u.resourceControlRequest);
2495 case Z_APDU_deleteResultSetResponse:
2496 process_deleteResultSetResponse(apdu->u.
2497 deleteResultSetResponse);
2500 printf("Received unknown APDU type (%d).\n",
2505 while (conn && cs_more(conn));
2506 #if HAVE_GETTIMEOFDAY
2507 gettimeofday (&tv_end, 0);
2509 printf ("S/U S/U=%ld/%ld %ld/%ld",
2510 (long) tv_start.tv_sec,
2511 (long) tv_start.tv_usec,
2512 (long) tv_end.tv_sec,
2513 (long) tv_end.tv_usec);
2515 printf ("Elapsed: %.6f\n",
2516 (double) tv_end.tv_usec / 1e6 + tv_end.tv_sec -
2517 ((double) tv_start.tv_usec / 1e6 + tv_start.tv_sec));
2524 static int cmd_help (char *line);
2528 int (*fun)(char *arg);
2530 char *(*rl_completerfunction)(const char *text, int state);
2531 int complete_filenames;
2533 {"open", cmd_open, "('tcp'|'ssl')':<host>[':'<port>][/<db>]",NULL,0},
2534 {"quit", cmd_quit, "",NULL,0},
2535 {"find", cmd_find, "<query>",NULL,0},
2536 {"delete", cmd_delete, "<setname>",NULL,0},
2537 {"base", cmd_base, "<base-name>",NULL,0},
2538 {"show", cmd_show, "<rec#>['+'<#recs>['+'<setname>]]",NULL,0},
2539 {"scan", cmd_scan, "<term>",NULL,0},
2540 {"sort", cmd_sort, "<sortkey> <flag> <sortkey> <flag> ...",NULL,0},
2541 {"sort+", cmd_sort_newset, "<sortkey> <flag> <sortkey> <flag> ...",NULL,0},
2542 {"authentication", cmd_authentication, "<acctstring>",NULL,0},
2543 {"lslb", cmd_lslb, "<largeSetLowerBound>",NULL,0},
2544 {"ssub", cmd_ssub, "<smallSetUpperBound>",NULL,0},
2545 {"mspn", cmd_mspn, "<mediumSetPresentNumber>",NULL,0},
2546 {"status", cmd_status, "",NULL,0},
2547 {"setnames", cmd_setnames, "",NULL,0},
2548 {"cancel", cmd_cancel, "",NULL,0},
2549 {"format", cmd_format, "<recordsyntax>",complete_format,0},
2550 {"schema", cmd_schema, "<schema>",complete_schema,0},
2551 {"elements", cmd_elements, "<elementSetName>",NULL,0},
2552 {"close", cmd_close, "",NULL,0},
2553 {"attributeset", cmd_attributeset, "<attrset>",complete_attributeset,0},
2554 {"querytype", cmd_querytype, "<type>",complete_querytype,0},
2555 {"refid", cmd_refid, "<id>",NULL,0},
2556 {"itemorder", cmd_itemorder, "ill|item <itemno>",NULL,0},
2557 {"update", cmd_update, "<item>",NULL,0},
2558 {"packagename", cmd_packagename, "<packagename>",NULL,0},
2559 {"proxy", cmd_proxy, "[('tcp'|'ssl')]<host>[':'<port>]",NULL,0},
2560 {"charset", cmd_charset, "<charset_name>",NULL,0},
2561 {"lang", cmd_lang, "<language_code>",NULL,0},
2562 {".", cmd_source, "<filename>",NULL,1},
2563 {"!", cmd_subshell, "Subshell command",NULL,0},
2564 {"set_apdufile", cmd_set_apdufile, "<filename>",NULL,0},
2565 {"set_marcdump", cmd_set_marcdump," <filename>",NULL,0},
2566 {"set_cclfields", cmd_set_cclfields,"<filename>",NULL,1},
2567 {"register_oid",cmd_register_oid,"<name> <class> <oid>",NULL,0},
2568 {"push_command",cmd_push_command,"<command>",command_generator,0},
2569 /* Server Admin Functions */
2570 {"adm-reindex", cmd_adm_reindex, "<database-name>",NULL,0},
2571 {"adm-truncate", cmd_adm_truncate, "('database'|'index')<object-name>",NULL,0},
2572 {"adm-create", cmd_adm_create, "",NULL,0},
2573 {"adm-drop", cmd_adm_drop, "('database'|'index')<object-name>",NULL,0},
2574 {"adm-import", cmd_adm_import, "<record-type> <dir> <pattern>",NULL,0},
2575 {"adm-refresh", cmd_adm_refresh, "",NULL,0},
2576 {"adm-commit", cmd_adm_commit, "",NULL,0},
2577 {"adm-shutdown", cmd_adm_shutdown, "",NULL,0},
2578 {"adm-startup", cmd_adm_startup, "",NULL,0},
2579 {"help", cmd_help, "", NULL},
2583 static int cmd_help (char *line)
2589 sscanf (line, "%20s", topic);
2592 printf("Commands:\n");
2593 for (i = 0; cmd[i].cmd; i++)
2594 if (*topic == 0 || strcmp (topic, cmd[i].cmd) == 0)
2595 printf(" %s %s\n", cmd[i].cmd, cmd[i].ad);
2596 if (strcmp (topic, "find") == 0)
2599 printf (" \"term\" Simple Term\n");
2600 printf (" @attr [attset] type=value op Attribute\n");
2601 printf (" @and opl opr And\n");
2602 printf (" @or opl opr Or\n");
2603 printf (" @not opl opr And-Not\n");
2604 printf (" @set set Result set\n");
2606 printf ("Bib-1 attribute types\n");
2608 printf ("4=Title 7=ISBN 8=ISSN 30=Date 62=Abstract 1003=Author 1016=Any\n");
2609 printf ("2=Relation: ");
2610 printf ("1< 2<= 3= 4>= 5> 6!= 102=Relevance\n");
2611 printf ("3=Position: ");
2612 printf ("1=First in Field 2=First in subfield 3=Any position\n");
2613 printf ("4=Structure: ");
2614 printf ("1=Phrase 2=Word 3=Key 4=Year 5=Date 6=WordList\n");
2615 printf ("5=Truncation: ");
2616 printf ("1=Right 2=Left 3=L&R 100=No 101=# 102=Re-1 103=Re-2\n");
2617 printf ("6=Completeness:");
2618 printf ("1=Incomplete subfield 2=Complete subfield 3=Complete field\n");
2623 void process_cmd_line(char* line)
2626 char word[32], arg[1024];
2628 #if HAVE_GETTIMEOFDAY
2629 gettimeofday (&tv_start, 0);
2632 if ((res = sscanf(line, "%31s %1023[^;]", word, arg)) <= 0)
2634 strcpy(word, last_cmd);
2639 strcpy(last_cmd, word);
2641 /* removed tailing spaces from the arg command */
2644 char* lastnonspace=NULL;
2653 *(++lastnonspace) = 0;
2657 for (i = 0; cmd[i].cmd; i++)
2658 if (!strncmp(cmd[i].cmd, word, strlen(word)))
2660 res = (*cmd[i].fun)(arg);
2664 if (!cmd[i].cmd) /* dump our help-screen */
2666 printf("Unknown command: %s.\n", word);
2671 if(apdu_file) fflush(apdu_file);
2674 wait_and_handle_responce();
2683 char *command_generator(const char *text, int state)
2689 for( ; cmd[idx].cmd; ++idx) {
2690 if (!strncmp(cmd[idx].cmd,text,strlen(text))) {
2691 ++idx; /* skip this entry on the next run */
2692 return strdup(cmd[idx-1].cmd);
2700 This function only known how to complete on the first word
2702 char ** readline_completer(char *text, int start, int end) {
2703 #if HAVE_READLINE_READLINE_H
2706 #if HAVE_READLINE_RL_COMPLETION_MATCHES
2707 char** res=rl_completion_matches(text,
2710 char** res=completion_matches(text,
2711 (CPFunction*)command_generator);
2713 rl_attempted_completion_over = 1;
2716 char arg[1024],word[32];
2718 if ((res = sscanf(rl_line_buffer, "%31s %1023[^;]", word, arg)) <= 0) {
2719 rl_attempted_completion_over = 1;
2723 if(start != strlen(word) +1 ) {
2724 rl_attempted_completion_over = 1;
2727 for (i = 0; cmd[i].cmd; i++) {
2728 if (!strncmp(cmd[i].cmd, word, strlen(word))) {
2734 if(!cmd[i].complete_filenames)
2735 rl_attempted_completion_over = 1;
2736 if(cmd[i].rl_completerfunction) {
2737 #ifdef HAVE_READLINE_RL_COMPLETION_MATCHES
2739 rl_completion_matches(text,
2740 cmd[i].rl_completerfunction);
2743 completion_matches(text,
2744 (CPFunction*)cmd[i].rl_completerfunction);
2746 rl_attempted_completion_over = 1;
2749 rl_attempted_completion_over = 1;
2759 static void client(void)
2765 #if HAVE_GETTIMEOFDAY
2766 gettimeofday (&tv_start, 0);
2771 char *line_in = NULL;
2772 #if HAVE_READLINE_READLINE_H
2775 line_in=readline(C_PROMPT);
2778 #if HAVE_READLINE_HISTORY_H
2780 add_history(line_in);
2782 strncpy(line, line_in, 1023);
2791 if (!fgets(line, 1023, stdin))
2793 if ((end_p = strchr (line, '\n')))
2796 process_cmd_line(line);
2800 int main(int argc, char **argv)
2803 char *open_command = 0;
2804 char *auth_command = 0;
2808 while ((ret = options("k:c:a:m:v:p:u:", argv, argc, &arg)) != -2)
2815 open_command = (char *) xmalloc (strlen(arg)+6);
2816 strcpy (open_command, "open ");
2817 strcat (open_command, arg);
2821 kilobytes = atoi(arg);
2824 if (!(marcdump = fopen (arg, "a")))
2831 strncpy (ccl_fields, arg, sizeof(ccl_fields)-1);
2832 ccl_fields[sizeof(ccl_fields)-1] = '\0';
2835 if (!strcmp(arg, "-"))
2838 apdu_file=fopen(arg, "a");
2841 yazProxy=strdup(arg);
2846 auth_command = (char *) xmalloc (strlen(arg)+6);
2847 strcpy (auth_command, "auth ");
2848 strcat (auth_command, arg);
2852 yaz_log_init (yaz_log_mask_str(arg), "", NULL);
2855 fprintf (stderr, "Usage: %s [-m <marclog>] [ -a <apdulog>] "
2856 "[-c cclfields]\n [-p <proxy-addr>] [-u <auth>] "
2857 "[-k size] [<server-addr>]\n",
2865 #ifdef HAVE_GETTIMEOFDAY
2866 gettimeofday (&tv_start, 0);
2868 process_cmd_line (auth_command);
2869 #if HAVE_READLINE_HISTORY_H
2870 add_history(auth_command);
2872 xfree(auth_command);
2876 #ifdef HAVE_GETTIMEOFDAY
2877 gettimeofday (&tv_start, 0);
2879 process_cmd_line (open_command);
2880 #if HAVE_READLINE_HISTORY_H
2881 add_history(open_command);
2883 xfree(open_command);