2 * Copyright (c) 1998-2000, Index Data.
3 * See the file LICENSE for details.
5 * $Log: yaz-my-client.cpp,v $
6 * Revision 1.2 2001-04-04 14:02:49 adam
7 * URSULA / Z-ruth service.
9 * Revision 1.1 2001/03/27 14:47:45 adam
10 * New server facility scheme.
12 * Revision 1.17 2001/03/26 14:43:49 adam
13 * New threaded PDU association.
15 * Revision 1.16 2000/11/01 14:22:59 adam
16 * Added fd parameter for method IYaz_PDU_Observer::clone.
18 * Revision 1.15 2000/10/11 11:58:16 adam
19 * Moved header files to include/yaz++. Switched to libtool and automake.
20 * Configure script creates yaz++-config script.
22 * Revision 1.14 2000/09/08 10:23:42 adam
23 * Added skeleton of yaz-z-server.
25 * Revision 1.13 2000/09/06 14:23:45 adam
28 * Revision 1.12 2000/09/04 08:59:16 adam
29 * Changed call to logging functions (yaz_ added).
31 * Revision 1.11 2000/07/04 13:48:49 adam
32 * Implemented upper-limit on proxy-to-target sessions.
34 * Revision 1.10 2000/05/30 03:12:27 ian
35 * minor change to stop g++ 2.95.2 complaining about taking the address
36 * of a member function.
38 * Revision 1.9 1999/12/06 13:52:45 adam
39 * Modified for new location of YAZ header files. Experimental threaded
42 * Revision 1.8 1999/11/10 10:02:34 adam
45 * Revision 1.7 1999/04/21 12:09:01 adam
46 * Many improvements. Modified to proxy server to work with "sessions"
49 * Revision 1.6 1999/04/20 10:30:05 adam
50 * Implemented various stuff for client and proxy. Updated calls
51 * to ODR to reflect new name parameter.
53 * Revision 1.5 1999/04/09 11:46:57 adam
54 * Added object Yaz_Z_Assoc. Much more functional client.
56 * Revision 1.4 1999/03/23 14:17:57 adam
57 * More work on timeout handling. Work on yaz-client.
59 * Revision 1.3 1999/02/02 14:01:18 adam
60 * First WIN32 port of YAZ++.
62 * Revision 1.2 1999/01/28 13:08:42 adam
63 * Yaz_PDU_Assoc better encapsulated. Memory leak fix in
64 * yaz-socket-manager.cc.
66 * Revision 1.1.1.1 1999/01/28 09:41:07 adam
67 * First implementation of YAZ++.
72 #include <yaz/options.h>
73 #include <yaz/diagbib1.h>
74 #include <yaz/marcdisp.h>
75 #include <yaz++/yaz-ir-assoc.h>
76 #include <yaz++/yaz-pdu-assoc.h>
77 #include <yaz++/yaz-socket-manager.h>
78 #include <yaz/zes-ursula.h>
81 #if HAVE_READLINE_READLINE_H
82 #include <readline/readline.h>
84 #if HAVE_READLINE_HISTORY_H
85 #include <readline/history.h>
89 class YAZ_EXPORT MyClient : public Yaz_IR_Assoc {
91 int m_interactive_flag;
92 char m_thisCommand[1024];
93 char m_lastCommand[1024];
95 Yaz_SocketManager *m_socketManager;
97 MyClient(IYaz_PDU_Observable *the_PDU_Observable,
98 Yaz_SocketManager *the_SocketManager);
99 IYaz_PDU_Observer *sessionNotify(
100 IYaz_PDU_Observable *the_PDU_Observable, int fd);
101 int args(Yaz_SocketManager *socketManager, int argc, char **argv);
102 int interactive(Yaz_SocketManager *socketManager);
104 void recv_initResponse(Z_InitResponse *initResponse);
105 void recv_searchResponse(Z_SearchResponse *searchResponse);
106 void recv_presentResponse(Z_PresentResponse *presentResponse);
107 void recv_records (Z_Records *records);
108 void recv_diagrecs(Z_DiagRec **pp, int num);
109 void recv_namePlusRecord (Z_NamePlusRecord *zpr, int offset);
110 void recv_record(Z_DatabaseRecord *record, int offset,
111 const char *databaseName);
112 void recv_textRecord(int type, const char *buf, size_t len);
113 void recv_genericRecord(Z_GenericRecord *r);
114 void display_genericRecord(Z_GenericRecord *r, int level);
115 void display_variant(Z_Variant *v, int level);
116 void connectNotify();
118 void timeoutNotify();
119 char *get_cookie (Z_OtherInformation **oi);
120 int processCommand(const char *cmd);
121 const char *MyClient::getCommand();
122 int cmd_open(char *host);
123 int cmd_connect(char *host);
124 int cmd_quit(char *args);
125 int cmd_close(char *args);
126 int cmd_find(char *args);
127 int cmd_show(char *args);
128 int cmd_cookie(char *args);
129 int cmd_init(char *args);
130 int cmd_format(char *args);
131 int cmd_proxy(char *args);
132 int cmd_ursula(char *args);
136 void MyClient::connectNotify()
138 printf ("Connection accepted by target\n");
139 set_lastReceived(-1);
142 void MyClient::timeoutNotify()
144 printf ("Connection timeout\n");
148 void MyClient::failNotify()
150 printf ("Connection closed by target\n");
151 set_lastReceived(-1);
154 IYaz_PDU_Observer *MyClient::sessionNotify(
155 IYaz_PDU_Observable *the_PDU_Observable, int fd)
157 return new MyClient(the_PDU_Observable, m_socketManager);
160 MyClient::MyClient(IYaz_PDU_Observable *the_PDU_Observable,
161 Yaz_SocketManager *the_socketManager) :
162 Yaz_IR_Assoc (the_PDU_Observable)
165 m_interactive_flag = 1;
166 m_thisCommand[0] = '\0';
167 m_lastCommand[0] = '\0';
168 m_socketManager = the_socketManager;
171 void usage(char *prog)
173 fprintf (stderr, "%s: [-v log] [-c cookie] [-p proxy] [zurl]\n", prog);
177 char *MyClient::get_cookie(Z_OtherInformation **otherInfo)
180 Z_OtherInformationUnit *oi;
182 ent.proto = PROTO_Z3950;
183 ent.oclass = CLASS_USERINFO;
184 ent.value = (oid_value) VAL_COOKIE;
186 if (oid_ent_to_oid (&ent, oid) &&
187 (oi = update_otherInformation(otherInfo, 0, oid, 1, 1)) &&
188 oi->which == Z_OtherInfo_characterInfo)
189 return oi->information.characterInfo;
193 void MyClient::recv_initResponse(Z_InitResponse *initResponse)
195 printf ("Got InitResponse. Status ");
196 if (*initResponse->result)
200 const char *p = get_cookie (&initResponse->otherInfo);
203 printf ("cookie = %s\n", p);
211 void MyClient::recv_diagrecs(Z_DiagRec **pp, int num)
215 Z_DefaultDiagFormat *r;
217 printf("Diagnostic message(s) from database:\n");
218 for (i = 0; i<num; i++)
220 Z_DiagRec *p = pp[i];
221 if (p->which != Z_DiagRec_defaultFormat)
223 printf("Diagnostic record not in default format.\n");
227 r = p->u.defaultFormat;
228 if (!(ent = oid_getentbyoid(r->diagnosticSetId)) ||
229 ent->oclass != CLASS_DIAGSET || ent->value != VAL_BIB1)
230 printf("Missing or unknown diagset\n");
231 printf(" [%d] %s", *r->condition, diagbib1_str(*r->condition));
235 case Z_DefaultDiagFormat_v2Addinfo:
236 printf (" -- v2 addinfo '%s'\n", r->u.v2Addinfo);
238 case Z_DefaultDiagFormat_v3Addinfo:
239 printf (" -- v3 addinfo '%s'\n", r->u.v3Addinfo);
243 if (r->addinfo && *r->addinfo)
244 printf(" -- '%s'\n", r->addinfo);
251 void MyClient::recv_textRecord(int type, const char *buf, size_t len)
253 fwrite (buf, 1, len, stdout);
254 fputc ('\n', stdout);
257 void MyClient::display_variant(Z_Variant *v, int level)
261 for (i = 0; i < v->num_triples; i++)
263 printf("%*sclass=%d,type=%d", level * 4, "", *v->triples[i]->zclass,
264 *v->triples[i]->type);
265 if (v->triples[i]->which == Z_Triple_internationalString)
266 printf(",value=%s\n", v->triples[i]->value.internationalString);
272 void MyClient::display_genericRecord(Z_GenericRecord *r, int level)
278 for (i = 0; i < r->num_elements; i++)
282 printf("%*s", level * 4, "");
286 printf("%d,", *t->tagType);
289 if (t->tagValue->which == Z_StringOrNumeric_numeric)
290 printf("%d) ", *t->tagValue->u.numeric);
292 printf("%s) ", t->tagValue->u.string);
293 if (t->content->which == Z_ElementData_subtree)
296 display_genericRecord(t->content->u.subtree, level+1);
298 else if (t->content->which == Z_ElementData_string)
299 printf("%s\n", t->content->u.string);
300 else if (t->content->which == Z_ElementData_numeric)
301 printf("%d\n", *t->content->u.numeric);
302 else if (t->content->which == Z_ElementData_oid)
304 int *ip = t->content->u.oid;
307 if ((oent = oid_getentbyoid(t->content->u.oid)))
308 printf("OID: %s\n", oent->desc);
312 while (ip && *ip >= 0)
313 printf(" %d", *(ip++));
317 else if (t->content->which == Z_ElementData_noDataRequested)
318 printf("[No data requested]\n");
319 else if (t->content->which == Z_ElementData_elementEmpty)
320 printf("[Element empty]\n");
321 else if (t->content->which == Z_ElementData_elementNotThere)
322 printf("[Element not there]\n");
325 if (t->appliedVariant)
326 display_variant(t->appliedVariant, level+1);
327 if (t->metaData && t->metaData->supportedVariants)
331 printf("%*s---- variant list\n", (level+1)*4, "");
332 for (c = 0; c < t->metaData->num_supportedVariants; c++)
334 printf("%*svariant #%d\n", (level+1)*4, "", c);
335 display_variant(t->metaData->supportedVariants[c], level + 2);
341 void MyClient::recv_genericRecord(Z_GenericRecord *r)
343 display_genericRecord(r, 0);
346 void MyClient::recv_record(Z_DatabaseRecord *record, int offset,
347 const char *databaseName)
349 Z_External *r = (Z_External*) record;
350 oident *ent = oid_getentbyoid(r->direct_reference);
353 * Tell the user what we got.
355 if (r->direct_reference)
357 printf("Record type: ");
359 printf("%s\n", ent->desc);
361 /* Check if this is a known, ASN.1 type tucked away in an octet string */
362 Z_ext_typeent *etype = z_ext_getentbyref(ent->value);
363 if (ent && (r->which == Z_External_octet || r->which == Z_External_single)
364 && (etype = z_ext_getentbyref(ent->value)))
369 * Call the given decoder to process the record.
371 odr_setbuf(odr_decode(), (char*)record->u.octet_aligned->buf,
372 record->u.octet_aligned->len, 0);
373 if (!(*etype->fun)(odr_decode(), (char **)&rr, 0, 0))
375 odr_perror(odr_decode(), "Decoding constructed record.");
376 fprintf(stderr, "[Near %d]\n", odr_offset(odr_decode()));
377 fprintf(stderr, "Packet dump:\n---------\n");
378 odr_dumpBER(stderr, (char*)record->u.octet_aligned->buf,
379 record->u.octet_aligned->len);
380 fprintf(stderr, "---------\n");
382 if (etype->what == Z_External_sutrs)
384 Z_SUTRS *sutrs = (Z_SUTRS *) rr;
385 recv_textRecord ((int) VAL_SUTRS, (const char *) sutrs->buf,
386 (size_t) sutrs->len);
390 if (r->which == Z_External_octet && record->u.octet_aligned->len)
416 marc_display((char*) record->u.octet_aligned->buf,stdout);
419 recv_textRecord((int) ent->value,
420 (const char *) record->u.octet_aligned->buf,
421 (size_t) record->u.octet_aligned->len);
424 else if (ent && ent->value == VAL_SUTRS && r->which == Z_External_sutrs)
425 recv_textRecord((int) VAL_SUTRS, (const char *) r->u.sutrs->buf,
426 (size_t) r->u.sutrs->len);
427 else if (ent && ent->value == VAL_GRS1 && r->which == Z_External_grs1)
428 recv_genericRecord(r->u.grs1);
431 printf("Unknown record representation.\n");
432 if (!z_External(odr_print(), &r, 0, 0))
434 odr_perror(odr_print(), "Printing external");
435 odr_reset(odr_print());
440 void MyClient::recv_namePlusRecord (Z_NamePlusRecord *zpr, int offset)
442 if (zpr->databaseName)
443 printf("[%s]", zpr->databaseName);
444 if (zpr->which == Z_NamePlusRecord_surrogateDiagnostic)
445 recv_diagrecs(&zpr->u.surrogateDiagnostic, 1);
447 recv_record(zpr->u.databaseRecord, offset, zpr->databaseName);
450 void MyClient::recv_records (Z_Records *records)
453 Z_DiagRec dr, *dr_p = &dr;
458 switch (records->which)
460 case Z_Records_DBOSD:
461 for (i = 0; i < records->u.databaseOrSurDiagnostics->num_records; i++)
462 recv_namePlusRecord(records->u.databaseOrSurDiagnostics->
463 records[i], i + m_setOffset);
464 m_setOffset += records->u.databaseOrSurDiagnostics->num_records;
468 dr.which = Z_DiagRec_defaultFormat;
469 dr.u.defaultFormat = records->u.nonSurrogateDiagnostic;
470 recv_diagrecs (&dr_p, 1);
472 recv_diagrecs (&records->u.nonSurrogateDiagnostic, 1);
475 case Z_Records_multipleNSD:
476 recv_diagrecs (records->u.multipleNonSurDiagnostics->diagRecs,
477 records->u.multipleNonSurDiagnostics->num_diagRecs);
482 void MyClient::recv_searchResponse(Z_SearchResponse *searchResponse)
484 printf ("Got SearchResponse. Status ");
485 if (!*searchResponse->searchStatus)
491 printf ("Hits: %d\n", *searchResponse->resultCount);
492 recv_records (searchResponse->records);
495 void MyClient::recv_presentResponse(Z_PresentResponse *presentResponse)
497 printf ("Got PresentResponse\n");
498 recv_records (presentResponse->records);
504 while (m_socketManager->processEvent() > 0)
506 if (get_lastReceived())
512 #define C_PROMPT "Z>"
514 int MyClient::cmd_connect(char *host)
523 int MyClient::cmd_open(char *host)
534 int MyClient::cmd_init(char *args)
536 if (send_initRequest() >= 0)
543 int MyClient::cmd_quit(char *args)
548 int MyClient::cmd_close(char *args)
554 int MyClient::cmd_find(char *args)
558 if (query.set_rpn(args) <= 0)
560 printf ("Bad RPN query\n");
563 if (send_searchRequest(&query) >= 0)
566 printf ("Not connected\n");
570 int MyClient::cmd_show(char *args)
572 int start = m_setOffset, number = 1;
574 sscanf (args, "%d %d", &start, &number);
576 if (send_presentRequest(start, number) >= 0)
579 printf ("Not connected\n");
583 int MyClient::cmd_cookie(char *args)
585 set_cookie(*args ? args : 0);
589 int MyClient::cmd_format(char *args)
591 set_preferredRecordSyntax(args);
595 int MyClient::cmd_proxy(char *args)
601 int MyClient::cmd_ursula(char *args)
603 Z_APDU *apdu = create_Z_PDU(Z_APDU_extendedServicesRequest);
604 Z_ExtendedServicesRequest *req = apdu->u.extendedServicesRequest;
606 req->packageType = odr_getoidbystr(odr_encode(), "1.2.840.10003");
608 Z_External *ext = (Z_External *) odr_malloc(odr_encode(), sizeof(*ext));
609 req->taskSpecificParameters = ext;
610 ext->direct_reference = req->packageType;
612 ext->indirect_reference = 0;
614 ext->which = Z_External_octet;
615 ext->u.single_ASN1_type = (Odr_oct *)
616 odr_malloc (odr_encode(), sizeof(Odr_oct));
618 Z_UrsPDU *pdu = (Z_UrsPDU *) odr_malloc (odr_encode(), sizeof(*pdu));
619 pdu->which = Z_UrsPDU_request;
620 pdu->u.request = (Z_UrsRequest *)
621 odr_malloc (odr_encode(), sizeof(*pdu->u.request));
622 pdu->u.request->libraryNo = odr_strdup(odr_encode(), "000200");
623 pdu->u.request->borrowerTickerNo = 0;
624 pdu->u.request->disposalType = 0;
625 pdu->u.request->lastUseDate = 0;
626 pdu->u.request->num_items = 0;
627 pdu->u.request->items = (Z_UrsRequestItem **) odr_nullval();
628 pdu->u.request->counter = 0;
629 pdu->u.request->priority = 0;
630 pdu->u.request->disposalNote = 0;
631 pdu->u.request->overrule = 0;
633 if (!z_UrsPDU (odr_encode(), &pdu, 0, ""))
635 yaz_log (LOG_LOG, "ursula encoding failed");
639 odr_getbuf (odr_encode(), &ext->u.single_ASN1_type->len, 0);
641 ext->u.single_ASN1_type->buf = (unsigned char*)
642 odr_malloc (odr_encode(), ext->u.single_ASN1_type->len);
643 memcpy (ext->u.single_ASN1_type->buf, buf, ext->u.single_ASN1_type->len);
644 ext->u.single_ASN1_type->size = ext->u.single_ASN1_type->len;
646 if (send_Z_PDU(apdu) >= 0)
651 int MyClient::processCommand(const char *commandLine)
653 char cmdStr[1024], cmdArgs[1024];
658 int (MyClient::*fun)(char *arg);
661 {"open", &MyClient::cmd_open, "<host>[':'<port>][/<database>]"},
662 {"connect", &MyClient::cmd_connect, "<host>[':'<port>][/<database>]"},
663 {"quit", &MyClient::cmd_quit, ""},
664 {"close", &MyClient::cmd_close, ""},
665 {"find", &MyClient::cmd_find, "<query>"},
666 {"show", &MyClient::cmd_show, "[<start> [<number>]]"},
667 {"cookie", &MyClient::cmd_cookie, "<cookie>"},
668 {"init", &MyClient::cmd_init, ""},
669 {"format", &MyClient::cmd_format, "<record-syntax>"},
670 {"proxy", &MyClient::cmd_proxy, "<host>:[':'<port>]"},
671 {"ursula", &MyClient::cmd_ursula, ""},
675 if (sscanf(commandLine, "%s %[^;]", cmdStr, cmdArgs) < 1)
678 for (i = 0; cmd[i].cmd; i++)
679 if (!strncmp(cmd[i].cmd, cmdStr, strlen(cmdStr)))
683 if (cmd[i].cmd) // Invoke command handler
684 res = (this->*cmd[i].fun)(cmdArgs);
685 else // Dump help screen
687 printf("Unknown command: %s.\n", cmdStr);
688 printf("Currently recognized commands:\n");
689 for (i = 0; cmd[i].cmd; i++)
690 printf(" %s %s\n", cmd[i].cmd, cmd[i].ad);
695 const char *MyClient::getCommand()
697 #if HAVE_READLINE_READLINE_H
698 // Read using GNU readline
700 line_in=readline(C_PROMPT);
703 #if HAVE_READLINE_HISTORY_H
705 add_history(line_in);
707 strncpy(m_thisCommand,line_in, 1023);
708 m_thisCommand[1023] = '\0';
711 // Read using fgets(3)
714 if (!fgets(m_thisCommand, 1023, stdin))
717 // Remove trailing whitespace
718 char *cp = m_thisCommand + strlen(m_thisCommand);
719 while (cp != m_thisCommand && strchr("\t \n", cp[-1]))
723 // Remove leading spaces...
724 while (*cp && strchr ("\t \n", *cp))
726 // Save command if non-empty
728 strcpy (m_lastCommand, cp);
729 return m_lastCommand;
732 int MyClient::interactive(Yaz_SocketManager *socketManager)
735 if (!m_interactive_flag)
737 while ((cmd = getCommand()))
739 if (!processCommand(cmd))
745 int MyClient::args(Yaz_SocketManager *socketManager, int argc, char **argv)
750 char *prog = argv[0];
753 while ((ret = options("c:p:v:q", argv, argc, &arg)) != -2)
777 yaz_log_init_level (yaz_log_mask_str(arg));
780 m_interactive_flag = 0;
799 int main(int argc, char **argv)
801 Yaz_SocketManager mySocketManager;
802 Yaz_PDU_Assoc *some = new Yaz_PDU_Assoc(&mySocketManager);
804 MyClient z(some, &mySocketManager);
806 if (z.args(&mySocketManager, argc, argv))
808 if (z.interactive(&mySocketManager))