2 * Copyright (c) 1998-2000, Index Data.
3 * See the file LICENSE for details.
5 * $Log: yaz-my-client.cpp,v $
6 * Revision 1.3 2001-04-05 13:09:44 adam
7 * Removed ursula dependancy.
9 * Revision 1.2 2001/04/04 14:02:49 adam
10 * URSULA / Z-ruth service.
12 * Revision 1.1 2001/03/27 14:47:45 adam
13 * New server facility scheme.
15 * Revision 1.17 2001/03/26 14:43:49 adam
16 * New threaded PDU association.
18 * Revision 1.16 2000/11/01 14:22:59 adam
19 * Added fd parameter for method IYaz_PDU_Observer::clone.
21 * Revision 1.15 2000/10/11 11:58:16 adam
22 * Moved header files to include/yaz++. Switched to libtool and automake.
23 * Configure script creates yaz++-config script.
25 * Revision 1.14 2000/09/08 10:23:42 adam
26 * Added skeleton of yaz-z-server.
28 * Revision 1.13 2000/09/06 14:23:45 adam
31 * Revision 1.12 2000/09/04 08:59:16 adam
32 * Changed call to logging functions (yaz_ added).
34 * Revision 1.11 2000/07/04 13:48:49 adam
35 * Implemented upper-limit on proxy-to-target sessions.
37 * Revision 1.10 2000/05/30 03:12:27 ian
38 * minor change to stop g++ 2.95.2 complaining about taking the address
39 * of a member function.
41 * Revision 1.9 1999/12/06 13:52:45 adam
42 * Modified for new location of YAZ header files. Experimental threaded
45 * Revision 1.8 1999/11/10 10:02:34 adam
48 * Revision 1.7 1999/04/21 12:09:01 adam
49 * Many improvements. Modified to proxy server to work with "sessions"
52 * Revision 1.6 1999/04/20 10:30:05 adam
53 * Implemented various stuff for client and proxy. Updated calls
54 * to ODR to reflect new name parameter.
56 * Revision 1.5 1999/04/09 11:46:57 adam
57 * Added object Yaz_Z_Assoc. Much more functional client.
59 * Revision 1.4 1999/03/23 14:17:57 adam
60 * More work on timeout handling. Work on yaz-client.
62 * Revision 1.3 1999/02/02 14:01:18 adam
63 * First WIN32 port of YAZ++.
65 * Revision 1.2 1999/01/28 13:08:42 adam
66 * Yaz_PDU_Assoc better encapsulated. Memory leak fix in
67 * yaz-socket-manager.cc.
69 * Revision 1.1.1.1 1999/01/28 09:41:07 adam
70 * First implementation of YAZ++.
75 #include <yaz/options.h>
76 #include <yaz/diagbib1.h>
77 #include <yaz/marcdisp.h>
78 #include <yaz++/yaz-ir-assoc.h>
79 #include <yaz++/yaz-pdu-assoc.h>
80 #include <yaz++/yaz-socket-manager.h>
83 #include <yaz/zes-ursula.h>
87 #if HAVE_READLINE_READLINE_H
88 #include <readline/readline.h>
90 #if HAVE_READLINE_HISTORY_H
91 #include <readline/history.h>
95 class YAZ_EXPORT MyClient : public Yaz_IR_Assoc {
97 int m_interactive_flag;
98 char m_thisCommand[1024];
99 char m_lastCommand[1024];
101 Yaz_SocketManager *m_socketManager;
103 MyClient(IYaz_PDU_Observable *the_PDU_Observable,
104 Yaz_SocketManager *the_SocketManager);
105 IYaz_PDU_Observer *sessionNotify(
106 IYaz_PDU_Observable *the_PDU_Observable, int fd);
107 int args(Yaz_SocketManager *socketManager, int argc, char **argv);
108 int interactive(Yaz_SocketManager *socketManager);
110 void recv_initResponse(Z_InitResponse *initResponse);
111 void recv_searchResponse(Z_SearchResponse *searchResponse);
112 void recv_presentResponse(Z_PresentResponse *presentResponse);
113 void recv_records (Z_Records *records);
114 void recv_diagrecs(Z_DiagRec **pp, int num);
115 void recv_namePlusRecord (Z_NamePlusRecord *zpr, int offset);
116 void recv_record(Z_DatabaseRecord *record, int offset,
117 const char *databaseName);
118 void recv_textRecord(int type, const char *buf, size_t len);
119 void recv_genericRecord(Z_GenericRecord *r);
120 void display_genericRecord(Z_GenericRecord *r, int level);
121 void display_variant(Z_Variant *v, int level);
122 void connectNotify();
124 void timeoutNotify();
125 char *get_cookie (Z_OtherInformation **oi);
126 int processCommand(const char *cmd);
127 const char *MyClient::getCommand();
128 int cmd_open(char *host);
129 int cmd_connect(char *host);
130 int cmd_quit(char *args);
131 int cmd_close(char *args);
132 int cmd_find(char *args);
133 int cmd_show(char *args);
134 int cmd_cookie(char *args);
135 int cmd_init(char *args);
136 int cmd_format(char *args);
137 int cmd_proxy(char *args);
138 #if HAVE_YAZ_URSULA_H
139 int cmd_ursula(char *args);
144 void MyClient::connectNotify()
146 printf ("Connection accepted by target\n");
147 set_lastReceived(-1);
150 void MyClient::timeoutNotify()
152 printf ("Connection timeout\n");
156 void MyClient::failNotify()
158 printf ("Connection closed by target\n");
159 set_lastReceived(-1);
162 IYaz_PDU_Observer *MyClient::sessionNotify(
163 IYaz_PDU_Observable *the_PDU_Observable, int fd)
165 return new MyClient(the_PDU_Observable, m_socketManager);
168 MyClient::MyClient(IYaz_PDU_Observable *the_PDU_Observable,
169 Yaz_SocketManager *the_socketManager) :
170 Yaz_IR_Assoc (the_PDU_Observable)
173 m_interactive_flag = 1;
174 m_thisCommand[0] = '\0';
175 m_lastCommand[0] = '\0';
176 m_socketManager = the_socketManager;
179 void usage(char *prog)
181 fprintf (stderr, "%s: [-v log] [-c cookie] [-p proxy] [zurl]\n", prog);
185 char *MyClient::get_cookie(Z_OtherInformation **otherInfo)
188 Z_OtherInformationUnit *oi;
190 ent.proto = PROTO_Z3950;
191 ent.oclass = CLASS_USERINFO;
192 ent.value = (oid_value) VAL_COOKIE;
194 if (oid_ent_to_oid (&ent, oid) &&
195 (oi = update_otherInformation(otherInfo, 0, oid, 1, 1)) &&
196 oi->which == Z_OtherInfo_characterInfo)
197 return oi->information.characterInfo;
201 void MyClient::recv_initResponse(Z_InitResponse *initResponse)
203 printf ("Got InitResponse. Status ");
204 if (*initResponse->result)
208 const char *p = get_cookie (&initResponse->otherInfo);
211 printf ("cookie = %s\n", p);
219 void MyClient::recv_diagrecs(Z_DiagRec **pp, int num)
223 Z_DefaultDiagFormat *r;
225 printf("Diagnostic message(s) from database:\n");
226 for (i = 0; i<num; i++)
228 Z_DiagRec *p = pp[i];
229 if (p->which != Z_DiagRec_defaultFormat)
231 printf("Diagnostic record not in default format.\n");
235 r = p->u.defaultFormat;
236 if (!(ent = oid_getentbyoid(r->diagnosticSetId)) ||
237 ent->oclass != CLASS_DIAGSET || ent->value != VAL_BIB1)
238 printf("Missing or unknown diagset\n");
239 printf(" [%d] %s", *r->condition, diagbib1_str(*r->condition));
243 case Z_DefaultDiagFormat_v2Addinfo:
244 printf (" -- v2 addinfo '%s'\n", r->u.v2Addinfo);
246 case Z_DefaultDiagFormat_v3Addinfo:
247 printf (" -- v3 addinfo '%s'\n", r->u.v3Addinfo);
251 if (r->addinfo && *r->addinfo)
252 printf(" -- '%s'\n", r->addinfo);
259 void MyClient::recv_textRecord(int type, const char *buf, size_t len)
261 fwrite (buf, 1, len, stdout);
262 fputc ('\n', stdout);
265 void MyClient::display_variant(Z_Variant *v, int level)
269 for (i = 0; i < v->num_triples; i++)
271 printf("%*sclass=%d,type=%d", level * 4, "", *v->triples[i]->zclass,
272 *v->triples[i]->type);
273 if (v->triples[i]->which == Z_Triple_internationalString)
274 printf(",value=%s\n", v->triples[i]->value.internationalString);
280 void MyClient::display_genericRecord(Z_GenericRecord *r, int level)
286 for (i = 0; i < r->num_elements; i++)
290 printf("%*s", level * 4, "");
294 printf("%d,", *t->tagType);
297 if (t->tagValue->which == Z_StringOrNumeric_numeric)
298 printf("%d) ", *t->tagValue->u.numeric);
300 printf("%s) ", t->tagValue->u.string);
301 if (t->content->which == Z_ElementData_subtree)
304 display_genericRecord(t->content->u.subtree, level+1);
306 else if (t->content->which == Z_ElementData_string)
307 printf("%s\n", t->content->u.string);
308 else if (t->content->which == Z_ElementData_numeric)
309 printf("%d\n", *t->content->u.numeric);
310 else if (t->content->which == Z_ElementData_oid)
312 int *ip = t->content->u.oid;
315 if ((oent = oid_getentbyoid(t->content->u.oid)))
316 printf("OID: %s\n", oent->desc);
320 while (ip && *ip >= 0)
321 printf(" %d", *(ip++));
325 else if (t->content->which == Z_ElementData_noDataRequested)
326 printf("[No data requested]\n");
327 else if (t->content->which == Z_ElementData_elementEmpty)
328 printf("[Element empty]\n");
329 else if (t->content->which == Z_ElementData_elementNotThere)
330 printf("[Element not there]\n");
333 if (t->appliedVariant)
334 display_variant(t->appliedVariant, level+1);
335 if (t->metaData && t->metaData->supportedVariants)
339 printf("%*s---- variant list\n", (level+1)*4, "");
340 for (c = 0; c < t->metaData->num_supportedVariants; c++)
342 printf("%*svariant #%d\n", (level+1)*4, "", c);
343 display_variant(t->metaData->supportedVariants[c], level + 2);
349 void MyClient::recv_genericRecord(Z_GenericRecord *r)
351 display_genericRecord(r, 0);
354 void MyClient::recv_record(Z_DatabaseRecord *record, int offset,
355 const char *databaseName)
357 Z_External *r = (Z_External*) record;
358 oident *ent = oid_getentbyoid(r->direct_reference);
361 * Tell the user what we got.
363 if (r->direct_reference)
365 printf("Record type: ");
367 printf("%s\n", ent->desc);
369 /* Check if this is a known, ASN.1 type tucked away in an octet string */
370 Z_ext_typeent *etype = z_ext_getentbyref(ent->value);
371 if (ent && (r->which == Z_External_octet || r->which == Z_External_single)
372 && (etype = z_ext_getentbyref(ent->value)))
377 * Call the given decoder to process the record.
379 odr_setbuf(odr_decode(), (char*)record->u.octet_aligned->buf,
380 record->u.octet_aligned->len, 0);
381 if (!(*etype->fun)(odr_decode(), (char **)&rr, 0, 0))
383 odr_perror(odr_decode(), "Decoding constructed record.");
384 fprintf(stderr, "[Near %d]\n", odr_offset(odr_decode()));
385 fprintf(stderr, "Packet dump:\n---------\n");
386 odr_dumpBER(stderr, (char*)record->u.octet_aligned->buf,
387 record->u.octet_aligned->len);
388 fprintf(stderr, "---------\n");
390 if (etype->what == Z_External_sutrs)
392 Z_SUTRS *sutrs = (Z_SUTRS *) rr;
393 recv_textRecord ((int) VAL_SUTRS, (const char *) sutrs->buf,
394 (size_t) sutrs->len);
398 if (r->which == Z_External_octet && record->u.octet_aligned->len)
424 marc_display((char*) record->u.octet_aligned->buf,stdout);
427 recv_textRecord((int) ent->value,
428 (const char *) record->u.octet_aligned->buf,
429 (size_t) record->u.octet_aligned->len);
432 else if (ent && ent->value == VAL_SUTRS && r->which == Z_External_sutrs)
433 recv_textRecord((int) VAL_SUTRS, (const char *) r->u.sutrs->buf,
434 (size_t) r->u.sutrs->len);
435 else if (ent && ent->value == VAL_GRS1 && r->which == Z_External_grs1)
436 recv_genericRecord(r->u.grs1);
439 printf("Unknown record representation.\n");
440 if (!z_External(odr_print(), &r, 0, 0))
442 odr_perror(odr_print(), "Printing external");
443 odr_reset(odr_print());
448 void MyClient::recv_namePlusRecord (Z_NamePlusRecord *zpr, int offset)
450 if (zpr->databaseName)
451 printf("[%s]", zpr->databaseName);
452 if (zpr->which == Z_NamePlusRecord_surrogateDiagnostic)
453 recv_diagrecs(&zpr->u.surrogateDiagnostic, 1);
455 recv_record(zpr->u.databaseRecord, offset, zpr->databaseName);
458 void MyClient::recv_records (Z_Records *records)
461 Z_DiagRec dr, *dr_p = &dr;
466 switch (records->which)
468 case Z_Records_DBOSD:
469 for (i = 0; i < records->u.databaseOrSurDiagnostics->num_records; i++)
470 recv_namePlusRecord(records->u.databaseOrSurDiagnostics->
471 records[i], i + m_setOffset);
472 m_setOffset += records->u.databaseOrSurDiagnostics->num_records;
476 dr.which = Z_DiagRec_defaultFormat;
477 dr.u.defaultFormat = records->u.nonSurrogateDiagnostic;
478 recv_diagrecs (&dr_p, 1);
480 recv_diagrecs (&records->u.nonSurrogateDiagnostic, 1);
483 case Z_Records_multipleNSD:
484 recv_diagrecs (records->u.multipleNonSurDiagnostics->diagRecs,
485 records->u.multipleNonSurDiagnostics->num_diagRecs);
490 void MyClient::recv_searchResponse(Z_SearchResponse *searchResponse)
492 printf ("Got SearchResponse. Status ");
493 if (!*searchResponse->searchStatus)
499 printf ("Hits: %d\n", *searchResponse->resultCount);
500 recv_records (searchResponse->records);
503 void MyClient::recv_presentResponse(Z_PresentResponse *presentResponse)
505 printf ("Got PresentResponse\n");
506 recv_records (presentResponse->records);
512 while (m_socketManager->processEvent() > 0)
514 if (get_lastReceived())
520 #define C_PROMPT "Z>"
522 int MyClient::cmd_connect(char *host)
531 int MyClient::cmd_open(char *host)
542 int MyClient::cmd_init(char *args)
544 if (send_initRequest() >= 0)
551 int MyClient::cmd_quit(char *args)
556 int MyClient::cmd_close(char *args)
562 int MyClient::cmd_find(char *args)
566 if (query.set_rpn(args) <= 0)
568 printf ("Bad RPN query\n");
571 if (send_searchRequest(&query) >= 0)
574 printf ("Not connected\n");
578 int MyClient::cmd_show(char *args)
580 int start = m_setOffset, number = 1;
582 sscanf (args, "%d %d", &start, &number);
584 if (send_presentRequest(start, number) >= 0)
587 printf ("Not connected\n");
591 int MyClient::cmd_cookie(char *args)
593 set_cookie(*args ? args : 0);
597 int MyClient::cmd_format(char *args)
599 set_preferredRecordSyntax(args);
603 int MyClient::cmd_proxy(char *args)
609 #if HAVE_YAZ_URSULA_H
610 int MyClient::cmd_ursula(char *args)
612 Z_APDU *apdu = create_Z_PDU(Z_APDU_extendedServicesRequest);
613 Z_ExtendedServicesRequest *req = apdu->u.extendedServicesRequest;
615 req->packageType = odr_getoidbystr(odr_encode(), "1.2.840.10003");
617 Z_External *ext = (Z_External *) odr_malloc(odr_encode(), sizeof(*ext));
618 req->taskSpecificParameters = ext;
619 ext->direct_reference = req->packageType;
621 ext->indirect_reference = 0;
623 ext->which = Z_External_octet;
624 ext->u.single_ASN1_type = (Odr_oct *)
625 odr_malloc (odr_encode(), sizeof(Odr_oct));
627 Z_UrsPDU *pdu = (Z_UrsPDU *) odr_malloc (odr_encode(), sizeof(*pdu));
628 pdu->which = Z_UrsPDU_request;
629 pdu->u.request = (Z_UrsRequest *)
630 odr_malloc (odr_encode(), sizeof(*pdu->u.request));
631 pdu->u.request->libraryNo = odr_strdup(odr_encode(), "000200");
632 pdu->u.request->borrowerTickerNo = 0;
633 pdu->u.request->disposalType = 0;
634 pdu->u.request->lastUseDate = 0;
635 pdu->u.request->num_items = 0;
636 pdu->u.request->items = (Z_UrsRequestItem **) odr_nullval();
637 pdu->u.request->counter = 0;
638 pdu->u.request->priority = 0;
639 pdu->u.request->disposalNote = 0;
640 pdu->u.request->overrule = 0;
642 if (!z_UrsPDU (odr_encode(), &pdu, 0, ""))
644 yaz_log (LOG_LOG, "ursula encoding failed");
648 odr_getbuf (odr_encode(), &ext->u.single_ASN1_type->len, 0);
650 ext->u.single_ASN1_type->buf = (unsigned char*)
651 odr_malloc (odr_encode(), ext->u.single_ASN1_type->len);
652 memcpy (ext->u.single_ASN1_type->buf, buf, ext->u.single_ASN1_type->len);
653 ext->u.single_ASN1_type->size = ext->u.single_ASN1_type->len;
655 if (send_Z_PDU(apdu) >= 0)
661 int MyClient::processCommand(const char *commandLine)
663 char cmdStr[1024], cmdArgs[1024];
668 int (MyClient::*fun)(char *arg);
671 {"open", &MyClient::cmd_open, "<host>[':'<port>][/<database>]"},
672 {"connect", &MyClient::cmd_connect, "<host>[':'<port>][/<database>]"},
673 {"quit", &MyClient::cmd_quit, ""},
674 {"close", &MyClient::cmd_close, ""},
675 {"find", &MyClient::cmd_find, "<query>"},
676 {"show", &MyClient::cmd_show, "[<start> [<number>]]"},
677 {"cookie", &MyClient::cmd_cookie, "<cookie>"},
678 {"init", &MyClient::cmd_init, ""},
679 {"format", &MyClient::cmd_format, "<record-syntax>"},
680 {"proxy", &MyClient::cmd_proxy, "<host>:[':'<port>]"},
681 #if HAVE_YAZ_URSULA_H
682 {"ursula", &MyClient::cmd_ursula, ""},
687 if (sscanf(commandLine, "%s %[^;]", cmdStr, cmdArgs) < 1)
690 for (i = 0; cmd[i].cmd; i++)
691 if (!strncmp(cmd[i].cmd, cmdStr, strlen(cmdStr)))
695 if (cmd[i].cmd) // Invoke command handler
696 res = (this->*cmd[i].fun)(cmdArgs);
697 else // Dump help screen
699 printf("Unknown command: %s.\n", cmdStr);
700 printf("Currently recognized commands:\n");
701 for (i = 0; cmd[i].cmd; i++)
702 printf(" %s %s\n", cmd[i].cmd, cmd[i].ad);
707 const char *MyClient::getCommand()
709 #if HAVE_READLINE_READLINE_H
710 // Read using GNU readline
712 line_in=readline(C_PROMPT);
715 #if HAVE_READLINE_HISTORY_H
717 add_history(line_in);
719 strncpy(m_thisCommand,line_in, 1023);
720 m_thisCommand[1023] = '\0';
723 // Read using fgets(3)
726 if (!fgets(m_thisCommand, 1023, stdin))
729 // Remove trailing whitespace
730 char *cp = m_thisCommand + strlen(m_thisCommand);
731 while (cp != m_thisCommand && strchr("\t \n", cp[-1]))
735 // Remove leading spaces...
736 while (*cp && strchr ("\t \n", *cp))
738 // Save command if non-empty
740 strcpy (m_lastCommand, cp);
741 return m_lastCommand;
744 int MyClient::interactive(Yaz_SocketManager *socketManager)
747 if (!m_interactive_flag)
749 while ((cmd = getCommand()))
751 if (!processCommand(cmd))
757 int MyClient::args(Yaz_SocketManager *socketManager, int argc, char **argv)
762 char *prog = argv[0];
765 while ((ret = options("c:p:v:q", argv, argc, &arg)) != -2)
789 yaz_log_init_level (yaz_log_mask_str(arg));
792 m_interactive_flag = 0;
811 int main(int argc, char **argv)
813 Yaz_SocketManager mySocketManager;
814 Yaz_PDU_Assoc *some = new Yaz_PDU_Assoc(&mySocketManager);
816 MyClient z(some, &mySocketManager);
818 if (z.args(&mySocketManager, argc, argv))
820 if (z.interactive(&mySocketManager))