2 * Copyright (c) 1998-2000, Index Data.
3 * See the file LICENSE for details.
5 * $Log: yaz-my-client.cpp,v $
6 * Revision 1.1 2001-03-27 14:47:45 adam
7 * New server facility scheme.
9 * Revision 1.17 2001/03/26 14:43:49 adam
10 * New threaded PDU association.
12 * Revision 1.16 2000/11/01 14:22:59 adam
13 * Added fd parameter for method IYaz_PDU_Observer::clone.
15 * Revision 1.15 2000/10/11 11:58:16 adam
16 * Moved header files to include/yaz++. Switched to libtool and automake.
17 * Configure script creates yaz++-config script.
19 * Revision 1.14 2000/09/08 10:23:42 adam
20 * Added skeleton of yaz-z-server.
22 * Revision 1.13 2000/09/06 14:23:45 adam
25 * Revision 1.12 2000/09/04 08:59:16 adam
26 * Changed call to logging functions (yaz_ added).
28 * Revision 1.11 2000/07/04 13:48:49 adam
29 * Implemented upper-limit on proxy-to-target sessions.
31 * Revision 1.10 2000/05/30 03:12:27 ian
32 * minor change to stop g++ 2.95.2 complaining about taking the address
33 * of a member function.
35 * Revision 1.9 1999/12/06 13:52:45 adam
36 * Modified for new location of YAZ header files. Experimental threaded
39 * Revision 1.8 1999/11/10 10:02:34 adam
42 * Revision 1.7 1999/04/21 12:09:01 adam
43 * Many improvements. Modified to proxy server to work with "sessions"
46 * Revision 1.6 1999/04/20 10:30:05 adam
47 * Implemented various stuff for client and proxy. Updated calls
48 * to ODR to reflect new name parameter.
50 * Revision 1.5 1999/04/09 11:46:57 adam
51 * Added object Yaz_Z_Assoc. Much more functional client.
53 * Revision 1.4 1999/03/23 14:17:57 adam
54 * More work on timeout handling. Work on yaz-client.
56 * Revision 1.3 1999/02/02 14:01:18 adam
57 * First WIN32 port of YAZ++.
59 * Revision 1.2 1999/01/28 13:08:42 adam
60 * Yaz_PDU_Assoc better encapsulated. Memory leak fix in
61 * yaz-socket-manager.cc.
63 * Revision 1.1.1.1 1999/01/28 09:41:07 adam
64 * First implementation of YAZ++.
69 #include <yaz/options.h>
70 #include <yaz/diagbib1.h>
71 #include <yaz++/yaz-ir-assoc.h>
72 #include <yaz++/yaz-pdu-assoc.h>
73 #include <yaz++/yaz-socket-manager.h>
76 #if HAVE_READLINE_READLINE_H
77 #include <readline/readline.h>
79 #if HAVE_READLINE_HISTORY_H
80 #include <readline/history.h>
84 class YAZ_EXPORT MyClient : public Yaz_IR_Assoc {
86 int m_interactive_flag;
87 char m_thisCommand[1024];
88 char m_lastCommand[1024];
90 Yaz_SocketManager *m_socketManager;
92 MyClient(IYaz_PDU_Observable *the_PDU_Observable,
93 Yaz_SocketManager *the_SocketManager);
94 IYaz_PDU_Observer *sessionNotify(
95 IYaz_PDU_Observable *the_PDU_Observable, int fd);
96 int args(Yaz_SocketManager *socketManager, int argc, char **argv);
97 int interactive(Yaz_SocketManager *socketManager);
99 void recv_initResponse(Z_InitResponse *initResponse);
100 void recv_searchResponse(Z_SearchResponse *searchResponse);
101 void recv_presentResponse(Z_PresentResponse *presentResponse);
102 void recv_records (Z_Records *records);
103 void recv_diagrecs(Z_DiagRec **pp, int num);
104 void recv_namePlusRecord (Z_NamePlusRecord *zpr, int offset);
105 void recv_record(Z_DatabaseRecord *record, int offset,
106 const char *databaseName);
107 void recv_textRecord(int type, const char *buf, size_t len);
108 void recv_genericRecord(Z_GenericRecord *r);
109 void display_genericRecord(Z_GenericRecord *r, int level);
110 void display_variant(Z_Variant *v, int level);
111 void connectNotify();
113 void timeoutNotify();
114 char *get_cookie (Z_OtherInformation **oi);
115 int processCommand(const char *cmd);
116 const char *MyClient::getCommand();
117 int cmd_open(char *host);
118 int cmd_connect(char *host);
119 int cmd_quit(char *args);
120 int cmd_close(char *args);
121 int cmd_find(char *args);
122 int cmd_show(char *args);
123 int cmd_cookie(char *args);
124 int cmd_init(char *args);
125 int cmd_format(char *args);
126 int cmd_proxy(char *args);
130 void MyClient::connectNotify()
132 printf ("Connection accepted by target\n");
133 set_lastReceived(-1);
136 void MyClient::timeoutNotify()
138 printf ("Connection timeout\n");
142 void MyClient::failNotify()
144 printf ("Connection closed by target\n");
145 set_lastReceived(-1);
148 IYaz_PDU_Observer *MyClient::sessionNotify(
149 IYaz_PDU_Observable *the_PDU_Observable, int fd)
151 return new MyClient(the_PDU_Observable, m_socketManager);
154 MyClient::MyClient(IYaz_PDU_Observable *the_PDU_Observable,
155 Yaz_SocketManager *the_socketManager) :
156 Yaz_IR_Assoc (the_PDU_Observable)
159 m_interactive_flag = 1;
160 m_thisCommand[0] = '\0';
161 m_lastCommand[0] = '\0';
162 m_socketManager = the_socketManager;
165 void usage(char *prog)
167 fprintf (stderr, "%s: [-v log] [-c cookie] [-p proxy] [zurl]\n", prog);
171 char *MyClient::get_cookie(Z_OtherInformation **otherInfo)
174 Z_OtherInformationUnit *oi;
176 ent.proto = PROTO_Z3950;
177 ent.oclass = CLASS_USERINFO;
178 ent.value = (oid_value) VAL_COOKIE;
180 if (oid_ent_to_oid (&ent, oid) &&
181 (oi = update_otherInformation(otherInfo, 0, oid, 1, 1)) &&
182 oi->which == Z_OtherInfo_characterInfo)
183 return oi->information.characterInfo;
187 void MyClient::recv_initResponse(Z_InitResponse *initResponse)
189 printf ("Got InitResponse. Status ");
190 if (*initResponse->result)
194 const char *p = get_cookie (&initResponse->otherInfo);
197 printf ("cookie = %s\n", p);
205 void MyClient::recv_diagrecs(Z_DiagRec **pp, int num)
209 Z_DefaultDiagFormat *r;
211 printf("Diagnostic message(s) from database:\n");
212 for (i = 0; i<num; i++)
214 Z_DiagRec *p = pp[i];
215 if (p->which != Z_DiagRec_defaultFormat)
217 printf("Diagnostic record not in default format.\n");
221 r = p->u.defaultFormat;
222 if (!(ent = oid_getentbyoid(r->diagnosticSetId)) ||
223 ent->oclass != CLASS_DIAGSET || ent->value != VAL_BIB1)
224 printf("Missing or unknown diagset\n");
225 printf(" [%d] %s", *r->condition, diagbib1_str(*r->condition));
229 case Z_DefaultDiagFormat_v2Addinfo:
230 printf (" -- v2 addinfo '%s'\n", r->u.v2Addinfo);
232 case Z_DefaultDiagFormat_v3Addinfo:
233 printf (" -- v3 addinfo '%s'\n", r->u.v3Addinfo);
237 if (r->addinfo && *r->addinfo)
238 printf(" -- '%s'\n", r->addinfo);
245 void MyClient::recv_textRecord(int type, const char *buf, size_t len)
247 fwrite (buf, 1, len, stdout);
248 fputc ('\n', stdout);
251 void MyClient::display_variant(Z_Variant *v, int level)
255 for (i = 0; i < v->num_triples; i++)
257 printf("%*sclass=%d,type=%d", level * 4, "", *v->triples[i]->zclass,
258 *v->triples[i]->type);
259 if (v->triples[i]->which == Z_Triple_internationalString)
260 printf(",value=%s\n", v->triples[i]->value.internationalString);
266 void MyClient::display_genericRecord(Z_GenericRecord *r, int level)
272 for (i = 0; i < r->num_elements; i++)
276 printf("%*s", level * 4, "");
280 printf("%d,", *t->tagType);
283 if (t->tagValue->which == Z_StringOrNumeric_numeric)
284 printf("%d) ", *t->tagValue->u.numeric);
286 printf("%s) ", t->tagValue->u.string);
287 if (t->content->which == Z_ElementData_subtree)
290 display_genericRecord(t->content->u.subtree, level+1);
292 else if (t->content->which == Z_ElementData_string)
293 printf("%s\n", t->content->u.string);
294 else if (t->content->which == Z_ElementData_numeric)
295 printf("%d\n", *t->content->u.numeric);
296 else if (t->content->which == Z_ElementData_oid)
298 int *ip = t->content->u.oid;
301 if ((oent = oid_getentbyoid(t->content->u.oid)))
302 printf("OID: %s\n", oent->desc);
306 while (ip && *ip >= 0)
307 printf(" %d", *(ip++));
311 else if (t->content->which == Z_ElementData_noDataRequested)
312 printf("[No data requested]\n");
313 else if (t->content->which == Z_ElementData_elementEmpty)
314 printf("[Element empty]\n");
315 else if (t->content->which == Z_ElementData_elementNotThere)
316 printf("[Element not there]\n");
319 if (t->appliedVariant)
320 display_variant(t->appliedVariant, level+1);
321 if (t->metaData && t->metaData->supportedVariants)
325 printf("%*s---- variant list\n", (level+1)*4, "");
326 for (c = 0; c < t->metaData->num_supportedVariants; c++)
328 printf("%*svariant #%d\n", (level+1)*4, "", c);
329 display_variant(t->metaData->supportedVariants[c], level + 2);
335 void MyClient::recv_genericRecord(Z_GenericRecord *r)
337 display_genericRecord(r, 0);
340 void MyClient::recv_record(Z_DatabaseRecord *record, int offset,
341 const char *databaseName)
343 Z_External *r = (Z_External*) record;
344 oident *ent = oid_getentbyoid(r->direct_reference);
347 * Tell the user what we got.
349 if (r->direct_reference)
351 printf("Record type: ");
353 printf("%s\n", ent->desc);
355 /* Check if this is a known, ASN.1 type tucked away in an octet string */
356 Z_ext_typeent *etype = z_ext_getentbyref(ent->value);
357 if (ent && (r->which == Z_External_octet || r->which == Z_External_single)
358 && (etype = z_ext_getentbyref(ent->value)))
363 * Call the given decoder to process the record.
365 odr_setbuf(odr_decode(), (char*)record->u.octet_aligned->buf,
366 record->u.octet_aligned->len, 0);
367 if (!(*etype->fun)(odr_decode(), (char **)&rr, 0, 0))
369 odr_perror(odr_decode(), "Decoding constructed record.");
370 fprintf(stderr, "[Near %d]\n", odr_offset(odr_decode()));
371 fprintf(stderr, "Packet dump:\n---------\n");
372 odr_dumpBER(stderr, (char*)record->u.octet_aligned->buf,
373 record->u.octet_aligned->len);
374 fprintf(stderr, "---------\n");
376 if (etype->what == Z_External_sutrs)
378 Z_SUTRS *sutrs = (Z_SUTRS *) rr;
379 recv_textRecord ((int) VAL_SUTRS, (const char *) sutrs->buf,
380 (size_t) sutrs->len);
384 if (r->which == Z_External_octet && record->u.octet_aligned->len)
386 recv_textRecord((int) ent->value,
387 (const char *) record->u.octet_aligned->buf,
388 (size_t) record->u.octet_aligned->len);
390 else if (ent && ent->value == VAL_SUTRS && r->which == Z_External_sutrs)
391 recv_textRecord((int) VAL_SUTRS, (const char *) r->u.sutrs->buf,
392 (size_t) r->u.sutrs->len);
393 else if (ent && ent->value == VAL_GRS1 && r->which == Z_External_grs1)
394 recv_genericRecord(r->u.grs1);
397 printf("Unknown record representation.\n");
398 if (!z_External(odr_print(), &r, 0, 0))
400 odr_perror(odr_print(), "Printing external");
401 odr_reset(odr_print());
406 void MyClient::recv_namePlusRecord (Z_NamePlusRecord *zpr, int offset)
408 if (zpr->databaseName)
409 printf("[%s]", zpr->databaseName);
410 if (zpr->which == Z_NamePlusRecord_surrogateDiagnostic)
411 recv_diagrecs(&zpr->u.surrogateDiagnostic, 1);
413 recv_record(zpr->u.databaseRecord, offset, zpr->databaseName);
416 void MyClient::recv_records (Z_Records *records)
419 Z_DiagRec dr, *dr_p = &dr;
424 switch (records->which)
426 case Z_Records_DBOSD:
427 for (i = 0; i < records->u.databaseOrSurDiagnostics->num_records; i++)
428 recv_namePlusRecord(records->u.databaseOrSurDiagnostics->
429 records[i], i + m_setOffset);
430 m_setOffset += records->u.databaseOrSurDiagnostics->num_records;
434 dr.which = Z_DiagRec_defaultFormat;
435 dr.u.defaultFormat = records->u.nonSurrogateDiagnostic;
436 recv_diagrecs (&dr_p, 1);
438 recv_diagrecs (&records->u.nonSurrogateDiagnostic, 1);
441 case Z_Records_multipleNSD:
442 recv_diagrecs (records->u.multipleNonSurDiagnostics->diagRecs,
443 records->u.multipleNonSurDiagnostics->num_diagRecs);
448 void MyClient::recv_searchResponse(Z_SearchResponse *searchResponse)
450 printf ("Got SearchResponse. Status ");
451 if (!*searchResponse->searchStatus)
457 printf ("Hits: %d\n", *searchResponse->resultCount);
458 recv_records (searchResponse->records);
461 void MyClient::recv_presentResponse(Z_PresentResponse *presentResponse)
463 printf ("Got PresentResponse\n");
464 recv_records (presentResponse->records);
470 while (m_socketManager->processEvent() > 0)
472 if (get_lastReceived())
478 #define C_PROMPT "Z>"
480 int MyClient::cmd_connect(char *host)
489 int MyClient::cmd_open(char *host)
500 int MyClient::cmd_init(char *args)
502 if (send_initRequest() >= 0)
509 int MyClient::cmd_quit(char *args)
514 int MyClient::cmd_close(char *args)
520 int MyClient::cmd_find(char *args)
524 if (query.set_rpn(args) <= 0)
526 printf ("Bad RPN query\n");
529 if (send_searchRequest(&query) >= 0)
532 printf ("Not connected\n");
536 int MyClient::cmd_show(char *args)
538 int start = m_setOffset, number = 1;
540 sscanf (args, "%d %d", &start, &number);
542 if (send_presentRequest(start, number) >= 0)
545 printf ("Not connected\n");
549 int MyClient::cmd_cookie(char *args)
551 set_cookie(*args ? args : 0);
555 int MyClient::cmd_format(char *args)
557 set_preferredRecordSyntax(args);
561 int MyClient::cmd_proxy(char *args)
567 int MyClient::processCommand(const char *commandLine)
569 char cmdStr[1024], cmdArgs[1024];
574 int (MyClient::*fun)(char *arg);
577 {"open", &MyClient::cmd_open, "<host>[':'<port>][/<database>]"},
578 {"connect", &MyClient::cmd_connect, "<host>[':'<port>][/<database>]"},
579 {"quit", &MyClient::cmd_quit, ""},
580 {"close", &MyClient::cmd_close, ""},
581 {"find", &MyClient::cmd_find, "<query>"},
582 {"show", &MyClient::cmd_show, "[<start> [<number>]]"},
583 {"cookie", &MyClient::cmd_cookie, "<cookie>"},
584 {"init", &MyClient::cmd_init, ""},
585 {"format", &MyClient::cmd_format, "<record-syntax>"},
586 {"proxy", &MyClient::cmd_proxy, "<host>:[':'<port>]"},
590 if (sscanf(commandLine, "%s %[^;]", cmdStr, cmdArgs) < 1)
593 for (i = 0; cmd[i].cmd; i++)
594 if (!strncmp(cmd[i].cmd, cmdStr, strlen(cmdStr)))
598 if (cmd[i].cmd) // Invoke command handler
599 res = (this->*cmd[i].fun)(cmdArgs);
600 else // Dump help screen
602 printf("Unknown command: %s.\n", cmdStr);
603 printf("Currently recognized commands:\n");
604 for (i = 0; cmd[i].cmd; i++)
605 printf(" %s %s\n", cmd[i].cmd, cmd[i].ad);
610 const char *MyClient::getCommand()
612 #if HAVE_READLINE_READLINE_H
613 // Read using GNU readline
615 line_in=readline(C_PROMPT);
618 #if HAVE_READLINE_HISTORY_H
620 add_history(line_in);
622 strncpy(m_thisCommand,line_in, 1023);
623 m_thisCommand[1023] = '\0';
626 // Read using fgets(3)
629 if (!fgets(m_thisCommand, 1023, stdin))
632 // Remove trailing whitespace
633 char *cp = m_thisCommand + strlen(m_thisCommand);
634 while (cp != m_thisCommand && strchr("\t \n", cp[-1]))
638 // Remove leading spaces...
639 while (*cp && strchr ("\t \n", *cp))
641 // Save command if non-empty
643 strcpy (m_lastCommand, cp);
644 return m_lastCommand;
647 int MyClient::interactive(Yaz_SocketManager *socketManager)
650 if (!m_interactive_flag)
652 while ((cmd = getCommand()))
654 if (!processCommand(cmd))
660 int MyClient::args(Yaz_SocketManager *socketManager, int argc, char **argv)
665 char *prog = argv[0];
668 while ((ret = options("c:p:v:q", argv, argc, &arg)) != -2)
692 yaz_log_init_level (yaz_log_mask_str(arg));
695 m_interactive_flag = 0;
714 int main(int argc, char **argv)
716 Yaz_SocketManager mySocketManager;
717 Yaz_PDU_Assoc *some = new Yaz_PDU_Assoc(&mySocketManager);
719 MyClient z(some, &mySocketManager);
721 if (z.args(&mySocketManager, argc, argv))
723 if (z.interactive(&mySocketManager))