2 * Copyright (c) 1995, Index Data.
3 * See the file LICENSE for details.
4 * Sebastian Hammer, Adam Dickmeiss
7 * Revision 1.24 1995-10-30 12:41:13 quinn
8 * Added hostname lookup for server.
10 * Revision 1.23 1995/10/18 16:12:30 quinn
13 * Revision 1.22 1995/10/11 14:49:12 quinn
16 * Revision 1.21 1995/09/29 17:01:47 quinn
19 * Revision 1.20 1995/08/29 14:24:13 quinn
20 * Added second half of close-handshake
22 * Revision 1.19 1995/08/29 11:17:28 quinn
23 * Added code to receive close
25 * Revision 1.18 1995/08/28 12:21:27 quinn
26 * Client can now ask for simple element set names.
28 * Revision 1.17 1995/08/17 12:45:02 quinn
29 * Fixed minor problems with GRS-1. Added support in c&s.
31 * Revision 1.16 1995/08/15 12:00:04 quinn
34 * Revision 1.15 1995/06/22 09:28:03 quinn
35 * Fixed bug in SUTRS processing.
37 * Revision 1.14 1995/06/19 12:37:41 quinn
40 * Revision 1.13 1995/06/16 10:29:11 quinn
41 * *** empty log message ***
43 * Revision 1.12 1995/06/15 07:44:57 quinn
46 * Revision 1.11 1995/06/14 15:26:40 quinn
47 * *** empty log message ***
49 * Revision 1.10 1995/06/06 14:56:58 quinn
52 * Revision 1.9 1995/06/06 08:15:19 quinn
55 * Revision 1.8 1995/06/05 10:52:22 quinn
58 * Revision 1.7 1995/06/02 09:50:09 quinn
61 * Revision 1.6 1995/05/31 08:29:21 quinn
62 * Nothing significant.
64 * Revision 1.5 1995/05/29 08:10:47 quinn
65 * Moved oid.c to util.
67 * Revision 1.4 1995/05/22 15:30:13 adam
68 * Client uses prefix query notation.
70 * Revision 1.3 1995/05/22 15:06:53 quinn
71 * *** empty log message ***
73 * Revision 1.2 1995/05/22 14:56:40 quinn
74 * *** empty log message ***
76 * Revision 1.1 1995/05/22 11:30:31 quinn
77 * Added prettier client.
83 * This is the obligatory little toy client, whose primary purpose is
84 * to illustrate the use of the YAZ service-level API.
96 #include <sys/select.h>
106 #include <marcdisp.h>
107 #include <diagbib1.h>
117 #define C_PROMPT "Z> "
119 static ODR out, in, print; /* encoding and decoding streams */
120 static COMSTACK conn = 0; /* our z-association */
121 static Z_IdAuthentication *auth = 0; /* our current auth definition */
122 static char database[512] = "Default"; /* Database name */
123 static int setnumber = 0; /* current result set number */
124 static int smallSetUpperBound = 0;
125 static int largeSetLowerBound = 1;
126 static int mediumSetPresentNumber = 0;
127 static Z_ElementSetNames *elementSetNames = 0;
128 static int setno = 1; /* current set offset */
129 static int protocol = PROTO_Z3950; /* current app protocol */
130 static int recordsyntax = VAL_USMARC;
131 static int sent_close = 0;
132 static ODR_MEM session_mem; /* memory handle for init-response */
133 static Z_InitResponse *session = 0; /* session parameters */
134 static char last_scan[512] = "0";
135 static char last_cmd[100] = "?";
138 static CCL_bibset bibset; /* CCL bibset handle */
142 static void send_apdu(Z_APDU *a)
147 if (!z_APDU(out, &a, 0))
149 odr_perror(out, "Encoding APDU");
152 buf = odr_getbuf(out, &len, 0);
153 odr_reset(out); /* release the APDU */
154 if (cs_put(conn, buf, len) < 0)
156 fprintf(stderr, "cs_put: %s", cs_errmsg(cs_errno(conn)));
161 /* INIT SERVICE ------------------------------- */
163 static void send_initRequest()
165 Z_APDU *apdu = zget_APDU(out, Z_APDU_initRequest);
166 Z_InitRequest *req = apdu->u.initRequest;
168 ODR_MASK_SET(req->options, Z_Options_search);
169 ODR_MASK_SET(req->options, Z_Options_present);
170 ODR_MASK_SET(req->options, Z_Options_namedResultSets);
171 ODR_MASK_SET(req->options, Z_Options_triggerResourceCtrl);
172 ODR_MASK_SET(req->options, Z_Options_scan);
174 ODR_MASK_SET(req->protocolVersion, Z_ProtocolVersion_1);
175 ODR_MASK_SET(req->protocolVersion, Z_ProtocolVersion_2);
176 ODR_MASK_SET(req->protocolVersion, Z_ProtocolVersion_3);
178 req->idAuthentication = auth;
181 printf("Sent initrequest.\n");
184 static int process_initResponse(Z_InitResponse *res)
186 /* save session parameters for later use */
187 session_mem = odr_extract_mem(in);
191 printf("Connection rejected by target.\n");
193 printf("Connection accepted by target.\n");
194 if (res->implementationId)
195 printf("ID : %s\n", res->implementationId);
196 if (res->implementationName)
197 printf("Name : %s\n", res->implementationName);
198 if (res->implementationVersion)
199 printf("Version: %s\n", res->implementationVersion);
200 if (res->userInformationField)
202 printf("UserInformationfield:\n");
203 if (!z_External(print, (Z_External**)&res-> userInformationField,
206 odr_perror(print, "Printing userinfo\n");
209 if (res->userInformationField->which == Z_External_octet)
211 printf("Guessing visiblestring:\n");
212 printf("'%s'\n", res->userInformationField->u. octet_aligned->buf);
218 int cmd_open(char *arg)
221 char type[100], addr[100];
226 printf("Already connected.\n");
229 if (!*arg || sscanf(arg, "%[^:]:%s", type, addr) < 2)
231 fprintf(stderr, "Usage: open (osi|tcp) ':' [tsel '/']host[':'port]\n");
235 if (!strcmp(type, "osi"))
237 if (!(add = mosi_strtoaddr(addr)))
247 if (!strcmp(type, "tcp"))
249 if (!(add = tcpip_strtoaddr(addr)))
255 protocol = PROTO_Z3950;
259 fprintf(stderr, "Bad type: %s\n", type);
262 if (!(conn = cs_create(t, 1, protocol)))
267 printf("Connecting...");
269 if (cs_connect(conn, add) < 0)
281 int cmd_authentication(char *arg)
283 static Z_IdAuthentication au;
284 static char open[256];
288 printf("Auth field set to null\n");
293 au.which = Z_IdAuthentication_open;
299 /* SEARCH SERVICE ------------------------------ */
301 void display_grs1(Z_GenericRecord *r, int level)
307 for (i = 0; i < r->num_elements; i++)
311 printf("%*s", level * 4, "");
315 printf("%d,", *t->tagType);
318 if (t->tagValue->which == Z_StringOrNumeric_numeric)
319 printf("%d) ", *t->tagValue->u.numeric);
321 printf("%s) ", t->tagValue->u.string);
322 if (t->content->which == Z_ElementData_subtree)
325 display_grs1(t->content->u.subtree, level+1);
327 else if (t->content->which == Z_ElementData_string)
328 printf("%s\n", t->content->u.string);
329 else if (t->content->which == Z_ElementData_numeric)
330 printf("%d\n", *t->content->u.numeric);
336 void display_record(Z_DatabaseRecord *p)
338 Z_External *r = (Z_External*) p;
339 oident *ent = oid_getentbyoid(r->direct_reference);
341 if (r->direct_reference)
343 printf("Record type: ");
345 printf("%s\n", ent->desc);
346 else if (!odr_oid(print, &r->direct_reference, 0))
348 odr_perror(print, "print oid");
352 if (r->which == Z_External_octet && p->u.octet_aligned->len)
353 marc_display ((char*)p->u.octet_aligned->buf, stdout);
354 else if (ent->value == VAL_SUTRS)
356 if (r->which != Z_External_sutrs)
358 printf("Expecting single SUTRS type for SUTRS.\n");
361 printf("%.*s", r->u.sutrs->len, r->u.sutrs->buf);
363 else if (ent->value == VAL_GRS1)
365 if (r->which != Z_External_grs1)
367 printf("Expecting single GRS type for GRS.\n");
370 display_grs1(r->u.grs1, 0);
374 printf("Unknown record representation.\n");
375 if (!z_External(print, &r, 0))
377 odr_perror(print, "Printing external");
383 static void display_diagrec(Z_DiagRec *p)
387 Z_DefaultDiagFormat *r;
392 printf("Diagnostic message from database:\n");
394 if (p->which != Z_DiagRec_defaultFormat)
396 printf("Diagnostic record not in default format.\n");
400 r = p->u.defaultFormat;
402 if (!(ent = oid_getentbyoid(r->diagnosticSetId)) ||
403 ent->class != CLASS_DIAGSET || ent->value != VAL_BIB1)
404 printf("Missing or unknown diagset\n");
405 printf(" [%d] %s", *r->condition, diagbib1_str(*r->condition));
406 if (r->addinfo && *r->addinfo)
407 printf(" -- %s\n", r->addinfo);
412 static void display_nameplusrecord(Z_NamePlusRecord *p)
415 printf("[%s]", p->databaseName);
416 if (p->which == Z_NamePlusRecord_surrogateDiagnostic)
417 display_diagrec(p->u.surrogateDiagnostic);
419 display_record(p->u.databaseRecord);
422 static void display_records(Z_Records *p)
426 if (p->which == Z_Records_NSD)
427 display_diagrec(p->u.nonSurrogateDiagnostic);
430 printf("Records: %d\n", p->u.databaseOrSurDiagnostics->num_records);
431 for (i = 0; i < p->u.databaseOrSurDiagnostics->num_records; i++)
432 display_nameplusrecord(p->u.databaseOrSurDiagnostics->records[i]);
436 static int send_searchRequest(char *arg)
438 Z_APDU *apdu = zget_APDU(out, Z_APDU_searchRequest);
439 Z_SearchRequest *req = apdu->u.searchRequest;
440 char *databaseNames = database;
444 struct ccl_rpn_node *rpn;
450 Z_RPNQuery *RPNquery;
458 rpn = ccl_find_str(bibset, arg, &error, &pos);
461 printf("CCL ERROR: %s\n", ccl_err_msg(error));
467 if (!strcmp(arg, "@big")) /* strictly for troublemaking */
469 static unsigned char big[2100];
472 /* send a very big referenceid to test transport stack etc. */
473 memset(big, 'A', 2100);
474 bigo.len = bigo.size = 2100;
476 req->referenceId = &bigo;
481 sprintf(setstring, "%d", ++setnumber);
482 req->resultSetName = setstring;
484 *req->smallSetUpperBound = smallSetUpperBound;
485 *req->largeSetLowerBound = largeSetLowerBound;
486 *req->mediumSetPresentNumber = mediumSetPresentNumber;
487 if (smallSetUpperBound > 0 || (largeSetLowerBound > 1 &&
488 mediumSetPresentNumber > 0))
492 prefsyn.proto = protocol;
493 prefsyn.class = CLASS_RECSYN;
494 prefsyn.value = recordsyntax;
495 req->preferredRecordSyntax = odr_oiddup(out, oid_getoidbyent(&prefsyn));
496 req->smallSetElementSetNames =
497 req->mediumSetElementSetNames = elementSetNames;
499 req->num_databaseNames = 1;
500 req->databaseNames = &databaseNames;
505 query.which = Z_Query_type_1;
508 assert((RPNquery = ccl_rpn_query(rpn)));
510 RPNquery = p_query_rpn (out, arg);
513 printf("Prefix query error\n");
517 bib1.proto = protocol;
518 bib1.class = CLASS_ATTSET;
519 bib1.value = VAL_BIB1;
520 RPNquery->attributeSetId = oid_getoidbyent(&bib1);
521 query.u.type_1 = RPNquery;
523 query.which = Z_Query_type_2;
524 query.u.type_2 = &ccl_query;
525 ccl_query.buf = (unsigned char*) arg;
526 ccl_query.len = strlen(arg);
531 printf("Sent searchRequest.\n");
535 static int process_searchResponse(Z_SearchResponse *res)
537 if (*res->searchStatus)
538 printf("Search was a success.\n");
540 printf("Search was a bloomin' failure.\n");
541 printf("Number of hits: %d, setno %d\n",
542 *res->resultCount, setnumber);
543 printf("records returned: %d\n",
544 *res->numberOfRecordsReturned);
545 setno += *res->numberOfRecordsReturned;
547 display_records(res->records);
551 static int cmd_find(char *arg)
555 printf("Find what?\n");
560 printf("Not connected yet\n");
563 if (!send_searchRequest(arg))
568 static int cmd_ssub(char *arg)
570 if (!(smallSetUpperBound = atoi(arg)))
575 static int cmd_lslb(char *arg)
577 if (!(largeSetLowerBound = atoi(arg)))
582 static int cmd_mspn(char *arg)
584 if (!(mediumSetPresentNumber = atoi(arg)))
589 static int cmd_status(char *arg)
591 printf("smallSetUpperBound: %d\n", smallSetUpperBound);
592 printf("largeSetLowerBound: %d\n", largeSetLowerBound);
593 printf("mediumSetPresentNumber: %d\n", mediumSetPresentNumber);
597 static int cmd_base(char *arg)
601 printf("Usage: base <database>\n");
604 strcpy(database, arg);
608 static int cmd_setnames(char *arg)
612 printf("Set numbering enabled.\n");
617 printf("Set numbering disabled.\n");
623 /* PRESENT SERVICE ----------------------------- */
625 static int send_presentRequest(char *arg)
627 Z_APDU *apdu = zget_APDU(out, Z_APDU_presentRequest);
628 Z_PresentRequest *req = apdu->u.presentRequest;
629 Z_RecordComposition compo;
635 if ((p = strchr(arg, '+')))
645 sprintf(setstring, "%d", setnumber);
646 req->resultSetId = setstring;
648 req->resultSetStartPoint = &setno;
649 req->numberOfRecordsRequested = &nos;
650 prefsyn.proto = protocol;
651 prefsyn.class = CLASS_RECSYN;
652 prefsyn.value = recordsyntax;
653 req->preferredRecordSyntax = oid_getoidbyent(&prefsyn);
656 req->recordComposition = &compo;
657 compo.which = Z_RecordComp_simple;
658 compo.u.simple = elementSetNames;
661 printf("Sent presentRequest (%d+%d).\n", setno, nos);
665 void process_close(Z_Close *req)
667 Z_APDU *apdu = zget_APDU(out, Z_APDU_close);
668 Z_Close *res = apdu->u.close;
670 static char *reasons[] =
675 "cost limit reached",
677 "security violation",
684 printf("Reason: %s, message: %s\n", reasons[*req->closeReason],
685 req->diagnosticInformation ? req->diagnosticInformation : "NULL");
688 printf("Goodbye.\n");
691 *res->closeReason = Z_Close_finished;
693 printf("Sent response.\n");
697 static int cmd_show(char *arg)
699 if (!send_presentRequest(arg))
704 int cmd_quit(char *arg)
706 printf("See you later, alligator.\n");
710 int cmd_cancel(char *arg)
712 Z_APDU *apdu = zget_APDU(out, Z_APDU_triggerResourceControlRequest);
713 Z_TriggerResourceControlRequest *req =
714 apdu->u.triggerResourceControlRequest;
719 printf("Session not initialized yet\n");
722 if (!ODR_MASK_GET(session->options, Z_Options_triggerResourceCtrl))
724 printf("Target doesn't support cancel (trigger resource ctrl)\n");
727 *req->requestedAction = Z_TriggerResourceCtrl_cancel;
728 req->resultSetWanted = &false;
731 printf("Sent cancel request\n");
735 int send_scanrequest(char *string, int pp, int num)
737 Z_APDU *apdu = zget_APDU(out, Z_APDU_scanRequest);
738 Z_ScanRequest *req = apdu->u.scanRequest;
742 req->num_databaseNames = 1;
743 req->databaseNames = &db;
744 attset.proto = protocol;
745 attset.class = CLASS_ATTSET;
746 attset.value = VAL_BIB1;
747 req->attributeSet = oid_getoidbyent(&attset);
748 req->termListAndStartPoint = p_query_scan(out, string);
749 req->numberOfTermsRequested = #
750 req->preferredPositionInResponse = &pp;
755 void display_term(Z_TermInfo *t)
757 if (t->term->which == Z_Term_general)
759 printf("%.*s (%d)\n", t->term->u.general->len, t->term->u.general->buf,
760 t->globalOccurrences ? *t->globalOccurrences : -1);
761 sprintf(last_scan, "%.*s", t->term->u.general->len,
762 t->term->u.general->buf);
765 printf("Term type not general.\n");
768 void process_scanResponse(Z_ScanResponse *res)
772 printf("SCAN: %d entries, position=%d\n", *res->numberOfEntriesReturned,
773 *res->positionOfTerm);
774 if (*res->scanStatus != Z_Scan_success)
775 printf("Scan returned code %d\n", *res->scanStatus);
778 if (res->entries->which == Z_ListEntries_entries)
780 Z_Entries *ent = res->entries->u.entries;
782 for (i = 0; i < ent->num_entries; i++)
783 if (ent->entries[i]->which == Z_Entry_termInfo)
785 printf("%c ", i + 1 == *res->positionOfTerm ? '*' : ' ');
786 display_term(ent->entries[i]->u.termInfo);
789 display_diagrec(ent->entries[i]->u.surrogateDiagnostic);
792 display_diagrec(res->entries->u.nonSurrogateDiagnostics->diagRecs[0]);
795 int cmd_scan(char *arg)
799 printf("Session not initialized yet\n");
802 if (!ODR_MASK_GET(session->options, Z_Options_scan))
804 printf("Target doesn't support scan\n");
809 if (send_scanrequest(arg, 5, 20) < 0)
813 if (send_scanrequest(last_scan, 1, 20) < 0)
818 int cmd_format(char *arg)
822 printf("Usage: format <recordsyntax>\n");
825 if (!strcmp(arg, "sutrs"))
827 printf("Preferred format is SUTRS.\n");
828 recordsyntax = VAL_SUTRS;
831 else if (!strcmp(arg, "usmarc"))
833 printf("Preferred format is USMARC\n");
834 recordsyntax = VAL_USMARC;
837 else if (!strcmp(arg, "danmarc"))
839 printf("Preferred format is DANMARC\n");
840 recordsyntax = VAL_DANMARC;
843 else if (!strcmp(arg, "grs1"))
845 printf("Preferred format is GRS1\n");
846 recordsyntax = VAL_GRS1;
851 printf("Specify one of {sutrs,usmarc,danmarc,grs1}.\n");
856 int cmd_elements(char *arg)
858 static Z_ElementSetNames esn;
859 static char what[100];
863 printf("Usage: elements <esn>\n");
867 esn.which = Z_ElementSetNames_generic;
868 esn.u.generic = what;
869 elementSetNames = &esn;
873 int cmd_close(char *arg)
875 Z_APDU *apdu = zget_APDU(out, Z_APDU_close);
876 Z_Close *req = apdu->u.close;
878 *req->closeReason = Z_Close_finished;
880 printf("Sent close request.\n");
885 static void initialize(void)
893 if (!(out = odr_createmem(ODR_ENCODE)) ||
894 !(in = odr_createmem(ODR_DECODE)) ||
895 !(print = odr_createmem(ODR_PRINT)))
897 fprintf(stderr, "failed to allocate ODR streams\n");
900 setvbuf(stdout, 0, _IONBF, 0);
904 bibset = ccl_qual_mk ();
905 inf = fopen ("default.bib", "r");
908 ccl_qual_file (bibset, inf);
915 static int client(void)
919 int (*fun)(char *arg);
922 {"open", cmd_open, "('tcp'|'osi')':'[<TSEL>'/']<HOST>[':'<PORT>]"},
923 {"quit", cmd_quit, ""},
924 {"find", cmd_find, "<CCL-QUERY>"},
925 {"base", cmd_base, "<BASE-NAME>"},
926 {"show", cmd_show, "<REC#>['+'<#RECS>]"},
927 {"scan", cmd_scan, "<TERM>"},
928 {"authentication", cmd_authentication, "<ACCTSTRING>"},
929 {"lslb", cmd_lslb, "<largeSetLowerBound>"},
930 {"ssub", cmd_ssub, "<smallSetUpperBound>"},
931 {"mspn", cmd_mspn, "<mediumSetPresentNumber>"},
932 {"status", cmd_status, ""},
933 {"setnames", cmd_setnames, ""},
934 {"cancel", cmd_cancel, ""},
935 {"format", cmd_format, "<recordsyntax>"},
936 {"elements", cmd_elements, "<elementSetName>"},
937 {"close", cmd_close, ""},
941 int netbufferlen = 0;
949 char line[1024], word[1024], arg[1024];
954 FD_SET(cs_fileno(conn), &input);
955 if ((res = select(20, &input, 0, 0, 0)) < 0)
962 if (FD_ISSET(0, &input))
964 /* quick & dirty way to get a command line. */
967 if ((res = sscanf(line, "%s %[^;]", word, arg)) <= 0)
969 strcpy(word, last_cmd);
974 strcpy(last_cmd, word);
975 for (i = 0; cmd[i].cmd; i++)
976 if (!strncmp(cmd[i].cmd, word, strlen(word)))
978 res = (*cmd[i].fun)(arg);
981 if (!cmd[i].cmd) /* dump our help-screen */
983 printf("Unknown command: %s.\n", word);
984 printf("Currently recognized commands:\n");
985 for (i = 0; cmd[i].cmd; i++)
986 printf(" %s %s\n", cmd[i].cmd, cmd[i].ad);
992 if (conn && FD_ISSET(cs_fileno(conn), &input))
996 if ((res = cs_get(conn, &netbuffer, &netbufferlen)) < 0)
1003 printf("Target closed connection.\n");
1006 odr_reset(in); /* release APDU from last round */
1007 odr_setbuf(in, netbuffer, res, 0);
1008 if (!z_APDU(in, &apdu, 0))
1010 odr_perror(in, "Decoding incoming APDU");
1011 fprintf(stderr, "[Near %d]\n", odr_offset(in));
1012 fprintf(stderr, "Packet dump:\n---------\n");
1013 odr_dumpBER(stderr, netbuffer, res);
1014 fprintf(stderr, "---------\n");
1018 if (!z_APDU(print, &apdu, 0))
1020 odr_perror(print, "Failed to print incoming APDU");
1027 case Z_APDU_initResponse:
1028 process_initResponse(apdu->u.initResponse);
1030 case Z_APDU_searchResponse:
1031 process_searchResponse(apdu->u.searchResponse);
1033 case Z_APDU_scanResponse:
1034 process_scanResponse(apdu->u.scanResponse);
1036 case Z_APDU_presentResponse:
1037 printf("Received presentResponse.\n");
1039 *apdu->u.presentResponse->numberOfRecordsReturned;
1040 if (apdu->u.presentResponse->records)
1041 display_records(apdu->u.presentResponse->records);
1043 printf("No records.\n");
1046 printf("Target has closed the association.\n");
1047 process_close(apdu->u.close);
1050 printf("Received unknown APDU type (%d).\n",
1057 while (cs_more(conn));
1063 int main(int argc, char **argv)