2 * Copyright (c) 1995, Index Data.
3 * See the file LICENSE for details.
4 * Sebastian Hammer, Adam Dickmeiss
7 * Revision 1.20 1995-08-29 14:24:13 quinn
8 * Added second half of close-handshake
10 * Revision 1.19 1995/08/29 11:17:28 quinn
11 * Added code to receive close
13 * Revision 1.18 1995/08/28 12:21:27 quinn
14 * Client can now ask for simple element set names.
16 * Revision 1.17 1995/08/17 12:45:02 quinn
17 * Fixed minor problems with GRS-1. Added support in c&s.
19 * Revision 1.16 1995/08/15 12:00:04 quinn
22 * Revision 1.15 1995/06/22 09:28:03 quinn
23 * Fixed bug in SUTRS processing.
25 * Revision 1.14 1995/06/19 12:37:41 quinn
28 * Revision 1.13 1995/06/16 10:29:11 quinn
29 * *** empty log message ***
31 * Revision 1.12 1995/06/15 07:44:57 quinn
34 * Revision 1.11 1995/06/14 15:26:40 quinn
35 * *** empty log message ***
37 * Revision 1.10 1995/06/06 14:56:58 quinn
40 * Revision 1.9 1995/06/06 08:15:19 quinn
43 * Revision 1.8 1995/06/05 10:52:22 quinn
46 * Revision 1.7 1995/06/02 09:50:09 quinn
49 * Revision 1.6 1995/05/31 08:29:21 quinn
50 * Nothing significant.
52 * Revision 1.5 1995/05/29 08:10:47 quinn
53 * Moved oid.c to util.
55 * Revision 1.4 1995/05/22 15:30:13 adam
56 * Client uses prefix query notation.
58 * Revision 1.3 1995/05/22 15:06:53 quinn
59 * *** empty log message ***
61 * Revision 1.2 1995/05/22 14:56:40 quinn
62 * *** empty log message ***
64 * Revision 1.1 1995/05/22 11:30:31 quinn
65 * Added prettier client.
71 * This is the obligatory little toy client, whose primary purpose is
72 * to illustrate the use of the YAZ service-level API.
80 #include <sys/select.h>
101 #define C_PROMPT "Z> "
103 static ODR out, in, print; /* encoding and decoding streams */
104 static COMSTACK conn = 0; /* our z-association */
105 static Z_IdAuthentication *auth = 0; /* our current auth definition */
106 static char database[512] = "Default"; /* Database name */
107 static int setnumber = 0; /* current result set number */
108 static int smallSetUpperBound = 0;
109 static int largeSetLowerBound = 1;
110 static int mediumSetPresentNumber = 0;
111 static Z_ElementSetNames *elementSetNames = 0;
112 static int setno = 1; /* current set offset */
113 static int protocol = PROTO_Z3950; /* current app protocol */
114 static int recordsyntax = VAL_USMARC;
115 static int sent_close = 0;
116 static ODR_MEM session_mem; /* memory handle for init-response */
117 static Z_InitResponse *session = 0; /* session parameters */
118 static char last_scan[512] = "0";
119 static char last_cmd[100] = "?";
122 static CCL_bibset bibset; /* CCL bibset handle */
126 static void send_apdu(Z_APDU *a)
131 if (!z_APDU(out, &a, 0))
133 odr_perror(out, "Encoding APDU");
136 buf = odr_getbuf(out, &len, 0);
137 odr_reset(out); /* release the APDU */
138 if (cs_put(conn, buf, len) < 0)
140 fprintf(stderr, "cs_put: %s", cs_errlist[cs_errno(conn)]);
145 /* INIT SERVICE ------------------------------- */
147 static void send_initRequest()
149 Z_APDU *apdu = zget_APDU(out, Z_APDU_initRequest);
150 Z_InitRequest *req = apdu->u.initRequest;
152 ODR_MASK_SET(req->options, Z_Options_search);
153 ODR_MASK_SET(req->options, Z_Options_present);
154 ODR_MASK_SET(req->options, Z_Options_namedResultSets);
155 ODR_MASK_SET(req->options, Z_Options_triggerResourceCtrl);
156 ODR_MASK_SET(req->options, Z_Options_scan);
158 ODR_MASK_SET(req->protocolVersion, Z_ProtocolVersion_1);
159 ODR_MASK_SET(req->protocolVersion, Z_ProtocolVersion_2);
160 ODR_MASK_SET(req->protocolVersion, Z_ProtocolVersion_3);
162 req->idAuthentication = auth;
165 printf("Sent initrequest.\n");
168 static int process_initResponse(Z_InitResponse *res)
170 /* save session parameters for later use */
171 session_mem = odr_extract_mem(in);
175 printf("Connection rejected by target.\n");
177 printf("Connection accepted by target.\n");
178 if (res->implementationId)
179 printf("ID : %s\n", res->implementationId);
180 if (res->implementationName)
181 printf("Name : %s\n", res->implementationName);
182 if (res->implementationVersion)
183 printf("Version: %s\n", res->implementationVersion);
184 if (res->userInformationField)
186 printf("UserInformationfield:\n");
187 if (!z_External(print, (Z_External**)&res-> userInformationField,
190 odr_perror(print, "Printing userinfo\n");
193 if (res->userInformationField->which == Z_External_octet)
195 printf("Guessing visiblestring:\n");
196 printf("'%s'\n", res->userInformationField->u. octet_aligned->buf);
202 int cmd_open(char *arg)
205 char type[100], addr[100];
210 printf("Already connected.\n");
213 if (!*arg || sscanf(arg, "%[^:]:%s", type, addr) < 2)
215 fprintf(stderr, "Usage: open (osi|tcp) ':' [tsel '/']host[':'port]\n");
219 if (!strcmp(type, "osi"))
221 if (!(add = mosi_strtoaddr(addr)))
231 if (!strcmp(type, "tcp"))
233 if (!(add = tcpip_strtoaddr(addr)))
239 protocol = PROTO_Z3950;
243 fprintf(stderr, "Bad type: %s\n", type);
246 if (!(conn = cs_create(t, 1, protocol)))
251 printf("Connecting...");
253 if (cs_connect(conn, add) < 0)
265 int cmd_authentication(char *arg)
267 static Z_IdAuthentication au;
268 static char open[256];
272 printf("Auth field set to null\n");
277 au.which = Z_IdAuthentication_open;
283 /* SEARCH SERVICE ------------------------------ */
285 void display_grs1(Z_GenericRecord *r, int level)
291 for (i = 0; i < r->num_elements; i++)
295 printf("%*s", level * 4, "");
299 printf("%d,", *t->tagType);
302 if (t->tagValue->which == Z_StringOrNumeric_numeric)
303 printf("%d) ", *t->tagValue->u.numeric);
305 printf("%s) ", t->tagValue->u.string);
306 if (t->content->which == Z_ElementData_subtree)
309 display_grs1(t->content->u.subtree, level+1);
311 else if (t->content->which == Z_ElementData_string)
312 printf("%s\n", t->content->u.string);
318 void display_record(Z_DatabaseRecord *p)
320 Z_External *r = (Z_External*) p;
321 oident *ent = oid_getentbyoid(r->direct_reference);
323 if (r->direct_reference)
325 printf("Record type: ");
327 printf("%s\n", ent->desc);
328 else if (!odr_oid(print, &r->direct_reference, 0))
330 odr_perror(print, "print oid");
334 if (r->which == Z_External_octet && p->u.octet_aligned->len)
335 marc_display ((char*)p->u.octet_aligned->buf, stdout);
336 else if (ent->value == VAL_SUTRS)
338 if (r->which != Z_External_sutrs)
340 printf("Expecting single SUTRS type for SUTRS.\n");
343 printf("%.*s", r->u.sutrs->len, r->u.sutrs->buf);
345 else if (ent->value == VAL_GRS1)
347 if (r->which != Z_External_grs1)
349 printf("Expecting single GRS type for GRS.\n");
352 display_grs1(r->u.grs1, 0);
356 printf("Unknown record representation.\n");
357 if (!z_External(print, &r, 0))
359 odr_perror(print, "Printing external");
365 static void display_diagrec(Z_DiagRec *p)
369 Z_DefaultDiagFormat *r;
374 printf("Diagnostic message from database:\n");
376 if (p->which != Z_DiagRec_defaultFormat)
378 printf("Diagnostic record not in default format.\n");
382 r = p->u.defaultFormat;
384 if (!(ent = oid_getentbyoid(r->diagnosticSetId)) ||
385 ent->class != CLASS_DIAGSET || ent->value != VAL_BIB1)
386 printf("Missing or unknown diagset\n");
387 printf(" [%d] %s", *r->condition, diagbib1_str(*r->condition));
388 if (r->addinfo && *r->addinfo)
389 printf(" -- %s\n", r->addinfo);
394 static void display_nameplusrecord(Z_NamePlusRecord *p)
397 printf("[%s]", p->databaseName);
398 if (p->which == Z_NamePlusRecord_surrogateDiagnostic)
399 display_diagrec(p->u.surrogateDiagnostic);
401 display_record(p->u.databaseRecord);
404 static void display_records(Z_Records *p)
408 if (p->which == Z_Records_NSD)
409 display_diagrec(p->u.nonSurrogateDiagnostic);
412 printf("Records: %d\n", p->u.databaseOrSurDiagnostics->num_records);
413 for (i = 0; i < p->u.databaseOrSurDiagnostics->num_records; i++)
414 display_nameplusrecord(p->u.databaseOrSurDiagnostics->records[i]);
418 static int send_searchRequest(char *arg)
420 Z_APDU *apdu = zget_APDU(out, Z_APDU_searchRequest);
421 Z_SearchRequest *req = apdu->u.searchRequest;
422 char *databaseNames = database;
426 struct ccl_rpn_node *rpn;
432 Z_RPNQuery *RPNquery;
440 rpn = ccl_find_str(bibset, arg, &error, &pos);
443 printf("CCL ERROR: %s\n", ccl_err_msg(error));
449 if (!strcmp(arg, "@big")) /* strictly for troublemaking */
451 static unsigned char big[2100];
454 /* send a very big referenceid to test transport stack etc. */
455 memset(big, 'A', 2100);
456 bigo.len = bigo.size = 2100;
458 req->referenceId = &bigo;
463 sprintf(setstring, "%d", ++setnumber);
464 req->resultSetName = setstring;
466 *req->smallSetUpperBound = smallSetUpperBound;
467 *req->largeSetLowerBound = largeSetLowerBound;
468 *req->mediumSetPresentNumber = mediumSetPresentNumber;
469 if (smallSetUpperBound > 0 || (largeSetLowerBound > 1 &&
470 mediumSetPresentNumber > 0))
474 prefsyn.proto = protocol;
475 prefsyn.class = CLASS_RECSYN;
476 prefsyn.value = recordsyntax;
477 req->preferredRecordSyntax = odr_oiddup(out, oid_getoidbyent(&prefsyn));
478 req->smallSetElementSetNames =
479 req->mediumSetElementSetNames = elementSetNames;
481 req->num_databaseNames = 1;
482 req->databaseNames = &databaseNames;
487 query.which = Z_Query_type_1;
490 assert((RPNquery = ccl_rpn_query(rpn)));
492 RPNquery = p_query_rpn (out, arg);
495 printf("Prefix query error\n");
499 bib1.proto = protocol;
500 bib1.class = CLASS_ATTSET;
501 bib1.value = VAL_BIB1;
502 RPNquery->attributeSetId = oid_getoidbyent(&bib1);
503 query.u.type_1 = RPNquery;
505 query.which = Z_Query_type_2;
506 query.u.type_2 = &ccl_query;
507 ccl_query.buf = (unsigned char*) arg;
508 ccl_query.len = strlen(arg);
513 printf("Sent searchRequest.\n");
517 static int process_searchResponse(Z_SearchResponse *res)
519 if (*res->searchStatus)
520 printf("Search was a success.\n");
522 printf("Search was a bloomin' failure.\n");
523 printf("Number of hits: %d, setno %d\n",
524 *res->resultCount, setnumber);
525 printf("records returned: %d\n",
526 *res->numberOfRecordsReturned);
527 setno += *res->numberOfRecordsReturned;
529 display_records(res->records);
533 static int cmd_find(char *arg)
537 printf("Find what?\n");
542 printf("Not connected yet\n");
545 if (!send_searchRequest(arg))
550 static int cmd_ssub(char *arg)
552 if (!(smallSetUpperBound = atoi(arg)))
557 static int cmd_lslb(char *arg)
559 if (!(largeSetLowerBound = atoi(arg)))
564 static int cmd_mspn(char *arg)
566 if (!(mediumSetPresentNumber = atoi(arg)))
571 static int cmd_status(char *arg)
573 printf("smallSetUpperBound: %d\n", smallSetUpperBound);
574 printf("largeSetLowerBound: %d\n", largeSetLowerBound);
575 printf("mediumSetPresentNumber: %d\n", mediumSetPresentNumber);
579 static int cmd_base(char *arg)
583 printf("Usage: base <database>\n");
586 strcpy(database, arg);
590 static int cmd_setnames(char *arg)
594 printf("Set numbering enabled.\n");
599 printf("Set numbering disabled.\n");
605 /* PRESENT SERVICE ----------------------------- */
607 static int send_presentRequest(char *arg)
609 Z_APDU *apdu = zget_APDU(out, Z_APDU_presentRequest);
610 Z_PresentRequest *req = apdu->u.presentRequest;
611 Z_RecordComposition compo;
617 if ((p = strchr(arg, '+')))
627 sprintf(setstring, "%d", setnumber);
628 req->resultSetId = setstring;
630 req->resultSetStartPoint = &setno;
631 req->numberOfRecordsRequested = &nos;
632 prefsyn.proto = protocol;
633 prefsyn.class = CLASS_RECSYN;
634 prefsyn.value = recordsyntax;
635 req->preferredRecordSyntax = oid_getoidbyent(&prefsyn);
638 req->recordComposition = &compo;
639 compo.which = Z_RecordComp_simple;
640 compo.u.simple = elementSetNames;
643 printf("Sent presentRequest (%d+%d).\n", setno, nos);
647 void process_close(Z_Close *req)
649 Z_APDU *apdu = zget_APDU(out, Z_APDU_close);
650 Z_Close *res = apdu->u.close;
652 static char *reasons[] =
666 printf("Reason: %s, message: %s\n", reasons[*req->closeReason],
667 req->diagnosticInformation ? req->diagnosticInformation : "NULL");
670 printf("Goodbye.\n");
673 *res->closeReason = Z_Close_finished;
675 printf("Sent response.\n");
679 static int cmd_show(char *arg)
681 if (!send_presentRequest(arg))
686 int cmd_quit(char *arg)
688 printf("See you later, alligator.\n");
692 int cmd_cancel(char *arg)
694 Z_APDU *apdu = zget_APDU(out, Z_APDU_triggerResourceControlRequest);
695 Z_TriggerResourceControlRequest *req =
696 apdu->u.triggerResourceControlRequest;
701 printf("Session not initialized yet\n");
704 if (!ODR_MASK_GET(session->options, Z_Options_triggerResourceCtrl))
706 printf("Target doesn't support cancel (trigger resource ctrl)\n");
709 *req->requestedAction = Z_TriggerResourceCtrl_cancel;
710 req->resultSetWanted = &false;
713 printf("Sent cancel request\n");
717 int send_scanrequest(char *string, int pp, int num)
719 Z_APDU *apdu = zget_APDU(out, Z_APDU_scanRequest);
720 Z_ScanRequest *req = apdu->u.scanRequest;
724 req->num_databaseNames = 1;
725 req->databaseNames = &db;
726 attset.proto = protocol;
727 attset.class = CLASS_ATTSET;
728 attset.value = VAL_BIB1;
729 req->attributeSet = oid_getoidbyent(&attset);
730 req->termListAndStartPoint = p_query_scan(out, string);
731 req->numberOfTermsRequested = #
732 req->preferredPositionInResponse = &pp;
737 void display_term(Z_TermInfo *t)
739 if (t->term->which == Z_Term_general)
741 printf("%.*s (%d)\n", t->term->u.general->len, t->term->u.general->buf,
742 t->globalOccurrences ? *t->globalOccurrences : -1);
743 sprintf(last_scan, "%.*s", t->term->u.general->len,
744 t->term->u.general->buf);
747 printf("Term type not general.\n");
750 void process_scanResponse(Z_ScanResponse *res)
754 printf("SCAN: %d entries, position=%d\n", *res->numberOfEntriesReturned,
755 *res->positionOfTerm);
756 if (*res->scanStatus != Z_Scan_success)
757 printf("Scan returned code %d\n", *res->scanStatus);
760 if (res->entries->which == Z_ListEntries_entries)
762 Z_Entries *ent = res->entries->u.entries;
764 for (i = 0; i < ent->num_entries; i++)
765 if (ent->entries[i]->which == Z_Entry_termInfo)
767 printf("%c ", i + 1 == *res->positionOfTerm ? '*' : ' ');
768 display_term(ent->entries[i]->u.termInfo);
771 display_diagrec(ent->entries[i]->u.surrogateDiagnostic);
774 display_diagrec(res->entries->u.nonSurrogateDiagnostics->diagRecs[0]);
777 int cmd_scan(char *arg)
781 printf("Session not initialized yet\n");
784 if (!ODR_MASK_GET(session->options, Z_Options_scan))
786 printf("Target doesn't support scan\n");
791 if (send_scanrequest(arg, 5, 20) < 0)
795 if (send_scanrequest(last_scan, 1, 20) < 0)
800 int cmd_format(char *arg)
804 printf("Usage: format <recordsyntax>\n");
807 if (!strcmp(arg, "sutrs"))
809 printf("Preferred format is SUTRS.\n");
810 recordsyntax = VAL_SUTRS;
813 else if (!strcmp(arg, "usmarc"))
815 printf("Preferred format is USMARC\n");
816 recordsyntax = VAL_USMARC;
819 else if (!strcmp(arg, "danmarc"))
821 printf("Preferred format is DANMARC\n");
822 recordsyntax = VAL_DANMARC;
825 else if (!strcmp(arg, "grs1"))
827 printf("Preferred format is GRS1\n");
828 recordsyntax = VAL_GRS1;
833 printf("Specify one of {sutrs,usmarc,danmarc,grs1}.\n");
838 int cmd_elements(char *arg)
840 static Z_ElementSetNames esn;
841 static char what[100];
845 printf("Usage: elements <esn>\n");
849 esn.which = Z_ElementSetNames_generic;
850 esn.u.generic = what;
851 elementSetNames = &esn;
855 int cmd_close(char *arg)
857 Z_APDU *apdu = zget_APDU(out, Z_APDU_close);
858 Z_Close *req = apdu->u.close;
860 *req->closeReason = Z_Close_finished;
862 printf("Sent close request.\n");
867 static void initialize(void)
875 if (!(out = odr_createmem(ODR_ENCODE)) ||
876 !(in = odr_createmem(ODR_DECODE)) ||
877 !(print = odr_createmem(ODR_PRINT)))
879 fprintf(stderr, "failed to allocate ODR streams\n");
882 setvbuf(stdout, 0, _IONBF, 0);
886 bibset = ccl_qual_mk ();
887 inf = fopen ("default.bib", "r");
890 ccl_qual_file (bibset, inf);
897 static int client(void)
901 int (*fun)(char *arg);
904 {"open", cmd_open, "('tcp'|'osi')':'[<TSEL>'/']<HOST>[':'<PORT>]"},
905 {"quit", cmd_quit, ""},
906 {"find", cmd_find, "<CCL-QUERY>"},
907 {"base", cmd_base, "<BASE-NAME>"},
908 {"show", cmd_show, "<REC#>['+'<#RECS>]"},
909 {"scan", cmd_scan, "<TERM>"},
910 {"authentication", cmd_authentication, "<ACCTSTRING>"},
911 {"lslb", cmd_lslb, "<largeSetLowerBound>"},
912 {"ssub", cmd_ssub, "<smallSetUpperBound>"},
913 {"mspn", cmd_mspn, "<mediumSetPresentNumber>"},
914 {"status", cmd_status, ""},
915 {"setnames", cmd_setnames, ""},
916 {"cancel", cmd_cancel, ""},
917 {"format", cmd_format, "<recordsyntax>"},
918 {"elements", cmd_elements, "<elementSetName>"},
919 {"close", cmd_close, ""},
923 int netbufferlen = 0;
931 char line[1024], word[1024], arg[1024];
936 FD_SET(cs_fileno(conn), &input);
937 if ((res = select(20, &input, 0, 0, 0)) < 0)
944 if (FD_ISSET(0, &input))
946 /* quick & dirty way to get a command line. */
949 if ((res = sscanf(line, "%s %[^;]", word, arg)) <= 0)
951 strcpy(word, last_cmd);
956 strcpy(last_cmd, word);
957 for (i = 0; cmd[i].cmd; i++)
958 if (!strncmp(cmd[i].cmd, word, strlen(word)))
960 res = (*cmd[i].fun)(arg);
963 if (!cmd[i].cmd) /* dump our help-screen */
965 printf("Unknown command: %s.\n", word);
966 printf("Currently recognized commands:\n");
967 for (i = 0; cmd[i].cmd; i++)
968 printf(" %s %s\n", cmd[i].cmd, cmd[i].ad);
974 if (conn && FD_ISSET(cs_fileno(conn), &input))
978 if ((res = cs_get(conn, &netbuffer, &netbufferlen)) < 0)
985 printf("Target closed connection.\n");
988 odr_reset(in); /* release APDU from last round */
989 odr_setbuf(in, netbuffer, res, 0);
990 if (!z_APDU(in, &apdu, 0))
992 odr_perror(in, "Decoding incoming APDU");
993 fprintf(stderr, "Packet dump:\n---------\n");
994 odr_dumpBER(stderr, netbuffer, res);
995 fprintf(stderr, "---------\n");
999 if (!z_APDU(print, &apdu, 0))
1001 odr_perror(print, "Failed to print incoming APDU");
1008 case Z_APDU_initResponse:
1009 process_initResponse(apdu->u.initResponse);
1011 case Z_APDU_searchResponse:
1012 process_searchResponse(apdu->u.searchResponse);
1014 case Z_APDU_scanResponse:
1015 process_scanResponse(apdu->u.scanResponse);
1017 case Z_APDU_presentResponse:
1018 printf("Received presentResponse.\n");
1020 *apdu->u.presentResponse->numberOfRecordsReturned;
1021 if (apdu->u.presentResponse->records)
1022 display_records(apdu->u.presentResponse->records);
1024 printf("No records.\n");
1027 printf("Target has closed the association.\n");
1028 process_close(apdu->u.close);
1031 printf("Received unknown APDU type (%d).\n",
1038 while (cs_more(conn));
1044 int main(int argc, char **argv)