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.13 2000-09-06 14:23:45 adam
10 * Revision 1.12 2000/09/04 08:59:16 adam
11 * Changed call to logging functions (yaz_ added).
13 * Revision 1.11 2000/07/04 13:48:49 adam
14 * Implemented upper-limit on proxy-to-target sessions.
16 * Revision 1.10 2000/05/30 03:12:27 ian
17 * minor change to stop g++ 2.95.2 complaining about taking the address
18 * of a member function.
20 * Revision 1.9 1999/12/06 13:52:45 adam
21 * Modified for new location of YAZ header files. Experimental threaded
24 * Revision 1.8 1999/11/10 10:02:34 adam
27 * Revision 1.7 1999/04/21 12:09:01 adam
28 * Many improvements. Modified to proxy server to work with "sessions"
31 * Revision 1.6 1999/04/20 10:30:05 adam
32 * Implemented various stuff for client and proxy. Updated calls
33 * to ODR to reflect new name parameter.
35 * Revision 1.5 1999/04/09 11:46:57 adam
36 * Added object Yaz_Z_Assoc. Much more functional client.
38 * Revision 1.4 1999/03/23 14:17:57 adam
39 * More work on timeout handling. Work on yaz-client.
41 * Revision 1.3 1999/02/02 14:01:18 adam
42 * First WIN32 port of YAZ++.
44 * Revision 1.2 1999/01/28 13:08:42 adam
45 * Yaz_PDU_Assoc better encapsulated. Memory leak fix in
46 * yaz-socket-manager.cc.
48 * Revision 1.1.1.1 1999/01/28 09:41:07 adam
49 * First implementation of YAZ++.
54 #include <yaz/options.h>
55 #include <yaz/diagbib1.h>
56 #include <yaz-ir-assoc.h>
57 #include <yaz-pdu-assoc.h>
58 #include <yaz-socket-manager.h>
61 #if HAVE_READLINE_READLINE_H
62 #include <readline/readline.h>
64 #if HAVE_READLINE_HISTORY_H
65 #include <readline/history.h>
69 class YAZ_EXPORT MyClient : public Yaz_IR_Assoc {
71 int m_interactive_flag;
72 char m_thisCommand[1024];
73 char m_lastCommand[1024];
75 Yaz_SocketManager *m_socketManager;
77 MyClient(IYaz_PDU_Observable *the_PDU_Observable,
78 Yaz_SocketManager *the_SocketManager);
79 IYaz_PDU_Observer *clone(IYaz_PDU_Observable *the_PDU_Observable);
80 int args(Yaz_SocketManager *socketManager, int argc, char **argv);
81 int interactive(Yaz_SocketManager *socketManager);
83 void recv_initResponse(Z_InitResponse *initResponse);
84 void recv_searchResponse(Z_SearchResponse *searchResponse);
85 void recv_presentResponse(Z_PresentResponse *presentResponse);
86 void recv_records (Z_Records *records);
87 void recv_diagrecs(Z_DiagRec **pp, int num);
88 void recv_namePlusRecord (Z_NamePlusRecord *zpr, int offset);
89 void recv_record(Z_DatabaseRecord *record, int offset,
90 const char *databaseName);
91 void recv_textRecord(int type, const char *buf, size_t len);
92 void recv_genericRecord(Z_GenericRecord *r);
93 void display_genericRecord(Z_GenericRecord *r, int level);
94 void display_variant(Z_Variant *v, int level);
98 char *get_cookie (Z_OtherInformation **oi);
99 int processCommand(const char *cmd);
100 const char *MyClient::getCommand();
101 int cmd_open(char *host);
102 int cmd_connect(char *host);
103 int cmd_quit(char *args);
104 int cmd_close(char *args);
105 int cmd_find(char *args);
106 int cmd_show(char *args);
107 int cmd_cookie(char *args);
108 int cmd_init(char *args);
109 int cmd_format(char *args);
110 int cmd_proxy(char *args);
114 void MyClient::connectNotify()
116 printf ("Connection accepted by target\n");
117 set_lastReceived(-1);
120 void MyClient::timeoutNotify()
122 printf ("Connection timeout\n");
126 void MyClient::failNotify()
128 printf ("Connection closed by target\n");
129 set_lastReceived(-1);
132 IYaz_PDU_Observer *MyClient::clone(IYaz_PDU_Observable *the_PDU_Observable)
134 return new MyClient(the_PDU_Observable, m_socketManager);
137 MyClient::MyClient(IYaz_PDU_Observable *the_PDU_Observable,
138 Yaz_SocketManager *the_socketManager) :
139 Yaz_IR_Assoc (the_PDU_Observable)
142 m_interactive_flag = 1;
143 m_thisCommand[0] = '\0';
144 m_lastCommand[0] = '\0';
145 m_socketManager = the_socketManager;
148 void usage(char *prog)
150 fprintf (stderr, "%s: [-v log] [-c cookie] [-p proxy] [zurl]\n", prog);
154 char *MyClient::get_cookie(Z_OtherInformation **otherInfo)
157 Z_OtherInformationUnit *oi;
159 ent.proto = PROTO_Z3950;
160 ent.oclass = CLASS_USERINFO;
161 ent.value = (oid_value) VAL_COOKIE;
163 if (oid_ent_to_oid (&ent, oid) &&
164 (oi = update_otherInformation(otherInfo, 0, oid, 1, 1)) &&
165 oi->which == Z_OtherInfo_characterInfo)
166 return oi->information.characterInfo;
170 void MyClient::recv_initResponse(Z_InitResponse *initResponse)
172 printf ("Got InitResponse. Status ");
173 if (*initResponse->result)
177 const char *p = get_cookie (&initResponse->otherInfo);
180 printf ("cookie = %s\n", p);
188 void MyClient::recv_diagrecs(Z_DiagRec **pp, int num)
192 Z_DefaultDiagFormat *r;
194 printf("Diagnostic message(s) from database:\n");
195 for (i = 0; i<num; i++)
197 Z_DiagRec *p = pp[i];
198 if (p->which != Z_DiagRec_defaultFormat)
200 printf("Diagnostic record not in default format.\n");
204 r = p->u.defaultFormat;
205 if (!(ent = oid_getentbyoid(r->diagnosticSetId)) ||
206 ent->oclass != CLASS_DIAGSET || ent->value != VAL_BIB1)
207 printf("Missing or unknown diagset\n");
208 printf(" [%d] %s", *r->condition, diagbib1_str(*r->condition));
212 case Z_DefaultDiagFormat_v2Addinfo:
213 printf (" -- v2 addinfo '%s'\n", r->u.v2Addinfo);
215 case Z_DefaultDiagFormat_v3Addinfo:
216 printf (" -- v3 addinfo '%s'\n", r->u.v3Addinfo);
220 if (r->addinfo && *r->addinfo)
221 printf(" -- '%s'\n", r->addinfo);
228 void MyClient::recv_textRecord(int type, const char *buf, size_t len)
230 fwrite (buf, 1, len, stdout);
231 fputc ('\n', stdout);
234 void MyClient::display_variant(Z_Variant *v, int level)
238 for (i = 0; i < v->num_triples; i++)
240 printf("%*sclass=%d,type=%d", level * 4, "", *v->triples[i]->zclass,
241 *v->triples[i]->type);
242 if (v->triples[i]->which == Z_Triple_internationalString)
243 printf(",value=%s\n", v->triples[i]->value.internationalString);
249 void MyClient::display_genericRecord(Z_GenericRecord *r, int level)
255 for (i = 0; i < r->num_elements; i++)
259 printf("%*s", level * 4, "");
263 printf("%d,", *t->tagType);
266 if (t->tagValue->which == Z_StringOrNumeric_numeric)
267 printf("%d) ", *t->tagValue->u.numeric);
269 printf("%s) ", t->tagValue->u.string);
270 if (t->content->which == Z_ElementData_subtree)
273 display_genericRecord(t->content->u.subtree, level+1);
275 else if (t->content->which == Z_ElementData_string)
276 printf("%s\n", t->content->u.string);
277 else if (t->content->which == Z_ElementData_numeric)
278 printf("%d\n", *t->content->u.numeric);
279 else if (t->content->which == Z_ElementData_oid)
281 int *ip = t->content->u.oid;
284 if ((oent = oid_getentbyoid(t->content->u.oid)))
285 printf("OID: %s\n", oent->desc);
289 while (ip && *ip >= 0)
290 printf(" %d", *(ip++));
294 else if (t->content->which == Z_ElementData_noDataRequested)
295 printf("[No data requested]\n");
296 else if (t->content->which == Z_ElementData_elementEmpty)
297 printf("[Element empty]\n");
298 else if (t->content->which == Z_ElementData_elementNotThere)
299 printf("[Element not there]\n");
302 if (t->appliedVariant)
303 display_variant(t->appliedVariant, level+1);
304 if (t->metaData && t->metaData->supportedVariants)
308 printf("%*s---- variant list\n", (level+1)*4, "");
309 for (c = 0; c < t->metaData->num_supportedVariants; c++)
311 printf("%*svariant #%d\n", (level+1)*4, "", c);
312 display_variant(t->metaData->supportedVariants[c], level + 2);
318 void MyClient::recv_genericRecord(Z_GenericRecord *r)
320 display_genericRecord(r, 0);
323 void MyClient::recv_record(Z_DatabaseRecord *record, int offset,
324 const char *databaseName)
326 Z_External *r = (Z_External*) record;
327 oident *ent = oid_getentbyoid(r->direct_reference);
330 * Tell the user what we got.
332 if (r->direct_reference)
334 printf("Record type: ");
336 printf("%s\n", ent->desc);
338 /* Check if this is a known, ASN.1 type tucked away in an octet string */
339 Z_ext_typeent *etype = z_ext_getentbyref(ent->value);
340 if (ent && (r->which == Z_External_octet || r->which == Z_External_single)
341 && (etype = z_ext_getentbyref(ent->value)))
346 * Call the given decoder to process the record.
348 odr_setbuf(odr_decode(), (char*)record->u.octet_aligned->buf,
349 record->u.octet_aligned->len, 0);
350 if (!(*etype->fun)(odr_decode(), (char **)&rr, 0, 0))
352 odr_perror(odr_decode(), "Decoding constructed record.");
353 fprintf(stderr, "[Near %d]\n", odr_offset(odr_decode()));
354 fprintf(stderr, "Packet dump:\n---------\n");
355 odr_dumpBER(stderr, (char*)record->u.octet_aligned->buf,
356 record->u.octet_aligned->len);
357 fprintf(stderr, "---------\n");
359 if (etype->what == Z_External_sutrs)
361 Z_SUTRS *sutrs = (Z_SUTRS *) rr;
362 recv_textRecord ((int) VAL_SUTRS, (const char *) sutrs->buf,
363 (size_t) sutrs->len);
367 if (r->which == Z_External_octet && record->u.octet_aligned->len)
369 recv_textRecord((int) ent->value,
370 (const char *) record->u.octet_aligned->buf,
371 (size_t) record->u.octet_aligned->len);
373 else if (ent && ent->value == VAL_SUTRS && r->which == Z_External_sutrs)
374 recv_textRecord((int) VAL_SUTRS, (const char *) r->u.sutrs->buf,
375 (size_t) r->u.sutrs->len);
376 else if (ent && ent->value == VAL_GRS1 && r->which == Z_External_grs1)
377 recv_genericRecord(r->u.grs1);
380 printf("Unknown record representation.\n");
381 if (!z_External(odr_print(), &r, 0, 0))
383 odr_perror(odr_print(), "Printing external");
384 odr_reset(odr_print());
389 void MyClient::recv_namePlusRecord (Z_NamePlusRecord *zpr, int offset)
391 if (zpr->databaseName)
392 printf("[%s]", zpr->databaseName);
393 if (zpr->which == Z_NamePlusRecord_surrogateDiagnostic)
394 recv_diagrecs(&zpr->u.surrogateDiagnostic, 1);
396 recv_record(zpr->u.databaseRecord, offset, zpr->databaseName);
399 void MyClient::recv_records (Z_Records *records)
402 Z_DiagRec dr, *dr_p = &dr;
407 switch (records->which)
409 case Z_Records_DBOSD:
410 for (i = 0; i < records->u.databaseOrSurDiagnostics->num_records; i++)
411 recv_namePlusRecord(records->u.databaseOrSurDiagnostics->
412 records[i], i + m_setOffset);
413 m_setOffset += records->u.databaseOrSurDiagnostics->num_records;
417 dr.which = Z_DiagRec_defaultFormat;
418 dr.u.defaultFormat = records->u.nonSurrogateDiagnostic;
419 recv_diagrecs (&dr_p, 1);
421 recv_diagrecs (&records->u.nonSurrogateDiagnostic, 1);
424 case Z_Records_multipleNSD:
425 recv_diagrecs (records->u.multipleNonSurDiagnostics->diagRecs,
426 records->u.multipleNonSurDiagnostics->num_diagRecs);
431 void MyClient::recv_searchResponse(Z_SearchResponse *searchResponse)
433 printf ("Got SearchResponse. Status ");
434 if (!*searchResponse->searchStatus)
440 printf ("Hits: %d\n", *searchResponse->resultCount);
441 recv_records (searchResponse->records);
444 void MyClient::recv_presentResponse(Z_PresentResponse *presentResponse)
446 printf ("Got PresentResponse\n");
447 recv_records (presentResponse->records);
453 while (m_socketManager->processEvent() > 0)
455 if (get_lastReceived())
461 #define C_PROMPT "Z>"
463 int MyClient::cmd_connect(char *host)
472 int MyClient::cmd_open(char *host)
483 int MyClient::cmd_init(char *args)
485 if (send_initRequest() >= 0)
492 int MyClient::cmd_quit(char *args)
497 int MyClient::cmd_close(char *args)
503 int MyClient::cmd_find(char *args)
507 if (query.set_rpn(args) <= 0)
509 printf ("Bad RPN query\n");
512 if (send_searchRequest(&query) >= 0)
515 printf ("Not connected\n");
519 int MyClient::cmd_show(char *args)
521 int start = m_setOffset, number = 1;
523 sscanf (args, "%d %d", &start, &number);
525 if (send_presentRequest(start, number) >= 0)
528 printf ("Not connected\n");
532 int MyClient::cmd_cookie(char *args)
534 set_cookie(*args ? args : 0);
538 int MyClient::cmd_format(char *args)
540 set_preferredRecordSyntax(args);
544 int MyClient::cmd_proxy(char *args)
550 int MyClient::processCommand(const char *commandLine)
552 char cmdStr[1024], cmdArgs[1024];
557 int (MyClient::*fun)(char *arg);
560 {"open", &MyClient::cmd_open, "<host>[':'<port>][/<database>]"},
561 {"connect", &MyClient::cmd_connect, "<host>[':'<port>][/<database>]"},
562 {"quit", &MyClient::cmd_quit, ""},
563 {"close", &MyClient::cmd_close, ""},
564 {"find", &MyClient::cmd_find, "<query>"},
565 {"show", &MyClient::cmd_show, "[<start> [<number>]]"},
566 {"cookie", &MyClient::cmd_cookie, "<cookie>"},
567 {"init", &MyClient::cmd_init, ""},
568 {"format", &MyClient::cmd_format, "<record-syntax>"},
569 {"proxy", &MyClient::cmd_proxy, "<host>:[':'<port>]"},
573 if (sscanf(commandLine, "%s %[^;]", cmdStr, cmdArgs) < 1)
576 for (i = 0; cmd[i].cmd; i++)
577 if (!strncmp(cmd[i].cmd, cmdStr, strlen(cmdStr)))
581 if (cmd[i].cmd) // Invoke command handler
582 res = (this->*cmd[i].fun)(cmdArgs);
583 else // Dump help screen
585 printf("Unknown command: %s.\n", cmdStr);
586 printf("Currently recognized commands:\n");
587 for (i = 0; cmd[i].cmd; i++)
588 printf(" %s %s\n", cmd[i].cmd, cmd[i].ad);
593 const char *MyClient::getCommand()
595 #if HAVE_READLINE_READLINE_H
596 // Read using GNU readline
598 line_in=readline(C_PROMPT);
601 #if HAVE_READLINE_HISTORY_H
603 add_history(line_in);
605 strncpy(m_thisCommand,line_in, 1023);
606 m_thisCommand[1023] = '\0';
609 // Read using fgets(3)
612 if (!fgets(m_thisCommand, 1023, stdin))
615 // Remove trailing whitespace
616 char *cp = m_thisCommand + strlen(m_thisCommand);
617 while (cp != m_thisCommand && strchr("\t \n", cp[-1]))
621 // Remove leading spaces...
622 while (*cp && strchr ("\t \n", *cp))
624 // Save command if non-empty
626 strcpy (m_lastCommand, cp);
627 return m_lastCommand;
630 int MyClient::interactive(Yaz_SocketManager *socketManager)
633 if (!m_interactive_flag)
635 while ((cmd = getCommand()))
637 if (!processCommand(cmd))
643 int MyClient::args(Yaz_SocketManager *socketManager, int argc, char **argv)
648 char *prog = argv[0];
651 while ((ret = options("c:p:v:q", argv, argc, &arg)) != -2)
675 yaz_log_init_level (yaz_log_mask_str(arg));
678 m_interactive_flag = 0;
697 int main(int argc, char **argv)
699 Yaz_SocketManager mySocketManager;
700 Yaz_PDU_Assoc *some = new Yaz_PDU_Assoc(&mySocketManager);
702 MyClient z(some, &mySocketManager);
704 if (z.args(&mySocketManager, argc, argv))
706 if (z.interactive(&mySocketManager))