2 * Copyright (c) 1998-2000, Index Data.
3 * See the file LICENSE for details.
4 * Sebastian Hammer, Adam Dickmeiss
6 * $Log: yaz-client.cpp,v $
7 * Revision 1.11 2000-07-04 13:48:49 adam
8 * Implemented upper-limit on proxy-to-target sessions.
10 * Revision 1.10 2000/05/30 03:12:27 ian
11 * minor change to stop g++ 2.95.2 complaining about taking the address
12 * of a member function.
14 * Revision 1.9 1999/12/06 13:52:45 adam
15 * Modified for new location of YAZ header files. Experimental threaded
18 * Revision 1.8 1999/11/10 10:02:34 adam
21 * Revision 1.7 1999/04/21 12:09:01 adam
22 * Many improvements. Modified to proxy server to work with "sessions"
25 * Revision 1.6 1999/04/20 10:30:05 adam
26 * Implemented various stuff for client and proxy. Updated calls
27 * to ODR to reflect new name parameter.
29 * Revision 1.5 1999/04/09 11:46:57 adam
30 * Added object Yaz_Z_Assoc. Much more functional client.
32 * Revision 1.4 1999/03/23 14:17:57 adam
33 * More work on timeout handling. Work on yaz-client.
35 * Revision 1.3 1999/02/02 14:01:18 adam
36 * First WIN32 port of YAZ++.
38 * Revision 1.2 1999/01/28 13:08:42 adam
39 * Yaz_PDU_Assoc better encapsulated. Memory leak fix in
40 * yaz-socket-manager.cc.
42 * Revision 1.1.1.1 1999/01/28 09:41:07 adam
43 * First implementation of YAZ++.
48 #include <yaz/options.h>
49 #include <yaz/diagbib1.h>
50 #include <yaz-ir-assoc.h>
51 #include <yaz-pdu-assoc.h>
52 #include <yaz-socket-manager.h>
55 #if HAVE_READLINE_READLINE_H
56 #include <readline/readline.h>
58 #if HAVE_READLINE_HISTORY_H
59 #include <readline/history.h>
63 class YAZ_EXPORT MyClient : public Yaz_IR_Assoc {
65 int m_interactive_flag;
66 char m_thisCommand[1024];
67 char m_lastCommand[1024];
69 Yaz_SocketManager *m_socketManager;
71 MyClient(IYaz_PDU_Observable *the_PDU_Observable,
72 Yaz_SocketManager *the_SocketManager);
73 IYaz_PDU_Observer *clone(IYaz_PDU_Observable *the_PDU_Observable);
74 int args(Yaz_SocketManager *socketManager, int argc, char **argv);
75 int interactive(Yaz_SocketManager *socketManager);
77 void recv_initResponse(Z_InitResponse *initResponse);
78 void recv_searchResponse(Z_SearchResponse *searchResponse);
79 void recv_presentResponse(Z_PresentResponse *presentResponse);
80 void recv_records (Z_Records *records);
81 void recv_diagrecs(Z_DiagRec **pp, int num);
82 void recv_namePlusRecord (Z_NamePlusRecord *zpr, int offset);
83 void recv_record(Z_DatabaseRecord *record, int offset,
84 const char *databaseName);
85 void recv_textRecord(int type, const char *buf, size_t len);
86 void recv_genericRecord(Z_GenericRecord *r);
87 void display_genericRecord(Z_GenericRecord *r, int level);
88 void display_variant(Z_Variant *v, int level);
92 char *get_cookie (Z_OtherInformation **oi);
93 int processCommand(const char *cmd);
94 const char *MyClient::getCommand();
95 int cmd_open(char *host);
96 int cmd_connect(char *host);
97 int cmd_quit(char *args);
98 int cmd_close(char *args);
99 int cmd_find(char *args);
100 int cmd_show(char *args);
101 int cmd_cookie(char *args);
102 int cmd_init(char *args);
103 int cmd_format(char *args);
104 int cmd_proxy(char *args);
108 void MyClient::connectNotify()
110 printf ("Connection accepted by target\n");
111 set_lastReceived(-1);
114 void MyClient::timeoutNotify()
116 printf ("Connection timeout\n");
120 void MyClient::failNotify()
122 printf ("Connection closed by target\n");
123 set_lastReceived(-1);
126 IYaz_PDU_Observer *MyClient::clone(IYaz_PDU_Observable *the_PDU_Observable)
128 return new MyClient(the_PDU_Observable, m_socketManager);
131 MyClient::MyClient(IYaz_PDU_Observable *the_PDU_Observable,
132 Yaz_SocketManager *the_socketManager) :
133 Yaz_IR_Assoc (the_PDU_Observable)
136 m_interactive_flag = 1;
137 m_thisCommand[0] = '\0';
138 m_lastCommand[0] = '\0';
139 m_socketManager = the_socketManager;
142 void usage(char *prog)
144 fprintf (stderr, "%s: [-v log] [-c cookie] [-p proxy] [zurl]\n", prog);
148 char *MyClient::get_cookie(Z_OtherInformation **otherInfo)
151 Z_OtherInformationUnit *oi;
153 ent.proto = PROTO_Z3950;
154 ent.oclass = CLASS_USERINFO;
155 ent.value = (oid_value) VAL_COOKIE;
157 if (oid_ent_to_oid (&ent, oid) &&
158 (oi = update_otherInformation(otherInfo, 0, oid, 1, 1)) &&
159 oi->which == Z_OtherInfo_characterInfo)
160 return oi->information.characterInfo;
164 void MyClient::recv_initResponse(Z_InitResponse *initResponse)
166 printf ("Got InitResponse. Status ");
167 if (*initResponse->result)
171 const char *p = get_cookie (&initResponse->otherInfo);
174 printf ("cookie = %s\n", p);
182 void MyClient::recv_diagrecs(Z_DiagRec **pp, int num)
186 Z_DefaultDiagFormat *r;
188 printf("Diagnostic message(s) from database:\n");
189 for (i = 0; i<num; i++)
191 Z_DiagRec *p = pp[i];
192 if (p->which != Z_DiagRec_defaultFormat)
194 printf("Diagnostic record not in default format.\n");
198 r = p->u.defaultFormat;
199 if (!(ent = oid_getentbyoid(r->diagnosticSetId)) ||
200 ent->oclass != CLASS_DIAGSET || ent->value != VAL_BIB1)
201 printf("Missing or unknown diagset\n");
202 printf(" [%d] %s", *r->condition, diagbib1_str(*r->condition));
206 case Z_DefaultDiagFormat_v2Addinfo:
207 printf (" -- v2 addinfo '%s'\n", r->u.v2Addinfo);
209 case Z_DefaultDiagFormat_v3Addinfo:
210 printf (" -- v3 addinfo '%s'\n", r->u.v3Addinfo);
214 if (r->addinfo && *r->addinfo)
215 printf(" -- '%s'\n", r->addinfo);
222 void MyClient::recv_textRecord(int type, const char *buf, size_t len)
224 fwrite (buf, 1, len, stdout);
225 fputc ('\n', stdout);
228 void MyClient::display_variant(Z_Variant *v, int level)
232 for (i = 0; i < v->num_triples; i++)
234 printf("%*sclass=%d,type=%d", level * 4, "", *v->triples[i]->zclass,
235 *v->triples[i]->type);
236 if (v->triples[i]->which == Z_Triple_internationalString)
237 printf(",value=%s\n", v->triples[i]->value.internationalString);
243 void MyClient::display_genericRecord(Z_GenericRecord *r, int level)
249 for (i = 0; i < r->num_elements; i++)
253 printf("%*s", level * 4, "");
257 printf("%d,", *t->tagType);
260 if (t->tagValue->which == Z_StringOrNumeric_numeric)
261 printf("%d) ", *t->tagValue->u.numeric);
263 printf("%s) ", t->tagValue->u.string);
264 if (t->content->which == Z_ElementData_subtree)
267 display_genericRecord(t->content->u.subtree, level+1);
269 else if (t->content->which == Z_ElementData_string)
270 printf("%s\n", t->content->u.string);
271 else if (t->content->which == Z_ElementData_numeric)
272 printf("%d\n", *t->content->u.numeric);
273 else if (t->content->which == Z_ElementData_oid)
275 int *ip = t->content->u.oid;
278 if ((oent = oid_getentbyoid(t->content->u.oid)))
279 printf("OID: %s\n", oent->desc);
283 while (ip && *ip >= 0)
284 printf(" %d", *(ip++));
288 else if (t->content->which == Z_ElementData_noDataRequested)
289 printf("[No data requested]\n");
290 else if (t->content->which == Z_ElementData_elementEmpty)
291 printf("[Element empty]\n");
292 else if (t->content->which == Z_ElementData_elementNotThere)
293 printf("[Element not there]\n");
296 if (t->appliedVariant)
297 display_variant(t->appliedVariant, level+1);
298 if (t->metaData && t->metaData->supportedVariants)
302 printf("%*s---- variant list\n", (level+1)*4, "");
303 for (c = 0; c < t->metaData->num_supportedVariants; c++)
305 printf("%*svariant #%d\n", (level+1)*4, "", c);
306 display_variant(t->metaData->supportedVariants[c], level + 2);
312 void MyClient::recv_genericRecord(Z_GenericRecord *r)
314 display_genericRecord(r, 0);
317 void MyClient::recv_record(Z_DatabaseRecord *record, int offset,
318 const char *databaseName)
320 Z_External *r = (Z_External*) record;
321 oident *ent = oid_getentbyoid(r->direct_reference);
324 * Tell the user what we got.
326 if (r->direct_reference)
328 printf("Record type: ");
330 printf("%s\n", ent->desc);
332 /* Check if this is a known, ASN.1 type tucked away in an octet string */
333 Z_ext_typeent *etype = z_ext_getentbyref(ent->value);
334 if (ent && (r->which == Z_External_octet || r->which == Z_External_single)
335 && (etype = z_ext_getentbyref(ent->value)))
340 * Call the given decoder to process the record.
342 odr_setbuf(odr_decode(), (char*)record->u.octet_aligned->buf,
343 record->u.octet_aligned->len, 0);
344 if (!(*etype->fun)(odr_decode(), (char **)&rr, 0, 0))
346 odr_perror(odr_decode(), "Decoding constructed record.");
347 fprintf(stderr, "[Near %d]\n", odr_offset(odr_decode()));
348 fprintf(stderr, "Packet dump:\n---------\n");
349 odr_dumpBER(stderr, (char*)record->u.octet_aligned->buf,
350 record->u.octet_aligned->len);
351 fprintf(stderr, "---------\n");
353 if (etype->what == Z_External_sutrs)
355 Z_SUTRS *sutrs = (Z_SUTRS *) rr;
356 recv_textRecord ((int) VAL_SUTRS, (const char *) sutrs->buf,
357 (size_t) sutrs->len);
361 if (r->which == Z_External_octet && record->u.octet_aligned->len)
363 recv_textRecord((int) ent->value,
364 (const char *) record->u.octet_aligned->buf,
365 (size_t) record->u.octet_aligned->len);
367 else if (ent && ent->value == VAL_SUTRS && r->which == Z_External_sutrs)
368 recv_textRecord((int) VAL_SUTRS, (const char *) r->u.sutrs->buf,
369 (size_t) r->u.sutrs->len);
370 else if (ent && ent->value == VAL_GRS1 && r->which == Z_External_grs1)
371 recv_genericRecord(r->u.grs1);
374 printf("Unknown record representation.\n");
375 if (!z_External(odr_print(), &r, 0, 0))
377 odr_perror(odr_print(), "Printing external");
378 odr_reset(odr_print());
383 void MyClient::recv_namePlusRecord (Z_NamePlusRecord *zpr, int offset)
385 if (zpr->databaseName)
386 printf("[%s]", zpr->databaseName);
387 if (zpr->which == Z_NamePlusRecord_surrogateDiagnostic)
388 recv_diagrecs(&zpr->u.surrogateDiagnostic, 1);
390 recv_record(zpr->u.databaseRecord, offset, zpr->databaseName);
393 void MyClient::recv_records (Z_Records *records)
396 Z_DiagRec dr, *dr_p = &dr;
401 switch (records->which)
403 case Z_Records_DBOSD:
404 for (i = 0; i < records->u.databaseOrSurDiagnostics->num_records; i++)
405 recv_namePlusRecord(records->u.databaseOrSurDiagnostics->
406 records[i], i + m_setOffset);
407 m_setOffset += records->u.databaseOrSurDiagnostics->num_records;
411 dr.which = Z_DiagRec_defaultFormat;
412 dr.u.defaultFormat = records->u.nonSurrogateDiagnostic;
413 recv_diagrecs (&dr_p, 1);
415 recv_diagrecs (&records->u.nonSurrogateDiagnostic, 1);
418 case Z_Records_multipleNSD:
419 recv_diagrecs (records->u.multipleNonSurDiagnostics->diagRecs,
420 records->u.multipleNonSurDiagnostics->num_diagRecs);
425 void MyClient::recv_searchResponse(Z_SearchResponse *searchResponse)
427 printf ("Got SearchResponse. Status ");
428 if (!*searchResponse->searchStatus)
434 printf ("Hits: %d\n", *searchResponse->resultCount);
435 recv_records (searchResponse->records);
438 void MyClient::recv_presentResponse(Z_PresentResponse *presentResponse)
440 printf ("Got PresentResponse\n");
441 recv_records (presentResponse->records);
447 while (m_socketManager->processEvent() > 0)
449 if (get_lastReceived())
455 #define C_PROMPT "Z>"
457 int MyClient::cmd_connect(char *host)
466 int MyClient::cmd_open(char *host)
477 int MyClient::cmd_init(char *args)
479 if (send_initRequest() >= 0)
486 int MyClient::cmd_quit(char *args)
491 int MyClient::cmd_close(char *args)
497 int MyClient::cmd_find(char *args)
501 if (query.set_rpn(args) <= 0)
503 printf ("Bad RPN query\n");
506 if (send_searchRequest(&query) >= 0)
509 printf ("Not connected\n");
513 int MyClient::cmd_show(char *args)
515 int start = m_setOffset, number = 1;
517 sscanf (args, "%d %d", &start, &number);
519 if (send_presentRequest(start, number) >= 0)
522 printf ("Not connected\n");
526 int MyClient::cmd_cookie(char *args)
528 set_cookie(*args ? args : 0);
532 int MyClient::cmd_format(char *args)
534 set_preferredRecordSyntax(args);
538 int MyClient::cmd_proxy(char *args)
544 int MyClient::processCommand(const char *commandLine)
546 char cmdStr[1024], cmdArgs[1024];
551 int (MyClient::*fun)(char *arg);
554 {"open", &MyClient::cmd_open, "<host>[':'<port>][/<database>]"},
555 {"connect", &MyClient::cmd_connect, "<host>[':'<port>][/<database>]"},
556 {"quit", &MyClient::cmd_quit, ""},
557 {"close", &MyClient::cmd_close, ""},
558 {"find", &MyClient::cmd_find, "<query>"},
559 {"show", &MyClient::cmd_show, "[<start> [<number>]]"},
560 {"cookie", &MyClient::cmd_cookie, "<cookie>"},
561 {"init", &MyClient::cmd_init, ""},
562 {"format", &MyClient::cmd_format, "<record-syntax>"},
563 {"proxy", &MyClient::cmd_proxy, "<host>:[':'<port>]"},
567 if (sscanf(commandLine, "%s %[^;]", cmdStr, cmdArgs) < 1)
570 for (i = 0; cmd[i].cmd; i++)
571 if (!strncmp(cmd[i].cmd, cmdStr, strlen(cmdStr)))
575 if (cmd[i].cmd) // Invoke command handler
576 res = (this->*cmd[i].fun)(cmdArgs);
577 else // Dump help screen
579 printf("Unknown command: %s.\n", cmdStr);
580 printf("Currently recognized commands:\n");
581 for (i = 0; cmd[i].cmd; i++)
582 printf(" %s %s\n", cmd[i].cmd, cmd[i].ad);
587 const char *MyClient::getCommand()
589 #if HAVE_READLINE_READLINE_H
590 // Read using GNU readline
592 line_in=readline(C_PROMPT);
595 #if HAVE_READLINE_HISTORY_H
597 add_history(line_in);
599 strncpy(m_thisCommand,line_in, 1023);
600 m_thisCommand[1023] = '\0';
603 // Read using fgets(3)
606 if (!fgets(m_thisCommand, 1023, stdin))
609 // Remove trailing whitespace
610 char *cp = m_thisCommand + strlen(m_thisCommand);
611 while (cp != m_thisCommand && strchr("\t \n", cp[-1]))
615 // Remove leading spaces...
616 while (*cp && strchr ("\t \n", *cp))
618 // Save command if non-empty
620 strcpy (m_lastCommand, cp);
621 return m_lastCommand;
624 int MyClient::interactive(Yaz_SocketManager *socketManager)
627 if (!m_interactive_flag)
629 while ((cmd = getCommand()))
631 if (!processCommand(cmd))
637 int MyClient::args(Yaz_SocketManager *socketManager, int argc, char **argv)
642 char *prog = argv[0];
645 while ((ret = options("c:p:v:q", argv, argc, &arg)) != -2)
669 log_init_level (log_mask_str(arg));
672 m_interactive_flag = 0;
691 int main(int argc, char **argv)
693 Yaz_SocketManager mySocketManager;
694 Yaz_PDU_Assoc *some = new Yaz_PDU_Assoc(&mySocketManager);
696 MyClient z(some, &mySocketManager);
698 if (z.args(&mySocketManager, argc, argv))
700 if (z.interactive(&mySocketManager))