2 * Copyright (c) 1998-2000, Index Data.
3 * See the file LICENSE for details.
5 * $Log: yaz-client.cpp,v $
6 * Revision 1.16 2000-11-01 14:22:59 adam
7 * Added fd parameter for method IYaz_PDU_Observer::clone.
9 * Revision 1.15 2000/10/11 11:58:16 adam
10 * Moved header files to include/yaz++. Switched to libtool and automake.
11 * Configure script creates yaz++-config script.
13 * Revision 1.14 2000/09/08 10:23:42 adam
14 * Added skeleton of yaz-z-server.
16 * Revision 1.13 2000/09/06 14:23:45 adam
19 * Revision 1.12 2000/09/04 08:59:16 adam
20 * Changed call to logging functions (yaz_ added).
22 * Revision 1.11 2000/07/04 13:48:49 adam
23 * Implemented upper-limit on proxy-to-target sessions.
25 * Revision 1.10 2000/05/30 03:12:27 ian
26 * minor change to stop g++ 2.95.2 complaining about taking the address
27 * of a member function.
29 * Revision 1.9 1999/12/06 13:52:45 adam
30 * Modified for new location of YAZ header files. Experimental threaded
33 * Revision 1.8 1999/11/10 10:02:34 adam
36 * Revision 1.7 1999/04/21 12:09:01 adam
37 * Many improvements. Modified to proxy server to work with "sessions"
40 * Revision 1.6 1999/04/20 10:30:05 adam
41 * Implemented various stuff for client and proxy. Updated calls
42 * to ODR to reflect new name parameter.
44 * Revision 1.5 1999/04/09 11:46:57 adam
45 * Added object Yaz_Z_Assoc. Much more functional client.
47 * Revision 1.4 1999/03/23 14:17:57 adam
48 * More work on timeout handling. Work on yaz-client.
50 * Revision 1.3 1999/02/02 14:01:18 adam
51 * First WIN32 port of YAZ++.
53 * Revision 1.2 1999/01/28 13:08:42 adam
54 * Yaz_PDU_Assoc better encapsulated. Memory leak fix in
55 * yaz-socket-manager.cc.
57 * Revision 1.1.1.1 1999/01/28 09:41:07 adam
58 * First implementation of YAZ++.
63 #include <yaz/options.h>
64 #include <yaz/diagbib1.h>
65 #include <yaz++/yaz-ir-assoc.h>
66 #include <yaz++/yaz-pdu-assoc.h>
67 #include <yaz++/yaz-socket-manager.h>
70 #if HAVE_READLINE_READLINE_H
71 #include <readline/readline.h>
73 #if HAVE_READLINE_HISTORY_H
74 #include <readline/history.h>
78 class YAZ_EXPORT MyClient : public Yaz_IR_Assoc {
80 int m_interactive_flag;
81 char m_thisCommand[1024];
82 char m_lastCommand[1024];
84 Yaz_SocketManager *m_socketManager;
86 MyClient(IYaz_PDU_Observable *the_PDU_Observable,
87 Yaz_SocketManager *the_SocketManager);
88 IYaz_PDU_Observer *clone(IYaz_PDU_Observable *the_PDU_Observable, int fd);
89 int args(Yaz_SocketManager *socketManager, int argc, char **argv);
90 int interactive(Yaz_SocketManager *socketManager);
92 void recv_initResponse(Z_InitResponse *initResponse);
93 void recv_searchResponse(Z_SearchResponse *searchResponse);
94 void recv_presentResponse(Z_PresentResponse *presentResponse);
95 void recv_records (Z_Records *records);
96 void recv_diagrecs(Z_DiagRec **pp, int num);
97 void recv_namePlusRecord (Z_NamePlusRecord *zpr, int offset);
98 void recv_record(Z_DatabaseRecord *record, int offset,
99 const char *databaseName);
100 void recv_textRecord(int type, const char *buf, size_t len);
101 void recv_genericRecord(Z_GenericRecord *r);
102 void display_genericRecord(Z_GenericRecord *r, int level);
103 void display_variant(Z_Variant *v, int level);
104 void connectNotify();
106 void timeoutNotify();
107 char *get_cookie (Z_OtherInformation **oi);
108 int processCommand(const char *cmd);
109 const char *MyClient::getCommand();
110 int cmd_open(char *host);
111 int cmd_connect(char *host);
112 int cmd_quit(char *args);
113 int cmd_close(char *args);
114 int cmd_find(char *args);
115 int cmd_show(char *args);
116 int cmd_cookie(char *args);
117 int cmd_init(char *args);
118 int cmd_format(char *args);
119 int cmd_proxy(char *args);
123 void MyClient::connectNotify()
125 printf ("Connection accepted by target\n");
126 set_lastReceived(-1);
129 void MyClient::timeoutNotify()
131 printf ("Connection timeout\n");
135 void MyClient::failNotify()
137 printf ("Connection closed by target\n");
138 set_lastReceived(-1);
141 IYaz_PDU_Observer *MyClient::clone(IYaz_PDU_Observable *the_PDU_Observable,
144 return new MyClient(the_PDU_Observable, m_socketManager);
147 MyClient::MyClient(IYaz_PDU_Observable *the_PDU_Observable,
148 Yaz_SocketManager *the_socketManager) :
149 Yaz_IR_Assoc (the_PDU_Observable)
152 m_interactive_flag = 1;
153 m_thisCommand[0] = '\0';
154 m_lastCommand[0] = '\0';
155 m_socketManager = the_socketManager;
158 void usage(char *prog)
160 fprintf (stderr, "%s: [-v log] [-c cookie] [-p proxy] [zurl]\n", prog);
164 char *MyClient::get_cookie(Z_OtherInformation **otherInfo)
167 Z_OtherInformationUnit *oi;
169 ent.proto = PROTO_Z3950;
170 ent.oclass = CLASS_USERINFO;
171 ent.value = (oid_value) VAL_COOKIE;
173 if (oid_ent_to_oid (&ent, oid) &&
174 (oi = update_otherInformation(otherInfo, 0, oid, 1, 1)) &&
175 oi->which == Z_OtherInfo_characterInfo)
176 return oi->information.characterInfo;
180 void MyClient::recv_initResponse(Z_InitResponse *initResponse)
182 printf ("Got InitResponse. Status ");
183 if (*initResponse->result)
187 const char *p = get_cookie (&initResponse->otherInfo);
190 printf ("cookie = %s\n", p);
198 void MyClient::recv_diagrecs(Z_DiagRec **pp, int num)
202 Z_DefaultDiagFormat *r;
204 printf("Diagnostic message(s) from database:\n");
205 for (i = 0; i<num; i++)
207 Z_DiagRec *p = pp[i];
208 if (p->which != Z_DiagRec_defaultFormat)
210 printf("Diagnostic record not in default format.\n");
214 r = p->u.defaultFormat;
215 if (!(ent = oid_getentbyoid(r->diagnosticSetId)) ||
216 ent->oclass != CLASS_DIAGSET || ent->value != VAL_BIB1)
217 printf("Missing or unknown diagset\n");
218 printf(" [%d] %s", *r->condition, diagbib1_str(*r->condition));
222 case Z_DefaultDiagFormat_v2Addinfo:
223 printf (" -- v2 addinfo '%s'\n", r->u.v2Addinfo);
225 case Z_DefaultDiagFormat_v3Addinfo:
226 printf (" -- v3 addinfo '%s'\n", r->u.v3Addinfo);
230 if (r->addinfo && *r->addinfo)
231 printf(" -- '%s'\n", r->addinfo);
238 void MyClient::recv_textRecord(int type, const char *buf, size_t len)
240 fwrite (buf, 1, len, stdout);
241 fputc ('\n', stdout);
244 void MyClient::display_variant(Z_Variant *v, int level)
248 for (i = 0; i < v->num_triples; i++)
250 printf("%*sclass=%d,type=%d", level * 4, "", *v->triples[i]->zclass,
251 *v->triples[i]->type);
252 if (v->triples[i]->which == Z_Triple_internationalString)
253 printf(",value=%s\n", v->triples[i]->value.internationalString);
259 void MyClient::display_genericRecord(Z_GenericRecord *r, int level)
265 for (i = 0; i < r->num_elements; i++)
269 printf("%*s", level * 4, "");
273 printf("%d,", *t->tagType);
276 if (t->tagValue->which == Z_StringOrNumeric_numeric)
277 printf("%d) ", *t->tagValue->u.numeric);
279 printf("%s) ", t->tagValue->u.string);
280 if (t->content->which == Z_ElementData_subtree)
283 display_genericRecord(t->content->u.subtree, level+1);
285 else if (t->content->which == Z_ElementData_string)
286 printf("%s\n", t->content->u.string);
287 else if (t->content->which == Z_ElementData_numeric)
288 printf("%d\n", *t->content->u.numeric);
289 else if (t->content->which == Z_ElementData_oid)
291 int *ip = t->content->u.oid;
294 if ((oent = oid_getentbyoid(t->content->u.oid)))
295 printf("OID: %s\n", oent->desc);
299 while (ip && *ip >= 0)
300 printf(" %d", *(ip++));
304 else if (t->content->which == Z_ElementData_noDataRequested)
305 printf("[No data requested]\n");
306 else if (t->content->which == Z_ElementData_elementEmpty)
307 printf("[Element empty]\n");
308 else if (t->content->which == Z_ElementData_elementNotThere)
309 printf("[Element not there]\n");
312 if (t->appliedVariant)
313 display_variant(t->appliedVariant, level+1);
314 if (t->metaData && t->metaData->supportedVariants)
318 printf("%*s---- variant list\n", (level+1)*4, "");
319 for (c = 0; c < t->metaData->num_supportedVariants; c++)
321 printf("%*svariant #%d\n", (level+1)*4, "", c);
322 display_variant(t->metaData->supportedVariants[c], level + 2);
328 void MyClient::recv_genericRecord(Z_GenericRecord *r)
330 display_genericRecord(r, 0);
333 void MyClient::recv_record(Z_DatabaseRecord *record, int offset,
334 const char *databaseName)
336 Z_External *r = (Z_External*) record;
337 oident *ent = oid_getentbyoid(r->direct_reference);
340 * Tell the user what we got.
342 if (r->direct_reference)
344 printf("Record type: ");
346 printf("%s\n", ent->desc);
348 /* Check if this is a known, ASN.1 type tucked away in an octet string */
349 Z_ext_typeent *etype = z_ext_getentbyref(ent->value);
350 if (ent && (r->which == Z_External_octet || r->which == Z_External_single)
351 && (etype = z_ext_getentbyref(ent->value)))
356 * Call the given decoder to process the record.
358 odr_setbuf(odr_decode(), (char*)record->u.octet_aligned->buf,
359 record->u.octet_aligned->len, 0);
360 if (!(*etype->fun)(odr_decode(), (char **)&rr, 0, 0))
362 odr_perror(odr_decode(), "Decoding constructed record.");
363 fprintf(stderr, "[Near %d]\n", odr_offset(odr_decode()));
364 fprintf(stderr, "Packet dump:\n---------\n");
365 odr_dumpBER(stderr, (char*)record->u.octet_aligned->buf,
366 record->u.octet_aligned->len);
367 fprintf(stderr, "---------\n");
369 if (etype->what == Z_External_sutrs)
371 Z_SUTRS *sutrs = (Z_SUTRS *) rr;
372 recv_textRecord ((int) VAL_SUTRS, (const char *) sutrs->buf,
373 (size_t) sutrs->len);
377 if (r->which == Z_External_octet && record->u.octet_aligned->len)
379 recv_textRecord((int) ent->value,
380 (const char *) record->u.octet_aligned->buf,
381 (size_t) record->u.octet_aligned->len);
383 else if (ent && ent->value == VAL_SUTRS && r->which == Z_External_sutrs)
384 recv_textRecord((int) VAL_SUTRS, (const char *) r->u.sutrs->buf,
385 (size_t) r->u.sutrs->len);
386 else if (ent && ent->value == VAL_GRS1 && r->which == Z_External_grs1)
387 recv_genericRecord(r->u.grs1);
390 printf("Unknown record representation.\n");
391 if (!z_External(odr_print(), &r, 0, 0))
393 odr_perror(odr_print(), "Printing external");
394 odr_reset(odr_print());
399 void MyClient::recv_namePlusRecord (Z_NamePlusRecord *zpr, int offset)
401 if (zpr->databaseName)
402 printf("[%s]", zpr->databaseName);
403 if (zpr->which == Z_NamePlusRecord_surrogateDiagnostic)
404 recv_diagrecs(&zpr->u.surrogateDiagnostic, 1);
406 recv_record(zpr->u.databaseRecord, offset, zpr->databaseName);
409 void MyClient::recv_records (Z_Records *records)
412 Z_DiagRec dr, *dr_p = &dr;
417 switch (records->which)
419 case Z_Records_DBOSD:
420 for (i = 0; i < records->u.databaseOrSurDiagnostics->num_records; i++)
421 recv_namePlusRecord(records->u.databaseOrSurDiagnostics->
422 records[i], i + m_setOffset);
423 m_setOffset += records->u.databaseOrSurDiagnostics->num_records;
427 dr.which = Z_DiagRec_defaultFormat;
428 dr.u.defaultFormat = records->u.nonSurrogateDiagnostic;
429 recv_diagrecs (&dr_p, 1);
431 recv_diagrecs (&records->u.nonSurrogateDiagnostic, 1);
434 case Z_Records_multipleNSD:
435 recv_diagrecs (records->u.multipleNonSurDiagnostics->diagRecs,
436 records->u.multipleNonSurDiagnostics->num_diagRecs);
441 void MyClient::recv_searchResponse(Z_SearchResponse *searchResponse)
443 printf ("Got SearchResponse. Status ");
444 if (!*searchResponse->searchStatus)
450 printf ("Hits: %d\n", *searchResponse->resultCount);
451 recv_records (searchResponse->records);
454 void MyClient::recv_presentResponse(Z_PresentResponse *presentResponse)
456 printf ("Got PresentResponse\n");
457 recv_records (presentResponse->records);
463 while (m_socketManager->processEvent() > 0)
465 if (get_lastReceived())
471 #define C_PROMPT "Z>"
473 int MyClient::cmd_connect(char *host)
482 int MyClient::cmd_open(char *host)
493 int MyClient::cmd_init(char *args)
495 if (send_initRequest() >= 0)
502 int MyClient::cmd_quit(char *args)
507 int MyClient::cmd_close(char *args)
513 int MyClient::cmd_find(char *args)
517 if (query.set_rpn(args) <= 0)
519 printf ("Bad RPN query\n");
522 if (send_searchRequest(&query) >= 0)
525 printf ("Not connected\n");
529 int MyClient::cmd_show(char *args)
531 int start = m_setOffset, number = 1;
533 sscanf (args, "%d %d", &start, &number);
535 if (send_presentRequest(start, number) >= 0)
538 printf ("Not connected\n");
542 int MyClient::cmd_cookie(char *args)
544 set_cookie(*args ? args : 0);
548 int MyClient::cmd_format(char *args)
550 set_preferredRecordSyntax(args);
554 int MyClient::cmd_proxy(char *args)
560 int MyClient::processCommand(const char *commandLine)
562 char cmdStr[1024], cmdArgs[1024];
567 int (MyClient::*fun)(char *arg);
570 {"open", &MyClient::cmd_open, "<host>[':'<port>][/<database>]"},
571 {"connect", &MyClient::cmd_connect, "<host>[':'<port>][/<database>]"},
572 {"quit", &MyClient::cmd_quit, ""},
573 {"close", &MyClient::cmd_close, ""},
574 {"find", &MyClient::cmd_find, "<query>"},
575 {"show", &MyClient::cmd_show, "[<start> [<number>]]"},
576 {"cookie", &MyClient::cmd_cookie, "<cookie>"},
577 {"init", &MyClient::cmd_init, ""},
578 {"format", &MyClient::cmd_format, "<record-syntax>"},
579 {"proxy", &MyClient::cmd_proxy, "<host>:[':'<port>]"},
583 if (sscanf(commandLine, "%s %[^;]", cmdStr, cmdArgs) < 1)
586 for (i = 0; cmd[i].cmd; i++)
587 if (!strncmp(cmd[i].cmd, cmdStr, strlen(cmdStr)))
591 if (cmd[i].cmd) // Invoke command handler
592 res = (this->*cmd[i].fun)(cmdArgs);
593 else // Dump help screen
595 printf("Unknown command: %s.\n", cmdStr);
596 printf("Currently recognized commands:\n");
597 for (i = 0; cmd[i].cmd; i++)
598 printf(" %s %s\n", cmd[i].cmd, cmd[i].ad);
603 const char *MyClient::getCommand()
605 #if HAVE_READLINE_READLINE_H
606 // Read using GNU readline
608 line_in=readline(C_PROMPT);
611 #if HAVE_READLINE_HISTORY_H
613 add_history(line_in);
615 strncpy(m_thisCommand,line_in, 1023);
616 m_thisCommand[1023] = '\0';
619 // Read using fgets(3)
622 if (!fgets(m_thisCommand, 1023, stdin))
625 // Remove trailing whitespace
626 char *cp = m_thisCommand + strlen(m_thisCommand);
627 while (cp != m_thisCommand && strchr("\t \n", cp[-1]))
631 // Remove leading spaces...
632 while (*cp && strchr ("\t \n", *cp))
634 // Save command if non-empty
636 strcpy (m_lastCommand, cp);
637 return m_lastCommand;
640 int MyClient::interactive(Yaz_SocketManager *socketManager)
643 if (!m_interactive_flag)
645 while ((cmd = getCommand()))
647 if (!processCommand(cmd))
653 int MyClient::args(Yaz_SocketManager *socketManager, int argc, char **argv)
658 char *prog = argv[0];
661 while ((ret = options("c:p:v:q", argv, argc, &arg)) != -2)
685 yaz_log_init_level (yaz_log_mask_str(arg));
688 m_interactive_flag = 0;
707 int main(int argc, char **argv)
709 Yaz_SocketManager mySocketManager;
710 Yaz_PDU_Assoc *some = new Yaz_PDU_Assoc(&mySocketManager);
712 MyClient z(some, &mySocketManager);
714 if (z.args(&mySocketManager, argc, argv))
716 if (z.interactive(&mySocketManager))