2 * Copyright (c) 1995, Index Data.
3 * See the file LICENSE for details.
4 * Sebastian Hammer, Adam Dickmeiss
7 * Revision 1.27 1995-12-12 16:37:02 quinn
8 * Added destroy element to data1_node.
10 * Revision 1.26 1995/12/12 14:11:00 quinn
13 * Revision 1.25 1995/11/13 09:27:22 quinn
14 * Fiddling with the variant stuff.
16 * Revision 1.24 1995/10/30 12:41:13 quinn
17 * Added hostname lookup for server.
19 * Revision 1.23 1995/10/18 16:12:30 quinn
22 * Revision 1.22 1995/10/11 14:49:12 quinn
25 * Revision 1.21 1995/09/29 17:01:47 quinn
28 * Revision 1.20 1995/08/29 14:24:13 quinn
29 * Added second half of close-handshake
31 * Revision 1.19 1995/08/29 11:17:28 quinn
32 * Added code to receive close
34 * Revision 1.18 1995/08/28 12:21:27 quinn
35 * Client can now ask for simple element set names.
37 * Revision 1.17 1995/08/17 12:45:02 quinn
38 * Fixed minor problems with GRS-1. Added support in c&s.
40 * Revision 1.16 1995/08/15 12:00:04 quinn
43 * Revision 1.15 1995/06/22 09:28:03 quinn
44 * Fixed bug in SUTRS processing.
46 * Revision 1.14 1995/06/19 12:37:41 quinn
49 * Revision 1.13 1995/06/16 10:29:11 quinn
50 * *** empty log message ***
52 * Revision 1.12 1995/06/15 07:44:57 quinn
55 * Revision 1.11 1995/06/14 15:26:40 quinn
56 * *** empty log message ***
58 * Revision 1.10 1995/06/06 14:56:58 quinn
61 * Revision 1.9 1995/06/06 08:15:19 quinn
64 * Revision 1.8 1995/06/05 10:52:22 quinn
67 * Revision 1.7 1995/06/02 09:50:09 quinn
70 * Revision 1.6 1995/05/31 08:29:21 quinn
71 * Nothing significant.
73 * Revision 1.5 1995/05/29 08:10:47 quinn
74 * Moved oid.c to util.
76 * Revision 1.4 1995/05/22 15:30:13 adam
77 * Client uses prefix query notation.
79 * Revision 1.3 1995/05/22 15:06:53 quinn
80 * *** empty log message ***
82 * Revision 1.2 1995/05/22 14:56:40 quinn
83 * *** empty log message ***
85 * Revision 1.1 1995/05/22 11:30:31 quinn
86 * Added prettier client.
92 * This is the obligatory little toy client, whose primary purpose is
93 * to illustrate the use of the YAZ service-level API.
101 #include <sys/time.h>
105 #include <sys/select.h>
108 #include <comstack.h>
115 #include <marcdisp.h>
116 #include <diagbib1.h>
126 #define C_PROMPT "Z> "
128 static ODR out, in, print; /* encoding and decoding streams */
129 static COMSTACK conn = 0; /* our z-association */
130 static Z_IdAuthentication *auth = 0; /* our current auth definition */
131 static char database[512] = "Default"; /* Database name */
132 static int setnumber = 0; /* current result set number */
133 static int smallSetUpperBound = 0;
134 static int largeSetLowerBound = 1;
135 static int mediumSetPresentNumber = 0;
136 static Z_ElementSetNames *elementSetNames = 0;
137 static int setno = 1; /* current set offset */
138 static int protocol = PROTO_Z3950; /* current app protocol */
139 static int recordsyntax = VAL_USMARC;
140 static int sent_close = 0;
141 static ODR_MEM session_mem; /* memory handle for init-response */
142 static Z_InitResponse *session = 0; /* session parameters */
143 static char last_scan[512] = "0";
144 static char last_cmd[100] = "?";
147 static CCL_bibset bibset; /* CCL bibset handle */
151 static void send_apdu(Z_APDU *a)
156 if (!z_APDU(out, &a, 0))
158 odr_perror(out, "Encoding APDU");
161 buf = odr_getbuf(out, &len, 0);
162 odr_reset(out); /* release the APDU */
163 if (cs_put(conn, buf, len) < 0)
165 fprintf(stderr, "cs_put: %s", cs_errmsg(cs_errno(conn)));
170 /* INIT SERVICE ------------------------------- */
172 static void send_initRequest()
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);
183 ODR_MASK_SET(req->protocolVersion, Z_ProtocolVersion_1);
184 ODR_MASK_SET(req->protocolVersion, Z_ProtocolVersion_2);
185 ODR_MASK_SET(req->protocolVersion, Z_ProtocolVersion_3);
187 *req->maximumRecordSize = 1024*1024;
189 req->idAuthentication = auth;
192 printf("Sent initrequest.\n");
195 static int process_initResponse(Z_InitResponse *res)
197 /* save session parameters for later use */
198 session_mem = odr_extract_mem(in);
202 printf("Connection rejected by target.\n");
204 printf("Connection accepted by target.\n");
205 if (res->implementationId)
206 printf("ID : %s\n", res->implementationId);
207 if (res->implementationName)
208 printf("Name : %s\n", res->implementationName);
209 if (res->implementationVersion)
210 printf("Version: %s\n", res->implementationVersion);
211 if (res->userInformationField)
213 printf("UserInformationfield:\n");
214 if (!z_External(print, (Z_External**)&res-> userInformationField,
217 odr_perror(print, "Printing userinfo\n");
220 if (res->userInformationField->which == Z_External_octet)
222 printf("Guessing visiblestring:\n");
223 printf("'%s'\n", res->userInformationField->u. octet_aligned->buf);
229 int cmd_open(char *arg)
232 char type[100], addr[100];
237 printf("Already connected.\n");
240 if (!*arg || sscanf(arg, "%[^:]:%s", type, addr) < 2)
242 fprintf(stderr, "Usage: open (osi|tcp) ':' [tsel '/']host[':'port]\n");
246 if (!strcmp(type, "osi"))
248 if (!(add = mosi_strtoaddr(addr)))
258 if (!strcmp(type, "tcp"))
260 if (!(add = tcpip_strtoaddr(addr)))
266 protocol = PROTO_Z3950;
270 fprintf(stderr, "Bad type: %s\n", type);
273 if (!(conn = cs_create(t, 1, protocol)))
278 printf("Connecting...");
280 if (cs_connect(conn, add) < 0)
292 int cmd_authentication(char *arg)
294 static Z_IdAuthentication au;
295 static char open[256];
299 printf("Auth field set to null\n");
304 au.which = Z_IdAuthentication_open;
310 /* SEARCH SERVICE ------------------------------ */
312 static void display_variant(Z_Variant *v, int level)
316 for (i = 0; i < v->num_triples; i++)
318 printf("%*sclass=%d,type=%d", level * 4, "", *v->triples[i]->class,
319 *v->triples[i]->type);
320 if (v->triples[i]->which == Z_Triple_internationalString)
321 printf(",value=%s\n", v->triples[i]->value.internationalString);
327 static void display_grs1(Z_GenericRecord *r, int level)
333 for (i = 0; i < r->num_elements; i++)
337 printf("%*s", level * 4, "");
341 printf("%d,", *t->tagType);
344 if (t->tagValue->which == Z_StringOrNumeric_numeric)
345 printf("%d) ", *t->tagValue->u.numeric);
347 printf("%s) ", t->tagValue->u.string);
348 if (t->content->which == Z_ElementData_subtree)
351 display_grs1(t->content->u.subtree, level+1);
353 else if (t->content->which == Z_ElementData_string)
354 printf("%s\n", t->content->u.string);
355 else if (t->content->which == Z_ElementData_numeric)
356 printf("%d\n", *t->content->u.numeric);
357 else if (t->content->which == Z_ElementData_noDataRequested)
358 printf("[No data requested]\n");
359 else if (t->content->which == Z_ElementData_elementEmpty)
360 printf("[Element empty]\n");
361 else if (t->content->which == Z_ElementData_elementNotThere)
362 printf("[Element not there]\n");
365 if (t->appliedVariant)
366 display_variant(t->appliedVariant, level+1);
367 if (t->metaData && t->metaData->supportedVariants)
371 printf("%*s---- variant list\n", (level+1)*4, "");
372 for (c = 0; c < t->metaData->num_supportedVariants; c++)
374 printf("%*svariant #%d\n", (level+1)*4, "", c);
375 display_variant(t->metaData->supportedVariants[c], level + 2);
381 static void display_record(Z_DatabaseRecord *p)
383 Z_External *r = (Z_External*) p;
384 oident *ent = oid_getentbyoid(r->direct_reference);
386 if (r->direct_reference)
388 printf("Record type: ");
390 printf("%s\n", ent->desc);
391 else if (!odr_oid(print, &r->direct_reference, 0))
393 odr_perror(print, "print oid");
397 if (r->which == Z_External_octet && p->u.octet_aligned->len)
398 marc_display ((char*)p->u.octet_aligned->buf, stdout);
399 else if (ent->value == VAL_SUTRS)
401 if (r->which != Z_External_sutrs)
403 printf("Expecting single SUTRS type for SUTRS.\n");
406 printf("%.*s", r->u.sutrs->len, r->u.sutrs->buf);
408 else if (ent->value == VAL_GRS1)
410 if (r->which != Z_External_grs1)
412 printf("Expecting single GRS type for GRS.\n");
415 display_grs1(r->u.grs1, 0);
419 printf("Unknown record representation.\n");
420 if (!z_External(print, &r, 0))
422 odr_perror(print, "Printing external");
428 static void display_diagrec(Z_DiagRec *p)
432 Z_DefaultDiagFormat *r;
437 printf("Diagnostic message from database:\n");
439 if (p->which != Z_DiagRec_defaultFormat)
441 printf("Diagnostic record not in default format.\n");
445 r = p->u.defaultFormat;
447 if (!(ent = oid_getentbyoid(r->diagnosticSetId)) ||
448 ent->class != CLASS_DIAGSET || ent->value != VAL_BIB1)
449 printf("Missing or unknown diagset\n");
450 printf(" [%d] %s", *r->condition, diagbib1_str(*r->condition));
451 if (r->addinfo && *r->addinfo)
452 printf(" -- %s\n", r->addinfo);
457 static void display_nameplusrecord(Z_NamePlusRecord *p)
460 printf("[%s]", p->databaseName);
461 if (p->which == Z_NamePlusRecord_surrogateDiagnostic)
462 display_diagrec(p->u.surrogateDiagnostic);
464 display_record(p->u.databaseRecord);
467 static void display_records(Z_Records *p)
471 if (p->which == Z_Records_NSD)
472 display_diagrec(p->u.nonSurrogateDiagnostic);
475 printf("Records: %d\n", p->u.databaseOrSurDiagnostics->num_records);
476 for (i = 0; i < p->u.databaseOrSurDiagnostics->num_records; i++)
477 display_nameplusrecord(p->u.databaseOrSurDiagnostics->records[i]);
481 static int send_searchRequest(char *arg)
483 Z_APDU *apdu = zget_APDU(out, Z_APDU_searchRequest);
484 Z_SearchRequest *req = apdu->u.searchRequest;
485 char *databaseNames = database;
489 struct ccl_rpn_node *rpn;
495 Z_RPNQuery *RPNquery;
503 rpn = ccl_find_str(bibset, arg, &error, &pos);
506 printf("CCL ERROR: %s\n", ccl_err_msg(error));
512 if (!strcmp(arg, "@big")) /* strictly for troublemaking */
514 static unsigned char big[2100];
517 /* send a very big referenceid to test transport stack etc. */
518 memset(big, 'A', 2100);
519 bigo.len = bigo.size = 2100;
521 req->referenceId = &bigo;
526 sprintf(setstring, "%d", ++setnumber);
527 req->resultSetName = setstring;
529 *req->smallSetUpperBound = smallSetUpperBound;
530 *req->largeSetLowerBound = largeSetLowerBound;
531 *req->mediumSetPresentNumber = mediumSetPresentNumber;
532 if (smallSetUpperBound > 0 || (largeSetLowerBound > 1 &&
533 mediumSetPresentNumber > 0))
537 prefsyn.proto = protocol;
538 prefsyn.class = CLASS_RECSYN;
539 prefsyn.value = recordsyntax;
540 req->preferredRecordSyntax = odr_oiddup(out, oid_getoidbyent(&prefsyn));
541 req->smallSetElementSetNames =
542 req->mediumSetElementSetNames = elementSetNames;
544 req->num_databaseNames = 1;
545 req->databaseNames = &databaseNames;
550 query.which = Z_Query_type_1;
553 assert((RPNquery = ccl_rpn_query(rpn)));
555 RPNquery = p_query_rpn (out, arg);
558 printf("Prefix query error\n");
562 bib1.proto = protocol;
563 bib1.class = CLASS_ATTSET;
564 bib1.value = VAL_BIB1;
565 RPNquery->attributeSetId = oid_getoidbyent(&bib1);
566 query.u.type_1 = RPNquery;
568 query.which = Z_Query_type_2;
569 query.u.type_2 = &ccl_query;
570 ccl_query.buf = (unsigned char*) arg;
571 ccl_query.len = strlen(arg);
576 printf("Sent searchRequest.\n");
580 static int process_searchResponse(Z_SearchResponse *res)
582 if (*res->searchStatus)
583 printf("Search was a success.\n");
585 printf("Search was a bloomin' failure.\n");
586 printf("Number of hits: %d, setno %d\n",
587 *res->resultCount, setnumber);
588 printf("records returned: %d\n",
589 *res->numberOfRecordsReturned);
590 setno += *res->numberOfRecordsReturned;
592 display_records(res->records);
596 static int cmd_find(char *arg)
600 printf("Find what?\n");
605 printf("Not connected yet\n");
608 if (!send_searchRequest(arg))
613 static int cmd_ssub(char *arg)
615 if (!(smallSetUpperBound = atoi(arg)))
620 static int cmd_lslb(char *arg)
622 if (!(largeSetLowerBound = atoi(arg)))
627 static int cmd_mspn(char *arg)
629 if (!(mediumSetPresentNumber = atoi(arg)))
634 static int cmd_status(char *arg)
636 printf("smallSetUpperBound: %d\n", smallSetUpperBound);
637 printf("largeSetLowerBound: %d\n", largeSetLowerBound);
638 printf("mediumSetPresentNumber: %d\n", mediumSetPresentNumber);
642 static int cmd_base(char *arg)
646 printf("Usage: base <database>\n");
649 strcpy(database, arg);
653 static int cmd_setnames(char *arg)
657 printf("Set numbering enabled.\n");
662 printf("Set numbering disabled.\n");
668 /* PRESENT SERVICE ----------------------------- */
670 static int send_presentRequest(char *arg)
672 Z_APDU *apdu = zget_APDU(out, Z_APDU_presentRequest);
673 Z_PresentRequest *req = apdu->u.presentRequest;
674 Z_RecordComposition compo;
680 if ((p = strchr(arg, '+')))
690 sprintf(setstring, "%d", setnumber);
691 req->resultSetId = setstring;
693 req->resultSetStartPoint = &setno;
694 req->numberOfRecordsRequested = &nos;
695 prefsyn.proto = protocol;
696 prefsyn.class = CLASS_RECSYN;
697 prefsyn.value = recordsyntax;
698 req->preferredRecordSyntax = oid_getoidbyent(&prefsyn);
701 req->recordComposition = &compo;
702 compo.which = Z_RecordComp_simple;
703 compo.u.simple = elementSetNames;
706 printf("Sent presentRequest (%d+%d).\n", setno, nos);
710 void process_close(Z_Close *req)
712 Z_APDU *apdu = zget_APDU(out, Z_APDU_close);
713 Z_Close *res = apdu->u.close;
715 static char *reasons[] =
720 "cost limit reached",
722 "security violation",
729 printf("Reason: %s, message: %s\n", reasons[*req->closeReason],
730 req->diagnosticInformation ? req->diagnosticInformation : "NULL");
733 printf("Goodbye.\n");
736 *res->closeReason = Z_Close_finished;
738 printf("Sent response.\n");
742 static int cmd_show(char *arg)
744 if (!send_presentRequest(arg))
749 int cmd_quit(char *arg)
751 printf("See you later, alligator.\n");
755 int cmd_cancel(char *arg)
757 Z_APDU *apdu = zget_APDU(out, Z_APDU_triggerResourceControlRequest);
758 Z_TriggerResourceControlRequest *req =
759 apdu->u.triggerResourceControlRequest;
764 printf("Session not initialized yet\n");
767 if (!ODR_MASK_GET(session->options, Z_Options_triggerResourceCtrl))
769 printf("Target doesn't support cancel (trigger resource ctrl)\n");
772 *req->requestedAction = Z_TriggerResourceCtrl_cancel;
773 req->resultSetWanted = &false;
776 printf("Sent cancel request\n");
780 int send_scanrequest(char *string, int pp, int num)
782 Z_APDU *apdu = zget_APDU(out, Z_APDU_scanRequest);
783 Z_ScanRequest *req = apdu->u.scanRequest;
787 req->num_databaseNames = 1;
788 req->databaseNames = &db;
789 attset.proto = protocol;
790 attset.class = CLASS_ATTSET;
791 attset.value = VAL_BIB1;
792 req->attributeSet = oid_getoidbyent(&attset);
793 req->termListAndStartPoint = p_query_scan(out, string);
794 req->numberOfTermsRequested = #
795 req->preferredPositionInResponse = &pp;
800 void display_term(Z_TermInfo *t)
802 if (t->term->which == Z_Term_general)
804 printf("%.*s (%d)\n", t->term->u.general->len, t->term->u.general->buf,
805 t->globalOccurrences ? *t->globalOccurrences : -1);
806 sprintf(last_scan, "%.*s", t->term->u.general->len,
807 t->term->u.general->buf);
810 printf("Term type not general.\n");
813 void process_scanResponse(Z_ScanResponse *res)
817 printf("SCAN: %d entries, position=%d\n", *res->numberOfEntriesReturned,
818 *res->positionOfTerm);
819 if (*res->scanStatus != Z_Scan_success)
820 printf("Scan returned code %d\n", *res->scanStatus);
823 if (res->entries->which == Z_ListEntries_entries)
825 Z_Entries *ent = res->entries->u.entries;
827 for (i = 0; i < ent->num_entries; i++)
828 if (ent->entries[i]->which == Z_Entry_termInfo)
830 printf("%c ", i + 1 == *res->positionOfTerm ? '*' : ' ');
831 display_term(ent->entries[i]->u.termInfo);
834 display_diagrec(ent->entries[i]->u.surrogateDiagnostic);
837 display_diagrec(res->entries->u.nonSurrogateDiagnostics->diagRecs[0]);
840 int cmd_scan(char *arg)
844 printf("Session not initialized yet\n");
847 if (!ODR_MASK_GET(session->options, Z_Options_scan))
849 printf("Target doesn't support scan\n");
854 if (send_scanrequest(arg, 5, 20) < 0)
858 if (send_scanrequest(last_scan, 1, 20) < 0)
863 int cmd_format(char *arg)
867 printf("Usage: format <recordsyntax>\n");
870 if (!strcmp(arg, "sutrs"))
872 printf("Preferred format is SUTRS.\n");
873 recordsyntax = VAL_SUTRS;
876 else if (!strcmp(arg, "usmarc"))
878 printf("Preferred format is USMARC\n");
879 recordsyntax = VAL_USMARC;
882 else if (!strcmp(arg, "danmarc"))
884 printf("Preferred format is DANMARC\n");
885 recordsyntax = VAL_DANMARC;
888 else if (!strcmp(arg, "grs1"))
890 printf("Preferred format is GRS1\n");
891 recordsyntax = VAL_GRS1;
896 printf("Specify one of {sutrs,usmarc,danmarc,grs1}.\n");
901 int cmd_elements(char *arg)
903 static Z_ElementSetNames esn;
904 static char what[100];
908 printf("Usage: elements <esn>\n");
912 esn.which = Z_ElementSetNames_generic;
913 esn.u.generic = what;
914 elementSetNames = &esn;
918 int cmd_close(char *arg)
920 Z_APDU *apdu = zget_APDU(out, Z_APDU_close);
921 Z_Close *req = apdu->u.close;
923 *req->closeReason = Z_Close_finished;
925 printf("Sent close request.\n");
930 static void initialize(void)
938 if (!(out = odr_createmem(ODR_ENCODE)) ||
939 !(in = odr_createmem(ODR_DECODE)) ||
940 !(print = odr_createmem(ODR_PRINT)))
942 fprintf(stderr, "failed to allocate ODR streams\n");
945 setvbuf(stdout, 0, _IONBF, 0);
949 bibset = ccl_qual_mk ();
950 inf = fopen ("default.bib", "r");
953 ccl_qual_file (bibset, inf);
960 static int client(void)
964 int (*fun)(char *arg);
967 {"open", cmd_open, "('tcp'|'osi')':'[<TSEL>'/']<HOST>[':'<PORT>]"},
968 {"quit", cmd_quit, ""},
969 {"find", cmd_find, "<CCL-QUERY>"},
970 {"base", cmd_base, "<BASE-NAME>"},
971 {"show", cmd_show, "<REC#>['+'<#RECS>]"},
972 {"scan", cmd_scan, "<TERM>"},
973 {"authentication", cmd_authentication, "<ACCTSTRING>"},
974 {"lslb", cmd_lslb, "<largeSetLowerBound>"},
975 {"ssub", cmd_ssub, "<smallSetUpperBound>"},
976 {"mspn", cmd_mspn, "<mediumSetPresentNumber>"},
977 {"status", cmd_status, ""},
978 {"setnames", cmd_setnames, ""},
979 {"cancel", cmd_cancel, ""},
980 {"format", cmd_format, "<recordsyntax>"},
981 {"elements", cmd_elements, "<elementSetName>"},
982 {"close", cmd_close, ""},
986 int netbufferlen = 0;
994 char line[1024], word[1024], arg[1024];
999 FD_SET(cs_fileno(conn), &input);
1000 if ((res = select(20, &input, 0, 0, 0)) < 0)
1007 if (FD_ISSET(0, &input))
1009 /* quick & dirty way to get a command line. */
1012 if ((res = sscanf(line, "%s %[^;]", word, arg)) <= 0)
1014 strcpy(word, last_cmd);
1019 strcpy(last_cmd, word);
1020 for (i = 0; cmd[i].cmd; i++)
1021 if (!strncmp(cmd[i].cmd, word, strlen(word)))
1023 res = (*cmd[i].fun)(arg);
1026 if (!cmd[i].cmd) /* dump our help-screen */
1028 printf("Unknown command: %s.\n", word);
1029 printf("Currently recognized commands:\n");
1030 for (i = 0; cmd[i].cmd; i++)
1031 printf(" %s %s\n", cmd[i].cmd, cmd[i].ad);
1037 if (conn && FD_ISSET(cs_fileno(conn), &input))
1041 if ((res = cs_get(conn, &netbuffer, &netbufferlen)) < 0)
1048 printf("Target closed connection.\n");
1051 odr_reset(in); /* release APDU from last round */
1052 odr_setbuf(in, netbuffer, res, 0);
1053 if (!z_APDU(in, &apdu, 0))
1055 odr_perror(in, "Decoding incoming APDU");
1056 fprintf(stderr, "[Near %d]\n", odr_offset(in));
1057 fprintf(stderr, "Packet dump:\n---------\n");
1058 odr_dumpBER(stderr, netbuffer, res);
1059 fprintf(stderr, "---------\n");
1063 if (!z_APDU(print, &apdu, 0))
1065 odr_perror(print, "Failed to print incoming APDU");
1072 case Z_APDU_initResponse:
1073 process_initResponse(apdu->u.initResponse);
1075 case Z_APDU_searchResponse:
1076 process_searchResponse(apdu->u.searchResponse);
1078 case Z_APDU_scanResponse:
1079 process_scanResponse(apdu->u.scanResponse);
1081 case Z_APDU_presentResponse:
1082 printf("Received presentResponse.\n");
1084 *apdu->u.presentResponse->numberOfRecordsReturned;
1085 if (apdu->u.presentResponse->records)
1086 display_records(apdu->u.presentResponse->records);
1088 printf("No records.\n");
1091 printf("Target has closed the association.\n");
1092 process_close(apdu->u.close);
1095 printf("Received unknown APDU type (%d).\n",
1102 while (cs_more(conn));
1108 int main(int argc, char **argv)