2 * Copyright (c) 1995-1998, Index Data.
3 * See the file LICENSE for details.
4 * Sebastian Hammer, Adam Dickmeiss
7 * Revision 1.64 1998-03-31 11:07:44 adam
8 * Furhter work on UNIverse resource report.
9 * Added Extended Services handling in frontend server.
11 * Revision 1.63 1998/03/05 08:05:10 adam
12 * Added a few casts to make C++ happy.
14 * Revision 1.62 1998/02/11 11:53:33 adam
15 * Changed code so that it compiles as C++.
17 * Revision 1.61 1998/02/10 11:03:06 adam
18 * Implemented command refid. Client prints reference-ID's, when present,
21 * Revision 1.60 1998/01/29 14:08:52 adam
22 * Better sort diagnostics.
24 * Revision 1.59 1998/01/29 13:17:56 adam
27 * Revision 1.58 1998/01/07 13:51:45 adam
30 * Revision 1.57 1998/01/07 12:58:22 adam
31 * Using fgets instead of gets.
33 * Revision 1.56 1997/11/05 09:18:31 adam
34 * The client handles records with no associated syntax.
36 * Revision 1.55 1997/10/31 12:20:08 adam
37 * Improved memory debugging for xmalloc/nmem.c. References to NMEM
38 * instead of ODR in n ESPEC-1 handling in source d1_espec.c.
39 * Bug fix: missing fclose in data1_read_espec1.
41 * Revision 1.54 1997/10/27 13:52:46 adam
42 * Header yaz-util includes all YAZ utility header files.
44 * Revision 1.53 1997/09/29 13:18:59 adam
45 * Added function, oid_ent_to_oid, to replace the function
46 * oid_getoidbyent, which is not thread safe.
48 * Revision 1.52 1997/09/29 07:20:31 adam
49 * Client code uses nmem_init.
51 * Revision 1.51 1997/09/26 09:41:55 adam
52 * Updated client to handle multiple diagnostics.
54 * Revision 1.50 1997/09/17 12:10:29 adam
57 * Revision 1.49 1997/09/04 13:45:17 adam
58 * Added UNImarc to list of available syntaxes.
60 * Revision 1.48 1997/09/01 08:48:44 adam
61 * New windows NT/95 port using MSV5.0. Only a few changes made
62 * to avoid warnings. Sub project created: client.dsp.
64 * Revision 1.47 1997/07/01 13:49:56 adam
65 * Take care of case when invalid target is specified on command line.
67 * Revision 1.46 1997/06/23 10:30:18 adam
68 * Added call to ccl_rpn_delete in search. Added ODR stream "out"
69 * as parameter to ccl_rpn_query to release RPN query.
71 * Revision 1.45 1997/05/14 06:53:29 adam
74 * Revision 1.44 1997/05/05 11:20:35 adam
75 * Client uses "options" utility and marc dump filename may be specified
76 * as an option (-m <file>).
78 * Revision 1.43 1996/11/08 11:03:26 adam
79 * Client accepts multiple database names.
81 * Revision 1.42 1996/10/08 10:44:57 quinn
84 * Revision 1.41 1996/10/07 15:29:03 quinn
87 * Revision 1.40 1996/08/29 14:19:34 quinn
88 * Fixed conflict (CVS)
90 * Revision 1.39 1996/08/27 10:43:22 quinn
91 * Made select() optional
93 * Revision 1.38 1996/08/12 14:09:11 adam
94 * Default prefix query attribute set defined by using p_query_attset.
96 * Revision 1.37 1996/07/06 19:58:29 quinn
97 * System headerfiles gathered in yconfig
99 * Revision 1.36 1996/06/10 08:53:47 quinn
102 * Revision 1.35 1996/06/03 09:45:50 quinn
103 * Added display of OIDs in the GRS routine.
105 * Revision 1.34 1996/05/09 07:26:49 quinn
106 * *** empty log message ***
108 * Revision 1.33 1996/05/09 07:25:22 quinn
111 * Revision 1.32 1996/03/15 11:05:33 adam
112 * The user can set the preferred query type (prefix, ccl, ..) with the
115 * Revision 1.31 1996/02/20 12:51:54 quinn
116 * Fixed problems with EXTERNAL.
118 * Revision 1.30 1996/02/12 18:18:09 quinn
121 * Revision 1.29 1996/01/02 08:57:25 quinn
122 * Changed enums in the ASN.1 .h files to #defines. Changed oident.class to oclass
124 * Revision 1.28 1995/12/14 11:09:31 quinn
125 * Added Explain record syntax to the format command.
127 * Revision 1.27 1995/12/12 16:37:02 quinn
128 * Added destroy element to data1_node.
130 * Revision 1.26 1995/12/12 14:11:00 quinn
133 * Revision 1.25 1995/11/13 09:27:22 quinn
134 * Fiddling with the variant stuff.
136 * Revision 1.24 1995/10/30 12:41:13 quinn
137 * Added hostname lookup for server.
139 * Revision 1.23 1995/10/18 16:12:30 quinn
140 * Better diagnostics.
142 * Revision 1.22 1995/10/11 14:49:12 quinn
145 * Revision 1.21 1995/09/29 17:01:47 quinn
148 * Revision 1.20 1995/08/29 14:24:13 quinn
149 * Added second half of close-handshake
151 * Revision 1.19 1995/08/29 11:17:28 quinn
152 * Added code to receive close
154 * Revision 1.18 1995/08/28 12:21:27 quinn
155 * Client can now ask for simple element set names.
157 * Revision 1.17 1995/08/17 12:45:02 quinn
158 * Fixed minor problems with GRS-1. Added support in c&s.
160 * Revision 1.16 1995/08/15 12:00:04 quinn
163 * Revision 1.15 1995/06/22 09:28:03 quinn
164 * Fixed bug in SUTRS processing.
166 * Revision 1.14 1995/06/19 12:37:41 quinn
169 * Revision 1.13 1995/06/16 10:29:11 quinn
170 * *** empty log message ***
172 * Revision 1.12 1995/06/15 07:44:57 quinn
175 * Revision 1.11 1995/06/14 15:26:40 quinn
176 * *** empty log message ***
178 * Revision 1.10 1995/06/06 14:56:58 quinn
179 * Better diagnostics.
181 * Revision 1.9 1995/06/06 08:15:19 quinn
184 * Revision 1.8 1995/06/05 10:52:22 quinn
187 * Revision 1.7 1995/06/02 09:50:09 quinn
190 * Revision 1.6 1995/05/31 08:29:21 quinn
191 * Nothing significant.
193 * Revision 1.5 1995/05/29 08:10:47 quinn
194 * Moved oid.c to util.
196 * Revision 1.4 1995/05/22 15:30:13 adam
197 * Client uses prefix query notation.
199 * Revision 1.3 1995/05/22 15:06:53 quinn
200 * *** empty log message ***
202 * Revision 1.2 1995/05/22 14:56:40 quinn
203 * *** empty log message ***
205 * Revision 1.1 1995/05/22 11:30:31 quinn
206 * Added prettier client.
212 * This is the obligatory little toy client, whose primary purpose is
213 * to illustrate the use of the YAZ service-level API.
221 #include <yaz-util.h>
223 #include <comstack.h>
230 #include <marcdisp.h>
231 #include <diagbib1.h>
239 #define C_PROMPT "Z> "
241 static ODR out, in, print; /* encoding and decoding streams */
242 static COMSTACK conn = 0; /* our z-association */
243 static Z_IdAuthentication *auth = 0; /* our current auth definition */
244 static char *databaseNames[128];
245 static int num_databaseNames = 0;
246 static int setnumber = 0; /* current result set number */
247 static int smallSetUpperBound = 0;
248 static int largeSetLowerBound = 1;
249 static int mediumSetPresentNumber = 0;
250 static Z_ElementSetNames *elementSetNames = 0;
251 static int setno = 1; /* current set offset */
252 static int protocol = PROTO_Z3950; /* current app protocol */
253 static int recordsyntax = VAL_USMARC;
254 static int sent_close = 0;
255 static ODR_MEM session_mem; /* memory handle for init-response */
256 static Z_InitResponse *session = 0; /* session parameters */
257 static char last_scan[512] = "0";
258 static char last_cmd[100] = "?";
259 static FILE *marcdump = 0;
260 static char *refid = NULL;
268 static QueryType queryType = QueryType_Prefix;
271 static CCL_bibset bibset; /* CCL bibset handle */
274 static void send_apdu(Z_APDU *a)
279 if (!z_APDU(out, &a, 0))
281 odr_perror(out, "Encoding APDU");
284 buf = odr_getbuf(out, &len, 0);
285 if (cs_put(conn, buf, len) < 0)
287 fprintf(stderr, "cs_put: %s", cs_errmsg(cs_errno(conn)));
290 odr_reset(out); /* release the APDU structure */
293 static void print_refid (Z_ReferenceId *id)
297 printf ("ReferenceId: '%.*s'\n", id->len, id->buf);
301 static Z_ReferenceId *set_refid (ODR out)
306 id = (Z_ReferenceId *) odr_malloc (out, sizeof(*id));
307 id->size = id->len = strlen(refid);
308 id->buf = (unsigned char *) odr_malloc (out, id->len);
309 memcpy (id->buf, refid, id->len);
313 /* INIT SERVICE ------------------------------- */
315 static void send_initRequest()
317 Z_APDU *apdu = zget_APDU(out, Z_APDU_initRequest);
318 Z_InitRequest *req = apdu->u.initRequest;
320 ODR_MASK_SET(req->options, Z_Options_search);
321 ODR_MASK_SET(req->options, Z_Options_present);
322 ODR_MASK_SET(req->options, Z_Options_namedResultSets);
323 ODR_MASK_SET(req->options, Z_Options_triggerResourceCtrl);
324 ODR_MASK_SET(req->options, Z_Options_scan);
325 ODR_MASK_SET(req->options, Z_Options_sort);
326 ODR_MASK_SET(req->options, Z_Options_extendedServices);
328 ODR_MASK_SET(req->protocolVersion, Z_ProtocolVersion_1);
329 ODR_MASK_SET(req->protocolVersion, Z_ProtocolVersion_2);
330 ODR_MASK_SET(req->protocolVersion, Z_ProtocolVersion_3);
332 *req->maximumRecordSize = 1024*1024;
334 req->idAuthentication = auth;
337 printf("Sent initrequest.\n");
340 static int process_initResponse(Z_InitResponse *res)
342 /* save session parameters for later use */
343 session_mem = odr_extract_mem(in);
347 printf("Connection rejected by target.\n");
349 printf("Connection accepted by target.\n");
350 if (res->implementationId)
351 printf("ID : %s\n", res->implementationId);
352 if (res->implementationName)
353 printf("Name : %s\n", res->implementationName);
354 if (res->implementationVersion)
355 printf("Version: %s\n", res->implementationVersion);
356 if (res->userInformationField)
358 printf("UserInformationfield:\n");
359 if (!z_External(print, (Z_External**)&res-> userInformationField,
362 odr_perror(print, "Printing userinfo\n");
365 if (res->userInformationField->which == Z_External_octet)
367 printf("Guessing visiblestring:\n");
368 printf("'%s'\n", res->userInformationField->u. octet_aligned->buf);
374 int cmd_open(char *arg)
377 char type[100], addr[100];
382 printf("Already connected.\n");
385 if (!*arg || sscanf(arg, "%[^:]:%s", type, addr) < 2)
387 fprintf(stderr, "Usage: open (osi|tcp) ':' [tsel '/']host[':'port]\n");
390 if (!strcmp(type, "tcp"))
393 protocol = PROTO_Z3950;
397 if (!strcmp(type, "osi"))
405 fprintf(stderr, "Bad type: %s\n", type);
408 if (!(conn = cs_create(t, 1, protocol)))
413 if (!(add = cs_straddr(conn, addr)))
418 printf("Connecting...");
420 if (cs_connect(conn, add) < 0)
432 int cmd_authentication(char *arg)
434 static Z_IdAuthentication au;
435 static char open[256];
439 printf("Auth field set to null\n");
444 au.which = Z_IdAuthentication_open;
450 /* SEARCH SERVICE ------------------------------ */
452 static void display_variant(Z_Variant *v, int level)
456 for (i = 0; i < v->num_triples; i++)
458 printf("%*sclass=%d,type=%d", level * 4, "", *v->triples[i]->zclass,
459 *v->triples[i]->type);
460 if (v->triples[i]->which == Z_Triple_internationalString)
461 printf(",value=%s\n", v->triples[i]->value.internationalString);
467 static void display_grs1(Z_GenericRecord *r, int level)
473 for (i = 0; i < r->num_elements; i++)
477 printf("%*s", level * 4, "");
481 printf("%d,", *t->tagType);
484 if (t->tagValue->which == Z_StringOrNumeric_numeric)
485 printf("%d) ", *t->tagValue->u.numeric);
487 printf("%s) ", t->tagValue->u.string);
488 if (t->content->which == Z_ElementData_subtree)
491 display_grs1(t->content->u.subtree, level+1);
493 else if (t->content->which == Z_ElementData_string)
494 printf("%s\n", t->content->u.string);
495 else if (t->content->which == Z_ElementData_numeric)
496 printf("%d\n", *t->content->u.numeric);
497 else if (t->content->which == Z_ElementData_oid)
499 int *ip = t->content->u.oid;
502 if ((oent = oid_getentbyoid(t->content->u.oid)))
503 printf("OID: %s\n", oent->desc);
507 while (ip && *ip >= 0)
508 printf(" %d", *(ip++));
512 else if (t->content->which == Z_ElementData_noDataRequested)
513 printf("[No data requested]\n");
514 else if (t->content->which == Z_ElementData_elementEmpty)
515 printf("[Element empty]\n");
516 else if (t->content->which == Z_ElementData_elementNotThere)
517 printf("[Element not there]\n");
520 if (t->appliedVariant)
521 display_variant(t->appliedVariant, level+1);
522 if (t->metaData && t->metaData->supportedVariants)
526 printf("%*s---- variant list\n", (level+1)*4, "");
527 for (c = 0; c < t->metaData->num_supportedVariants; c++)
529 printf("%*svariant #%d\n", (level+1)*4, "", c);
530 display_variant(t->metaData->supportedVariants[c], level + 2);
536 static void display_record(Z_DatabaseRecord *p)
538 Z_External *r = (Z_External*) p;
539 oident *ent = oid_getentbyoid(r->direct_reference);
542 * Tell the user what we got.
544 if (r->direct_reference)
546 printf("Record type: ");
548 printf("%s\n", ent->desc);
549 else if (!odr_oid(print, &r->direct_reference, 0))
551 odr_perror(print, "print oid");
555 /* Check if this is a known, ASN.1 type tucked away in an octet string */
556 if (ent && r->which == Z_External_octet)
558 Z_ext_typeent *type = z_ext_getentbyref(ent->value);
564 * Call the given decoder to process the record.
566 odr_setbuf(in, (char*)p->u.octet_aligned->buf,
567 p->u.octet_aligned->len, 0);
568 if (!(*type->fun)(in, (char **)&rr, 0))
570 odr_perror(in, "Decoding constructed record.");
571 fprintf(stderr, "[Near %d]\n", odr_offset(in));
572 fprintf(stderr, "Packet dump:\n---------\n");
573 odr_dumpBER(stderr, (char*)p->u.octet_aligned->buf,
574 p->u.octet_aligned->len);
575 fprintf(stderr, "---------\n");
579 * Note: we throw away the original, BER-encoded record here.
580 * Do something else with it if you want to keep it.
582 r->u.sutrs = (Odr_oct *)rr; /* we don't actually check the type here. */
583 r->which = type->what;
586 if (ent && ent->value == VAL_SOIF)
587 printf("%.*s", r->u.octet_aligned->len, r->u.octet_aligned->buf);
588 else if (r->which == Z_External_octet && p->u.octet_aligned->len)
590 const char *marc_buf = (char*)p->u.octet_aligned->buf;
591 marc_display (marc_buf, NULL);
593 fwrite (marc_buf, strlen (marc_buf), 1, marcdump);
595 else if (ent && ent->value == VAL_SUTRS)
597 if (r->which != Z_External_sutrs)
599 printf("Expecting single SUTRS type for SUTRS.\n");
602 printf("%.*s", r->u.sutrs->len, r->u.sutrs->buf);
604 else if (ent && ent->value == VAL_GRS1)
606 if (r->which != Z_External_grs1)
608 printf("Expecting single GRS type for GRS.\n");
611 display_grs1(r->u.grs1, 0);
615 printf("Unknown record representation.\n");
616 if (!z_External(print, &r, 0))
618 odr_perror(print, "Printing external");
625 static void display_diagrecs(Z_DiagRec **pp, int num)
629 Z_DefaultDiagFormat *r;
631 printf("Diagnostic message(s) from database:\n");
632 for (i = 0; i<num; i++)
634 Z_DiagRec *p = pp[i];
635 if (p->which != Z_DiagRec_defaultFormat)
637 printf("Diagnostic record not in default format.\n");
641 r = p->u.defaultFormat;
642 if (!(ent = oid_getentbyoid(r->diagnosticSetId)) ||
643 ent->oclass != CLASS_DIAGSET || ent->value != VAL_BIB1)
644 printf("Missing or unknown diagset\n");
645 printf(" [%d] %s", *r->condition, diagbib1_str(*r->condition));
646 if (r->addinfo && *r->addinfo)
647 printf(" -- '%s'\n", r->addinfo);
654 static void display_nameplusrecord(Z_NamePlusRecord *p)
657 printf("[%s]", p->databaseName);
658 if (p->which == Z_NamePlusRecord_surrogateDiagnostic)
659 display_diagrecs(&p->u.surrogateDiagnostic, 1);
661 display_record(p->u.databaseRecord);
664 static void display_records(Z_Records *p)
668 if (p->which == Z_Records_NSD)
669 display_diagrecs (&p->u.nonSurrogateDiagnostic, 1);
670 else if (p->which == Z_Records_multipleNSD)
671 display_diagrecs (p->u.multipleNonSurDiagnostics->diagRecs,
672 p->u.multipleNonSurDiagnostics->num_diagRecs);
675 printf("Records: %d\n", p->u.databaseOrSurDiagnostics->num_records);
676 for (i = 0; i < p->u.databaseOrSurDiagnostics->num_records; i++)
677 display_nameplusrecord(p->u.databaseOrSurDiagnostics->records[i]);
681 static int send_searchRequest(char *arg)
683 Z_APDU *apdu = zget_APDU(out, Z_APDU_searchRequest);
684 Z_SearchRequest *req = apdu->u.searchRequest;
688 struct ccl_rpn_node *rpn;
693 Z_RPNQuery *RPNquery;
697 if (queryType == QueryType_CCL2RPN)
699 rpn = ccl_find_str(bibset, arg, &error, &pos);
702 printf("CCL ERROR: %s\n", ccl_err_msg(error));
707 req->referenceId = set_refid (out);
708 if (!strcmp(arg, "@big")) /* strictly for troublemaking */
710 static unsigned char big[2100];
713 /* send a very big referenceid to test transport stack etc. */
714 memset(big, 'A', 2100);
715 bigo.len = bigo.size = 2100;
717 req->referenceId = &bigo;
722 sprintf(setstring, "%d", ++setnumber);
723 req->resultSetName = setstring;
725 *req->smallSetUpperBound = smallSetUpperBound;
726 *req->largeSetLowerBound = largeSetLowerBound;
727 *req->mediumSetPresentNumber = mediumSetPresentNumber;
728 if (smallSetUpperBound > 0 || (largeSetLowerBound > 1 &&
729 mediumSetPresentNumber > 0))
733 prefsyn.proto = protocol;
734 prefsyn.oclass = CLASS_RECSYN;
735 prefsyn.value = recordsyntax;
736 req->preferredRecordSyntax =
737 odr_oiddup(out, oid_ent_to_oid(&prefsyn, oid));
738 req->smallSetElementSetNames =
739 req->mediumSetElementSetNames = elementSetNames;
741 req->num_databaseNames = num_databaseNames;
742 req->databaseNames = databaseNames;
748 case QueryType_Prefix:
749 query.which = Z_Query_type_1;
750 RPNquery = p_query_rpn (out, protocol, arg);
753 printf("Prefix query error\n");
756 query.u.type_1 = RPNquery;
759 query.which = Z_Query_type_2;
760 query.u.type_2 = &ccl_query;
761 ccl_query.buf = (unsigned char*) arg;
762 ccl_query.len = strlen(arg);
765 case QueryType_CCL2RPN:
766 query.which = Z_Query_type_1;
767 assert((RPNquery = ccl_rpn_query(out, rpn)));
768 bib1.proto = protocol;
769 bib1.oclass = CLASS_ATTSET;
770 bib1.value = VAL_BIB1;
771 RPNquery->attributeSetId = oid_ent_to_oid(&bib1, oid);
772 query.u.type_1 = RPNquery;
773 ccl_rpn_delete (rpn);
777 printf ("Unsupported query type\n");
782 printf("Sent searchRequest.\n");
786 static int process_searchResponse(Z_SearchResponse *res)
788 printf ("Received SearchResponse.\n");
789 print_refid (res->referenceId);
790 if (*res->searchStatus)
791 printf("Search was a success.\n");
793 printf("Search was a bloomin' failure.\n");
794 printf("Number of hits: %d, setno %d\n",
795 *res->resultCount, setnumber);
796 printf("records returned: %d\n",
797 *res->numberOfRecordsReturned);
798 setno += *res->numberOfRecordsReturned;
800 display_records(res->records);
804 static void print_level(int iLevel)
807 for (i = 0; i < iLevel * 4; i++)
811 static void print_int(int iLevel, const char *pTag, int *pInt)
816 printf("%s: %d\n", pTag, *pInt);
820 static void print_string(int iLevel, const char *pTag, const char *pString)
825 printf("%s: %s\n", pTag, pString);
829 static void print_oid(int iLevel, const char *pTag, Odr_oid *pOid)
837 for (; *pInt != -1; pInt++)
838 printf(" %d", *pInt);
843 static void print_referenceId(int iLevel, Z_ReferenceId *referenceId)
845 if (referenceId != NULL)
850 printf("Ref Id (%d, %d): ", referenceId->len, referenceId->size);
851 for (i = 0; i < referenceId->len; i++)
852 printf("%c", referenceId->buf[i]);
857 static void print_string_or_numeric(int iLevel, const char *pTag, Z_StringOrNumeric *pStringNumeric)
859 if (pStringNumeric != NULL)
861 switch (pStringNumeric->which)
863 case Z_StringOrNumeric_string:
864 print_string(iLevel, pTag, pStringNumeric->u.string);
867 case Z_StringOrNumeric_numeric:
868 print_int(iLevel, pTag, pStringNumeric->u.numeric);
873 printf("%s: valid type for Z_StringOrNumeric\n", pTag);
879 static void print_universe_report_duplicate(int iLevel, Z_UniverseReportDuplicate *pUniverseReportDuplicate)
881 if (pUniverseReportDuplicate != NULL)
884 printf("Universe Report Duplicate: \n");
886 print_string_or_numeric(iLevel, "Hit No", pUniverseReportDuplicate->hitno);
890 static void print_universe_report_hits(int iLevel, Z_UniverseReportHits *pUniverseReportHits)
892 if (pUniverseReportHits != NULL)
895 printf("Universe Report Hits: \n");
897 print_string_or_numeric(iLevel, "Database", pUniverseReportHits->database);
898 print_string_or_numeric(iLevel, "Hits", pUniverseReportHits->hits);
902 static void print_universe_report(int iLevel, Z_UniverseReport *pUniverseReport)
904 if (pUniverseReport != NULL)
907 printf("Universe Report: \n");
909 print_int(iLevel, "Total Hits", pUniverseReport->totalHits);
910 switch (pUniverseReport->which)
912 case Z_UniverseReport_databaseHits:
913 print_universe_report_hits(iLevel, pUniverseReport->u.databaseHits);
916 case Z_UniverseReport_duplicate:
917 print_universe_report_duplicate(iLevel, pUniverseReport->u.duplicate);
922 printf("Type: %d\n", pUniverseReport->which);
928 static void print_external(int iLevel, Z_External *pExternal)
930 if (pExternal != NULL)
933 printf("External: \n");
935 print_oid(iLevel, "Direct Reference", pExternal->direct_reference);
936 print_int(iLevel, "InDirect Reference", pExternal->indirect_reference);
937 print_string(iLevel, "Descriptor", pExternal->descriptor);
938 switch (pExternal->which)
940 case Z_External_universeReport:
941 print_universe_report(iLevel, pExternal->u.universeReport);
946 printf("Type: %d\n", pExternal->which);
952 static int process_resourceControlRequest (Z_ResourceControlRequest *req)
954 printf ("Received ResourceControlRequest.\n");
955 print_referenceId(1, req->referenceId);
956 print_int(1, "Suspended Flag", req->suspendedFlag);
957 print_int(1, "Partial Results Available", req->partialResultsAvailable);
958 print_int(1, "Response Required", req->responseRequired);
959 print_int(1, "Triggered Request Flag", req->triggeredRequestFlag);
960 print_external(1, req->resourceReport);
964 void process_ESResponse(Z_ExtendedServicesResponse *res)
966 printf("process_ESResponse\n");
969 static Z_External *CreateItemOrderExternal(int itemno)
971 Z_External *r = odr_malloc(out, sizeof(Z_External));
972 oident ItemOrderRequest;
974 ItemOrderRequest.proto = PROTO_Z3950;
975 ItemOrderRequest.oclass = CLASS_EXTSERV;
976 ItemOrderRequest.value = VAL_ITEMORDER;
978 r->direct_reference = odr_oiddup(out,oid_getoidbyent(&ItemOrderRequest));
979 r->indirect_reference = odr_malloc(out,sizeof(int));
980 *r->indirect_reference = 0;
982 r->descriptor = "Extended services item order";
984 r->which = Z_External_itemOrder;
986 r->u.itemOrder = odr_malloc(out,sizeof(Z_ItemOrder));
987 memset(r->u.itemOrder, 0, sizeof(Z_ItemOrder));
988 r->u.itemOrder->which=Z_ItemOrder_esRequest;
990 r->u.itemOrder->u.esRequest = odr_malloc(out,sizeof(Z_IORequest));
991 memset(r->u.itemOrder->u.esRequest, 0, sizeof(Z_IORequest));
993 r->u.itemOrder->u.esRequest->toKeep = odr_malloc(out,sizeof(Z_IOOriginPartToKeep));
994 memset(r->u.itemOrder->u.esRequest->toKeep, 0, sizeof(Z_IOOriginPartToKeep));
995 r->u.itemOrder->u.esRequest->notToKeep = odr_malloc(out,sizeof(Z_IOOriginPartNotToKeep));
996 memset(r->u.itemOrder->u.esRequest->notToKeep, 0, sizeof(Z_IOOriginPartNotToKeep));
998 r->u.itemOrder->u.esRequest->toKeep->supplDescription = NULL;
999 r->u.itemOrder->u.esRequest->toKeep->contact = NULL;
1000 r->u.itemOrder->u.esRequest->toKeep->addlBilling = NULL;
1002 r->u.itemOrder->u.esRequest->notToKeep->resultSetItem = odr_malloc(out, sizeof(Z_IOResultSetItem));
1003 memset(r->u.itemOrder->u.esRequest->notToKeep->resultSetItem, 0, sizeof(Z_IOResultSetItem));
1004 r->u.itemOrder->u.esRequest->notToKeep->resultSetItem->resultSetId = "1";
1006 r->u.itemOrder->u.esRequest->notToKeep->resultSetItem->item = odr_malloc(out, sizeof(int));
1007 *r->u.itemOrder->u.esRequest->notToKeep->resultSetItem->item = itemno;
1009 r->u.itemOrder->u.esRequest->notToKeep->itemRequest = NULL;
1013 /* II : Added to do DALI Item Order Extended services request */
1014 static int send_itemorder(char *arg)
1017 Z_APDU *apdu = zget_APDU(out, Z_APDU_extendedServicesRequest );
1018 Z_ExtendedServicesRequest *req = apdu->u.extendedServicesRequest;
1019 oident ItemOrderRequest;
1024 /* Set up item order request */
1026 /* Function being performed by this extended services request */
1027 req->function = odr_malloc(out, sizeof(int));
1028 *req->function = Z_ExtendedServicesRequest_create;
1030 /* Package type, Using protocol ILL ( But that's not in the oid.h file yet */
1031 /* create an object of class Extended Service, value Item Order */
1032 ItemOrderRequest.proto = PROTO_Z3950;
1033 ItemOrderRequest.oclass = CLASS_EXTSERV;
1034 ItemOrderRequest.value = VAL_ITEMORDER;
1035 req->packageType = odr_oiddup(out,oid_getoidbyent(&ItemOrderRequest));
1036 req->packageName = "1.Extendedserveq";
1038 /* ** taskSpecificParameters ** */
1039 req->taskSpecificParameters = CreateItemOrderExternal(itemno);
1041 /* waitAction - Create the ILL request and that's it */
1042 *req->waitAction = Z_ExtendedServicesRequest_wait;
1048 /* II : Added to do DALI Item Order Extended services request */
1049 static int cmd_itemorder(char *arg)
1051 printf("Item order request\n");
1054 send_itemorder(arg);
1058 static int cmd_find(char *arg)
1062 printf("Find what?\n");
1067 printf("Not connected yet\n");
1070 if (!send_searchRequest(arg))
1075 static int cmd_ssub(char *arg)
1077 if (!(smallSetUpperBound = atoi(arg)))
1082 static int cmd_lslb(char *arg)
1084 if (!(largeSetLowerBound = atoi(arg)))
1089 static int cmd_mspn(char *arg)
1091 if (!(mediumSetPresentNumber = atoi(arg)))
1096 static int cmd_status(char *arg)
1098 printf("smallSetUpperBound: %d\n", smallSetUpperBound);
1099 printf("largeSetLowerBound: %d\n", largeSetLowerBound);
1100 printf("mediumSetPresentNumber: %d\n", mediumSetPresentNumber);
1104 static int cmd_base(char *arg)
1111 printf("Usage: base <database> <database> ...\n");
1114 for (i = 0; i<num_databaseNames; i++)
1115 xfree (databaseNames[i]);
1116 num_databaseNames = 0;
1119 if (!(cp = strchr(arg, ' ')))
1120 cp = arg + strlen(arg);
1123 databaseNames[num_databaseNames] = (char *)xmalloc (1 + cp - arg);
1124 memcpy (databaseNames[num_databaseNames], arg, cp - arg);
1125 databaseNames[num_databaseNames++][cp - arg] = '\0';
1133 static int cmd_setnames(char *arg)
1137 printf("Set numbering enabled.\n");
1142 printf("Set numbering disabled.\n");
1148 /* PRESENT SERVICE ----------------------------- */
1150 static int send_presentRequest(char *arg)
1152 Z_APDU *apdu = zget_APDU(out, Z_APDU_presentRequest);
1153 Z_PresentRequest *req = apdu->u.presentRequest;
1154 Z_RecordComposition compo;
1159 char setstring[100];
1161 req->referenceId = set_refid (out);
1162 if ((p = strchr(arg, '+')))
1169 if (p && (p=strchr(p+1, '+')))
1171 strcpy (setstring, p+1);
1172 req->resultSetId = setstring;
1174 else if (setnumber >= 0)
1176 sprintf(setstring, "%d", setnumber);
1177 req->resultSetId = setstring;
1182 static Z_Range range;
1183 static Z_Range *rangep = ⦥
1184 req->num_ranges = 1;
1186 req->resultSetStartPoint = &setno;
1187 req->numberOfRecordsRequested = &nos;
1188 prefsyn.proto = protocol;
1189 prefsyn.oclass = CLASS_RECSYN;
1190 prefsyn.value = recordsyntax;
1191 req->preferredRecordSyntax = oid_ent_to_oid(&prefsyn, oid);
1193 if (elementSetNames)
1195 req->recordComposition = &compo;
1196 compo.which = Z_RecordComp_simple;
1197 compo.u.simple = elementSetNames;
1200 printf("Sent presentRequest (%d+%d).\n", setno, nos);
1204 void process_close(Z_Close *req)
1206 Z_APDU *apdu = zget_APDU(out, Z_APDU_close);
1207 Z_Close *res = apdu->u.close;
1209 static char *reasons[] =
1214 "cost limit reached",
1216 "security violation",
1223 printf("Reason: %s, message: %s\n", reasons[*req->closeReason],
1224 req->diagnosticInformation ? req->diagnosticInformation : "NULL");
1227 printf("Goodbye.\n");
1230 *res->closeReason = Z_Close_finished;
1232 printf("Sent response.\n");
1236 static int cmd_show(char *arg)
1238 if (!send_presentRequest(arg))
1243 int cmd_quit(char *arg)
1245 printf("See you later, alligator.\n");
1250 int cmd_cancel(char *arg)
1252 Z_APDU *apdu = zget_APDU(out, Z_APDU_triggerResourceControlRequest);
1253 Z_TriggerResourceControlRequest *req =
1254 apdu->u.triggerResourceControlRequest;
1259 printf("Session not initialized yet\n");
1262 if (!ODR_MASK_GET(session->options, Z_Options_triggerResourceCtrl))
1264 printf("Target doesn't support cancel (trigger resource ctrl)\n");
1267 *req->requestedAction = Z_TriggerResourceCtrl_cancel;
1268 req->resultSetWanted = &rfalse;
1271 printf("Sent cancel request\n");
1275 int send_scanrequest(char *string, int pp, int num)
1277 Z_APDU *apdu = zget_APDU(out, Z_APDU_scanRequest);
1278 Z_ScanRequest *req = apdu->u.scanRequest;
1280 req->referenceId = set_refid (out);
1281 req->num_databaseNames = num_databaseNames;
1282 req->databaseNames = databaseNames;
1283 req->termListAndStartPoint = p_query_scan(out, protocol,
1284 &req->attributeSet, string);
1285 req->numberOfTermsRequested = #
1286 req->preferredPositionInResponse = &pp;
1291 int send_sortrequest(char *arg, int newset)
1293 Z_APDU *apdu = zget_APDU(out, Z_APDU_sortRequest);
1294 Z_SortRequest *req = apdu->u.sortRequest;
1295 Z_SortKeySpecList *sksl = (Z_SortKeySpecList *)odr_malloc (out, sizeof(*sksl));
1297 char sort_string[32], sort_flags[32];
1303 sprintf (setstring, "%d", setnumber);
1305 sprintf (setstring, "default");
1307 req->referenceId = set_refid (out);
1309 req->inputResultSetNames =
1310 (Z_StringList *)odr_malloc (out, sizeof(*req->inputResultSetNames));
1311 req->inputResultSetNames->num_strings = 1;
1312 req->inputResultSetNames->strings =
1313 (char **)odr_malloc (out, sizeof(*req->inputResultSetNames->strings));
1314 req->inputResultSetNames->strings[0] =
1315 (char *)odr_malloc (out, strlen(setstring)+1);
1316 strcpy (req->inputResultSetNames->strings[0], setstring);
1318 if (newset && setnumber >= 0)
1319 sprintf (setstring, "%d", ++setnumber);
1321 req->sortedResultSetName = (char *)odr_malloc (out, strlen(setstring)+1);
1322 strcpy (req->sortedResultSetName, setstring);
1324 req->sortSequence = sksl;
1325 sksl->num_specs = 0;
1326 sksl->specs = (Z_SortKeySpec **)odr_malloc (out, sizeof(sksl->specs) * 20);
1328 bib1.proto = protocol;
1329 bib1.oclass = CLASS_ATTSET;
1330 bib1.value = VAL_BIB1;
1331 while ((sscanf (arg, "%31s %31s%n", sort_string, sort_flags, &off)) == 2
1335 char *sort_string_sep;
1336 Z_SortKeySpec *sks = (Z_SortKeySpec *)odr_malloc (out, sizeof(*sks));
1337 Z_SortKey *sk = (Z_SortKey *)odr_malloc (out, sizeof(*sk));
1340 sksl->specs[sksl->num_specs++] = sks;
1341 sks->sortElement = (Z_SortElement *)odr_malloc (out, sizeof(*sks->sortElement));
1342 sks->sortElement->which = Z_SortElement_generic;
1343 sks->sortElement->u.generic = sk;
1345 if ((sort_string_sep = strchr (sort_string, '=')))
1347 Z_AttributeElement *el = (Z_AttributeElement *)odr_malloc (out, sizeof(*el));
1348 sk->which = Z_SortKey_sortAttributes;
1349 sk->u.sortAttributes =
1350 (Z_SortAttributes *)odr_malloc (out, sizeof(*sk->u.sortAttributes));
1351 sk->u.sortAttributes->id = oid_ent_to_oid(&bib1, oid);
1352 sk->u.sortAttributes->list =
1353 (Z_AttributeList *)odr_malloc (out, sizeof(*sk->u.sortAttributes->list));
1354 sk->u.sortAttributes->list->num_attributes = 1;
1355 sk->u.sortAttributes->list->attributes =
1356 (Z_AttributeElement **)odr_malloc (out,
1357 sizeof(*sk->u.sortAttributes->list->attributes));
1358 sk->u.sortAttributes->list->attributes[0] = el;
1359 el->attributeSet = 0;
1360 el->attributeType = (int *)odr_malloc (out, sizeof(*el->attributeType));
1361 *el->attributeType = atoi (sort_string);
1362 el->which = Z_AttributeValue_numeric;
1363 el->value.numeric = (int *)odr_malloc (out, sizeof(*el->value.numeric));
1364 *el->value.numeric = atoi (sort_string_sep + 1);
1368 sk->which = Z_SortKey_sortField;
1369 sk->u.sortField = (char *)odr_malloc (out, strlen(sort_string)+1);
1370 strcpy (sk->u.sortField, sort_string);
1372 sks->sortRelation = (int *)odr_malloc (out, sizeof(*sks->sortRelation));
1373 *sks->sortRelation = Z_SortRelation_ascending;
1374 sks->caseSensitivity = (int *)odr_malloc (out, sizeof(*sks->caseSensitivity));
1375 *sks->caseSensitivity = Z_SortCase_caseSensitive;
1377 sks->missingValueAction = NULL;
1379 for (i = 0; sort_flags[i]; i++)
1381 switch (sort_flags[i])
1386 *sks->sortRelation = Z_SortRelation_ascending;
1391 *sks->sortRelation = Z_SortRelation_descending;
1395 *sks->caseSensitivity = Z_SortCase_caseInsensitive;
1399 *sks->caseSensitivity = Z_SortCase_caseSensitive;
1404 if (!sksl->num_specs)
1406 printf ("Missing sort specifications\n");
1413 void display_term(Z_TermInfo *t)
1415 if (t->term->which == Z_Term_general)
1417 printf("%.*s (%d)\n", t->term->u.general->len, t->term->u.general->buf,
1418 t->globalOccurrences ? *t->globalOccurrences : -1);
1419 sprintf(last_scan, "%.*s", t->term->u.general->len,
1420 t->term->u.general->buf);
1423 printf("Term type not general.\n");
1426 void process_scanResponse(Z_ScanResponse *res)
1430 printf("Received ScanResponse\n");
1431 print_refid (res->referenceId);
1432 printf("%d entries", *res->numberOfEntriesReturned);
1433 if (res->positionOfTerm)
1434 printf (", position=%d", *res->positionOfTerm);
1436 if (*res->scanStatus != Z_Scan_success)
1437 printf("Scan returned code %d\n", *res->scanStatus);
1440 if (res->entries->which == Z_ListEntries_entries)
1442 Z_Entries *ent = res->entries->u.entries;
1444 for (i = 0; i < ent->num_entries; i++)
1445 if (ent->entries[i]->which == Z_Entry_termInfo)
1447 printf("%c ", i + 1 == *res->positionOfTerm ? '*' : ' ');
1448 display_term(ent->entries[i]->u.termInfo);
1451 display_diagrecs(&ent->entries[i]->u.surrogateDiagnostic, 1);
1454 display_diagrecs(&res->entries->
1455 u.nonSurrogateDiagnostics->diagRecs[0], 1);
1458 void process_sortResponse(Z_SortResponse *res)
1460 printf("Received SortResponse: status=");
1461 switch (*res->sortStatus)
1463 case Z_SortStatus_success:
1464 printf ("success"); break;
1465 case Z_SortStatus_partial_1:
1466 printf ("partial"); break;
1467 case Z_SortStatus_failure:
1468 printf ("failure"); break;
1470 printf ("unknown (%d)", *res->sortStatus);
1473 print_refid (res->referenceId);
1474 if (res->diagnostics)
1475 display_diagrecs(res->diagnostics->diagRecs,
1476 res->diagnostics->num_diagRecs);
1479 int cmd_sort_generic(char *arg, int newset)
1483 printf("Session not initialized yet\n");
1486 if (!ODR_MASK_GET(session->options, Z_Options_sort))
1488 printf("Target doesn't support sort\n");
1493 if (send_sortrequest(arg, newset) < 0)
1500 int cmd_sort(char *arg)
1502 return cmd_sort_generic (arg, 0);
1505 int cmd_sort_newset (char *arg)
1507 return cmd_sort_generic (arg, 1);
1510 int cmd_scan(char *arg)
1514 printf("Session not initialized yet\n");
1517 if (!ODR_MASK_GET(session->options, Z_Options_scan))
1519 printf("Target doesn't support scan\n");
1524 if (send_scanrequest(arg, 5, 20) < 0)
1528 if (send_scanrequest(last_scan, 1, 20) < 0)
1533 int cmd_format(char *arg)
1537 printf("Usage: format <recordsyntax>\n");
1540 recordsyntax = oid_getvalbyname (arg);
1541 if (recordsyntax == VAL_NONE)
1543 printf ("unknown record syntax\n");
1549 int cmd_elements(char *arg)
1551 static Z_ElementSetNames esn;
1552 static char what[100];
1556 printf("Usage: elements <esn>\n");
1560 esn.which = Z_ElementSetNames_generic;
1561 esn.u.generic = what;
1562 elementSetNames = &esn;
1566 int cmd_attributeset(char *arg)
1572 printf("Usage: attributeset <setname>\n");
1575 sscanf(arg, "%s", what);
1576 if (p_query_attset (what))
1578 printf("Unknown attribute set name\n");
1584 int cmd_querytype (char *arg)
1586 if (!strcmp (arg, "ccl"))
1587 queryType = QueryType_CCL;
1588 else if (!strcmp (arg, "prefix"))
1589 queryType = QueryType_Prefix;
1591 else if (!strcmp (arg, "ccl2rpn") || !strcmp (arg, "cclrpn"))
1592 queryType = QueryType_CCL2RPN;
1596 printf ("Querytype must be one of:\n");
1597 printf (" prefix - Prefix query\n");
1598 printf (" ccl - CCL query\n");
1600 printf (" ccl2rpn - CCL query converted to RPN\n");
1607 int cmd_refid (char *arg)
1613 refid = (char *) xmalloc (strlen(arg)+1);
1614 strcpy (refid, arg);
1619 int cmd_close(char *arg)
1621 Z_APDU *apdu = zget_APDU(out, Z_APDU_close);
1622 Z_Close *req = apdu->u.close;
1624 *req->closeReason = Z_Close_finished;
1626 printf("Sent close request.\n");
1631 static void initialize(void)
1637 if (!(out = odr_createmem(ODR_ENCODE)) ||
1638 !(in = odr_createmem(ODR_DECODE)) ||
1639 !(print = odr_createmem(ODR_PRINT)))
1641 fprintf(stderr, "failed to allocate ODR streams\n");
1644 setvbuf(stdout, 0, _IONBF, 0);
1647 bibset = ccl_qual_mk ();
1648 inf = fopen ("default.bib", "r");
1651 ccl_qual_file (bibset, inf);
1657 static int client(int wait)
1661 int (*fun)(char *arg);
1664 {"open", cmd_open, "('tcp'|'osi')':'[<tsel>'/']<host>[':'<port>]"},
1665 {"quit", cmd_quit, ""},
1666 {"find", cmd_find, "<query>"},
1667 {"base", cmd_base, "<base-name>"},
1668 {"show", cmd_show, "<rec#>['+'<#recs>['+'<setname>]]"},
1669 {"scan", cmd_scan, "<term>"},
1670 {"sort", cmd_sort, "<sortkey> <flag> <sortkey> <flag> ..."},
1671 {"sort+", cmd_sort_newset, "<sortkey> <flag> <sortkey> <flag> ..."},
1672 {"authentication", cmd_authentication, "<acctstring>"},
1673 {"lslb", cmd_lslb, "<largeSetLowerBound>"},
1674 {"ssub", cmd_ssub, "<smallSetUpperBound>"},
1675 {"mspn", cmd_mspn, "<mediumSetPresentNumber>"},
1676 {"status", cmd_status, ""},
1677 {"setnames", cmd_setnames, ""},
1678 {"cancel", cmd_cancel, ""},
1679 {"format", cmd_format, "<recordsyntax>"},
1680 {"elements", cmd_elements, "<elementSetName>"},
1681 {"close", cmd_close, ""},
1682 {"attributeset", cmd_attributeset, "<attrset>"},
1683 {"querytype", cmd_querytype, "<type>"},
1684 {"refid", cmd_refid, "<id>"},
1685 {"itemorder", cmd_itemorder, "<item>"},
1689 int netbufferlen = 0;
1699 char line[1024], word[1024], arg[1024];
1705 FD_SET(cs_fileno(conn), &input);
1706 if ((res = select(20, &input, 0, 0, 0)) < 0)
1713 if (!wait && FD_ISSET(0, &input))
1718 /* quick & dirty way to get a command line. */
1720 if (!fgets(line, 1023, stdin))
1722 if ((end_p = strchr (line, '\n')))
1724 if ((res = sscanf(line, "%s %[^;]", word, arg)) <= 0)
1726 strcpy(word, last_cmd);
1731 strcpy(last_cmd, word);
1732 for (i = 0; cmd[i].cmd; i++)
1733 if (!strncmp(cmd[i].cmd, word, strlen(word)))
1735 res = (*cmd[i].fun)(arg);
1738 if (!cmd[i].cmd) /* dump our help-screen */
1740 printf("Unknown command: %s.\n", word);
1741 printf("Currently recognized commands:\n");
1742 for (i = 0; cmd[i].cmd; i++)
1743 printf(" %s %s\n", cmd[i].cmd, cmd[i].ad);
1754 if (conn && FD_ISSET(cs_fileno(conn), &input))
1759 if ((res = cs_get(conn, &netbuffer, &netbufferlen)) < 0)
1766 printf("Target closed connection.\n");
1769 odr_reset(in); /* release APDU from last round */
1770 odr_setbuf(in, netbuffer, res, 0);
1771 if (!z_APDU(in, &apdu, 0))
1773 odr_perror(in, "Decoding incoming APDU");
1774 fprintf(stderr, "[Near %d]\n", odr_offset(in));
1775 fprintf(stderr, "Packet dump:\n---------\n");
1776 odr_dumpBER(stderr, netbuffer, res);
1777 fprintf(stderr, "---------\n");
1781 if (!z_APDU(print, &apdu, 0))
1783 odr_perror(print, "Failed to print incoming APDU");
1790 case Z_APDU_initResponse:
1791 process_initResponse(apdu->u.initResponse);
1793 case Z_APDU_searchResponse:
1794 process_searchResponse(apdu->u.searchResponse);
1796 case Z_APDU_scanResponse:
1797 process_scanResponse(apdu->u.scanResponse);
1799 case Z_APDU_presentResponse:
1800 print_refid (apdu->u.presentResponse->referenceId);
1802 *apdu->u.presentResponse->numberOfRecordsReturned;
1803 if (apdu->u.presentResponse->records)
1804 display_records(apdu->u.presentResponse->records);
1806 printf("No records.\n");
1808 case Z_APDU_sortResponse:
1809 process_sortResponse(apdu->u.sortResponse);
1811 case Z_APDU_extendedServicesResponse:
1812 printf("Got extended services response\n");
1813 process_ESResponse(apdu->u.extendedServicesResponse);
1816 printf("Target has closed the association.\n");
1817 process_close(apdu->u.close);
1819 case Z_APDU_resourceControlRequest:
1820 process_resourceControlRequest
1821 (apdu->u.resourceControlRequest);
1824 printf("Received unknown APDU type (%d).\n",
1829 while (cs_more(conn));
1837 int main(int argc, char **argv)
1845 cmd_base("Default");
1847 while ((ret = options("m:", argv, argc, &arg)) != -2)
1852 if (cmd_open (arg) == 2)
1856 if (!(marcdump = fopen (arg, "a")))
1863 fprintf (stderr, "Usage: %s [-m <marclog>] [<server-addr>]\n",
1870 return client (opened);