2 * Copyright (c) 1995-2002, Index Data
3 * See the file LICENSE for details.
5 * $Id: client.c,v 1.148 2002-04-08 11:40:41 adam 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>
24 #include <yaz/pquery.h>
25 #include <yaz/sortspec.h>
32 #include <yaz/yaz-ccl.h>
35 #if HAVE_READLINE_READLINE_H
36 #include <readline/readline.h>
38 #if HAVE_READLINE_HISTORY_H
39 #include <readline/history.h>
46 #include "tabcomplete.h"
48 #define C_PROMPT "Z> "
50 static ODR out, in, print; /* encoding and decoding streams */
51 static FILE *apdu_file = 0;
52 static COMSTACK conn = 0; /* our z-association */
53 static Z_IdAuthentication *auth = 0; /* our current auth definition */
54 char *databaseNames[128];
55 int num_databaseNames = 0;
56 static Z_External *record_last = 0;
57 static int setnumber = -1; /* current result set number */
58 static int smallSetUpperBound = 0;
59 static int largeSetLowerBound = 1;
60 static int mediumSetPresentNumber = 0;
61 static Z_ElementSetNames *elementSetNames = 0;
62 static int setno = 1; /* current set offset */
63 static enum oid_proto protocol = PROTO_Z3950; /* current app protocol */
64 static enum oid_value recordsyntax = VAL_USMARC;
65 static enum oid_value schema = VAL_NONE;
66 static int sent_close = 0;
67 static NMEM session_mem = NULL; /* memory handle for init-response */
68 static Z_InitResponse *session = 0; /* session parameters */
69 static char last_scan_line[512] = "0";
70 static char last_scan_query[512] = "0";
71 static char ccl_fields[512] = "default.bib";
72 static char* esPackageName = 0;
73 static char* yazProxy = 0;
74 static int kilobytes = 1024;
76 static char last_cmd[32] = "?";
77 static FILE *marcdump = 0;
78 static char *refid = NULL;
86 static QueryType queryType = QueryType_Prefix;
89 static CCL_bibset bibset; /* CCL bibset handle */
92 #if HAVE_READLINE_READLINE_H
93 #ifndef RL_READLINE_VERSION
94 int rl_attempted_completion_over = 0;
98 /* set this one to 1, to avoid decode of unknown MARCs */
99 #define AVOID_MARC_DECODE 1
101 /* nice helper macro as extensive tabbing gives spaces at the en of the args lines */
102 #define REMOVE_TAILING_BLANKS(a) {\
103 char* args_end=(a)+strlen(a)-1; \
104 while(isspace(*args_end)) {*args_end=0;--args_end;}; \
108 void process_cmd_line(char* line);
109 char ** readline_completer(char *text, int start, int end);
110 char *command_generator(const char *text, int state);
113 ODR getODROutputStream()
118 void send_apdu(Z_APDU *a)
125 z_APDU(print, &a, 0, 0);
128 if (!z_APDU(out, &a, 0, 0))
130 odr_perror(out, "Encoding APDU");
133 buf = odr_getbuf(out, &len, 0);
134 /* printf ("sending APDU of size %d\n", len); */
135 if (cs_put(conn, buf, len) < 0)
137 fprintf(stderr, "cs_put: %s", cs_errmsg(cs_errno(conn)));
140 odr_reset(out); /* release the APDU structure */
143 static void print_stringn(const unsigned char *buf, size_t len)
146 for (i = 0; i<len; i++)
147 if ((buf[i] <= 126 && buf[i] >= 32) || strchr ("\n\r\t\f", buf[i]))
148 printf ("%c", buf[i]);
150 printf ("\\X%02X", buf[i]);
153 static void print_refid (Z_ReferenceId *id)
157 printf ("Reference Id: ");
158 print_stringn (id->buf, id->len);
163 static Z_ReferenceId *set_refid (ODR out)
168 id = (Z_ReferenceId *) odr_malloc (out, sizeof(*id));
169 id->size = id->len = strlen(refid);
170 id->buf = (unsigned char *) odr_malloc (out, id->len);
171 memcpy (id->buf, refid, id->len);
175 /* INIT SERVICE ------------------------------- */
177 static void send_initRequest(const char* type_and_host)
179 Z_APDU *apdu = zget_APDU(out, Z_APDU_initRequest);
180 Z_InitRequest *req = apdu->u.initRequest;
182 ODR_MASK_SET(req->options, Z_Options_search);
183 ODR_MASK_SET(req->options, Z_Options_present);
184 ODR_MASK_SET(req->options, Z_Options_namedResultSets);
185 ODR_MASK_SET(req->options, Z_Options_triggerResourceCtrl);
186 ODR_MASK_SET(req->options, Z_Options_scan);
187 ODR_MASK_SET(req->options, Z_Options_sort);
188 ODR_MASK_SET(req->options, Z_Options_extendedServices);
189 ODR_MASK_SET(req->options, Z_Options_delSet);
191 ODR_MASK_SET(req->protocolVersion, Z_ProtocolVersion_1);
192 ODR_MASK_SET(req->protocolVersion, Z_ProtocolVersion_2);
193 ODR_MASK_SET(req->protocolVersion, Z_ProtocolVersion_3);
195 *req->maximumRecordSize = 1024*kilobytes;
196 *req->preferredMessageSize = 1024*kilobytes;
198 req->idAuthentication = auth;
200 req->referenceId = set_refid (out);
203 yaz_oi_set_string_oidval(&req->otherInfo, out, VAL_PROXY,
207 printf("Sent initrequest.\n");
210 static int process_initResponse(Z_InitResponse *res)
212 /* save session parameters for later use */
213 session_mem = odr_extract_mem(in);
217 printf("Connection rejected by target.\n");
219 printf("Connection accepted by target.\n");
220 if (res->implementationId)
221 printf("ID : %s\n", res->implementationId);
222 if (res->implementationName)
223 printf("Name : %s\n", res->implementationName);
224 if (res->implementationVersion)
225 printf("Version: %s\n", res->implementationVersion);
226 if (res->userInformationField)
228 printf("UserInformationfield:\n");
229 if (!z_External(print, (Z_External**)&res-> userInformationField,
232 odr_perror(print, "Printing userinfo\n");
235 if (res->userInformationField->which == Z_External_octet)
237 printf("Guessing visiblestring:\n");
238 printf("'%s'\n", res->userInformationField->u. octet_aligned->buf);
243 if (ODR_MASK_GET(res->options, Z_Options_search))
245 if (ODR_MASK_GET(res->options, Z_Options_present))
247 if (ODR_MASK_GET(res->options, Z_Options_delSet))
249 if (ODR_MASK_GET(res->options, Z_Options_resourceReport))
250 printf (" resourceReport");
251 if (ODR_MASK_GET(res->options, Z_Options_resourceCtrl))
252 printf (" resourceCtrl");
253 if (ODR_MASK_GET(res->options, Z_Options_accessCtrl))
254 printf (" accessCtrl");
255 if (ODR_MASK_GET(res->options, Z_Options_scan))
257 if (ODR_MASK_GET(res->options, Z_Options_sort))
259 if (ODR_MASK_GET(res->options, Z_Options_extendedServices))
260 printf (" extendedServices");
261 if (ODR_MASK_GET(res->options, Z_Options_level_1Segmentation))
262 printf (" level1Segmentation");
263 if (ODR_MASK_GET(res->options, Z_Options_level_2Segmentation))
264 printf (" level2Segmentation");
265 if (ODR_MASK_GET(res->options, Z_Options_concurrentOperations))
266 printf (" concurrentOperations");
267 if (ODR_MASK_GET(res->options, Z_Options_namedResultSets))
269 printf (" namedResultSets");
272 if (ODR_MASK_GET(res->options, Z_Options_encapsulation))
273 printf (" encapsulation");
274 if (ODR_MASK_GET(res->options, Z_Options_resultCount))
275 printf (" resultCount");
276 if (ODR_MASK_GET(res->options, Z_Options_negotiationModel))
277 printf (" negotiationModel");
278 if (ODR_MASK_GET(res->options, Z_Options_duplicateDetection))
279 printf (" duplicateDetection");
280 if (ODR_MASK_GET(res->options, Z_Options_queryType104))
281 printf (" queryType104");
287 static int cmd_base(char *arg)
294 printf("Usage: base <database> <database> ...\n");
297 for (i = 0; i<num_databaseNames; i++)
298 xfree (databaseNames[i]);
299 num_databaseNames = 0;
302 if (!(cp = strchr(arg, ' ')))
303 cp = arg + strlen(arg);
306 databaseNames[num_databaseNames] = (char *)xmalloc (1 + cp - arg);
307 memcpy (databaseNames[num_databaseNames], arg, cp - arg);
308 databaseNames[num_databaseNames++][cp - arg] = '\0';
316 int cmd_open(char *arg)
319 char type_and_host[101], base[101];
324 printf("Already connected.\n");
330 nmem_destroy (session_mem);
336 if (sscanf (arg, "%100[^/]/%100s", type_and_host, base) < 1)
340 conn = cs_create_host(yazProxy, 1, &add);
342 conn = cs_create_host(type_and_host, 1, &add);
346 printf ("Couldn't create comstack\n");
349 printf("Connecting...");
351 if (cs_connect(conn, add) < 0)
353 printf ("error = %s\n", cs_strerror(conn));
354 if (conn->cerrno == CSYSERR)
362 send_initRequest(type_and_host);
368 int cmd_authentication(char *arg)
370 static Z_IdAuthentication au;
371 static char user[40], group[40], pass[40];
372 static Z_IdPass idPass;
377 printf("Auth field set to null\n");
381 r = sscanf (arg, "%39s %39s %39s", user, group, pass);
384 printf("Auth field set to null\n");
390 au.which = Z_IdAuthentication_open;
396 au.which = Z_IdAuthentication_idPass;
397 au.u.idPass = &idPass;
398 idPass.groupId = group;
399 idPass.userId = user;
400 idPass.password = pass;
405 /* SEARCH SERVICE ------------------------------ */
407 static void display_variant(Z_Variant *v, int level)
411 for (i = 0; i < v->num_triples; i++)
413 printf("%*sclass=%d,type=%d", level * 4, "", *v->triples[i]->zclass,
414 *v->triples[i]->type);
415 if (v->triples[i]->which == Z_Triple_internationalString)
416 printf(",value=%s\n", v->triples[i]->value.internationalString);
422 static void display_grs1(Z_GenericRecord *r, int level)
428 for (i = 0; i < r->num_elements; i++)
432 printf("%*s", level * 4, "");
436 printf("%d,", *t->tagType);
439 if (t->tagValue->which == Z_StringOrNumeric_numeric)
440 printf("%d) ", *t->tagValue->u.numeric);
442 printf("%s) ", t->tagValue->u.string);
443 if (t->content->which == Z_ElementData_subtree)
446 display_grs1(t->content->u.subtree, level+1);
448 else if (t->content->which == Z_ElementData_string)
449 printf("%s\n", t->content->u.string);
450 else if (t->content->which == Z_ElementData_numeric)
451 printf("%d\n", *t->content->u.numeric);
452 else if (t->content->which == Z_ElementData_oid)
454 int *ip = t->content->u.oid;
457 if ((oent = oid_getentbyoid(t->content->u.oid)))
458 printf("OID: %s\n", oent->desc);
462 while (ip && *ip >= 0)
463 printf(" %d", *(ip++));
467 else if (t->content->which == Z_ElementData_noDataRequested)
468 printf("[No data requested]\n");
469 else if (t->content->which == Z_ElementData_elementEmpty)
470 printf("[Element empty]\n");
471 else if (t->content->which == Z_ElementData_elementNotThere)
472 printf("[Element not there]\n");
475 if (t->appliedVariant)
476 display_variant(t->appliedVariant, level+1);
477 if (t->metaData && t->metaData->supportedVariants)
481 printf("%*s---- variant list\n", (level+1)*4, "");
482 for (c = 0; c < t->metaData->num_supportedVariants; c++)
484 printf("%*svariant #%d\n", (level+1)*4, "", c);
485 display_variant(t->metaData->supportedVariants[c], level + 2);
492 static void print_record(const unsigned char *buf, size_t len)
495 print_stringn (buf, len);
496 /* add newline if not already added ... */
497 if (i <= 0 || buf[i-1] != '\n')
501 static void display_record(Z_External *r)
503 oident *ent = oid_getentbyoid(r->direct_reference);
507 * Tell the user what we got.
509 if (r->direct_reference)
511 printf("Record type: ");
513 printf("%s\n", ent->desc);
514 else if (!odr_oid(print, &r->direct_reference, 0, 0))
516 odr_perror(print, "print oid");
520 /* Check if this is a known, ASN.1 type tucked away in an octet string */
521 if (ent && r->which == Z_External_octet)
523 Z_ext_typeent *type = z_ext_getentbyref(ent->value);
529 * Call the given decoder to process the record.
531 odr_setbuf(in, (char*)r->u.octet_aligned->buf,
532 r->u.octet_aligned->len, 0);
533 if (!(*type->fun)(in, (char **)&rr, 0, 0))
535 odr_perror(in, "Decoding constructed record.");
536 fprintf(stderr, "[Near %d]\n", odr_offset(in));
537 fprintf(stderr, "Packet dump:\n---------\n");
538 odr_dumpBER(stderr, (char*)r->u.octet_aligned->buf,
539 r->u.octet_aligned->len);
540 fprintf(stderr, "---------\n");
544 * Note: we throw away the original, BER-encoded record here.
545 * Do something else with it if you want to keep it.
547 r->u.sutrs = (Z_SUTRS *) rr; /* we don't actually check the type here. */
548 r->which = type->what;
551 if (ent && ent->value == VAL_SOIF)
552 print_record((const unsigned char *) r->u.octet_aligned->buf,
553 r->u.octet_aligned->len);
554 else if (r->which == Z_External_octet && r->u.octet_aligned->len)
556 const char *octet_buf = (char*)r->u.octet_aligned->buf;
557 if (ent->value == VAL_TEXT_XML || ent->value == VAL_APPLICATION_XML ||
558 ent->value == VAL_HTML)
560 print_record((const unsigned char *) octet_buf,
561 r->u.octet_aligned->len);
563 else if (ent->value == VAL_POSTSCRIPT)
565 int size = r->u.octet_aligned->len;
568 print_record((const unsigned char *) octet_buf, size);
573 #if AVOID_MARC_DECODE
574 /* primitive check for a marc OID 5.1-29 except 16 */
575 ent->oidsuffix[0] == 5 && ent->oidsuffix[1] < 30 &&
576 ent->oidsuffix[1] != 16
582 if (marc_display_exl (octet_buf, NULL, 0 /* debug */,
583 r->u.octet_aligned->len) <= 0)
585 printf ("bad MARC. Dumping as it is:\n");
586 print_record((const unsigned char*) octet_buf,
587 r->u.octet_aligned->len);
592 print_record((const unsigned char*) octet_buf,
593 r->u.octet_aligned->len);
597 fwrite (octet_buf, 1, r->u.octet_aligned->len, marcdump);
599 else if (ent && ent->value == VAL_SUTRS)
601 if (r->which != Z_External_sutrs)
603 printf("Expecting single SUTRS type for SUTRS.\n");
606 print_record(r->u.sutrs->buf, r->u.sutrs->len);
608 else if (ent && ent->value == VAL_GRS1)
610 if (r->which != Z_External_grs1)
612 printf("Expecting single GRS type for GRS.\n");
615 display_grs1(r->u.grs1, 0);
619 printf("Unknown record representation.\n");
620 if (!z_External(print, &r, 0, 0))
622 odr_perror(print, "Printing external");
628 static void display_diagrecs(Z_DiagRec **pp, int num)
632 Z_DefaultDiagFormat *r;
634 printf("Diagnostic message(s) from database:\n");
635 for (i = 0; i<num; i++)
637 Z_DiagRec *p = pp[i];
638 if (p->which != Z_DiagRec_defaultFormat)
640 printf("Diagnostic record not in default format.\n");
644 r = p->u.defaultFormat;
645 if (!(ent = oid_getentbyoid(r->diagnosticSetId)) ||
646 ent->oclass != CLASS_DIAGSET || ent->value != VAL_BIB1)
647 printf("Missing or unknown diagset\n");
648 printf(" [%d] %s", *r->condition, diagbib1_str(*r->condition));
651 case Z_DefaultDiagFormat_v2Addinfo:
652 printf (" -- v2 addinfo '%s'\n", r->u.v2Addinfo);
654 case Z_DefaultDiagFormat_v3Addinfo:
655 printf (" -- v3 addinfo '%s'\n", r->u.v3Addinfo);
662 static void display_nameplusrecord(Z_NamePlusRecord *p)
665 printf("[%s]", p->databaseName);
666 if (p->which == Z_NamePlusRecord_surrogateDiagnostic)
667 display_diagrecs(&p->u.surrogateDiagnostic, 1);
668 else if (p->which == Z_NamePlusRecord_databaseRecord)
669 display_record(p->u.databaseRecord);
672 static void display_records(Z_Records *p)
676 if (p->which == Z_Records_NSD)
678 Z_DiagRec dr, *dr_p = &dr;
679 dr.which = Z_DiagRec_defaultFormat;
680 dr.u.defaultFormat = p->u.nonSurrogateDiagnostic;
681 display_diagrecs (&dr_p, 1);
683 else if (p->which == Z_Records_multipleNSD)
684 display_diagrecs (p->u.multipleNonSurDiagnostics->diagRecs,
685 p->u.multipleNonSurDiagnostics->num_diagRecs);
688 printf("Records: %d\n", p->u.databaseOrSurDiagnostics->num_records);
689 for (i = 0; i < p->u.databaseOrSurDiagnostics->num_records; i++)
690 display_nameplusrecord(p->u.databaseOrSurDiagnostics->records[i]);
694 static int send_deleteResultSetRequest(char *arg)
699 Z_APDU *apdu = zget_APDU(out, Z_APDU_deleteResultSetRequest);
700 Z_DeleteResultSetRequest *req = apdu->u.deleteResultSetRequest;
702 req->referenceId = set_refid (out);
704 req->num_resultSetList =
705 sscanf (arg, "%30s %30s %30s %30s %30s %30s %30s %30s",
706 names[0], names[1], names[2], names[3],
707 names[4], names[5], names[6], names[7]);
709 req->deleteFunction = (int *)
710 odr_malloc (out, sizeof(*req->deleteFunction));
711 if (req->num_resultSetList > 0)
713 *req->deleteFunction = Z_DeleteRequest_list;
714 req->resultSetList = (char **)
715 odr_malloc (out, sizeof(*req->resultSetList)*
716 req->num_resultSetList);
717 for (i = 0; i<req->num_resultSetList; i++)
718 req->resultSetList[i] = names[i];
722 *req->deleteFunction = Z_DeleteRequest_all;
723 req->resultSetList = 0;
727 printf("Sent deleteResultSetRequest.\n");
731 static int send_searchRequest(char *arg)
733 Z_APDU *apdu = zget_APDU(out, Z_APDU_searchRequest);
734 Z_SearchRequest *req = apdu->u.searchRequest;
738 struct ccl_rpn_node *rpn = NULL;
742 Z_RPNQuery *RPNquery;
746 if (queryType == QueryType_CCL2RPN)
748 rpn = ccl_find_str(bibset, arg, &error, &pos);
751 printf("CCL ERROR: %s\n", ccl_err_msg(error));
756 req->referenceId = set_refid (out);
757 if (!strcmp(arg, "@big")) /* strictly for troublemaking */
759 static unsigned char big[2100];
762 /* send a very big referenceid to test transport stack etc. */
763 memset(big, 'A', 2100);
764 bigo.len = bigo.size = 2100;
766 req->referenceId = &bigo;
771 sprintf(setstring, "%d", ++setnumber);
772 req->resultSetName = setstring;
774 *req->smallSetUpperBound = smallSetUpperBound;
775 *req->largeSetLowerBound = largeSetLowerBound;
776 *req->mediumSetPresentNumber = mediumSetPresentNumber;
777 if (smallSetUpperBound > 0 || (largeSetLowerBound > 1 &&
778 mediumSetPresentNumber > 0))
782 prefsyn.proto = protocol;
783 prefsyn.oclass = CLASS_RECSYN;
784 prefsyn.value = recordsyntax;
785 req->preferredRecordSyntax =
786 odr_oiddup(out, oid_ent_to_oid(&prefsyn, oid));
787 req->smallSetElementSetNames =
788 req->mediumSetElementSetNames = elementSetNames;
790 req->num_databaseNames = num_databaseNames;
791 req->databaseNames = databaseNames;
797 case QueryType_Prefix:
798 query.which = Z_Query_type_1;
799 RPNquery = p_query_rpn (out, protocol, arg);
802 printf("Prefix query error\n");
805 query.u.type_1 = RPNquery;
808 query.which = Z_Query_type_2;
809 query.u.type_2 = &ccl_query;
810 ccl_query.buf = (unsigned char*) arg;
811 ccl_query.len = strlen(arg);
814 case QueryType_CCL2RPN:
815 query.which = Z_Query_type_1;
816 RPNquery = ccl_rpn_query(out, rpn);
819 printf ("Couldn't convert from CCL to RPN\n");
822 query.u.type_1 = RPNquery;
823 ccl_rpn_delete (rpn);
827 printf ("Unsupported query type\n");
832 printf("Sent searchRequest.\n");
836 /* display Query Expression as part of searchResult-1 */
837 static void display_queryExpression (Z_QueryExpression *qe)
841 if (qe->which == Z_QueryExpression_term)
843 if (qe->u.term->queryTerm)
845 Z_Term *term = qe->u.term->queryTerm;
846 if (term->which == Z_Term_general)
847 printf (" %.*s", term->u.general->len, term->u.general->buf);
853 /* see if we can find USR:SearchResult-1 */
854 static void display_searchResult (Z_OtherInformation *o)
859 for (i = 0; i < o->num_elements; i++)
861 if (o->list[i]->which == Z_OtherInfo_externallyDefinedInfo)
863 Z_External *ext = o->list[i]->information.externallyDefinedInfo;
865 if (ext->which == Z_External_searchResult1)
868 Z_SearchInfoReport *sr = ext->u.searchResult1;
869 printf ("SearchResult-1:");
870 for (j = 0; j < sr->num; j++)
872 if (!sr->elements[j]->subqueryExpression)
874 display_queryExpression (
875 sr->elements[j]->subqueryExpression);
876 display_queryExpression (
877 sr->elements[j]->subqueryInterpretation);
878 display_queryExpression (
879 sr->elements[j]->subqueryRecommendation);
880 if (sr->elements[j]->subqueryCount)
881 printf ("(%d)", *sr->elements[j]->subqueryCount);
889 static int process_searchResponse(Z_SearchResponse *res)
891 printf ("Received SearchResponse.\n");
892 print_refid (res->referenceId);
893 if (*res->searchStatus)
894 printf("Search was a success.\n");
896 printf("Search was a bloomin' failure.\n");
897 printf("Number of hits: %d", *res->resultCount);
899 printf (", setno %d", setnumber);
901 display_searchResult (res->additionalSearchInfo);
902 printf("records returned: %d\n",
903 *res->numberOfRecordsReturned);
904 setno += *res->numberOfRecordsReturned;
906 display_records(res->records);
910 static void print_level(int iLevel)
913 for (i = 0; i < iLevel * 4; i++)
917 static void print_int(int iLevel, const char *pTag, int *pInt)
922 printf("%s: %d\n", pTag, *pInt);
926 static void print_string(int iLevel, const char *pTag, const char *pString)
931 printf("%s: %s\n", pTag, pString);
935 static void print_oid(int iLevel, const char *pTag, Odr_oid *pOid)
943 for (; *pInt != -1; pInt++)
944 printf(" %d", *pInt);
949 static void print_referenceId(int iLevel, Z_ReferenceId *referenceId)
951 if (referenceId != NULL)
956 printf("Ref Id (%d, %d): ", referenceId->len, referenceId->size);
957 for (i = 0; i < referenceId->len; i++)
958 printf("%c", referenceId->buf[i]);
963 static void print_string_or_numeric(int iLevel, const char *pTag, Z_StringOrNumeric *pStringNumeric)
965 if (pStringNumeric != NULL)
967 switch (pStringNumeric->which)
969 case Z_StringOrNumeric_string:
970 print_string(iLevel, pTag, pStringNumeric->u.string);
973 case Z_StringOrNumeric_numeric:
974 print_int(iLevel, pTag, pStringNumeric->u.numeric);
979 printf("%s: valid type for Z_StringOrNumeric\n", pTag);
985 static void print_universe_report_duplicate(int iLevel, Z_UniverseReportDuplicate *pUniverseReportDuplicate)
987 if (pUniverseReportDuplicate != NULL)
990 printf("Universe Report Duplicate: \n");
992 print_string_or_numeric(iLevel, "Hit No",
993 pUniverseReportDuplicate->hitno);
998 print_universe_report_hits(int iLevel,
999 Z_UniverseReportHits *pUniverseReportHits)
1001 if (pUniverseReportHits != NULL)
1003 print_level(iLevel);
1004 printf("Universe Report Hits: \n");
1006 print_string_or_numeric(iLevel, "Database",
1007 pUniverseReportHits->database);
1008 print_string_or_numeric(iLevel, "Hits", pUniverseReportHits->hits);
1012 static void print_universe_report(int iLevel, Z_UniverseReport *pUniverseReport)
1014 if (pUniverseReport != NULL)
1016 print_level(iLevel);
1017 printf("Universe Report: \n");
1019 print_int(iLevel, "Total Hits", pUniverseReport->totalHits);
1020 switch (pUniverseReport->which)
1022 case Z_UniverseReport_databaseHits:
1023 print_universe_report_hits(iLevel, pUniverseReport->u.databaseHits);
1026 case Z_UniverseReport_duplicate:
1027 print_universe_report_duplicate(iLevel, pUniverseReport->u.duplicate);
1031 print_level(iLevel);
1032 printf("Type: %d\n", pUniverseReport->which);
1038 static void print_external(int iLevel, Z_External *pExternal)
1040 if (pExternal != NULL)
1042 print_level(iLevel);
1043 printf("External: \n");
1045 print_oid(iLevel, "Direct Reference", pExternal->direct_reference);
1046 print_int(iLevel, "InDirect Reference", pExternal->indirect_reference);
1047 print_string(iLevel, "Descriptor", pExternal->descriptor);
1048 switch (pExternal->which)
1050 case Z_External_universeReport:
1051 print_universe_report(iLevel, pExternal->u.universeReport);
1055 print_level(iLevel);
1056 printf("Type: %d\n", pExternal->which);
1062 static int process_resourceControlRequest (Z_ResourceControlRequest *req)
1064 printf ("Received ResourceControlRequest.\n");
1065 print_referenceId(1, req->referenceId);
1066 print_int(1, "Suspended Flag", req->suspendedFlag);
1067 print_int(1, "Partial Results Available", req->partialResultsAvailable);
1068 print_int(1, "Response Required", req->responseRequired);
1069 print_int(1, "Triggered Request Flag", req->triggeredRequestFlag);
1070 print_external(1, req->resourceReport);
1074 void process_ESResponse(Z_ExtendedServicesResponse *res)
1077 switch (*res->operationStatus)
1079 case Z_ExtendedServicesResponse_done:
1082 case Z_ExtendedServicesResponse_accepted:
1083 printf ("accepted\n");
1085 case Z_ExtendedServicesResponse_failure:
1086 printf ("failure\n");
1087 display_diagrecs(res->diagnostics, res->num_diagnostics);
1090 printf ("unknown\n");
1092 if ( (*res->operationStatus != Z_ExtendedServicesResponse_failure) &&
1093 (res->num_diagnostics != 0) ) {
1094 display_diagrecs(res->diagnostics, res->num_diagnostics);
1096 print_refid (res->referenceId);
1097 if (res->taskPackage &&
1098 res->taskPackage->which == Z_External_extendedService)
1100 Z_TaskPackage *taskPackage = res->taskPackage->u.extendedService;
1101 Odr_oct *id = taskPackage->targetReference;
1102 Z_External *ext = taskPackage->taskSpecificParameters;
1106 printf ("Target Reference: ");
1107 print_stringn (id->buf, id->len);
1110 if (ext->which == Z_External_update)
1112 Z_IUUpdateTaskPackage *utp = ext->u.update->u.taskPackage;
1113 if (utp && utp->targetPart)
1115 Z_IUTargetPart *targetPart = utp->targetPart;
1118 for (i = 0; i<targetPart->num_taskPackageRecords; i++)
1121 Z_IUTaskPackageRecordStructure *tpr =
1122 targetPart->taskPackageRecords[i];
1123 printf ("task package record %d\n", i+1);
1124 if (tpr->which == Z_IUTaskPackageRecordStructure_record)
1126 display_record (tpr->u.record);
1130 printf ("other type\n");
1140 const char *get_ill_element (void *clientData, const char *element)
1145 static Z_External *create_external_itemRequest()
1147 struct ill_get_ctl ctl;
1148 ILL_ItemRequest *req;
1150 int item_request_size = 0;
1151 char *item_request_buf = 0;
1155 ctl.f = get_ill_element;
1157 req = ill_get_ItemRequest(&ctl, "ill", 0);
1159 printf ("ill_get_ItemRequest failed\n");
1161 if (!ill_ItemRequest (out, &req, 0, 0))
1165 ill_ItemRequest(print, &req, 0, 0);
1168 item_request_buf = odr_getbuf (out, &item_request_size, 0);
1169 if (item_request_buf)
1170 odr_setbuf (out, item_request_buf, item_request_size, 1);
1171 printf ("Couldn't encode ItemRequest, size %d\n", item_request_size);
1178 item_request_buf = odr_getbuf (out, &item_request_size, 0);
1179 oid.proto = PROTO_GENERAL;
1180 oid.oclass = CLASS_GENERAL;
1181 oid.value = VAL_ISO_ILL_1;
1183 r = (Z_External *) odr_malloc (out, sizeof(*r));
1184 r->direct_reference = odr_oiddup(out,oid_getoidbyent(&oid));
1185 r->indirect_reference = 0;
1187 r->which = Z_External_single;
1189 r->u.single_ASN1_type = (Odr_oct *)
1190 odr_malloc (out, sizeof(*r->u.single_ASN1_type));
1191 r->u.single_ASN1_type->buf = (unsigned char *)
1192 odr_malloc (out, item_request_size);
1193 r->u.single_ASN1_type->len = item_request_size;
1194 r->u.single_ASN1_type->size = item_request_size;
1195 memcpy (r->u.single_ASN1_type->buf, item_request_buf,
1197 printf ("len = %d\n", item_request_size);
1203 #ifdef YAZ_MODULE_ill
1204 static Z_External *create_external_ILL_APDU(int which)
1206 struct ill_get_ctl ctl;
1209 int ill_request_size = 0;
1210 char *ill_request_buf = 0;
1214 ctl.f = get_ill_element;
1216 ill_apdu = ill_get_APDU(&ctl, "ill", 0);
1218 if (!ill_APDU (out, &ill_apdu, 0, 0))
1222 printf ("-------------------\n");
1223 ill_APDU(print, &ill_apdu, 0, 0);
1225 printf ("-------------------\n");
1227 ill_request_buf = odr_getbuf (out, &ill_request_size, 0);
1228 if (ill_request_buf)
1229 odr_setbuf (out, ill_request_buf, ill_request_size, 1);
1230 printf ("Couldn't encode ILL-Request, size %d\n", ill_request_size);
1236 ill_request_buf = odr_getbuf (out, &ill_request_size, 0);
1238 oid.proto = PROTO_GENERAL;
1239 oid.oclass = CLASS_GENERAL;
1240 oid.value = VAL_ISO_ILL_1;
1242 r = (Z_External *) odr_malloc (out, sizeof(*r));
1243 r->direct_reference = odr_oiddup(out,oid_getoidbyent(&oid));
1244 r->indirect_reference = 0;
1246 r->which = Z_External_single;
1248 r->u.single_ASN1_type = (Odr_oct *)
1249 odr_malloc (out, sizeof(*r->u.single_ASN1_type));
1250 r->u.single_ASN1_type->buf = (unsigned char *)
1251 odr_malloc (out, ill_request_size);
1252 r->u.single_ASN1_type->len = ill_request_size;
1253 r->u.single_ASN1_type->size = ill_request_size;
1254 memcpy (r->u.single_ASN1_type->buf, ill_request_buf, ill_request_size);
1255 printf ("len = %d\n", ill_request_size);
1262 static Z_External *create_ItemOrderExternal(const char *type, int itemno)
1264 Z_External *r = (Z_External *) odr_malloc(out, sizeof(Z_External));
1265 oident ItemOrderRequest;
1267 ItemOrderRequest.proto = PROTO_Z3950;
1268 ItemOrderRequest.oclass = CLASS_EXTSERV;
1269 ItemOrderRequest.value = VAL_ITEMORDER;
1271 r->direct_reference = odr_oiddup(out,oid_getoidbyent(&ItemOrderRequest));
1272 r->indirect_reference = 0;
1275 r->which = Z_External_itemOrder;
1277 r->u.itemOrder = (Z_ItemOrder *) odr_malloc(out,sizeof(Z_ItemOrder));
1278 memset(r->u.itemOrder, 0, sizeof(Z_ItemOrder));
1279 r->u.itemOrder->which=Z_IOItemOrder_esRequest;
1281 r->u.itemOrder->u.esRequest = (Z_IORequest *)
1282 odr_malloc(out,sizeof(Z_IORequest));
1283 memset(r->u.itemOrder->u.esRequest, 0, sizeof(Z_IORequest));
1285 r->u.itemOrder->u.esRequest->toKeep = (Z_IOOriginPartToKeep *)
1286 odr_malloc(out,sizeof(Z_IOOriginPartToKeep));
1287 memset(r->u.itemOrder->u.esRequest->toKeep, 0, sizeof(Z_IOOriginPartToKeep));
1288 r->u.itemOrder->u.esRequest->notToKeep = (Z_IOOriginPartNotToKeep *)
1289 odr_malloc(out,sizeof(Z_IOOriginPartNotToKeep));
1290 memset(r->u.itemOrder->u.esRequest->notToKeep, 0, sizeof(Z_IOOriginPartNotToKeep));
1292 r->u.itemOrder->u.esRequest->toKeep->supplDescription = NULL;
1293 r->u.itemOrder->u.esRequest->toKeep->contact = NULL;
1294 r->u.itemOrder->u.esRequest->toKeep->addlBilling = NULL;
1296 r->u.itemOrder->u.esRequest->notToKeep->resultSetItem =
1297 (Z_IOResultSetItem *) odr_malloc(out, sizeof(Z_IOResultSetItem));
1298 memset(r->u.itemOrder->u.esRequest->notToKeep->resultSetItem, 0, sizeof(Z_IOResultSetItem));
1299 r->u.itemOrder->u.esRequest->notToKeep->resultSetItem->resultSetId = "1";
1301 r->u.itemOrder->u.esRequest->notToKeep->resultSetItem->item =
1302 (int *) odr_malloc(out, sizeof(int));
1303 *r->u.itemOrder->u.esRequest->notToKeep->resultSetItem->item = itemno;
1306 if (!strcmp (type, "item") || !strcmp(type, "2"))
1308 printf ("using item-request\n");
1309 r->u.itemOrder->u.esRequest->notToKeep->itemRequest =
1310 create_external_itemRequest();
1312 else if (!strcmp(type, "ill") || !strcmp(type, "1"))
1314 printf ("using ILL-request\n");
1315 r->u.itemOrder->u.esRequest->notToKeep->itemRequest =
1316 create_external_ILL_APDU(ILL_APDU_ILL_Request);
1318 else if (!strcmp(type, "xml") || !strcmp(type, "3"))
1320 const char *xml_buf =
1322 " <type>request</type>\n"
1323 " <libraryNo>000200</libraryNo>\n"
1324 " <borrowerTicketNo> 1212 </borrowerTicketNo>\n"
1326 r->u.itemOrder->u.esRequest->notToKeep->itemRequest =
1327 z_ext_record (out, VAL_TEXT_XML, xml_buf, strlen(xml_buf));
1330 r->u.itemOrder->u.esRequest->notToKeep->itemRequest = 0;
1333 r->u.itemOrder->u.esRequest->notToKeep->itemRequest = 0;
1338 static int send_itemorder(const char *type, int itemno)
1340 Z_APDU *apdu = zget_APDU(out, Z_APDU_extendedServicesRequest);
1341 Z_ExtendedServicesRequest *req = apdu->u.extendedServicesRequest;
1342 oident ItemOrderRequest;
1344 ItemOrderRequest.proto = PROTO_Z3950;
1345 ItemOrderRequest.oclass = CLASS_EXTSERV;
1346 ItemOrderRequest.value = VAL_ITEMORDER;
1347 req->packageType = odr_oiddup(out,oid_getoidbyent(&ItemOrderRequest));
1348 req->packageName = esPackageName;
1350 req->taskSpecificParameters = create_ItemOrderExternal(type, itemno);
1356 static int cmd_update(char *arg)
1358 Z_APDU *apdu = zget_APDU(out, Z_APDU_extendedServicesRequest );
1359 Z_ExtendedServicesRequest *req = apdu->u.extendedServicesRequest;
1362 Z_IUOriginPartToKeep *toKeep;
1363 Z_IUSuppliedRecords *notToKeep;
1365 printf ("Update request\n");
1370 update_oid.proto = PROTO_Z3950;
1371 update_oid.oclass = CLASS_EXTSERV;
1372 update_oid.value = VAL_DBUPDATE;
1373 oid_ent_to_oid (&update_oid, oid);
1374 req->packageType = odr_oiddup(out,oid);
1375 req->packageName = esPackageName;
1377 req->referenceId = set_refid (out);
1379 r = req->taskSpecificParameters = (Z_External *)
1380 odr_malloc (out, sizeof(*r));
1381 r->direct_reference = odr_oiddup(out,oid);
1382 r->indirect_reference = 0;
1384 r->which = Z_External_update;
1385 r->u.update = (Z_IUUpdate *) odr_malloc(out, sizeof(*r->u.update));
1386 r->u.update->which = Z_IUUpdate_esRequest;
1387 r->u.update->u.esRequest = (Z_IUUpdateEsRequest *)
1388 odr_malloc(out, sizeof(*r->u.update->u.esRequest));
1389 toKeep = r->u.update->u.esRequest->toKeep = (Z_IUOriginPartToKeep *)
1390 odr_malloc(out, sizeof(*r->u.update->u.esRequest->toKeep));
1391 toKeep->databaseName = databaseNames[0];
1393 toKeep->elementSetName = 0;
1394 toKeep->actionQualifier = 0;
1395 toKeep->action = (int *) odr_malloc(out, sizeof(*toKeep->action));
1396 *toKeep->action = Z_IUOriginPartToKeep_recordInsert;
1398 notToKeep = r->u.update->u.esRequest->notToKeep = (Z_IUSuppliedRecords *)
1399 odr_malloc(out, sizeof(*r->u.update->u.esRequest->notToKeep));
1401 notToKeep->elements = (Z_IUSuppliedRecords_elem **)
1402 odr_malloc(out, sizeof(*notToKeep->elements));
1403 notToKeep->elements[0] = (Z_IUSuppliedRecords_elem *)
1404 odr_malloc(out, sizeof(**notToKeep->elements));
1405 notToKeep->elements[0]->u.number = 0;
1406 notToKeep->elements[0]->supplementalId = 0;
1407 notToKeep->elements[0]->correlationInfo = 0;
1408 notToKeep->elements[0]->record = record_last;
1415 static int cmd_itemorder(char *arg)
1420 if (sscanf (arg, "%10s %d", type, &itemno) != 2)
1423 printf("Item order request\n");
1425 send_itemorder(type, itemno);
1429 static int cmd_find(char *arg)
1433 printf("Find what?\n");
1438 printf("Not connected yet\n");
1441 if (!send_searchRequest(arg))
1446 static int cmd_delete(char *arg)
1450 printf("Not connected yet\n");
1453 if (!send_deleteResultSetRequest(arg))
1458 static int cmd_ssub(char *arg)
1460 if (!(smallSetUpperBound = atoi(arg)))
1465 static int cmd_lslb(char *arg)
1467 if (!(largeSetLowerBound = atoi(arg)))
1472 static int cmd_mspn(char *arg)
1474 if (!(mediumSetPresentNumber = atoi(arg)))
1479 static int cmd_status(char *arg)
1481 printf("smallSetUpperBound: %d\n", smallSetUpperBound);
1482 printf("largeSetLowerBound: %d\n", largeSetLowerBound);
1483 printf("mediumSetPresentNumber: %d\n", mediumSetPresentNumber);
1487 static int cmd_setnames(char *arg)
1489 if (*arg == '1') /* enable ? */
1491 else if (*arg == '0') /* disable ? */
1493 else if (setnumber < 0) /* no args, toggle .. */
1499 printf("Set numbering enabled.\n");
1501 printf("Set numbering disabled.\n");
1505 /* PRESENT SERVICE ----------------------------- */
1507 static int send_presentRequest(char *arg)
1509 Z_APDU *apdu = zget_APDU(out, Z_APDU_presentRequest);
1510 Z_PresentRequest *req = apdu->u.presentRequest;
1511 Z_RecordComposition compo;
1516 char setstring[100];
1518 req->referenceId = set_refid (out);
1519 if ((p = strchr(arg, '+')))
1526 if (p && (p=strchr(p+1, '+')))
1528 strcpy (setstring, p+1);
1529 req->resultSetId = setstring;
1531 else if (setnumber >= 0)
1533 sprintf(setstring, "%d", setnumber);
1534 req->resultSetId = setstring;
1536 req->resultSetStartPoint = &setno;
1537 req->numberOfRecordsRequested = &nos;
1538 prefsyn.proto = protocol;
1539 prefsyn.oclass = CLASS_RECSYN;
1540 prefsyn.value = recordsyntax;
1541 req->preferredRecordSyntax =
1542 odr_oiddup (out, oid_ent_to_oid(&prefsyn, oid));
1544 if (schema != VAL_NONE)
1548 prefschema.proto = protocol;
1549 prefschema.oclass = CLASS_SCHEMA;
1550 prefschema.value = schema;
1552 req->recordComposition = &compo;
1553 compo.which = Z_RecordComp_complex;
1554 compo.u.complex = (Z_CompSpec *)
1555 odr_malloc(out, sizeof(*compo.u.complex));
1556 compo.u.complex->selectAlternativeSyntax = (bool_t *)
1557 odr_malloc(out, sizeof(bool_t));
1558 *compo.u.complex->selectAlternativeSyntax = 0;
1560 compo.u.complex->generic = (Z_Specification *)
1561 odr_malloc(out, sizeof(*compo.u.complex->generic));
1562 compo.u.complex->generic->schema = (Odr_oid *)
1563 odr_oiddup(out, oid_ent_to_oid(&prefschema, oid));
1564 if (!compo.u.complex->generic->schema)
1566 /* OID wasn't a schema! Try record syntax instead. */
1567 prefschema.oclass = CLASS_RECSYN;
1568 compo.u.complex->generic->schema = (Odr_oid *)
1569 odr_oiddup(out, oid_ent_to_oid(&prefschema, oid));
1571 if (!elementSetNames)
1572 compo.u.complex->generic->elementSpec = 0;
1575 compo.u.complex->generic->elementSpec = (Z_ElementSpec *)
1576 odr_malloc(out, sizeof(Z_ElementSpec));
1577 compo.u.complex->generic->elementSpec->which =
1578 Z_ElementSpec_elementSetName;
1579 compo.u.complex->generic->elementSpec->u.elementSetName =
1580 elementSetNames->u.generic;
1582 compo.u.complex->num_dbSpecific = 0;
1583 compo.u.complex->dbSpecific = 0;
1584 compo.u.complex->num_recordSyntax = 0;
1585 compo.u.complex->recordSyntax = 0;
1587 else if (elementSetNames)
1589 req->recordComposition = &compo;
1590 compo.which = Z_RecordComp_simple;
1591 compo.u.simple = elementSetNames;
1594 printf("Sent presentRequest (%d+%d).\n", setno, nos);
1598 static void close_session (void)
1604 nmem_destroy (session_mem);
1610 void process_close(Z_Close *req)
1612 Z_APDU *apdu = zget_APDU(out, Z_APDU_close);
1613 Z_Close *res = apdu->u.close;
1615 static char *reasons[] =
1620 "cost limit reached",
1622 "security violation",
1629 printf("Reason: %s, message: %s\n", reasons[*req->closeReason],
1630 req->diagnosticInformation ? req->diagnosticInformation : "NULL");
1635 *res->closeReason = Z_Close_finished;
1637 printf("Sent response.\n");
1642 static int cmd_show(char *arg)
1646 printf("Not connected yet\n");
1649 if (!send_presentRequest(arg))
1654 int cmd_quit(char *arg)
1656 printf("See you later, alligator.\n");
1662 int cmd_cancel(char *arg)
1664 Z_APDU *apdu = zget_APDU(out, Z_APDU_triggerResourceControlRequest);
1665 Z_TriggerResourceControlRequest *req =
1666 apdu->u.triggerResourceControlRequest;
1671 printf("Session not initialized yet\n");
1674 if (!ODR_MASK_GET(session->options, Z_Options_triggerResourceCtrl))
1676 printf("Target doesn't support cancel (trigger resource ctrl)\n");
1679 *req->requestedAction = Z_TriggerResourceCtrl_cancel;
1680 req->resultSetWanted = &rfalse;
1683 printf("Sent cancel request\n");
1687 int send_scanrequest(const char *query, int pp, int num, const char *term)
1689 Z_APDU *apdu = zget_APDU(out, Z_APDU_scanRequest);
1690 Z_ScanRequest *req = apdu->u.scanRequest;
1695 if (queryType == QueryType_CCL2RPN)
1699 struct ccl_rpn_node *rpn;
1701 rpn = ccl_find_str (bibset, query, &error, &pos);
1704 printf("CCL ERROR: %s\n", ccl_err_msg(error));
1708 bib1.proto = PROTO_Z3950;
1709 bib1.oclass = CLASS_ATTSET;
1710 bib1.value = VAL_BIB1;
1711 req->attributeSet = oid_ent_to_oid (&bib1, oid);
1712 if (!(req->termListAndStartPoint = ccl_scan_query (out, rpn)))
1714 printf("Couldn't convert CCL to Scan term\n");
1717 ccl_rpn_delete (rpn);
1720 if (use_rpn && !(req->termListAndStartPoint =
1721 p_query_scan(out, protocol, &req->attributeSet, query)))
1723 printf("Prefix query error\n");
1728 if (req->termListAndStartPoint->term &&
1729 req->termListAndStartPoint->term->which == Z_Term_general &&
1730 req->termListAndStartPoint->term->u.general)
1732 req->termListAndStartPoint->term->u.general->buf =
1733 (unsigned char *) odr_strdup(out, term);
1734 req->termListAndStartPoint->term->u.general->len =
1735 req->termListAndStartPoint->term->u.general->size =
1739 req->referenceId = set_refid (out);
1740 req->num_databaseNames = num_databaseNames;
1741 req->databaseNames = databaseNames;
1742 req->numberOfTermsRequested = #
1743 req->preferredPositionInResponse = &pp;
1748 int send_sortrequest(char *arg, int newset)
1750 Z_APDU *apdu = zget_APDU(out, Z_APDU_sortRequest);
1751 Z_SortRequest *req = apdu->u.sortRequest;
1752 Z_SortKeySpecList *sksl = (Z_SortKeySpecList *)
1753 odr_malloc (out, sizeof(*sksl));
1757 sprintf (setstring, "%d", setnumber);
1759 sprintf (setstring, "default");
1761 req->referenceId = set_refid (out);
1763 req->num_inputResultSetNames = 1;
1764 req->inputResultSetNames = (Z_InternationalString **)
1765 odr_malloc (out, sizeof(*req->inputResultSetNames));
1766 req->inputResultSetNames[0] = odr_strdup (out, setstring);
1768 if (newset && setnumber >= 0)
1769 sprintf (setstring, "%d", ++setnumber);
1771 req->sortedResultSetName = odr_strdup (out, setstring);
1773 req->sortSequence = yaz_sort_spec (out, arg);
1774 if (!req->sortSequence)
1776 printf ("Missing sort specifications\n");
1783 void display_term(Z_TermInfo *t)
1785 if (t->term->which == Z_Term_general)
1787 printf("%.*s", t->term->u.general->len, t->term->u.general->buf);
1788 sprintf(last_scan_line, "%.*s", t->term->u.general->len,
1789 t->term->u.general->buf);
1792 printf("Term (not general)");
1793 if (t->globalOccurrences)
1794 printf (" (%d)\n", *t->globalOccurrences);
1799 void process_scanResponse(Z_ScanResponse *res)
1802 Z_Entry **entries = NULL;
1803 int num_entries = 0;
1805 printf("Received ScanResponse\n");
1806 print_refid (res->referenceId);
1807 printf("%d entries", *res->numberOfEntriesReturned);
1808 if (res->positionOfTerm)
1809 printf (", position=%d", *res->positionOfTerm);
1811 if (*res->scanStatus != Z_Scan_success)
1812 printf("Scan returned code %d\n", *res->scanStatus);
1815 if ((entries = res->entries->entries))
1816 num_entries = res->entries->num_entries;
1817 for (i = 0; i < num_entries; i++)
1819 int pos_term = res->positionOfTerm ? *res->positionOfTerm : -1;
1820 if (entries[i]->which == Z_Entry_termInfo)
1822 printf("%c ", i + 1 == pos_term ? '*' : ' ');
1823 display_term(entries[i]->u.termInfo);
1826 display_diagrecs(&entries[i]->u.surrogateDiagnostic, 1);
1828 if (res->entries->nonsurrogateDiagnostics)
1829 display_diagrecs (res->entries->nonsurrogateDiagnostics,
1830 res->entries->num_nonsurrogateDiagnostics);
1833 void process_sortResponse(Z_SortResponse *res)
1835 printf("Received SortResponse: status=");
1836 switch (*res->sortStatus)
1838 case Z_SortStatus_success:
1839 printf ("success"); break;
1840 case Z_SortStatus_partial_1:
1841 printf ("partial"); break;
1842 case Z_SortStatus_failure:
1843 printf ("failure"); break;
1845 printf ("unknown (%d)", *res->sortStatus);
1848 print_refid (res->referenceId);
1849 if (res->diagnostics)
1850 display_diagrecs(res->diagnostics,
1851 res->num_diagnostics);
1854 void process_deleteResultSetResponse (Z_DeleteResultSetResponse *res)
1856 printf("Got deleteResultSetResponse status=%d\n",
1857 *res->deleteOperationStatus);
1858 if (res->deleteListStatuses)
1861 for (i = 0; i < res->deleteListStatuses->num; i++)
1863 printf ("%s status=%d\n", res->deleteListStatuses->elements[i]->id,
1864 *res->deleteListStatuses->elements[i]->status);
1869 int cmd_sort_generic(char *arg, int newset)
1873 printf("Session not initialized yet\n");
1876 if (!ODR_MASK_GET(session->options, Z_Options_sort))
1878 printf("Target doesn't support sort\n");
1883 if (send_sortrequest(arg, newset) < 0)
1890 int cmd_sort(char *arg)
1892 return cmd_sort_generic (arg, 0);
1895 int cmd_sort_newset (char *arg)
1897 return cmd_sort_generic (arg, 1);
1900 int cmd_scan(char *arg)
1904 printf("Session not initialized yet\n");
1907 if (!ODR_MASK_GET(session->options, Z_Options_scan))
1909 printf("Target doesn't support scan\n");
1914 strcpy (last_scan_query, arg);
1915 if (send_scanrequest(arg, 1, 20, 0) < 0)
1920 if (send_scanrequest(last_scan_query, 1, 20, last_scan_line) < 0)
1926 int cmd_schema(char *arg)
1933 schema = oid_getvalbyname (arg);
1934 if (schema == VAL_NONE)
1936 printf ("unknown schema\n");
1942 int cmd_format(char *arg)
1946 printf("Usage: format <recordsyntax>\n");
1949 recordsyntax = oid_getvalbyname (arg);
1950 if (recordsyntax == VAL_NONE)
1952 printf ("unknown record syntax\n");
1958 int cmd_elements(char *arg)
1960 static Z_ElementSetNames esn;
1961 static char what[100];
1965 elementSetNames = 0;
1969 esn.which = Z_ElementSetNames_generic;
1970 esn.u.generic = what;
1971 elementSetNames = &esn;
1975 int cmd_attributeset(char *arg)
1981 printf("Usage: attributeset <setname>\n");
1984 sscanf(arg, "%s", what);
1985 if (p_query_attset (what))
1987 printf("Unknown attribute set name\n");
1993 int cmd_querytype (char *arg)
1995 if (!strcmp (arg, "ccl"))
1996 queryType = QueryType_CCL;
1997 else if (!strcmp (arg, "prefix") || !strcmp(arg, "rpn"))
1998 queryType = QueryType_Prefix;
2000 else if (!strcmp (arg, "ccl2rpn") || !strcmp (arg, "cclrpn"))
2001 queryType = QueryType_CCL2RPN;
2005 printf ("Querytype must be one of:\n");
2006 printf (" prefix - Prefix query\n");
2007 printf (" ccl - CCL query\n");
2009 printf (" ccl2rpn - CCL query converted to RPN\n");
2016 int cmd_refid (char *arg)
2022 refid = (char *) xmalloc (strlen(arg)+1);
2023 strcpy (refid, arg);
2028 int cmd_close(char *arg)
2035 apdu = zget_APDU(out, Z_APDU_close);
2036 req = apdu->u.close;
2037 *req->closeReason = Z_Close_finished;
2039 printf("Sent close request.\n");
2044 int cmd_packagename(char* arg)
2046 xfree (esPackageName);
2047 esPackageName = NULL;
2050 esPackageName = (char *) xmalloc (strlen(arg)+1);
2051 strcpy (esPackageName, arg);
2056 int cmd_proxy(char* arg)
2062 yazProxy = (char *) xmalloc (strlen(arg)+1);
2063 strcpy (yazProxy, arg);
2068 int cmd_source(char* arg)
2070 /* first should open the file and read one line at a time.. */
2072 char line[1024], *cp;
2075 char* args_end=(arg)+strlen(arg)-1;
2076 while(isspace(*args_end))
2081 REMOVE_TAILING_BLANKS(arg);
2084 fprintf(stderr,"Error in source command use a filename\n");
2088 includeFile = fopen (arg, "r");
2091 fprintf(stderr,"Unable to open file %s for reading\n",arg);
2095 while(!feof(includeFile)) {
2096 memset(line,0,sizeof(line));
2097 fgets(line,sizeof(line),includeFile);
2099 if(strlen(line) < 2) continue;
2100 if(line[0] == '#') continue;
2102 if ((cp = strrchr (line, '\n')))
2105 process_cmd_line(line);
2108 if(fclose(includeFile)<0) {
2109 perror("unable to close include file");
2115 int cmd_subshell(char* args)
2120 system(getenv("SHELL"));
2126 int cmd_set_apdufile(char* arg)
2128 REMOVE_TAILING_BLANKS(arg);
2130 if(apdu_file && apdu_file != stderr) { /* don't close stdout*/
2131 perror("unable to close apdu log file");
2139 if(!strcmp(arg,"-"))
2142 apdu_file=fopen(arg, "a");
2145 perror("unable to open apdu log file no apdu log loaded");
2147 odr_setprint(print, apdu_file);
2153 int cmd_set_cclfields(char* arg)
2158 REMOVE_TAILING_BLANKS(arg);
2160 bibset = ccl_qual_mk ();
2161 inf = fopen (arg, "r");
2164 ccl_qual_file (bibset, inf);
2168 fprintf(stderr,"Not compiled with the yaz ccl module\n");
2174 int cmd_set_marcdump(char* arg)
2176 if(marcdump && marcdump != stderr) { /* don't close stdout*/
2177 perror("unable to close apdu log file");
2185 if(!strcmp(arg,"-"))
2188 marcdump=fopen(arg, "a");
2191 perror("unable to open apdu marcdump file no marcdump done\n");
2197 int cmd_set_proxy(char* arg) {
2198 if(yazProxy) free(yazProxy);
2201 if(strlen(arg) > 1) {
2202 yazProxy=strdup(arg);
2208 this command takes 3 arge {name class oid}
2210 int cmd_register_oid(char* args) {
2215 {"appctx",CLASS_APPCTX},
2216 {"absyn",CLASS_ABSYN},
2217 {"attset",CLASS_ATTSET},
2218 {"transyn",CLASS_TRANSYN},
2219 {"diagset",CLASS_DIAGSET},
2220 {"recsyn",CLASS_RECSYN},
2221 {"resform",CLASS_RESFORM},
2222 {"accform",CLASS_ACCFORM},
2223 {"extserv",CLASS_EXTSERV},
2224 {"userinfo",CLASS_USERINFO},
2225 {"elemspec",CLASS_ELEMSPEC},
2226 {"varset",CLASS_VARSET},
2227 {"schema",CLASS_SCHEMA},
2228 {"tagset",CLASS_TAGSET},
2229 {"general",CLASS_GENERAL},
2232 char oname_str[101], oclass_str[101], oid_str[101];
2235 oid_class oidclass = CLASS_GENERAL;
2236 int val = 0, oid[OID_SIZE];
2237 struct oident * new_oident=NULL;
2239 if (sscanf (args, "%100[^ ] %100[^ ] %100s",
2240 oname_str,oclass_str, oid_str) < 1) {
2241 printf("Error in regristrate command \n");
2245 for (i = 0; oid_classes[i].className; i++) {
2246 if (!strcmp(oid_classes[i].className, oclass_str))
2248 oidclass=oid_classes[i].oclass;
2253 if(!(oid_classes[i].className)) {
2254 printf("Unknonwn oid class %s\n",oclass_str);
2262 while (isdigit (*name))
2264 val = val*10 + (*name - '0');
2277 new_oident=oid_addent (oid,PROTO_GENERAL,oidclass,oname_str,VAL_DYNAMIC);
2278 if(strcmp(new_oident->desc,oname_str)) {
2279 fprintf(stderr,"oid is already named as %s, regristration faild\n",
2285 int cmd_push_command(char* arg) {
2286 #if HAVE_READLINE_HISTORY_H
2290 fprintf(stderr,"Not compiled with the readline/history module\n");
2295 void source_rcfile() {
2296 /* Look for a $HOME/.yazclientrc and source it if it exists */
2297 struct stat statbuf;
2299 char* homedir=getenv("HOME");
2300 if(!homedir) return;
2302 sprintf(buffer,"%s/.yazclientrc",homedir);
2304 if(stat(buffer,&statbuf)==0) {
2308 if(stat(".yazclientrc",&statbuf)==0) {
2309 cmd_source(".yazclientrc");
2314 static void initialize(void)
2319 if (!(out = odr_createmem(ODR_ENCODE)) ||
2320 !(in = odr_createmem(ODR_DECODE)) ||
2321 !(print = odr_createmem(ODR_PRINT)))
2323 fprintf(stderr, "failed to allocate ODR streams\n");
2328 setvbuf(stdout, 0, _IONBF, 0);
2330 odr_setprint(print, apdu_file);
2333 bibset = ccl_qual_mk ();
2334 inf = fopen (ccl_fields, "r");
2337 ccl_qual_file (bibset, inf);
2341 cmd_base("Default");
2343 #if HAVE_READLINE_READLINE_H
2344 rl_attempted_completion_function = (CPPFunction*)readline_completer;
2351 #if HAVE_GETTIMEOFDAY
2352 struct timeval tv_start, tv_end;
2355 void wait_and_handle_responce()
2360 int netbufferlen = 0;
2368 if ((res = cs_get(conn, &netbuffer, &netbufferlen)) < 0)
2370 printf("Target closed connection\n");
2376 printf("Target closed connection.\n");
2380 odr_reset(in); /* release APDU from last round */
2382 odr_setbuf(in, netbuffer, res, 0);
2383 if (!z_APDU(in, &apdu, 0, 0))
2385 odr_perror(in, "Decoding incoming APDU");
2386 fprintf(stderr, "[Near %d]\n", odr_offset(in));
2387 fprintf(stderr, "Packet dump:\n---------\n");
2388 odr_dumpBER(stderr, netbuffer, res);
2389 fprintf(stderr, "---------\n");
2391 z_APDU(print, &apdu, 0, 0);
2395 if (apdu_file && !z_APDU(print, &apdu, 0, 0))
2397 odr_perror(print, "Failed to print incoming APDU");
2403 case Z_APDU_initResponse:
2404 process_initResponse(apdu->u.initResponse);
2406 case Z_APDU_searchResponse:
2407 process_searchResponse(apdu->u.searchResponse);
2409 case Z_APDU_scanResponse:
2410 process_scanResponse(apdu->u.scanResponse);
2412 case Z_APDU_presentResponse:
2413 print_refid (apdu->u.presentResponse->referenceId);
2415 *apdu->u.presentResponse->numberOfRecordsReturned;
2416 if (apdu->u.presentResponse->records)
2417 display_records(apdu->u.presentResponse->records);
2419 printf("No records.\n");
2420 printf ("nextResultSetPosition = %d\n",
2421 *apdu->u.presentResponse->nextResultSetPosition);
2423 case Z_APDU_sortResponse:
2424 process_sortResponse(apdu->u.sortResponse);
2426 case Z_APDU_extendedServicesResponse:
2427 printf("Got extended services response\n");
2428 process_ESResponse(apdu->u.extendedServicesResponse);
2431 printf("Target has closed the association.\n");
2432 process_close(apdu->u.close);
2434 case Z_APDU_resourceControlRequest:
2435 process_resourceControlRequest
2436 (apdu->u.resourceControlRequest);
2438 case Z_APDU_deleteResultSetResponse:
2439 process_deleteResultSetResponse(apdu->u.
2440 deleteResultSetResponse);
2443 printf("Received unknown APDU type (%d).\n",
2448 while (conn && cs_more(conn));
2449 #if HAVE_GETTIMEOFDAY
2450 gettimeofday (&tv_end, 0);
2452 printf ("S/U S/U=%ld/%ld %ld/%ld",
2453 (long) tv_start.tv_sec,
2454 (long) tv_start.tv_usec,
2455 (long) tv_end.tv_sec,
2456 (long) tv_end.tv_usec);
2458 printf ("Elapsed: %.6f\n",
2459 (double) tv_end.tv_usec / 1e6 + tv_end.tv_sec -
2460 ((double) tv_start.tv_usec / 1e6 + tv_start.tv_sec));
2467 static int cmd_help (char *line);
2471 int (*fun)(char *arg);
2473 char *(*rl_completerfunction)(const char *text, int state);
2474 int complete_filenames;
2476 {"open", cmd_open, "('tcp'|'ssl')':<host>[':'<port>][/<db>]",NULL,0},
2477 {"quit", cmd_quit, "",NULL,0},
2478 {"find", cmd_find, "<query>",NULL,0},
2479 {"delete", cmd_delete, "<setname>",NULL,0},
2480 {"base", cmd_base, "<base-name>",NULL,0},
2481 {"show", cmd_show, "<rec#>['+'<#recs>['+'<setname>]]",NULL,0},
2482 {"scan", cmd_scan, "<term>",NULL,0},
2483 {"sort", cmd_sort, "<sortkey> <flag> <sortkey> <flag> ...",NULL,0},
2484 {"sort+", cmd_sort_newset, "<sortkey> <flag> <sortkey> <flag> ...",NULL,0},
2485 {"authentication", cmd_authentication, "<acctstring>",NULL,0},
2486 {"lslb", cmd_lslb, "<largeSetLowerBound>",NULL,0},
2487 {"ssub", cmd_ssub, "<smallSetUpperBound>",NULL,0},
2488 {"mspn", cmd_mspn, "<mediumSetPresentNumber>",NULL,0},
2489 {"status", cmd_status, "",NULL,0},
2490 {"setnames", cmd_setnames, "",NULL,0},
2491 {"cancel", cmd_cancel, "",NULL,0},
2492 {"format", cmd_format, "<recordsyntax>",complete_format,0},
2493 {"schema", cmd_schema, "<schema>",complete_schema,0},
2494 {"elements", cmd_elements, "<elementSetName>",NULL,0},
2495 {"close", cmd_close, "",NULL,0},
2496 {"attributeset", cmd_attributeset, "<attrset>",complete_attributeset,0},
2497 {"querytype", cmd_querytype, "<type>",complete_querytype,0},
2498 {"refid", cmd_refid, "<id>",NULL,0},
2499 {"itemorder", cmd_itemorder, "ill|item <itemno>",NULL,0},
2500 {"update", cmd_update, "<item>",NULL,0},
2501 {"packagename", cmd_packagename, "<packagename>",NULL,0},
2502 {"proxy", cmd_proxy, "[('tcp'|'ssl')]<host>[':'<port>]",NULL,0},
2503 {".", cmd_source, "<filename>",NULL,1},
2504 {"!", cmd_subshell, "Subshell command",NULL,0},
2505 {"set_apdufile", cmd_set_apdufile, "<filename>",NULL,0},
2506 {"set_marcdump", cmd_set_marcdump," <filename>",NULL,0},
2507 {"set_cclfields", cmd_set_cclfields,"<filename>",NULL,1},
2508 {"register_oid",cmd_register_oid,"<name> <class> <oid>",NULL,0},
2509 {"push_command",cmd_push_command,"<command>",command_generator,0},
2510 /* Server Admin Functions */
2511 {"adm-reindex", cmd_adm_reindex, "<database-name>",NULL,0},
2512 {"adm-truncate", cmd_adm_truncate, "('database'|'index')<object-name>",NULL,0},
2513 {"adm-create", cmd_adm_create, "",NULL,0},
2514 {"adm-drop", cmd_adm_drop, "('database'|'index')<object-name>",NULL,0},
2515 {"adm-import", cmd_adm_import, "<record-type> <dir> <pattern>",NULL,0},
2516 {"adm-refresh", cmd_adm_refresh, "",NULL,0},
2517 {"adm-commit", cmd_adm_commit, "",NULL,0},
2518 {"adm-shutdown", cmd_adm_shutdown, "",NULL,0},
2519 {"adm-startup", cmd_adm_startup, "",NULL,0},
2520 {"help", cmd_help, "", NULL},
2524 static int cmd_help (char *line)
2530 sscanf (line, "%20s", topic);
2533 printf("Commands:\n");
2534 for (i = 0; cmd[i].cmd; i++)
2535 if (*topic == 0 || strcmp (topic, cmd[i].cmd) == 0)
2536 printf(" %s %s\n", cmd[i].cmd, cmd[i].ad);
2537 if (strcmp (topic, "find") == 0)
2540 printf (" \"term\" Simple Term\n");
2541 printf (" @attr [attset] type=value op Attribute\n");
2542 printf (" @and opl opr And\n");
2543 printf (" @or opl opr Or\n");
2544 printf (" @not opl opr And-Not\n");
2545 printf (" @set set Result set\n");
2547 printf ("Bib-1 attribute types\n");
2549 printf ("4=Title 7=ISBN 8=ISSN 30=Date 62=Abstract 1003=Author 1016=Any\n");
2550 printf ("2=Relation: ");
2551 printf ("1< 2<= 3= 4>= 5> 6!= 102=Relevance\n");
2552 printf ("3=Position: ");
2553 printf ("1=First in Field 2=First in subfield 3=Any position\n");
2554 printf ("4=Structure: ");
2555 printf ("1=Phrase 2=Word 3=Key 4=Year 5=Date 6=WordList\n");
2556 printf ("5=Truncation: ");
2557 printf ("1=Right 2=Left 3=L&R 100=No 101=# 102=Re-1 103=Re-2\n");
2558 printf ("6=Completeness:");
2559 printf ("1=Incomplete subfield 2=Complete subfield 3=Complete field\n");
2564 void process_cmd_line(char* line)
2567 char word[32], arg[1024];
2569 #if HAVE_GETTIMEOFDAY
2570 gettimeofday (&tv_start, 0);
2573 if ((res = sscanf(line, "%31s %1023[^;]", word, arg)) <= 0)
2575 strcpy(word, last_cmd);
2580 strcpy(last_cmd, word);
2582 /* removed tailing spaces from the arg command */
2585 char* lastnonspace=NULL;
2594 *(++lastnonspace) = 0;
2598 for (i = 0; cmd[i].cmd; i++)
2599 if (!strncmp(cmd[i].cmd, word, strlen(word)))
2601 res = (*cmd[i].fun)(arg);
2605 if (!cmd[i].cmd) /* dump our help-screen */
2607 printf("Unknown command: %s.\n", word);
2612 if(apdu_file) fflush(apdu_file);
2615 wait_and_handle_responce();
2624 char *command_generator(const char *text, int state)
2630 for( ; cmd[idx].cmd; ++idx) {
2631 if (!strncmp(cmd[idx].cmd,text,strlen(text))) {
2632 ++idx; /* skip this entry on the next run */
2633 return strdup(cmd[idx-1].cmd);
2641 This function only known how to complete on the first word
2643 char ** readline_completer(char *text, int start, int end) {
2644 #if HAVE_READLINE_READLINE_H
2647 #ifdef RL_READLINE_VERSION
2648 char** res=rl_completion_matches(text,
2651 char** res=completion_matches(text,
2652 (CPFunction*)command_generator);
2654 rl_attempted_completion_over = 1;
2657 char arg[1024],word[32];
2659 if ((res = sscanf(rl_line_buffer, "%31s %1023[^;]", word, arg)) <= 0) {
2660 rl_attempted_completion_over = 1;
2664 if(start != strlen(word) +1 ) {
2665 rl_attempted_completion_over = 1;
2668 for (i = 0; cmd[i].cmd; i++) {
2669 if (!strncmp(cmd[i].cmd, word, strlen(word))) {
2675 if(!cmd[i].complete_filenames)
2676 rl_attempted_completion_over = 1;
2677 if(cmd[i].rl_completerfunction) {
2678 #ifdef RL_READLINE_VERSION
2680 rl_completion_matches(text,
2681 cmd[i].rl_completerfunction);
2684 completion_matches(text,
2685 (CPFunction*)cmd[i].rl_completerfunction);
2687 rl_attempted_completion_over = 1;
2690 rl_attempted_completion_over = 1;
2700 static void client(void)
2706 #if HAVE_GETTIMEOFDAY
2707 gettimeofday (&tv_start, 0);
2712 char *line_in = NULL;
2713 #if HAVE_READLINE_READLINE_H
2716 line_in=readline(C_PROMPT);
2719 #if HAVE_READLINE_HISTORY_H
2721 add_history(line_in);
2723 strncpy(line, line_in, 1023);
2732 if (!fgets(line, 1023, stdin))
2734 if ((end_p = strchr (line, '\n')))
2737 process_cmd_line(line);
2741 int main(int argc, char **argv)
2744 char *open_command = 0;
2745 char *auth_command = 0;
2749 while ((ret = options("k:c:a:m:v:p:u:", argv, argc, &arg)) != -2)
2756 open_command = (char *) xmalloc (strlen(arg)+6);
2757 strcpy (open_command, "open ");
2758 strcat (open_command, arg);
2762 kilobytes = atoi(arg);
2765 if (!(marcdump = fopen (arg, "a")))
2772 strncpy (ccl_fields, arg, sizeof(ccl_fields)-1);
2773 ccl_fields[sizeof(ccl_fields)-1] = '\0';
2776 if (!strcmp(arg, "-"))
2779 apdu_file=fopen(arg, "a");
2782 yazProxy=strdup(arg);
2787 auth_command = (char *) xmalloc (strlen(arg)+6);
2788 strcpy (auth_command, "auth ");
2789 strcat (auth_command, arg);
2793 yaz_log_init (yaz_log_mask_str(arg), "", NULL);
2796 fprintf (stderr, "Usage: %s [-m <marclog>] [ -a <apdulog>] "
2797 "[-c cclfields]\n [-p <proxy-addr>] [-u <auth>] "
2798 "[-k size] [<server-addr>]\n",
2806 #ifdef HAVE_GETTIMEOFDAY
2807 gettimeofday (&tv_start, 0);
2809 process_cmd_line (auth_command);
2810 #if HAVE_READLINE_HISTORY_H
2811 add_history(auth_command);
2813 xfree(auth_command);
2817 #ifdef HAVE_GETTIMEOFDAY
2818 gettimeofday (&tv_start, 0);
2820 process_cmd_line (open_command);
2821 #if HAVE_READLINE_HISTORY_H
2822 add_history(open_command);
2824 xfree(open_command);