2 * Copyright (c) 1995-2002, Index Data
3 * See the file LICENSE for details.
5 * $Id: client.c,v 1.142 2002-02-12 21:12:39 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 */
93 /* set this one to 1, to avoid decode of unknown MARCs */
94 #define AVOID_MARC_DECODE 1
96 /* nice helper macro as extensive tabbing gives spaces at the en of the args lines */
97 #define REMOVE_TAILING_BLANKS(a) {\
98 char* args_end=(a)+strlen(a)-1; \
99 while(isspace(*args_end)) {*args_end=0;--args_end;}; \
103 void process_cmd_line(char* line);
104 char ** readline_completer(char *text, int start, int end);
105 char *command_generator(const char *text, int state);
108 ODR getODROutputStream()
113 void send_apdu(Z_APDU *a)
120 z_APDU(print, &a, 0, 0);
123 if (!z_APDU(out, &a, 0, 0))
125 odr_perror(out, "Encoding APDU");
128 buf = odr_getbuf(out, &len, 0);
129 /* printf ("sending APDU of size %d\n", len); */
130 if (cs_put(conn, buf, len) < 0)
132 fprintf(stderr, "cs_put: %s", cs_errmsg(cs_errno(conn)));
135 odr_reset(out); /* release the APDU structure */
138 static void print_stringn(const unsigned char *buf, size_t len)
141 for (i = 0; i<len; i++)
142 if ((buf[i] <= 126 && buf[i] >= 32) || strchr ("\n\r\t\f", buf[i]))
143 fputc (buf[i], stdout);
145 printf ("\\X%02X", buf[i]);
148 static void print_refid (Z_ReferenceId *id)
152 printf ("Reference Id: ");
153 print_stringn (id->buf, id->len);
158 static Z_ReferenceId *set_refid (ODR out)
163 id = (Z_ReferenceId *) odr_malloc (out, sizeof(*id));
164 id->size = id->len = strlen(refid);
165 id->buf = (unsigned char *) odr_malloc (out, id->len);
166 memcpy (id->buf, refid, id->len);
170 /* INIT SERVICE ------------------------------- */
172 static void send_initRequest(const char* type_and_host)
174 Z_APDU *apdu = zget_APDU(out, Z_APDU_initRequest);
175 Z_InitRequest *req = apdu->u.initRequest;
177 ODR_MASK_SET(req->options, Z_Options_search);
178 ODR_MASK_SET(req->options, Z_Options_present);
179 ODR_MASK_SET(req->options, Z_Options_namedResultSets);
180 ODR_MASK_SET(req->options, Z_Options_triggerResourceCtrl);
181 ODR_MASK_SET(req->options, Z_Options_scan);
182 ODR_MASK_SET(req->options, Z_Options_sort);
183 ODR_MASK_SET(req->options, Z_Options_extendedServices);
184 ODR_MASK_SET(req->options, Z_Options_delSet);
186 ODR_MASK_SET(req->protocolVersion, Z_ProtocolVersion_1);
187 ODR_MASK_SET(req->protocolVersion, Z_ProtocolVersion_2);
188 ODR_MASK_SET(req->protocolVersion, Z_ProtocolVersion_3);
190 *req->maximumRecordSize = 1024*kilobytes;
191 *req->preferredMessageSize = 1024*kilobytes;
193 req->idAuthentication = auth;
195 req->referenceId = set_refid (out);
198 yaz_oi_set_string_oidval(&req->otherInfo, out, VAL_PROXY,
202 printf("Sent initrequest.\n");
205 static int process_initResponse(Z_InitResponse *res)
207 /* save session parameters for later use */
208 session_mem = odr_extract_mem(in);
212 printf("Connection rejected by target.\n");
214 printf("Connection accepted by target.\n");
215 if (res->implementationId)
216 printf("ID : %s\n", res->implementationId);
217 if (res->implementationName)
218 printf("Name : %s\n", res->implementationName);
219 if (res->implementationVersion)
220 printf("Version: %s\n", res->implementationVersion);
221 if (res->userInformationField)
223 printf("UserInformationfield:\n");
224 if (!z_External(print, (Z_External**)&res-> userInformationField,
227 odr_perror(print, "Printing userinfo\n");
230 if (res->userInformationField->which == Z_External_octet)
232 printf("Guessing visiblestring:\n");
233 printf("'%s'\n", res->userInformationField->u. octet_aligned->buf);
238 if (ODR_MASK_GET(res->options, Z_Options_search))
240 if (ODR_MASK_GET(res->options, Z_Options_present))
242 if (ODR_MASK_GET(res->options, Z_Options_delSet))
244 if (ODR_MASK_GET(res->options, Z_Options_resourceReport))
245 printf (" resourceReport");
246 if (ODR_MASK_GET(res->options, Z_Options_resourceCtrl))
247 printf (" resourceCtrl");
248 if (ODR_MASK_GET(res->options, Z_Options_accessCtrl))
249 printf (" accessCtrl");
250 if (ODR_MASK_GET(res->options, Z_Options_scan))
252 if (ODR_MASK_GET(res->options, Z_Options_sort))
254 if (ODR_MASK_GET(res->options, Z_Options_extendedServices))
255 printf (" extendedServices");
256 if (ODR_MASK_GET(res->options, Z_Options_level_1Segmentation))
257 printf (" level1Segmentation");
258 if (ODR_MASK_GET(res->options, Z_Options_level_2Segmentation))
259 printf (" level2Segmentation");
260 if (ODR_MASK_GET(res->options, Z_Options_concurrentOperations))
261 printf (" concurrentOperations");
262 if (ODR_MASK_GET(res->options, Z_Options_namedResultSets))
264 printf (" namedResultSets");
267 if (ODR_MASK_GET(res->options, Z_Options_encapsulation))
268 printf (" encapsulation");
269 if (ODR_MASK_GET(res->options, Z_Options_resultCount))
270 printf (" resultCount");
271 if (ODR_MASK_GET(res->options, Z_Options_negotiationModel))
272 printf (" negotiationModel");
273 if (ODR_MASK_GET(res->options, Z_Options_duplicateDetection))
274 printf (" duplicateDetection");
275 if (ODR_MASK_GET(res->options, Z_Options_queryType104))
276 printf (" queryType104");
282 static int cmd_base(char *arg)
289 printf("Usage: base <database> <database> ...\n");
292 for (i = 0; i<num_databaseNames; i++)
293 xfree (databaseNames[i]);
294 num_databaseNames = 0;
297 if (!(cp = strchr(arg, ' ')))
298 cp = arg + strlen(arg);
301 databaseNames[num_databaseNames] = (char *)xmalloc (1 + cp - arg);
302 memcpy (databaseNames[num_databaseNames], arg, cp - arg);
303 databaseNames[num_databaseNames++][cp - arg] = '\0';
312 int cmd_open(char *arg)
315 char type_and_host[101], base[101];
320 printf("Already connected.\n");
326 nmem_destroy (session_mem);
332 if (sscanf (arg, "%100[^/]/%100s", type_and_host, base) < 1)
336 conn = cs_create_host(yazProxy, 1, &add);
338 conn = cs_create_host(type_and_host, 1, &add);
342 printf ("Couldn't create comstack\n");
345 printf("Connecting...");
347 if (cs_connect(conn, add) < 0)
349 printf ("error = %s\n", cs_strerror(conn));
350 if (conn->cerrno == CSYSERR)
358 send_initRequest(type_and_host);
364 int cmd_authentication(char *arg)
366 static Z_IdAuthentication au;
367 static char user[40], group[40], pass[40];
368 static Z_IdPass idPass;
373 printf("Auth field set to null\n");
377 r = sscanf (arg, "%39s %39s %39s", user, group, pass);
380 printf("Auth field set to null\n");
386 au.which = Z_IdAuthentication_open;
392 au.which = Z_IdAuthentication_idPass;
393 au.u.idPass = &idPass;
394 idPass.groupId = group;
395 idPass.userId = user;
396 idPass.password = pass;
401 /* SEARCH SERVICE ------------------------------ */
403 static void display_variant(Z_Variant *v, int level)
407 for (i = 0; i < v->num_triples; i++)
409 printf("%*sclass=%d,type=%d", level * 4, "", *v->triples[i]->zclass,
410 *v->triples[i]->type);
411 if (v->triples[i]->which == Z_Triple_internationalString)
412 printf(",value=%s\n", v->triples[i]->value.internationalString);
418 static void display_grs1(Z_GenericRecord *r, int level)
424 for (i = 0; i < r->num_elements; i++)
428 printf("%*s", level * 4, "");
432 printf("%d,", *t->tagType);
435 if (t->tagValue->which == Z_StringOrNumeric_numeric)
436 printf("%d) ", *t->tagValue->u.numeric);
438 printf("%s) ", t->tagValue->u.string);
439 if (t->content->which == Z_ElementData_subtree)
442 display_grs1(t->content->u.subtree, level+1);
444 else if (t->content->which == Z_ElementData_string)
445 printf("%s\n", t->content->u.string);
446 else if (t->content->which == Z_ElementData_numeric)
447 printf("%d\n", *t->content->u.numeric);
448 else if (t->content->which == Z_ElementData_oid)
450 int *ip = t->content->u.oid;
453 if ((oent = oid_getentbyoid(t->content->u.oid)))
454 printf("OID: %s\n", oent->desc);
458 while (ip && *ip >= 0)
459 printf(" %d", *(ip++));
463 else if (t->content->which == Z_ElementData_noDataRequested)
464 printf("[No data requested]\n");
465 else if (t->content->which == Z_ElementData_elementEmpty)
466 printf("[Element empty]\n");
467 else if (t->content->which == Z_ElementData_elementNotThere)
468 printf("[Element not there]\n");
471 if (t->appliedVariant)
472 display_variant(t->appliedVariant, level+1);
473 if (t->metaData && t->metaData->supportedVariants)
477 printf("%*s---- variant list\n", (level+1)*4, "");
478 for (c = 0; c < t->metaData->num_supportedVariants; c++)
480 printf("%*svariant #%d\n", (level+1)*4, "", c);
481 display_variant(t->metaData->supportedVariants[c], level + 2);
488 static void print_record(const unsigned char *buf, size_t len)
491 print_stringn (buf, len);
492 /* add newline if not already added ... */
493 if (i <= 0 || buf[i-1] != '\n')
494 fputc ('\n', stdout);
497 static void display_record(Z_External *r)
499 oident *ent = oid_getentbyoid(r->direct_reference);
503 * Tell the user what we got.
505 if (r->direct_reference)
507 printf("Record type: ");
509 printf("%s\n", ent->desc);
510 else if (!odr_oid(print, &r->direct_reference, 0, 0))
512 odr_perror(print, "print oid");
516 /* Check if this is a known, ASN.1 type tucked away in an octet string */
517 if (ent && r->which == Z_External_octet)
519 Z_ext_typeent *type = z_ext_getentbyref(ent->value);
525 * Call the given decoder to process the record.
527 odr_setbuf(in, (char*)r->u.octet_aligned->buf,
528 r->u.octet_aligned->len, 0);
529 if (!(*type->fun)(in, (char **)&rr, 0, 0))
531 odr_perror(in, "Decoding constructed record.");
532 fprintf(stderr, "[Near %d]\n", odr_offset(in));
533 fprintf(stderr, "Packet dump:\n---------\n");
534 odr_dumpBER(stderr, (char*)r->u.octet_aligned->buf,
535 r->u.octet_aligned->len);
536 fprintf(stderr, "---------\n");
540 * Note: we throw away the original, BER-encoded record here.
541 * Do something else with it if you want to keep it.
543 r->u.sutrs = (Z_SUTRS *) rr; /* we don't actually check the type here. */
544 r->which = type->what;
547 if (ent && ent->value == VAL_SOIF)
548 print_record((const unsigned char *) r->u.octet_aligned->buf,
549 r->u.octet_aligned->len);
550 else if (r->which == Z_External_octet && r->u.octet_aligned->len)
552 const char *octet_buf = (char*)r->u.octet_aligned->buf;
553 if (ent->value == VAL_TEXT_XML || ent->value == VAL_APPLICATION_XML ||
554 ent->value == VAL_HTML)
556 print_record((const unsigned char *) octet_buf,
557 r->u.octet_aligned->len);
559 else if (ent->value == VAL_POSTSCRIPT)
561 int size = r->u.octet_aligned->len;
564 print_record((const unsigned char *) octet_buf, size);
569 #if AVOID_MARC_DECODE
570 /* primitive check for a marc OID 5.1-29 */
571 ent->oidsuffix[0] == 5 && ent->oidsuffix[1] < 30
577 if (marc_display_exl (octet_buf, NULL, 0 /* debug */,
578 r->u.octet_aligned->len) <= 0)
580 printf ("bad MARC. Dumping as it is:\n");
581 print_record((const unsigned char*) octet_buf,
582 r->u.octet_aligned->len);
587 print_record((const unsigned char*) octet_buf,
588 r->u.octet_aligned->len);
592 fwrite (octet_buf, 1, r->u.octet_aligned->len, marcdump);
594 else if (ent && ent->value == VAL_SUTRS)
596 if (r->which != Z_External_sutrs)
598 printf("Expecting single SUTRS type for SUTRS.\n");
601 print_record(r->u.sutrs->buf, r->u.sutrs->len);
603 else if (ent && ent->value == VAL_GRS1)
605 if (r->which != Z_External_grs1)
607 printf("Expecting single GRS type for GRS.\n");
610 display_grs1(r->u.grs1, 0);
614 printf("Unknown record representation.\n");
615 if (!z_External(print, &r, 0, 0))
617 odr_perror(print, "Printing external");
624 static void display_diagrecs(Z_DiagRec **pp, int num)
628 Z_DefaultDiagFormat *r;
630 printf("Diagnostic message(s) from database:\n");
631 for (i = 0; i<num; i++)
633 Z_DiagRec *p = pp[i];
634 if (p->which != Z_DiagRec_defaultFormat)
636 printf("Diagnostic record not in default format.\n");
640 r = p->u.defaultFormat;
641 if (!(ent = oid_getentbyoid(r->diagnosticSetId)) ||
642 ent->oclass != CLASS_DIAGSET || ent->value != VAL_BIB1)
643 printf("Missing or unknown diagset\n");
644 printf(" [%d] %s", *r->condition, diagbib1_str(*r->condition));
647 case Z_DefaultDiagFormat_v2Addinfo:
648 printf (" -- v2 addinfo '%s'\n", r->u.v2Addinfo);
650 case Z_DefaultDiagFormat_v3Addinfo:
651 printf (" -- v3 addinfo '%s'\n", r->u.v3Addinfo);
658 static void display_nameplusrecord(Z_NamePlusRecord *p)
661 printf("[%s]", p->databaseName);
662 if (p->which == Z_NamePlusRecord_surrogateDiagnostic)
663 display_diagrecs(&p->u.surrogateDiagnostic, 1);
664 else if (p->which == Z_NamePlusRecord_databaseRecord)
665 display_record(p->u.databaseRecord);
668 static void display_records(Z_Records *p)
672 if (p->which == Z_Records_NSD)
674 Z_DiagRec dr, *dr_p = &dr;
675 dr.which = Z_DiagRec_defaultFormat;
676 dr.u.defaultFormat = p->u.nonSurrogateDiagnostic;
677 display_diagrecs (&dr_p, 1);
679 else if (p->which == Z_Records_multipleNSD)
680 display_diagrecs (p->u.multipleNonSurDiagnostics->diagRecs,
681 p->u.multipleNonSurDiagnostics->num_diagRecs);
684 printf("Records: %d\n", p->u.databaseOrSurDiagnostics->num_records);
685 for (i = 0; i < p->u.databaseOrSurDiagnostics->num_records; i++)
686 display_nameplusrecord(p->u.databaseOrSurDiagnostics->records[i]);
690 static int send_deleteResultSetRequest(char *arg)
695 Z_APDU *apdu = zget_APDU(out, Z_APDU_deleteResultSetRequest);
696 Z_DeleteResultSetRequest *req = apdu->u.deleteResultSetRequest;
698 req->referenceId = set_refid (out);
700 req->num_resultSetList =
701 sscanf (arg, "%30s %30s %30s %30s %30s %30s %30s %30s",
702 names[0], names[1], names[2], names[3],
703 names[4], names[5], names[6], names[7]);
705 req->deleteFunction = (int *)
706 odr_malloc (out, sizeof(*req->deleteFunction));
707 if (req->num_resultSetList > 0)
709 *req->deleteFunction = Z_DeleteRequest_list;
710 req->resultSetList = (char **)
711 odr_malloc (out, sizeof(*req->resultSetList)*
712 req->num_resultSetList);
713 for (i = 0; i<req->num_resultSetList; i++)
714 req->resultSetList[i] = names[i];
718 *req->deleteFunction = Z_DeleteRequest_all;
719 req->resultSetList = 0;
723 printf("Sent deleteResultSetRequest.\n");
727 static int send_searchRequest(char *arg)
729 Z_APDU *apdu = zget_APDU(out, Z_APDU_searchRequest);
730 Z_SearchRequest *req = apdu->u.searchRequest;
734 struct ccl_rpn_node *rpn = NULL;
738 Z_RPNQuery *RPNquery;
742 if (queryType == QueryType_CCL2RPN)
744 rpn = ccl_find_str(bibset, arg, &error, &pos);
747 printf("CCL ERROR: %s\n", ccl_err_msg(error));
752 req->referenceId = set_refid (out);
753 if (!strcmp(arg, "@big")) /* strictly for troublemaking */
755 static unsigned char big[2100];
758 /* send a very big referenceid to test transport stack etc. */
759 memset(big, 'A', 2100);
760 bigo.len = bigo.size = 2100;
762 req->referenceId = &bigo;
767 sprintf(setstring, "%d", ++setnumber);
768 req->resultSetName = setstring;
770 *req->smallSetUpperBound = smallSetUpperBound;
771 *req->largeSetLowerBound = largeSetLowerBound;
772 *req->mediumSetPresentNumber = mediumSetPresentNumber;
773 if (smallSetUpperBound > 0 || (largeSetLowerBound > 1 &&
774 mediumSetPresentNumber > 0))
778 prefsyn.proto = protocol;
779 prefsyn.oclass = CLASS_RECSYN;
780 prefsyn.value = recordsyntax;
781 req->preferredRecordSyntax =
782 odr_oiddup(out, oid_ent_to_oid(&prefsyn, oid));
783 req->smallSetElementSetNames =
784 req->mediumSetElementSetNames = elementSetNames;
786 req->num_databaseNames = num_databaseNames;
787 req->databaseNames = databaseNames;
793 case QueryType_Prefix:
794 query.which = Z_Query_type_1;
795 RPNquery = p_query_rpn (out, protocol, arg);
798 printf("Prefix query error\n");
801 query.u.type_1 = RPNquery;
804 query.which = Z_Query_type_2;
805 query.u.type_2 = &ccl_query;
806 ccl_query.buf = (unsigned char*) arg;
807 ccl_query.len = strlen(arg);
810 case QueryType_CCL2RPN:
811 query.which = Z_Query_type_1;
812 RPNquery = ccl_rpn_query(out, rpn);
815 printf ("Couldn't convert from CCL to RPN\n");
818 query.u.type_1 = RPNquery;
819 ccl_rpn_delete (rpn);
823 printf ("Unsupported query type\n");
828 printf("Sent searchRequest.\n");
832 static int process_searchResponse(Z_SearchResponse *res)
834 printf ("Received SearchResponse.\n");
835 print_refid (res->referenceId);
836 if (*res->searchStatus)
837 printf("Search was a success.\n");
839 printf("Search was a bloomin' failure.\n");
840 printf("Number of hits: %d", *res->resultCount);
842 printf (", setno %d", setnumber);
843 printf("\nrecords returned: %d\n",
844 *res->numberOfRecordsReturned);
845 setno += *res->numberOfRecordsReturned;
847 display_records(res->records);
851 static void print_level(int iLevel)
854 for (i = 0; i < iLevel * 4; i++)
858 static void print_int(int iLevel, const char *pTag, int *pInt)
863 printf("%s: %d\n", pTag, *pInt);
867 static void print_string(int iLevel, const char *pTag, const char *pString)
872 printf("%s: %s\n", pTag, pString);
876 static void print_oid(int iLevel, const char *pTag, Odr_oid *pOid)
884 for (; *pInt != -1; pInt++)
885 printf(" %d", *pInt);
890 static void print_referenceId(int iLevel, Z_ReferenceId *referenceId)
892 if (referenceId != NULL)
897 printf("Ref Id (%d, %d): ", referenceId->len, referenceId->size);
898 for (i = 0; i < referenceId->len; i++)
899 printf("%c", referenceId->buf[i]);
904 static void print_string_or_numeric(int iLevel, const char *pTag, Z_StringOrNumeric *pStringNumeric)
906 if (pStringNumeric != NULL)
908 switch (pStringNumeric->which)
910 case Z_StringOrNumeric_string:
911 print_string(iLevel, pTag, pStringNumeric->u.string);
914 case Z_StringOrNumeric_numeric:
915 print_int(iLevel, pTag, pStringNumeric->u.numeric);
920 printf("%s: valid type for Z_StringOrNumeric\n", pTag);
926 static void print_universe_report_duplicate(int iLevel, Z_UniverseReportDuplicate *pUniverseReportDuplicate)
928 if (pUniverseReportDuplicate != NULL)
931 printf("Universe Report Duplicate: \n");
933 print_string_or_numeric(iLevel, "Hit No", pUniverseReportDuplicate->hitno);
937 static void print_universe_report_hits(int iLevel, Z_UniverseReportHits *pUniverseReportHits)
939 if (pUniverseReportHits != NULL)
942 printf("Universe Report Hits: \n");
944 print_string_or_numeric(iLevel, "Database", pUniverseReportHits->database);
945 print_string_or_numeric(iLevel, "Hits", pUniverseReportHits->hits);
949 static void print_universe_report(int iLevel, Z_UniverseReport *pUniverseReport)
951 if (pUniverseReport != NULL)
954 printf("Universe Report: \n");
956 print_int(iLevel, "Total Hits", pUniverseReport->totalHits);
957 switch (pUniverseReport->which)
959 case Z_UniverseReport_databaseHits:
960 print_universe_report_hits(iLevel, pUniverseReport->u.databaseHits);
963 case Z_UniverseReport_duplicate:
964 print_universe_report_duplicate(iLevel, pUniverseReport->u.duplicate);
969 printf("Type: %d\n", pUniverseReport->which);
975 static void print_external(int iLevel, Z_External *pExternal)
977 if (pExternal != NULL)
980 printf("External: \n");
982 print_oid(iLevel, "Direct Reference", pExternal->direct_reference);
983 print_int(iLevel, "InDirect Reference", pExternal->indirect_reference);
984 print_string(iLevel, "Descriptor", pExternal->descriptor);
985 switch (pExternal->which)
987 case Z_External_universeReport:
988 print_universe_report(iLevel, pExternal->u.universeReport);
993 printf("Type: %d\n", pExternal->which);
999 static int process_resourceControlRequest (Z_ResourceControlRequest *req)
1001 printf ("Received ResourceControlRequest.\n");
1002 print_referenceId(1, req->referenceId);
1003 print_int(1, "Suspended Flag", req->suspendedFlag);
1004 print_int(1, "Partial Results Available", req->partialResultsAvailable);
1005 print_int(1, "Response Required", req->responseRequired);
1006 print_int(1, "Triggered Request Flag", req->triggeredRequestFlag);
1007 print_external(1, req->resourceReport);
1011 void process_ESResponse(Z_ExtendedServicesResponse *res)
1014 switch (*res->operationStatus)
1016 case Z_ExtendedServicesResponse_done:
1019 case Z_ExtendedServicesResponse_accepted:
1020 printf ("accepted\n");
1022 case Z_ExtendedServicesResponse_failure:
1023 printf ("failure\n");
1024 display_diagrecs(res->diagnostics, res->num_diagnostics);
1027 printf ("unknown\n");
1029 if ( (*res->operationStatus != Z_ExtendedServicesResponse_failure) &&
1030 (res->num_diagnostics != 0) ) {
1031 display_diagrecs(res->diagnostics, res->num_diagnostics);
1033 print_refid (res->referenceId);
1034 if (res->taskPackage &&
1035 res->taskPackage->which == Z_External_extendedService)
1037 Z_TaskPackage *taskPackage = res->taskPackage->u.extendedService;
1038 Odr_oct *id = taskPackage->targetReference;
1039 Z_External *ext = taskPackage->taskSpecificParameters;
1043 printf ("Target Reference: ");
1044 print_stringn (id->buf, id->len);
1047 if (ext->which == Z_External_update)
1049 Z_IUUpdateTaskPackage *utp = ext->u.update->u.taskPackage;
1050 if (utp && utp->targetPart)
1052 Z_IUTargetPart *targetPart = utp->targetPart;
1055 for (i = 0; i<targetPart->num_taskPackageRecords; i++)
1058 Z_IUTaskPackageRecordStructure *tpr =
1059 targetPart->taskPackageRecords[i];
1060 printf ("task package record %d\n", i+1);
1061 if (tpr->which == Z_IUTaskPackageRecordStructure_record)
1063 display_record (tpr->u.record);
1067 printf ("other type\n");
1077 const char *get_ill_element (void *clientData, const char *element)
1082 static Z_External *create_external_itemRequest()
1084 struct ill_get_ctl ctl;
1085 ILL_ItemRequest *req;
1087 int item_request_size = 0;
1088 char *item_request_buf = 0;
1092 ctl.f = get_ill_element;
1094 req = ill_get_ItemRequest(&ctl, "ill", 0);
1096 printf ("ill_get_ItemRequest failed\n");
1098 if (!ill_ItemRequest (out, &req, 0, 0))
1102 ill_ItemRequest(print, &req, 0, 0);
1105 item_request_buf = odr_getbuf (out, &item_request_size, 0);
1106 if (item_request_buf)
1107 odr_setbuf (out, item_request_buf, item_request_size, 1);
1108 printf ("Couldn't encode ItemRequest, size %d\n", item_request_size);
1115 item_request_buf = odr_getbuf (out, &item_request_size, 0);
1116 oid.proto = PROTO_GENERAL;
1117 oid.oclass = CLASS_GENERAL;
1118 oid.value = VAL_ISO_ILL_1;
1120 r = (Z_External *) odr_malloc (out, sizeof(*r));
1121 r->direct_reference = odr_oiddup(out,oid_getoidbyent(&oid));
1122 r->indirect_reference = 0;
1124 r->which = Z_External_single;
1126 r->u.single_ASN1_type = (Odr_oct *)
1127 odr_malloc (out, sizeof(*r->u.single_ASN1_type));
1128 r->u.single_ASN1_type->buf = (unsigned char *)
1129 odr_malloc (out, item_request_size);
1130 r->u.single_ASN1_type->len = item_request_size;
1131 r->u.single_ASN1_type->size = item_request_size;
1132 memcpy (r->u.single_ASN1_type->buf, item_request_buf,
1134 printf ("len = %d\n", item_request_size);
1140 #ifdef YAZ_MODULE_ill
1141 static Z_External *create_external_ILL_APDU(int which)
1143 struct ill_get_ctl ctl;
1146 int ill_request_size = 0;
1147 char *ill_request_buf = 0;
1151 ctl.f = get_ill_element;
1153 ill_apdu = ill_get_APDU(&ctl, "ill", 0);
1155 if (!ill_APDU (out, &ill_apdu, 0, 0))
1159 printf ("-------------------\n");
1160 ill_APDU(print, &ill_apdu, 0, 0);
1162 printf ("-------------------\n");
1164 ill_request_buf = odr_getbuf (out, &ill_request_size, 0);
1165 if (ill_request_buf)
1166 odr_setbuf (out, ill_request_buf, ill_request_size, 1);
1167 printf ("Couldn't encode ILL-Request, size %d\n", ill_request_size);
1173 ill_request_buf = odr_getbuf (out, &ill_request_size, 0);
1175 oid.proto = PROTO_GENERAL;
1176 oid.oclass = CLASS_GENERAL;
1177 oid.value = VAL_ISO_ILL_1;
1179 r = (Z_External *) odr_malloc (out, sizeof(*r));
1180 r->direct_reference = odr_oiddup(out,oid_getoidbyent(&oid));
1181 r->indirect_reference = 0;
1183 r->which = Z_External_single;
1185 r->u.single_ASN1_type = (Odr_oct *)
1186 odr_malloc (out, sizeof(*r->u.single_ASN1_type));
1187 r->u.single_ASN1_type->buf = (unsigned char *)
1188 odr_malloc (out, ill_request_size);
1189 r->u.single_ASN1_type->len = ill_request_size;
1190 r->u.single_ASN1_type->size = ill_request_size;
1191 memcpy (r->u.single_ASN1_type->buf, ill_request_buf, ill_request_size);
1192 printf ("len = %d\n", ill_request_size);
1199 static Z_External *create_ItemOrderExternal(const char *type, int itemno)
1201 Z_External *r = (Z_External *) odr_malloc(out, sizeof(Z_External));
1202 oident ItemOrderRequest;
1204 ItemOrderRequest.proto = PROTO_Z3950;
1205 ItemOrderRequest.oclass = CLASS_EXTSERV;
1206 ItemOrderRequest.value = VAL_ITEMORDER;
1208 r->direct_reference = odr_oiddup(out,oid_getoidbyent(&ItemOrderRequest));
1209 r->indirect_reference = 0;
1212 r->which = Z_External_itemOrder;
1214 r->u.itemOrder = (Z_ItemOrder *) odr_malloc(out,sizeof(Z_ItemOrder));
1215 memset(r->u.itemOrder, 0, sizeof(Z_ItemOrder));
1216 r->u.itemOrder->which=Z_IOItemOrder_esRequest;
1218 r->u.itemOrder->u.esRequest = (Z_IORequest *)
1219 odr_malloc(out,sizeof(Z_IORequest));
1220 memset(r->u.itemOrder->u.esRequest, 0, sizeof(Z_IORequest));
1222 r->u.itemOrder->u.esRequest->toKeep = (Z_IOOriginPartToKeep *)
1223 odr_malloc(out,sizeof(Z_IOOriginPartToKeep));
1224 memset(r->u.itemOrder->u.esRequest->toKeep, 0, sizeof(Z_IOOriginPartToKeep));
1225 r->u.itemOrder->u.esRequest->notToKeep = (Z_IOOriginPartNotToKeep *)
1226 odr_malloc(out,sizeof(Z_IOOriginPartNotToKeep));
1227 memset(r->u.itemOrder->u.esRequest->notToKeep, 0, sizeof(Z_IOOriginPartNotToKeep));
1229 r->u.itemOrder->u.esRequest->toKeep->supplDescription = NULL;
1230 r->u.itemOrder->u.esRequest->toKeep->contact = NULL;
1231 r->u.itemOrder->u.esRequest->toKeep->addlBilling = NULL;
1233 r->u.itemOrder->u.esRequest->notToKeep->resultSetItem =
1234 (Z_IOResultSetItem *) odr_malloc(out, sizeof(Z_IOResultSetItem));
1235 memset(r->u.itemOrder->u.esRequest->notToKeep->resultSetItem, 0, sizeof(Z_IOResultSetItem));
1236 r->u.itemOrder->u.esRequest->notToKeep->resultSetItem->resultSetId = "1";
1238 r->u.itemOrder->u.esRequest->notToKeep->resultSetItem->item =
1239 (int *) odr_malloc(out, sizeof(int));
1240 *r->u.itemOrder->u.esRequest->notToKeep->resultSetItem->item = itemno;
1243 if (!strcmp (type, "item") || !strcmp(type, "2"))
1245 printf ("using item-request\n");
1246 r->u.itemOrder->u.esRequest->notToKeep->itemRequest =
1247 create_external_itemRequest();
1249 else if (!strcmp(type, "ill") || !strcmp(type, "1"))
1251 printf ("using ILL-request\n");
1252 r->u.itemOrder->u.esRequest->notToKeep->itemRequest =
1253 create_external_ILL_APDU(ILL_APDU_ILL_Request);
1255 else if (!strcmp(type, "xml") || !strcmp(type, "3"))
1257 const char *xml_buf =
1259 " <type>request</type>\n"
1260 " <libraryNo>000200</libraryNo>\n"
1261 " <borrowerTicketNo> 1212 </borrowerTicketNo>\n"
1263 r->u.itemOrder->u.esRequest->notToKeep->itemRequest =
1264 z_ext_record (out, VAL_TEXT_XML, xml_buf, strlen(xml_buf));
1267 r->u.itemOrder->u.esRequest->notToKeep->itemRequest = 0;
1270 r->u.itemOrder->u.esRequest->notToKeep->itemRequest = 0;
1275 static int send_itemorder(const char *type, int itemno)
1277 Z_APDU *apdu = zget_APDU(out, Z_APDU_extendedServicesRequest);
1278 Z_ExtendedServicesRequest *req = apdu->u.extendedServicesRequest;
1279 oident ItemOrderRequest;
1281 ItemOrderRequest.proto = PROTO_Z3950;
1282 ItemOrderRequest.oclass = CLASS_EXTSERV;
1283 ItemOrderRequest.value = VAL_ITEMORDER;
1284 req->packageType = odr_oiddup(out,oid_getoidbyent(&ItemOrderRequest));
1285 req->packageName = esPackageName;
1287 req->taskSpecificParameters = create_ItemOrderExternal(type, itemno);
1293 static int cmd_update(char *arg)
1295 Z_APDU *apdu = zget_APDU(out, Z_APDU_extendedServicesRequest );
1296 Z_ExtendedServicesRequest *req = apdu->u.extendedServicesRequest;
1299 Z_IUOriginPartToKeep *toKeep;
1300 Z_IUSuppliedRecords *notToKeep;
1302 printf ("Update request\n");
1307 update_oid.proto = PROTO_Z3950;
1308 update_oid.oclass = CLASS_EXTSERV;
1309 update_oid.value = VAL_DBUPDATE;
1310 oid_ent_to_oid (&update_oid, oid);
1311 req->packageType = odr_oiddup(out,oid);
1312 req->packageName = esPackageName;
1314 req->referenceId = set_refid (out);
1316 r = req->taskSpecificParameters = (Z_External *)
1317 odr_malloc (out, sizeof(*r));
1318 r->direct_reference = odr_oiddup(out,oid);
1319 r->indirect_reference = 0;
1321 r->which = Z_External_update;
1322 r->u.update = (Z_IUUpdate *) odr_malloc(out, sizeof(*r->u.update));
1323 r->u.update->which = Z_IUUpdate_esRequest;
1324 r->u.update->u.esRequest = (Z_IUUpdateEsRequest *)
1325 odr_malloc(out, sizeof(*r->u.update->u.esRequest));
1326 toKeep = r->u.update->u.esRequest->toKeep = (Z_IUOriginPartToKeep *)
1327 odr_malloc(out, sizeof(*r->u.update->u.esRequest->toKeep));
1328 toKeep->databaseName = databaseNames[0];
1330 toKeep->elementSetName = 0;
1331 toKeep->actionQualifier = 0;
1332 toKeep->action = (int *) odr_malloc(out, sizeof(*toKeep->action));
1333 *toKeep->action = Z_IUOriginPartToKeep_recordInsert;
1335 notToKeep = r->u.update->u.esRequest->notToKeep = (Z_IUSuppliedRecords *)
1336 odr_malloc(out, sizeof(*r->u.update->u.esRequest->notToKeep));
1338 notToKeep->elements = (Z_IUSuppliedRecords_elem **)
1339 odr_malloc(out, sizeof(*notToKeep->elements));
1340 notToKeep->elements[0] = (Z_IUSuppliedRecords_elem *)
1341 odr_malloc(out, sizeof(**notToKeep->elements));
1342 notToKeep->elements[0]->u.number = 0;
1343 notToKeep->elements[0]->supplementalId = 0;
1344 notToKeep->elements[0]->correlationInfo = 0;
1345 notToKeep->elements[0]->record = record_last;
1352 /* II : Added to do DALI Item Order Extended services request */
1353 static int cmd_itemorder(char *arg)
1358 if (sscanf (arg, "%10s %d", type, &itemno) != 2)
1361 printf("Item order request\n");
1363 send_itemorder(type, itemno);
1367 static int cmd_find(char *arg)
1371 printf("Find what?\n");
1376 printf("Not connected yet\n");
1379 if (!send_searchRequest(arg))
1384 static int cmd_delete(char *arg)
1388 printf("Not connected yet\n");
1391 if (!send_deleteResultSetRequest(arg))
1396 static int cmd_ssub(char *arg)
1398 if (!(smallSetUpperBound = atoi(arg)))
1403 static int cmd_lslb(char *arg)
1405 if (!(largeSetLowerBound = atoi(arg)))
1410 static int cmd_mspn(char *arg)
1412 if (!(mediumSetPresentNumber = atoi(arg)))
1417 static int cmd_status(char *arg)
1419 printf("smallSetUpperBound: %d\n", smallSetUpperBound);
1420 printf("largeSetLowerBound: %d\n", largeSetLowerBound);
1421 printf("mediumSetPresentNumber: %d\n", mediumSetPresentNumber);
1425 static int cmd_setnames(char *arg)
1427 if (*arg == '1') /* enable ? */
1429 else if (*arg == '0') /* disable ? */
1431 else if (setnumber < 0) /* no args, toggle .. */
1437 printf("Set numbering enabled.\n");
1439 printf("Set numbering disabled.\n");
1443 /* PRESENT SERVICE ----------------------------- */
1445 static int send_presentRequest(char *arg)
1447 Z_APDU *apdu = zget_APDU(out, Z_APDU_presentRequest);
1448 Z_PresentRequest *req = apdu->u.presentRequest;
1449 Z_RecordComposition compo;
1454 char setstring[100];
1456 req->referenceId = set_refid (out);
1457 if ((p = strchr(arg, '+')))
1464 if (p && (p=strchr(p+1, '+')))
1466 strcpy (setstring, p+1);
1467 req->resultSetId = setstring;
1469 else if (setnumber >= 0)
1471 sprintf(setstring, "%d", setnumber);
1472 req->resultSetId = setstring;
1477 static Z_Range range;
1478 static Z_Range *rangep = ⦥
1479 req->num_ranges = 1;
1481 req->resultSetStartPoint = &setno;
1482 req->numberOfRecordsRequested = &nos;
1483 prefsyn.proto = protocol;
1484 prefsyn.oclass = CLASS_RECSYN;
1485 prefsyn.value = recordsyntax;
1486 req->preferredRecordSyntax =
1487 odr_oiddup (out, oid_ent_to_oid(&prefsyn, oid));
1489 if (schema != VAL_NONE)
1493 prefschema.proto = protocol;
1494 prefschema.oclass = CLASS_SCHEMA;
1495 prefschema.value = schema;
1497 req->recordComposition = &compo;
1498 compo.which = Z_RecordComp_complex;
1499 compo.u.complex = (Z_CompSpec *)
1500 odr_malloc(out, sizeof(*compo.u.complex));
1501 compo.u.complex->selectAlternativeSyntax = (bool_t *)
1502 odr_malloc(out, sizeof(bool_t));
1503 *compo.u.complex->selectAlternativeSyntax = 0;
1505 compo.u.complex->generic = (Z_Specification *)
1506 odr_malloc(out, sizeof(*compo.u.complex->generic));
1507 compo.u.complex->generic->schema = (Odr_oid *)
1508 odr_oiddup(out, oid_ent_to_oid(&prefschema, oid));
1509 if (!compo.u.complex->generic->schema)
1511 /* OID wasn't a schema! Try record syntax instead. */
1512 prefschema.oclass = CLASS_RECSYN;
1513 compo.u.complex->generic->schema = (Odr_oid *)
1514 odr_oiddup(out, oid_ent_to_oid(&prefschema, oid));
1516 if (!elementSetNames)
1517 compo.u.complex->generic->elementSpec = 0;
1520 compo.u.complex->generic->elementSpec = (Z_ElementSpec *)
1521 odr_malloc(out, sizeof(Z_ElementSpec));
1522 compo.u.complex->generic->elementSpec->which =
1523 Z_ElementSpec_elementSetName;
1524 compo.u.complex->generic->elementSpec->u.elementSetName =
1525 elementSetNames->u.generic;
1527 compo.u.complex->num_dbSpecific = 0;
1528 compo.u.complex->dbSpecific = 0;
1529 compo.u.complex->num_recordSyntax = 0;
1530 compo.u.complex->recordSyntax = 0;
1532 else if (elementSetNames)
1534 req->recordComposition = &compo;
1535 compo.which = Z_RecordComp_simple;
1536 compo.u.simple = elementSetNames;
1539 printf("Sent presentRequest (%d+%d).\n", setno, nos);
1543 void process_close(Z_Close *req)
1545 Z_APDU *apdu = zget_APDU(out, Z_APDU_close);
1546 Z_Close *res = apdu->u.close;
1548 static char *reasons[] =
1553 "cost limit reached",
1555 "security violation",
1562 printf("Reason: %s, message: %s\n", reasons[*req->closeReason],
1563 req->diagnosticInformation ? req->diagnosticInformation : "NULL");
1570 nmem_destroy (session_mem);
1577 *res->closeReason = Z_Close_finished;
1579 printf("Sent response.\n");
1584 static int cmd_show(char *arg)
1588 printf("Not connected yet\n");
1591 if (!send_presentRequest(arg))
1596 int cmd_quit(char *arg)
1598 printf("See you later, alligator.\n");
1604 int cmd_cancel(char *arg)
1606 Z_APDU *apdu = zget_APDU(out, Z_APDU_triggerResourceControlRequest);
1607 Z_TriggerResourceControlRequest *req =
1608 apdu->u.triggerResourceControlRequest;
1613 printf("Session not initialized yet\n");
1616 if (!ODR_MASK_GET(session->options, Z_Options_triggerResourceCtrl))
1618 printf("Target doesn't support cancel (trigger resource ctrl)\n");
1621 *req->requestedAction = Z_TriggerResourceCtrl_cancel;
1622 req->resultSetWanted = &rfalse;
1625 printf("Sent cancel request\n");
1629 int send_scanrequest(const char *query, int pp, int num, const char *term)
1631 Z_APDU *apdu = zget_APDU(out, Z_APDU_scanRequest);
1632 Z_ScanRequest *req = apdu->u.scanRequest;
1637 if (queryType == QueryType_CCL2RPN)
1641 struct ccl_rpn_node *rpn;
1643 rpn = ccl_find_str (bibset, query, &error, &pos);
1646 printf("CCL ERROR: %s\n", ccl_err_msg(error));
1650 bib1.proto = PROTO_Z3950;
1651 bib1.oclass = CLASS_ATTSET;
1652 bib1.value = VAL_BIB1;
1653 req->attributeSet = oid_ent_to_oid (&bib1, oid);
1654 if (!(req->termListAndStartPoint = ccl_scan_query (out, rpn)))
1656 printf("Couldn't convert CCL to Scan term\n");
1659 ccl_rpn_delete (rpn);
1662 if (use_rpn && !(req->termListAndStartPoint =
1663 p_query_scan(out, protocol, &req->attributeSet, query)))
1665 printf("Prefix query error\n");
1670 if (req->termListAndStartPoint->term &&
1671 req->termListAndStartPoint->term->which == Z_Term_general &&
1672 req->termListAndStartPoint->term->u.general)
1674 req->termListAndStartPoint->term->u.general->buf =
1675 (unsigned char *) odr_strdup(out, term);
1676 req->termListAndStartPoint->term->u.general->len =
1677 req->termListAndStartPoint->term->u.general->size =
1681 req->referenceId = set_refid (out);
1682 req->num_databaseNames = num_databaseNames;
1683 req->databaseNames = databaseNames;
1684 req->numberOfTermsRequested = #
1685 req->preferredPositionInResponse = &pp;
1690 int send_sortrequest(char *arg, int newset)
1692 Z_APDU *apdu = zget_APDU(out, Z_APDU_sortRequest);
1693 Z_SortRequest *req = apdu->u.sortRequest;
1694 Z_SortKeySpecList *sksl = (Z_SortKeySpecList *)
1695 odr_malloc (out, sizeof(*sksl));
1699 sprintf (setstring, "%d", setnumber);
1701 sprintf (setstring, "default");
1703 req->referenceId = set_refid (out);
1705 req->num_inputResultSetNames = 1;
1706 req->inputResultSetNames = (Z_InternationalString **)
1707 odr_malloc (out, sizeof(*req->inputResultSetNames));
1708 req->inputResultSetNames[0] = odr_strdup (out, setstring);
1710 if (newset && setnumber >= 0)
1711 sprintf (setstring, "%d", ++setnumber);
1713 req->sortedResultSetName = odr_strdup (out, setstring);
1715 req->sortSequence = yaz_sort_spec (out, arg);
1716 if (!req->sortSequence)
1718 printf ("Missing sort specifications\n");
1725 void display_term(Z_TermInfo *t)
1727 if (t->term->which == Z_Term_general)
1729 printf("%.*s", t->term->u.general->len, t->term->u.general->buf);
1730 sprintf(last_scan_line, "%.*s", t->term->u.general->len,
1731 t->term->u.general->buf);
1734 printf("Term (not general)");
1735 if (t->globalOccurrences)
1736 printf (" (%d)\n", *t->globalOccurrences);
1741 void process_scanResponse(Z_ScanResponse *res)
1744 Z_Entry **entries = NULL;
1745 int num_entries = 0;
1747 printf("Received ScanResponse\n");
1748 print_refid (res->referenceId);
1749 printf("%d entries", *res->numberOfEntriesReturned);
1750 if (res->positionOfTerm)
1751 printf (", position=%d", *res->positionOfTerm);
1753 if (*res->scanStatus != Z_Scan_success)
1754 printf("Scan returned code %d\n", *res->scanStatus);
1757 if ((entries = res->entries->entries))
1758 num_entries = res->entries->num_entries;
1759 for (i = 0; i < num_entries; i++)
1761 int pos_term = res->positionOfTerm ? *res->positionOfTerm : -1;
1762 if (entries[i]->which == Z_Entry_termInfo)
1764 printf("%c ", i + 1 == pos_term ? '*' : ' ');
1765 display_term(entries[i]->u.termInfo);
1768 display_diagrecs(&entries[i]->u.surrogateDiagnostic, 1);
1770 if (res->entries->nonsurrogateDiagnostics)
1771 display_diagrecs (res->entries->nonsurrogateDiagnostics,
1772 res->entries->num_nonsurrogateDiagnostics);
1775 void process_sortResponse(Z_SortResponse *res)
1777 printf("Received SortResponse: status=");
1778 switch (*res->sortStatus)
1780 case Z_SortStatus_success:
1781 printf ("success"); break;
1782 case Z_SortStatus_partial_1:
1783 printf ("partial"); break;
1784 case Z_SortStatus_failure:
1785 printf ("failure"); break;
1787 printf ("unknown (%d)", *res->sortStatus);
1790 print_refid (res->referenceId);
1791 if (res->diagnostics)
1792 display_diagrecs(res->diagnostics,
1793 res->num_diagnostics);
1796 void process_deleteResultSetResponse (Z_DeleteResultSetResponse *res)
1798 printf("Got deleteResultSetResponse status=%d\n",
1799 *res->deleteOperationStatus);
1800 if (res->deleteListStatuses)
1803 for (i = 0; i < res->deleteListStatuses->num; i++)
1805 printf ("%s status=%d\n", res->deleteListStatuses->elements[i]->id,
1806 *res->deleteListStatuses->elements[i]->status);
1811 int cmd_sort_generic(char *arg, int newset)
1815 printf("Session not initialized yet\n");
1818 if (!ODR_MASK_GET(session->options, Z_Options_sort))
1820 printf("Target doesn't support sort\n");
1825 if (send_sortrequest(arg, newset) < 0)
1832 int cmd_sort(char *arg)
1834 return cmd_sort_generic (arg, 0);
1837 int cmd_sort_newset (char *arg)
1839 return cmd_sort_generic (arg, 1);
1842 int cmd_scan(char *arg)
1846 printf("Session not initialized yet\n");
1849 if (!ODR_MASK_GET(session->options, Z_Options_scan))
1851 printf("Target doesn't support scan\n");
1856 strcpy (last_scan_query, arg);
1857 if (send_scanrequest(arg, 1, 20, 0) < 0)
1862 if (send_scanrequest(last_scan_query, 1, 20, last_scan_line) < 0)
1868 int cmd_schema(char *arg)
1875 schema = oid_getvalbyname (arg);
1876 if (schema == VAL_NONE)
1878 printf ("unknown schema\n");
1884 int cmd_format(char *arg)
1888 printf("Usage: format <recordsyntax>\n");
1891 recordsyntax = oid_getvalbyname (arg);
1892 if (recordsyntax == VAL_NONE)
1894 printf ("unknown record syntax\n");
1900 int cmd_elements(char *arg)
1902 static Z_ElementSetNames esn;
1903 static char what[100];
1907 elementSetNames = 0;
1911 esn.which = Z_ElementSetNames_generic;
1912 esn.u.generic = what;
1913 elementSetNames = &esn;
1917 int cmd_attributeset(char *arg)
1923 printf("Usage: attributeset <setname>\n");
1926 sscanf(arg, "%s", what);
1927 if (p_query_attset (what))
1929 printf("Unknown attribute set name\n");
1935 int cmd_querytype (char *arg)
1937 if (!strcmp (arg, "ccl"))
1938 queryType = QueryType_CCL;
1939 else if (!strcmp (arg, "prefix") || !strcmp(arg, "rpn"))
1940 queryType = QueryType_Prefix;
1942 else if (!strcmp (arg, "ccl2rpn") || !strcmp (arg, "cclrpn"))
1943 queryType = QueryType_CCL2RPN;
1947 printf ("Querytype must be one of:\n");
1948 printf (" prefix - Prefix query\n");
1949 printf (" ccl - CCL query\n");
1951 printf (" ccl2rpn - CCL query converted to RPN\n");
1958 int cmd_refid (char *arg)
1964 refid = (char *) xmalloc (strlen(arg)+1);
1965 strcpy (refid, arg);
1970 int cmd_close(char *arg)
1977 apdu = zget_APDU(out, Z_APDU_close);
1978 req = apdu->u.close;
1979 *req->closeReason = Z_Close_finished;
1981 printf("Sent close request.\n");
1986 int cmd_packagename(char* arg)
1988 xfree (esPackageName);
1989 esPackageName = NULL;
1992 esPackageName = (char *) xmalloc (strlen(arg)+1);
1993 strcpy (esPackageName, arg);
1998 int cmd_proxy(char* arg)
2004 yazProxy = (char *) xmalloc (strlen(arg)+1);
2005 strcpy (yazProxy, arg);
2010 int cmd_source(char* arg)
2012 /* first should open the file and read one line at a time.. */
2014 char line[1024], *cp;
2017 char* args_end=(arg)+strlen(arg)-1;
2018 while(isspace(*args_end))
2023 REMOVE_TAILING_BLANKS(arg);
2026 fprintf(stderr,"Error in source command use a filename\n");
2030 includeFile = fopen (arg, "r");
2033 fprintf(stderr,"Unable to open file %s for reading\n",arg);
2037 while(!feof(includeFile)) {
2038 memset(line,0,sizeof(line));
2039 fgets(line,sizeof(line),includeFile);
2041 if(strlen(line) < 2) continue;
2042 if(line[0] == '#') continue;
2044 if ((cp = strrchr (line, '\n')))
2047 process_cmd_line(line);
2050 if(fclose(includeFile)<0) {
2051 perror("unable to close include file");
2057 int cmd_subshell(char* args)
2062 system(getenv("SHELL"));
2068 int cmd_set_apdufile(char* arg)
2070 REMOVE_TAILING_BLANKS(arg);
2072 if(apdu_file && apdu_file != stderr) { /* don't close stdout*/
2073 perror("unable to close apdu log file");
2081 if(!strcmp(arg,"-"))
2084 apdu_file=fopen(arg, "a");
2087 perror("unable to open apdu log file no apdu log loaded");
2089 odr_setprint(print, apdu_file);
2095 int cmd_set_cclfields(char* arg)
2100 REMOVE_TAILING_BLANKS(arg);
2102 bibset = ccl_qual_mk ();
2103 inf = fopen (arg, "r");
2106 ccl_qual_file (bibset, inf);
2110 fprintf(stderr,"Not compiled with the yaz ccl module\n");
2116 int cmd_set_marcdump(char* arg)
2118 if(marcdump && marcdump != stderr) { /* don't close stdout*/
2119 perror("unable to close apdu log file");
2127 if(!strcmp(arg,"-"))
2130 marcdump=fopen(arg, "a");
2133 perror("unable to open apdu marcdump file no marcdump done\n");
2139 int cmd_set_proxy(char* arg) {
2140 if(yazProxy) free(yazProxy);
2143 if(strlen(arg) > 1) {
2144 yazProxy=strdup(arg);
2150 this command takes 3 arge {name class oid}
2152 int cmd_register_oid(char* args) {
2157 {"appctx",CLASS_APPCTX},
2158 {"absyn",CLASS_ABSYN},
2159 {"attset",CLASS_ATTSET},
2160 {"transyn",CLASS_TRANSYN},
2161 {"diagset",CLASS_DIAGSET},
2162 {"recsyn",CLASS_RECSYN},
2163 {"resform",CLASS_RESFORM},
2164 {"accform",CLASS_ACCFORM},
2165 {"extserv",CLASS_EXTSERV},
2166 {"userinfo",CLASS_USERINFO},
2167 {"elemspec",CLASS_ELEMSPEC},
2168 {"varset",CLASS_VARSET},
2169 {"schema",CLASS_SCHEMA},
2170 {"tagset",CLASS_TAGSET},
2171 {"general",CLASS_GENERAL},
2174 char oname_str[101], oclass_str[101], oid_str[101];
2177 oid_class oidclass = CLASS_GENERAL;
2178 int val = 0, oid[OID_SIZE];
2179 struct oident * new_oident=NULL;
2181 if (sscanf (args, "%100[^ ] %100[^ ] %100s",
2182 oname_str,oclass_str, oid_str) < 1) {
2183 printf("Error in regristrate command \n");
2187 for (i = 0; oid_classes[i].className; i++) {
2188 if (!strcmp(oid_classes[i].className, oclass_str))
2190 oidclass=oid_classes[i].oclass;
2195 if(!(oid_classes[i].className)) {
2196 printf("Unknonwn oid class %s\n",oclass_str);
2204 while (isdigit (*name))
2206 val = val*10 + (*name - '0');
2219 new_oident=oid_addent (oid,PROTO_GENERAL,oidclass,oname_str,VAL_DYNAMIC);
2220 if(strcmp(new_oident->desc,oname_str)) {
2221 fprintf(stderr,"oid is already named as %s, regristration faild\n",
2227 int cmd_push_command(char* arg) {
2228 #if HAVE_READLINE_HISTORY_H
2232 fprintf(stderr,"Not compiled with the readline/history module\n");
2237 void source_rcfile() {
2238 /* Look for a $HOME/.yazclientrc and source it if it exists */
2239 struct stat statbuf;
2241 char* homedir=getenv("HOME");
2242 if(!homedir) return;
2244 sprintf(buffer,"%s/.yazclientrc",homedir);
2246 if(stat(buffer,&statbuf)==0) {
2250 if(stat(".yazclientrc",&statbuf)==0) {
2251 cmd_source(".yazclientrc");
2256 static void initialize(void)
2261 if (!(out = odr_createmem(ODR_ENCODE)) ||
2262 !(in = odr_createmem(ODR_DECODE)) ||
2263 !(print = odr_createmem(ODR_PRINT)))
2265 fprintf(stderr, "failed to allocate ODR streams\n");
2270 setvbuf(stdout, 0, _IONBF, 0);
2272 odr_setprint(print, apdu_file);
2275 bibset = ccl_qual_mk ();
2276 inf = fopen (ccl_fields, "r");
2279 ccl_qual_file (bibset, inf);
2283 cmd_base("Default");
2285 #if HAVE_READLINE_READLINE_H
2286 rl_attempted_completion_function = (CPPFunction*)readline_completer;
2293 #if HAVE_GETTIMEOFDAY
2294 struct timeval tv_start, tv_end;
2297 void wait_and_handle_responce()
2302 int netbufferlen = 0;
2310 if ((res = cs_get(conn, &netbuffer, &netbufferlen)) < 0)
2317 printf("Target closed connection.\n");
2320 odr_reset(in); /* release APDU from last round */
2322 odr_setbuf(in, netbuffer, res, 0);
2323 if (!z_APDU(in, &apdu, 0, 0))
2325 odr_perror(in, "Decoding incoming APDU");
2326 fprintf(stderr, "[Near %d]\n", odr_offset(in));
2327 fprintf(stderr, "Packet dump:\n---------\n");
2328 odr_dumpBER(stderr, netbuffer, res);
2329 fprintf(stderr, "---------\n");
2331 z_APDU(print, &apdu, 0, 0);
2334 if (apdu_file && !z_APDU(print, &apdu, 0, 0))
2336 odr_perror(print, "Failed to print incoming APDU");
2342 case Z_APDU_initResponse:
2343 process_initResponse(apdu->u.initResponse);
2345 case Z_APDU_searchResponse:
2346 process_searchResponse(apdu->u.searchResponse);
2348 case Z_APDU_scanResponse:
2349 process_scanResponse(apdu->u.scanResponse);
2351 case Z_APDU_presentResponse:
2352 print_refid (apdu->u.presentResponse->referenceId);
2354 *apdu->u.presentResponse->numberOfRecordsReturned;
2355 if (apdu->u.presentResponse->records)
2356 display_records(apdu->u.presentResponse->records);
2358 printf("No records.\n");
2359 printf ("nextResultSetPosition = %d\n",
2360 *apdu->u.presentResponse->nextResultSetPosition);
2362 case Z_APDU_sortResponse:
2363 process_sortResponse(apdu->u.sortResponse);
2365 case Z_APDU_extendedServicesResponse:
2366 printf("Got extended services response\n");
2367 process_ESResponse(apdu->u.extendedServicesResponse);
2370 printf("Target has closed the association.\n");
2371 process_close(apdu->u.close);
2373 case Z_APDU_resourceControlRequest:
2374 process_resourceControlRequest
2375 (apdu->u.resourceControlRequest);
2377 case Z_APDU_deleteResultSetResponse:
2378 process_deleteResultSetResponse(apdu->u.
2379 deleteResultSetResponse);
2382 printf("Received unknown APDU type (%d).\n",
2387 while (conn && cs_more(conn));
2388 #if HAVE_GETTIMEOFDAY
2389 gettimeofday (&tv_end, 0);
2391 printf ("S/U S/U=%ld/%ld %ld/%ld",
2392 (long) tv_start.tv_sec,
2393 (long) tv_start.tv_usec,
2394 (long) tv_end.tv_sec,
2395 (long) tv_end.tv_usec);
2397 printf ("Elapsed: %.6f\n",
2398 (double) tv_end.tv_usec / 1e6 + tv_end.tv_sec -
2399 ((double) tv_start.tv_usec / 1e6 + tv_start.tv_sec));
2408 int (*fun)(char *arg);
2410 char *(*rl_completerfunction)(const char *text, int state);
2411 int complete_filenames;
2413 {"open", cmd_open, "('tcp'|'ssl')':<host>[':'<port>][/<db>]",NULL,0},
2414 {"quit", cmd_quit, "",NULL,0},
2415 {"find", cmd_find, "<query>",NULL,0},
2416 {"delete", cmd_delete, "<setname>",NULL,0},
2417 {"base", cmd_base, "<base-name>",NULL,0},
2418 {"show", cmd_show, "<rec#>['+'<#recs>['+'<setname>]]",NULL,0},
2419 {"scan", cmd_scan, "<term>",NULL,0},
2420 {"sort", cmd_sort, "<sortkey> <flag> <sortkey> <flag> ...",NULL,0},
2421 {"sort+", cmd_sort_newset, "<sortkey> <flag> <sortkey> <flag> ...",NULL,0},
2422 {"authentication", cmd_authentication, "<acctstring>",NULL,0},
2423 {"lslb", cmd_lslb, "<largeSetLowerBound>",NULL,0},
2424 {"ssub", cmd_ssub, "<smallSetUpperBound>",NULL,0},
2425 {"mspn", cmd_mspn, "<mediumSetPresentNumber>",NULL,0},
2426 {"status", cmd_status, "",NULL,0},
2427 {"setnames", cmd_setnames, "",NULL,0},
2428 {"cancel", cmd_cancel, "",NULL,0},
2429 {"format", cmd_format, "<recordsyntax>",complete_format,0},
2430 {"schema", cmd_schema, "<schema>",complete_schema,0},
2431 {"elements", cmd_elements, "<elementSetName>",NULL,0},
2432 {"close", cmd_close, "",NULL,0},
2433 {"attributeset", cmd_attributeset, "<attrset>",complete_attributeset,0},
2434 {"querytype", cmd_querytype, "<type>",complete_querytype,0},
2435 {"refid", cmd_refid, "<id>",NULL,0},
2436 {"itemorder", cmd_itemorder, "ill|item <itemno>",NULL,0},
2437 {"update", cmd_update, "<item>",NULL,0},
2438 {"packagename", cmd_packagename, "<packagename>",NULL,0},
2439 {"proxy", cmd_proxy, "[('tcp'|'ssl')]<host>[':'<port>]",NULL,0},
2440 {".", cmd_source, "<filename>",NULL,1},
2441 {"!", cmd_subshell, "Subshell command",NULL,0},
2442 {"set_apdufile", cmd_set_apdufile, "<filename>",NULL,0},
2443 {"set_marcdump", cmd_set_marcdump," <filename>",NULL,0},
2444 {"set_cclfields", cmd_set_cclfields,"<filename>",NULL,1},
2445 {"register_oid",cmd_register_oid,"<name> <class> <oid>",NULL,0},
2446 {"push_command",cmd_push_command,"<command>",command_generator,0},
2447 /* Server Admin Functions */
2448 {"adm-reindex", cmd_adm_reindex, "<database-name>",NULL,0},
2449 {"adm-truncate", cmd_adm_truncate, "('database'|'index')<object-name>",NULL,0},
2450 {"adm-create", cmd_adm_create, "",NULL,0},
2451 {"adm-drop", cmd_adm_drop, "('database'|'index')<object-name>",NULL,0},
2452 {"adm-import", cmd_adm_import, "<record-type> <dir> <pattern>",NULL,0},
2453 {"adm-refresh", cmd_adm_refresh, "",NULL,0},
2454 {"adm-commit", cmd_adm_commit, "",NULL,0},
2455 {"adm-shutdown", cmd_adm_shutdown, "",NULL,0},
2456 {"adm-startup", cmd_adm_startup, "",NULL,0},
2460 void process_cmd_line(char* line)
2463 char word[32], arg[1024];
2465 #if HAVE_GETTIMEOFDAY
2466 gettimeofday (&tv_start, 0);
2469 if ((res = sscanf(line, "%31s %1023[^;]", word, arg)) <= 0)
2471 strcpy(word, last_cmd);
2476 strcpy(last_cmd, word);
2478 /* removed tailing spaces from the arg command */
2481 char* lastnonspace=NULL;
2490 *(++lastnonspace) = 0;
2494 for (i = 0; cmd[i].cmd; i++)
2495 if (!strncmp(cmd[i].cmd, word, strlen(word)))
2497 res = (*cmd[i].fun)(arg);
2500 if (!cmd[i].cmd) /* dump our help-screen */
2502 printf("Unknown command: %s.\n", word);
2503 printf("Currently recognized commands:\n");
2504 for (i = 0; cmd[i].cmd; i++)
2505 printf(" %s %s\n", cmd[i].cmd, cmd[i].ad);
2509 if(apdu_file) fflush(apdu_file);
2512 wait_and_handle_responce();
2521 char *command_generator(const char *text, int state)
2523 static idx; // index is the last used the last time command_generator was called
2527 for( ; cmd[idx].cmd; ++idx) {
2528 if (!strncmp(cmd[idx].cmd,text,strlen(text))) {
2529 ++idx; /* skip this entry on the next run */
2530 return strdup(cmd[idx-1].cmd);
2538 This function only known how to complete on the first word
2540 char ** readline_completer(char *text, int start, int end) {
2541 #if HAVE_READLINE_READLINE_H
2544 #ifdef RL_READLINE_VERSION
2545 char** res=rl_completion_matches(text,
2548 char** res=completion_matches(text,
2549 (CPFunction*)command_generator);
2551 rl_attempted_completion_over = 1;
2554 char arg[1024],word[32];
2556 if ((res = sscanf(rl_line_buffer, "%31s %1023[^;]", word, arg)) <= 0) {
2557 rl_attempted_completion_over = 1;
2561 if(start != strlen(word) +1 ) {
2562 rl_attempted_completion_over = 1;
2565 for (i = 0; cmd[i].cmd; i++) {
2566 if (!strncmp(cmd[i].cmd, word, strlen(word))) {
2572 if(!cmd[i].complete_filenames)
2573 rl_attempted_completion_over = 1;
2574 if(cmd[i].rl_completerfunction) {
2575 #ifdef RL_READLINE_VERSION
2577 rl_completion_matches(text,
2578 cmd[i].rl_completerfunction);
2581 completion_matches(text,
2582 (CPFunction*)cmd[i].rl_completerfunction);
2584 rl_attempted_completion_over = 1;
2587 rl_attempted_completion_over = 1;
2597 static void client(void)
2603 #if HAVE_GETTIMEOFDAY
2604 gettimeofday (&tv_start, 0);
2609 char *line_in = NULL;
2610 #if HAVE_READLINE_READLINE_H
2613 line_in=readline(C_PROMPT);
2616 #if HAVE_READLINE_HISTORY_H
2618 add_history(line_in);
2620 strncpy(line, line_in, 1023);
2629 if (!fgets(line, 1023, stdin))
2631 if ((end_p = strchr (line, '\n')))
2634 process_cmd_line(line);
2638 int main(int argc, char **argv)
2641 char *open_command = 0;
2642 char *auth_command = 0;
2646 while ((ret = options("k:c:a:m:v:p:u:", argv, argc, &arg)) != -2)
2653 open_command = (char *) xmalloc (strlen(arg)+6);
2654 strcpy (open_command, "open ");
2655 strcat (open_command, arg);
2659 kilobytes = atoi(arg);
2662 if (!(marcdump = fopen (arg, "a")))
2669 strncpy (ccl_fields, arg, sizeof(ccl_fields)-1);
2670 ccl_fields[sizeof(ccl_fields)-1] = '\0';
2673 if (!strcmp(arg, "-"))
2676 apdu_file=fopen(arg, "a");
2679 yazProxy=strdup(arg);
2684 auth_command = (char *) xmalloc (strlen(arg)+6);
2685 strcpy (auth_command, "auth ");
2686 strcat (auth_command, arg);
2690 yaz_log_init (yaz_log_mask_str(arg), "", NULL);
2693 fprintf (stderr, "Usage: %s [-m <marclog>] [ -a <apdulog>] "
2694 "[-c cclfields]\n [-p <proxy-addr>] [-u <auth>] "
2695 "[-k size] [<server-addr>]\n",
2703 #ifdef HAVE_GETTIMEOFDAY
2704 gettimeofday (&tv_start, 0);
2706 process_cmd_line (auth_command);
2707 #if HAVE_READLINE_HISTORY_H
2708 add_history(auth_command);
2710 xfree(auth_command);
2714 #ifdef HAVE_GETTIMEOFDAY
2715 gettimeofday (&tv_start, 0);
2717 process_cmd_line (open_command);
2718 #if HAVE_READLINE_HISTORY_H
2719 add_history(open_command);
2721 xfree(open_command);