2 * Copyright (c) 1998-2000, Index Data.
3 * See the file LICENSE for details.
5 * $Log: yaz-my-client.cpp,v $
6 * Revision 1.5 2001-04-10 10:48:08 adam
7 * Fixed problem where proxy could cash bad result sets.
9 * Revision 1.4 2001/04/05 15:12:24 adam
12 * Revision 1.3 2001/04/05 13:09:44 adam
13 * Removed ursula dependancy.
15 * Revision 1.2 2001/04/04 14:02:49 adam
16 * URSULA / Z-ruth service.
18 * Revision 1.1 2001/03/27 14:47:45 adam
19 * New server facility scheme.
21 * Revision 1.17 2001/03/26 14:43:49 adam
22 * New threaded PDU association.
24 * Revision 1.16 2000/11/01 14:22:59 adam
25 * Added fd parameter for method IYaz_PDU_Observer::clone.
27 * Revision 1.15 2000/10/11 11:58:16 adam
28 * Moved header files to include/yaz++. Switched to libtool and automake.
29 * Configure script creates yaz++-config script.
31 * Revision 1.14 2000/09/08 10:23:42 adam
32 * Added skeleton of yaz-z-server.
34 * Revision 1.13 2000/09/06 14:23:45 adam
37 * Revision 1.12 2000/09/04 08:59:16 adam
38 * Changed call to logging functions (yaz_ added).
40 * Revision 1.11 2000/07/04 13:48:49 adam
41 * Implemented upper-limit on proxy-to-target sessions.
43 * Revision 1.10 2000/05/30 03:12:27 ian
44 * minor change to stop g++ 2.95.2 complaining about taking the address
45 * of a member function.
47 * Revision 1.9 1999/12/06 13:52:45 adam
48 * Modified for new location of YAZ header files. Experimental threaded
51 * Revision 1.8 1999/11/10 10:02:34 adam
54 * Revision 1.7 1999/04/21 12:09:01 adam
55 * Many improvements. Modified to proxy server to work with "sessions"
58 * Revision 1.6 1999/04/20 10:30:05 adam
59 * Implemented various stuff for client and proxy. Updated calls
60 * to ODR to reflect new name parameter.
62 * Revision 1.5 1999/04/09 11:46:57 adam
63 * Added object Yaz_Z_Assoc. Much more functional client.
65 * Revision 1.4 1999/03/23 14:17:57 adam
66 * More work on timeout handling. Work on yaz-client.
68 * Revision 1.3 1999/02/02 14:01:18 adam
69 * First WIN32 port of YAZ++.
71 * Revision 1.2 1999/01/28 13:08:42 adam
72 * Yaz_PDU_Assoc better encapsulated. Memory leak fix in
73 * yaz-socket-manager.cc.
75 * Revision 1.1.1.1 1999/01/28 09:41:07 adam
76 * First implementation of YAZ++.
81 #include <yaz/options.h>
82 #include <yaz/diagbib1.h>
83 #include <yaz/marcdisp.h>
84 #include <yaz++/yaz-ir-assoc.h>
85 #include <yaz++/yaz-pdu-assoc.h>
86 #include <yaz++/yaz-socket-manager.h>
89 #include <yaz/zes-ursula.h>
93 #if HAVE_READLINE_READLINE_H
94 #include <readline/readline.h>
96 #if HAVE_READLINE_HISTORY_H
97 #include <readline/history.h>
101 class YAZ_EXPORT MyClient : public Yaz_IR_Assoc {
103 int m_interactive_flag;
104 char m_thisCommand[1024];
105 char m_lastCommand[1024];
107 Yaz_SocketManager *m_socketManager;
109 MyClient(IYaz_PDU_Observable *the_PDU_Observable,
110 Yaz_SocketManager *the_SocketManager);
111 IYaz_PDU_Observer *sessionNotify(
112 IYaz_PDU_Observable *the_PDU_Observable, int fd);
113 int args(Yaz_SocketManager *socketManager, int argc, char **argv);
114 int interactive(Yaz_SocketManager *socketManager);
116 void recv_initResponse(Z_InitResponse *initResponse);
117 void recv_searchResponse(Z_SearchResponse *searchResponse);
118 void recv_presentResponse(Z_PresentResponse *presentResponse);
119 void recv_records (Z_Records *records);
120 void recv_diagrecs(Z_DiagRec **pp, int num);
121 void recv_namePlusRecord (Z_NamePlusRecord *zpr, int offset);
122 void recv_record(Z_DatabaseRecord *record, int offset,
123 const char *databaseName);
124 void recv_textRecord(int type, const char *buf, size_t len);
125 void recv_genericRecord(Z_GenericRecord *r);
126 void display_genericRecord(Z_GenericRecord *r, int level);
127 void display_variant(Z_Variant *v, int level);
128 void connectNotify();
130 void timeoutNotify();
131 char *get_cookie (Z_OtherInformation **oi);
132 int processCommand(const char *cmd);
133 const char *MyClient::getCommand();
134 int cmd_open(char *host);
135 int cmd_connect(char *host);
136 int cmd_quit(char *args);
137 int cmd_close(char *args);
138 int cmd_find(char *args);
139 int cmd_show(char *args);
140 int cmd_cookie(char *args);
141 int cmd_init(char *args);
142 int cmd_format(char *args);
143 int cmd_proxy(char *args);
144 #if HAVE_YAZ_URSULA_H
145 int cmd_ursula(char *args);
150 void MyClient::connectNotify()
152 printf ("Connection accepted by target\n");
153 set_lastReceived(-1);
156 void MyClient::timeoutNotify()
158 printf ("Connection timeout\n");
162 void MyClient::failNotify()
164 printf ("Connection closed by target\n");
165 set_lastReceived(-1);
168 IYaz_PDU_Observer *MyClient::sessionNotify(
169 IYaz_PDU_Observable *the_PDU_Observable, int fd)
171 return new MyClient(the_PDU_Observable, m_socketManager);
174 MyClient::MyClient(IYaz_PDU_Observable *the_PDU_Observable,
175 Yaz_SocketManager *the_socketManager) :
176 Yaz_IR_Assoc (the_PDU_Observable)
179 m_interactive_flag = 1;
180 m_thisCommand[0] = '\0';
181 m_lastCommand[0] = '\0';
182 m_socketManager = the_socketManager;
185 void usage(char *prog)
187 fprintf (stderr, "%s: [-v log] [-c cookie] [-p proxy] [zurl]\n", prog);
191 char *MyClient::get_cookie(Z_OtherInformation **otherInfo)
194 Z_OtherInformationUnit *oi;
196 ent.proto = PROTO_Z3950;
197 ent.oclass = CLASS_USERINFO;
198 ent.value = (oid_value) VAL_COOKIE;
200 if (oid_ent_to_oid (&ent, oid) &&
201 (oi = update_otherInformation(otherInfo, 0, oid, 1, 1)) &&
202 oi->which == Z_OtherInfo_characterInfo)
203 return oi->information.characterInfo;
207 void MyClient::recv_initResponse(Z_InitResponse *initResponse)
209 printf ("Got InitResponse. Status ");
210 if (*initResponse->result)
214 const char *p = get_cookie (&initResponse->otherInfo);
217 printf ("cookie = %s\n", p);
225 void MyClient::recv_diagrecs(Z_DiagRec **pp, int num)
229 Z_DefaultDiagFormat *r;
231 printf("Diagnostic message(s) from database:\n");
232 for (i = 0; i<num; i++)
234 Z_DiagRec *p = pp[i];
235 if (p->which != Z_DiagRec_defaultFormat)
237 printf("Diagnostic record not in default format.\n");
241 r = p->u.defaultFormat;
242 if (!(ent = oid_getentbyoid(r->diagnosticSetId)) ||
243 ent->oclass != CLASS_DIAGSET || ent->value != VAL_BIB1)
244 printf("Missing or unknown diagset\n");
245 printf(" [%d] %s", *r->condition, diagbib1_str(*r->condition));
249 case Z_DefaultDiagFormat_v2Addinfo:
250 printf (" -- v2 addinfo '%s'\n", r->u.v2Addinfo);
252 case Z_DefaultDiagFormat_v3Addinfo:
253 printf (" -- v3 addinfo '%s'\n", r->u.v3Addinfo);
257 if (r->addinfo && *r->addinfo)
258 printf(" -- '%s'\n", r->addinfo);
265 void MyClient::recv_textRecord(int type, const char *buf, size_t len)
267 fwrite (buf, 1, len, stdout);
268 fputc ('\n', stdout);
271 void MyClient::display_variant(Z_Variant *v, int level)
275 for (i = 0; i < v->num_triples; i++)
277 printf("%*sclass=%d,type=%d", level * 4, "", *v->triples[i]->zclass,
278 *v->triples[i]->type);
279 if (v->triples[i]->which == Z_Triple_internationalString)
280 printf(",value=%s\n", v->triples[i]->value.internationalString);
286 void MyClient::display_genericRecord(Z_GenericRecord *r, int level)
292 for (i = 0; i < r->num_elements; i++)
296 printf("%*s", level * 4, "");
300 printf("%d,", *t->tagType);
303 if (t->tagValue->which == Z_StringOrNumeric_numeric)
304 printf("%d) ", *t->tagValue->u.numeric);
306 printf("%s) ", t->tagValue->u.string);
307 if (t->content->which == Z_ElementData_subtree)
310 display_genericRecord(t->content->u.subtree, level+1);
312 else if (t->content->which == Z_ElementData_string)
313 printf("%s\n", t->content->u.string);
314 else if (t->content->which == Z_ElementData_numeric)
315 printf("%d\n", *t->content->u.numeric);
316 else if (t->content->which == Z_ElementData_oid)
318 int *ip = t->content->u.oid;
321 if ((oent = oid_getentbyoid(t->content->u.oid)))
322 printf("OID: %s\n", oent->desc);
326 while (ip && *ip >= 0)
327 printf(" %d", *(ip++));
331 else if (t->content->which == Z_ElementData_noDataRequested)
332 printf("[No data requested]\n");
333 else if (t->content->which == Z_ElementData_elementEmpty)
334 printf("[Element empty]\n");
335 else if (t->content->which == Z_ElementData_elementNotThere)
336 printf("[Element not there]\n");
339 if (t->appliedVariant)
340 display_variant(t->appliedVariant, level+1);
341 if (t->metaData && t->metaData->supportedVariants)
345 printf("%*s---- variant list\n", (level+1)*4, "");
346 for (c = 0; c < t->metaData->num_supportedVariants; c++)
348 printf("%*svariant #%d\n", (level+1)*4, "", c);
349 display_variant(t->metaData->supportedVariants[c], level + 2);
355 void MyClient::recv_genericRecord(Z_GenericRecord *r)
357 display_genericRecord(r, 0);
360 void MyClient::recv_record(Z_DatabaseRecord *record, int offset,
361 const char *databaseName)
363 Z_External *r = (Z_External*) record;
364 oident *ent = oid_getentbyoid(r->direct_reference);
367 * Tell the user what we got.
369 if (r->direct_reference)
371 printf("Record type: ");
373 printf("%s\n", ent->desc);
375 /* Check if this is a known, ASN.1 type tucked away in an octet string */
376 Z_ext_typeent *etype = z_ext_getentbyref(ent->value);
377 if (ent && (r->which == Z_External_octet || r->which == Z_External_single)
378 && (etype = z_ext_getentbyref(ent->value)))
383 * Call the given decoder to process the record.
385 odr_setbuf(odr_decode(), (char*)record->u.octet_aligned->buf,
386 record->u.octet_aligned->len, 0);
387 if (!(*etype->fun)(odr_decode(), (char **)&rr, 0, 0))
389 odr_perror(odr_decode(), "Decoding constructed record.");
390 fprintf(stderr, "[Near %d]\n", odr_offset(odr_decode()));
391 fprintf(stderr, "Packet dump:\n---------\n");
392 odr_dumpBER(stderr, (char*)record->u.octet_aligned->buf,
393 record->u.octet_aligned->len);
394 fprintf(stderr, "---------\n");
396 if (etype->what == Z_External_sutrs)
398 Z_SUTRS *sutrs = (Z_SUTRS *) rr;
399 recv_textRecord ((int) VAL_SUTRS, (const char *) sutrs->buf,
400 (size_t) sutrs->len);
404 if (r->which == Z_External_octet && record->u.octet_aligned->len)
430 marc_display((char*) record->u.octet_aligned->buf,0);
433 recv_textRecord((int) ent->value,
434 (const char *) record->u.octet_aligned->buf,
435 (size_t) record->u.octet_aligned->len);
438 else if (ent && ent->value == VAL_SUTRS && r->which == Z_External_sutrs)
439 recv_textRecord((int) VAL_SUTRS, (const char *) r->u.sutrs->buf,
440 (size_t) r->u.sutrs->len);
441 else if (ent && ent->value == VAL_GRS1 && r->which == Z_External_grs1)
442 recv_genericRecord(r->u.grs1);
445 printf("Unknown record representation.\n");
446 if (!z_External(odr_print(), &r, 0, 0))
448 odr_perror(odr_print(), "Printing external");
449 odr_reset(odr_print());
454 void MyClient::recv_namePlusRecord (Z_NamePlusRecord *zpr, int offset)
456 if (zpr->databaseName)
457 printf("[%s]", zpr->databaseName);
458 if (zpr->which == Z_NamePlusRecord_surrogateDiagnostic)
459 recv_diagrecs(&zpr->u.surrogateDiagnostic, 1);
461 recv_record(zpr->u.databaseRecord, offset, zpr->databaseName);
464 void MyClient::recv_records (Z_Records *records)
467 Z_DiagRec dr, *dr_p = &dr;
472 switch (records->which)
474 case Z_Records_DBOSD:
475 for (i = 0; i < records->u.databaseOrSurDiagnostics->num_records; i++)
476 recv_namePlusRecord(records->u.databaseOrSurDiagnostics->
477 records[i], i + m_setOffset);
478 m_setOffset += records->u.databaseOrSurDiagnostics->num_records;
482 dr.which = Z_DiagRec_defaultFormat;
483 dr.u.defaultFormat = records->u.nonSurrogateDiagnostic;
484 recv_diagrecs (&dr_p, 1);
486 recv_diagrecs (&records->u.nonSurrogateDiagnostic, 1);
489 case Z_Records_multipleNSD:
490 recv_diagrecs (records->u.multipleNonSurDiagnostics->diagRecs,
491 records->u.multipleNonSurDiagnostics->num_diagRecs);
496 void MyClient::recv_searchResponse(Z_SearchResponse *searchResponse)
498 printf ("Got SearchResponse. Status ");
499 if (!*searchResponse->searchStatus)
506 printf ("Hits: %d\n", *searchResponse->resultCount);
508 recv_records (searchResponse->records);
511 void MyClient::recv_presentResponse(Z_PresentResponse *presentResponse)
513 printf ("Got PresentResponse\n");
514 recv_records (presentResponse->records);
520 while (m_socketManager->processEvent() > 0)
522 if (get_lastReceived())
528 #define C_PROMPT "Z>"
530 int MyClient::cmd_connect(char *host)
539 int MyClient::cmd_open(char *host)
550 int MyClient::cmd_init(char *args)
552 if (send_initRequest() >= 0)
559 int MyClient::cmd_quit(char *args)
564 int MyClient::cmd_close(char *args)
570 int MyClient::cmd_find(char *args)
574 if (query.set_rpn(args) <= 0)
576 printf ("Bad RPN query\n");
579 if (send_searchRequest(&query) >= 0)
582 printf ("Not connected\n");
586 int MyClient::cmd_show(char *args)
588 int start = m_setOffset, number = 1;
590 sscanf (args, "%d %d", &start, &number);
592 if (send_presentRequest(start, number) >= 0)
595 printf ("Not connected\n");
599 int MyClient::cmd_cookie(char *args)
601 set_cookie(*args ? args : 0);
605 int MyClient::cmd_format(char *args)
607 set_preferredRecordSyntax(args);
611 int MyClient::cmd_proxy(char *args)
617 #if HAVE_YAZ_URSULA_H
618 int MyClient::cmd_ursula(char *args)
620 Z_APDU *apdu = create_Z_PDU(Z_APDU_extendedServicesRequest);
621 Z_ExtendedServicesRequest *req = apdu->u.extendedServicesRequest;
623 req->packageType = odr_getoidbystr(odr_encode(), "1.2.840.10003");
625 Z_External *ext = (Z_External *) odr_malloc(odr_encode(), sizeof(*ext));
626 req->taskSpecificParameters = ext;
627 ext->direct_reference = req->packageType;
629 ext->indirect_reference = 0;
631 ext->which = Z_External_octet;
632 ext->u.single_ASN1_type = (Odr_oct *)
633 odr_malloc (odr_encode(), sizeof(Odr_oct));
635 Z_UrsPDU *pdu = (Z_UrsPDU *) odr_malloc (odr_encode(), sizeof(*pdu));
636 pdu->which = Z_UrsPDU_request;
637 pdu->u.request = (Z_UrsRequest *)
638 odr_malloc (odr_encode(), sizeof(*pdu->u.request));
639 pdu->u.request->libraryNo = odr_strdup(odr_encode(), "000200");
640 pdu->u.request->borrowerTickerNo = 0;
641 pdu->u.request->disposalType = 0;
642 pdu->u.request->lastUseDate = 0;
643 pdu->u.request->num_items = 0;
644 pdu->u.request->items = (Z_UrsRequestItem **) odr_nullval();
645 pdu->u.request->counter = 0;
646 pdu->u.request->priority = 0;
647 pdu->u.request->disposalNote = 0;
648 pdu->u.request->overrule = 0;
650 if (!z_UrsPDU (odr_encode(), &pdu, 0, ""))
652 yaz_log (LOG_LOG, "ursula encoding failed");
656 odr_getbuf (odr_encode(), &ext->u.single_ASN1_type->len, 0);
658 ext->u.single_ASN1_type->buf = (unsigned char*)
659 odr_malloc (odr_encode(), ext->u.single_ASN1_type->len);
660 memcpy (ext->u.single_ASN1_type->buf, buf, ext->u.single_ASN1_type->len);
661 ext->u.single_ASN1_type->size = ext->u.single_ASN1_type->len;
663 if (send_Z_PDU(apdu) >= 0)
669 int MyClient::processCommand(const char *commandLine)
671 char cmdStr[1024], cmdArgs[1024];
676 int (MyClient::*fun)(char *arg);
679 {"open", &MyClient::cmd_open, "<host>[':'<port>][/<database>]"},
680 {"connect", &MyClient::cmd_connect, "<host>[':'<port>][/<database>]"},
681 {"quit", &MyClient::cmd_quit, ""},
682 {"close", &MyClient::cmd_close, ""},
683 {"find", &MyClient::cmd_find, "<query>"},
684 {"show", &MyClient::cmd_show, "[<start> [<number>]]"},
685 {"cookie", &MyClient::cmd_cookie, "<cookie>"},
686 {"init", &MyClient::cmd_init, ""},
687 {"format", &MyClient::cmd_format, "<record-syntax>"},
688 {"proxy", &MyClient::cmd_proxy, "<host>:[':'<port>]"},
689 #if HAVE_YAZ_URSULA_H
690 {"ursula", &MyClient::cmd_ursula, ""},
695 if (sscanf(commandLine, "%s %[^;]", cmdStr, cmdArgs) < 1)
698 for (i = 0; cmd[i].cmd; i++)
699 if (!strncmp(cmd[i].cmd, cmdStr, strlen(cmdStr)))
703 if (cmd[i].cmd) // Invoke command handler
704 res = (this->*cmd[i].fun)(cmdArgs);
705 else // Dump help screen
707 printf("Unknown command: %s.\n", cmdStr);
708 printf("Currently recognized commands:\n");
709 for (i = 0; cmd[i].cmd; i++)
710 printf(" %s %s\n", cmd[i].cmd, cmd[i].ad);
715 const char *MyClient::getCommand()
717 #if HAVE_READLINE_READLINE_H
718 // Read using GNU readline
720 line_in=readline(C_PROMPT);
723 #if HAVE_READLINE_HISTORY_H
725 add_history(line_in);
727 strncpy(m_thisCommand,line_in, 1023);
728 m_thisCommand[1023] = '\0';
731 // Read using fgets(3)
734 if (!fgets(m_thisCommand, 1023, stdin))
737 // Remove trailing whitespace
738 char *cp = m_thisCommand + strlen(m_thisCommand);
739 while (cp != m_thisCommand && strchr("\t \n", cp[-1]))
743 // Remove leading spaces...
744 while (*cp && strchr ("\t \n", *cp))
746 // Save command if non-empty
748 strcpy (m_lastCommand, cp);
749 return m_lastCommand;
752 int MyClient::interactive(Yaz_SocketManager *socketManager)
755 if (!m_interactive_flag)
757 while ((cmd = getCommand()))
759 if (!processCommand(cmd))
765 int MyClient::args(Yaz_SocketManager *socketManager, int argc, char **argv)
770 char *prog = argv[0];
773 while ((ret = options("c:p:v:q", argv, argc, &arg)) != -2)
797 yaz_log_init_level (yaz_log_mask_str(arg));
800 m_interactive_flag = 0;
819 int main(int argc, char **argv)
821 Yaz_SocketManager mySocketManager;
822 Yaz_PDU_Assoc *some = new Yaz_PDU_Assoc(&mySocketManager);
824 MyClient z(some, &mySocketManager);
826 if (z.args(&mySocketManager, argc, argv))
828 if (z.interactive(&mySocketManager))