2 * Copyright (c) 1998-2000, Index Data.
3 * See the file LICENSE for details.
5 * $Log: yaz-client.cpp,v $
6 * Revision 1.15 2000-10-11 11:58:16 adam
7 * Moved header files to include/yaz++. Switched to libtool and automake.
8 * Configure script creates yaz++-config script.
10 * Revision 1.14 2000/09/08 10:23:42 adam
11 * Added skeleton of yaz-z-server.
13 * Revision 1.13 2000/09/06 14:23:45 adam
16 * Revision 1.12 2000/09/04 08:59:16 adam
17 * Changed call to logging functions (yaz_ added).
19 * Revision 1.11 2000/07/04 13:48:49 adam
20 * Implemented upper-limit on proxy-to-target sessions.
22 * Revision 1.10 2000/05/30 03:12:27 ian
23 * minor change to stop g++ 2.95.2 complaining about taking the address
24 * of a member function.
26 * Revision 1.9 1999/12/06 13:52:45 adam
27 * Modified for new location of YAZ header files. Experimental threaded
30 * Revision 1.8 1999/11/10 10:02:34 adam
33 * Revision 1.7 1999/04/21 12:09:01 adam
34 * Many improvements. Modified to proxy server to work with "sessions"
37 * Revision 1.6 1999/04/20 10:30:05 adam
38 * Implemented various stuff for client and proxy. Updated calls
39 * to ODR to reflect new name parameter.
41 * Revision 1.5 1999/04/09 11:46:57 adam
42 * Added object Yaz_Z_Assoc. Much more functional client.
44 * Revision 1.4 1999/03/23 14:17:57 adam
45 * More work on timeout handling. Work on yaz-client.
47 * Revision 1.3 1999/02/02 14:01:18 adam
48 * First WIN32 port of YAZ++.
50 * Revision 1.2 1999/01/28 13:08:42 adam
51 * Yaz_PDU_Assoc better encapsulated. Memory leak fix in
52 * yaz-socket-manager.cc.
54 * Revision 1.1.1.1 1999/01/28 09:41:07 adam
55 * First implementation of YAZ++.
60 #include <yaz/options.h>
61 #include <yaz/diagbib1.h>
62 #include <yaz++/yaz-ir-assoc.h>
63 #include <yaz++/yaz-pdu-assoc.h>
64 #include <yaz++/yaz-socket-manager.h>
67 #if HAVE_READLINE_READLINE_H
68 #include <readline/readline.h>
70 #if HAVE_READLINE_HISTORY_H
71 #include <readline/history.h>
75 class YAZ_EXPORT MyClient : public Yaz_IR_Assoc {
77 int m_interactive_flag;
78 char m_thisCommand[1024];
79 char m_lastCommand[1024];
81 Yaz_SocketManager *m_socketManager;
83 MyClient(IYaz_PDU_Observable *the_PDU_Observable,
84 Yaz_SocketManager *the_SocketManager);
85 IYaz_PDU_Observer *clone(IYaz_PDU_Observable *the_PDU_Observable);
86 int args(Yaz_SocketManager *socketManager, int argc, char **argv);
87 int interactive(Yaz_SocketManager *socketManager);
89 void recv_initResponse(Z_InitResponse *initResponse);
90 void recv_searchResponse(Z_SearchResponse *searchResponse);
91 void recv_presentResponse(Z_PresentResponse *presentResponse);
92 void recv_records (Z_Records *records);
93 void recv_diagrecs(Z_DiagRec **pp, int num);
94 void recv_namePlusRecord (Z_NamePlusRecord *zpr, int offset);
95 void recv_record(Z_DatabaseRecord *record, int offset,
96 const char *databaseName);
97 void recv_textRecord(int type, const char *buf, size_t len);
98 void recv_genericRecord(Z_GenericRecord *r);
99 void display_genericRecord(Z_GenericRecord *r, int level);
100 void display_variant(Z_Variant *v, int level);
101 void connectNotify();
103 void timeoutNotify();
104 char *get_cookie (Z_OtherInformation **oi);
105 int processCommand(const char *cmd);
106 const char *MyClient::getCommand();
107 int cmd_open(char *host);
108 int cmd_connect(char *host);
109 int cmd_quit(char *args);
110 int cmd_close(char *args);
111 int cmd_find(char *args);
112 int cmd_show(char *args);
113 int cmd_cookie(char *args);
114 int cmd_init(char *args);
115 int cmd_format(char *args);
116 int cmd_proxy(char *args);
120 void MyClient::connectNotify()
122 printf ("Connection accepted by target\n");
123 set_lastReceived(-1);
126 void MyClient::timeoutNotify()
128 printf ("Connection timeout\n");
132 void MyClient::failNotify()
134 printf ("Connection closed by target\n");
135 set_lastReceived(-1);
138 IYaz_PDU_Observer *MyClient::clone(IYaz_PDU_Observable *the_PDU_Observable)
140 return new MyClient(the_PDU_Observable, m_socketManager);
143 MyClient::MyClient(IYaz_PDU_Observable *the_PDU_Observable,
144 Yaz_SocketManager *the_socketManager) :
145 Yaz_IR_Assoc (the_PDU_Observable)
148 m_interactive_flag = 1;
149 m_thisCommand[0] = '\0';
150 m_lastCommand[0] = '\0';
151 m_socketManager = the_socketManager;
154 void usage(char *prog)
156 fprintf (stderr, "%s: [-v log] [-c cookie] [-p proxy] [zurl]\n", prog);
160 char *MyClient::get_cookie(Z_OtherInformation **otherInfo)
163 Z_OtherInformationUnit *oi;
165 ent.proto = PROTO_Z3950;
166 ent.oclass = CLASS_USERINFO;
167 ent.value = (oid_value) VAL_COOKIE;
169 if (oid_ent_to_oid (&ent, oid) &&
170 (oi = update_otherInformation(otherInfo, 0, oid, 1, 1)) &&
171 oi->which == Z_OtherInfo_characterInfo)
172 return oi->information.characterInfo;
176 void MyClient::recv_initResponse(Z_InitResponse *initResponse)
178 printf ("Got InitResponse. Status ");
179 if (*initResponse->result)
183 const char *p = get_cookie (&initResponse->otherInfo);
186 printf ("cookie = %s\n", p);
194 void MyClient::recv_diagrecs(Z_DiagRec **pp, int num)
198 Z_DefaultDiagFormat *r;
200 printf("Diagnostic message(s) from database:\n");
201 for (i = 0; i<num; i++)
203 Z_DiagRec *p = pp[i];
204 if (p->which != Z_DiagRec_defaultFormat)
206 printf("Diagnostic record not in default format.\n");
210 r = p->u.defaultFormat;
211 if (!(ent = oid_getentbyoid(r->diagnosticSetId)) ||
212 ent->oclass != CLASS_DIAGSET || ent->value != VAL_BIB1)
213 printf("Missing or unknown diagset\n");
214 printf(" [%d] %s", *r->condition, diagbib1_str(*r->condition));
218 case Z_DefaultDiagFormat_v2Addinfo:
219 printf (" -- v2 addinfo '%s'\n", r->u.v2Addinfo);
221 case Z_DefaultDiagFormat_v3Addinfo:
222 printf (" -- v3 addinfo '%s'\n", r->u.v3Addinfo);
226 if (r->addinfo && *r->addinfo)
227 printf(" -- '%s'\n", r->addinfo);
234 void MyClient::recv_textRecord(int type, const char *buf, size_t len)
236 fwrite (buf, 1, len, stdout);
237 fputc ('\n', stdout);
240 void MyClient::display_variant(Z_Variant *v, int level)
244 for (i = 0; i < v->num_triples; i++)
246 printf("%*sclass=%d,type=%d", level * 4, "", *v->triples[i]->zclass,
247 *v->triples[i]->type);
248 if (v->triples[i]->which == Z_Triple_internationalString)
249 printf(",value=%s\n", v->triples[i]->value.internationalString);
255 void MyClient::display_genericRecord(Z_GenericRecord *r, int level)
261 for (i = 0; i < r->num_elements; i++)
265 printf("%*s", level * 4, "");
269 printf("%d,", *t->tagType);
272 if (t->tagValue->which == Z_StringOrNumeric_numeric)
273 printf("%d) ", *t->tagValue->u.numeric);
275 printf("%s) ", t->tagValue->u.string);
276 if (t->content->which == Z_ElementData_subtree)
279 display_genericRecord(t->content->u.subtree, level+1);
281 else if (t->content->which == Z_ElementData_string)
282 printf("%s\n", t->content->u.string);
283 else if (t->content->which == Z_ElementData_numeric)
284 printf("%d\n", *t->content->u.numeric);
285 else if (t->content->which == Z_ElementData_oid)
287 int *ip = t->content->u.oid;
290 if ((oent = oid_getentbyoid(t->content->u.oid)))
291 printf("OID: %s\n", oent->desc);
295 while (ip && *ip >= 0)
296 printf(" %d", *(ip++));
300 else if (t->content->which == Z_ElementData_noDataRequested)
301 printf("[No data requested]\n");
302 else if (t->content->which == Z_ElementData_elementEmpty)
303 printf("[Element empty]\n");
304 else if (t->content->which == Z_ElementData_elementNotThere)
305 printf("[Element not there]\n");
308 if (t->appliedVariant)
309 display_variant(t->appliedVariant, level+1);
310 if (t->metaData && t->metaData->supportedVariants)
314 printf("%*s---- variant list\n", (level+1)*4, "");
315 for (c = 0; c < t->metaData->num_supportedVariants; c++)
317 printf("%*svariant #%d\n", (level+1)*4, "", c);
318 display_variant(t->metaData->supportedVariants[c], level + 2);
324 void MyClient::recv_genericRecord(Z_GenericRecord *r)
326 display_genericRecord(r, 0);
329 void MyClient::recv_record(Z_DatabaseRecord *record, int offset,
330 const char *databaseName)
332 Z_External *r = (Z_External*) record;
333 oident *ent = oid_getentbyoid(r->direct_reference);
336 * Tell the user what we got.
338 if (r->direct_reference)
340 printf("Record type: ");
342 printf("%s\n", ent->desc);
344 /* Check if this is a known, ASN.1 type tucked away in an octet string */
345 Z_ext_typeent *etype = z_ext_getentbyref(ent->value);
346 if (ent && (r->which == Z_External_octet || r->which == Z_External_single)
347 && (etype = z_ext_getentbyref(ent->value)))
352 * Call the given decoder to process the record.
354 odr_setbuf(odr_decode(), (char*)record->u.octet_aligned->buf,
355 record->u.octet_aligned->len, 0);
356 if (!(*etype->fun)(odr_decode(), (char **)&rr, 0, 0))
358 odr_perror(odr_decode(), "Decoding constructed record.");
359 fprintf(stderr, "[Near %d]\n", odr_offset(odr_decode()));
360 fprintf(stderr, "Packet dump:\n---------\n");
361 odr_dumpBER(stderr, (char*)record->u.octet_aligned->buf,
362 record->u.octet_aligned->len);
363 fprintf(stderr, "---------\n");
365 if (etype->what == Z_External_sutrs)
367 Z_SUTRS *sutrs = (Z_SUTRS *) rr;
368 recv_textRecord ((int) VAL_SUTRS, (const char *) sutrs->buf,
369 (size_t) sutrs->len);
373 if (r->which == Z_External_octet && record->u.octet_aligned->len)
375 recv_textRecord((int) ent->value,
376 (const char *) record->u.octet_aligned->buf,
377 (size_t) record->u.octet_aligned->len);
379 else if (ent && ent->value == VAL_SUTRS && r->which == Z_External_sutrs)
380 recv_textRecord((int) VAL_SUTRS, (const char *) r->u.sutrs->buf,
381 (size_t) r->u.sutrs->len);
382 else if (ent && ent->value == VAL_GRS1 && r->which == Z_External_grs1)
383 recv_genericRecord(r->u.grs1);
386 printf("Unknown record representation.\n");
387 if (!z_External(odr_print(), &r, 0, 0))
389 odr_perror(odr_print(), "Printing external");
390 odr_reset(odr_print());
395 void MyClient::recv_namePlusRecord (Z_NamePlusRecord *zpr, int offset)
397 if (zpr->databaseName)
398 printf("[%s]", zpr->databaseName);
399 if (zpr->which == Z_NamePlusRecord_surrogateDiagnostic)
400 recv_diagrecs(&zpr->u.surrogateDiagnostic, 1);
402 recv_record(zpr->u.databaseRecord, offset, zpr->databaseName);
405 void MyClient::recv_records (Z_Records *records)
408 Z_DiagRec dr, *dr_p = &dr;
413 switch (records->which)
415 case Z_Records_DBOSD:
416 for (i = 0; i < records->u.databaseOrSurDiagnostics->num_records; i++)
417 recv_namePlusRecord(records->u.databaseOrSurDiagnostics->
418 records[i], i + m_setOffset);
419 m_setOffset += records->u.databaseOrSurDiagnostics->num_records;
423 dr.which = Z_DiagRec_defaultFormat;
424 dr.u.defaultFormat = records->u.nonSurrogateDiagnostic;
425 recv_diagrecs (&dr_p, 1);
427 recv_diagrecs (&records->u.nonSurrogateDiagnostic, 1);
430 case Z_Records_multipleNSD:
431 recv_diagrecs (records->u.multipleNonSurDiagnostics->diagRecs,
432 records->u.multipleNonSurDiagnostics->num_diagRecs);
437 void MyClient::recv_searchResponse(Z_SearchResponse *searchResponse)
439 printf ("Got SearchResponse. Status ");
440 if (!*searchResponse->searchStatus)
446 printf ("Hits: %d\n", *searchResponse->resultCount);
447 recv_records (searchResponse->records);
450 void MyClient::recv_presentResponse(Z_PresentResponse *presentResponse)
452 printf ("Got PresentResponse\n");
453 recv_records (presentResponse->records);
459 while (m_socketManager->processEvent() > 0)
461 if (get_lastReceived())
467 #define C_PROMPT "Z>"
469 int MyClient::cmd_connect(char *host)
478 int MyClient::cmd_open(char *host)
489 int MyClient::cmd_init(char *args)
491 if (send_initRequest() >= 0)
498 int MyClient::cmd_quit(char *args)
503 int MyClient::cmd_close(char *args)
509 int MyClient::cmd_find(char *args)
513 if (query.set_rpn(args) <= 0)
515 printf ("Bad RPN query\n");
518 if (send_searchRequest(&query) >= 0)
521 printf ("Not connected\n");
525 int MyClient::cmd_show(char *args)
527 int start = m_setOffset, number = 1;
529 sscanf (args, "%d %d", &start, &number);
531 if (send_presentRequest(start, number) >= 0)
534 printf ("Not connected\n");
538 int MyClient::cmd_cookie(char *args)
540 set_cookie(*args ? args : 0);
544 int MyClient::cmd_format(char *args)
546 set_preferredRecordSyntax(args);
550 int MyClient::cmd_proxy(char *args)
556 int MyClient::processCommand(const char *commandLine)
558 char cmdStr[1024], cmdArgs[1024];
563 int (MyClient::*fun)(char *arg);
566 {"open", &MyClient::cmd_open, "<host>[':'<port>][/<database>]"},
567 {"connect", &MyClient::cmd_connect, "<host>[':'<port>][/<database>]"},
568 {"quit", &MyClient::cmd_quit, ""},
569 {"close", &MyClient::cmd_close, ""},
570 {"find", &MyClient::cmd_find, "<query>"},
571 {"show", &MyClient::cmd_show, "[<start> [<number>]]"},
572 {"cookie", &MyClient::cmd_cookie, "<cookie>"},
573 {"init", &MyClient::cmd_init, ""},
574 {"format", &MyClient::cmd_format, "<record-syntax>"},
575 {"proxy", &MyClient::cmd_proxy, "<host>:[':'<port>]"},
579 if (sscanf(commandLine, "%s %[^;]", cmdStr, cmdArgs) < 1)
582 for (i = 0; cmd[i].cmd; i++)
583 if (!strncmp(cmd[i].cmd, cmdStr, strlen(cmdStr)))
587 if (cmd[i].cmd) // Invoke command handler
588 res = (this->*cmd[i].fun)(cmdArgs);
589 else // Dump help screen
591 printf("Unknown command: %s.\n", cmdStr);
592 printf("Currently recognized commands:\n");
593 for (i = 0; cmd[i].cmd; i++)
594 printf(" %s %s\n", cmd[i].cmd, cmd[i].ad);
599 const char *MyClient::getCommand()
601 #if HAVE_READLINE_READLINE_H
602 // Read using GNU readline
604 line_in=readline(C_PROMPT);
607 #if HAVE_READLINE_HISTORY_H
609 add_history(line_in);
611 strncpy(m_thisCommand,line_in, 1023);
612 m_thisCommand[1023] = '\0';
615 // Read using fgets(3)
618 if (!fgets(m_thisCommand, 1023, stdin))
621 // Remove trailing whitespace
622 char *cp = m_thisCommand + strlen(m_thisCommand);
623 while (cp != m_thisCommand && strchr("\t \n", cp[-1]))
627 // Remove leading spaces...
628 while (*cp && strchr ("\t \n", *cp))
630 // Save command if non-empty
632 strcpy (m_lastCommand, cp);
633 return m_lastCommand;
636 int MyClient::interactive(Yaz_SocketManager *socketManager)
639 if (!m_interactive_flag)
641 while ((cmd = getCommand()))
643 if (!processCommand(cmd))
649 int MyClient::args(Yaz_SocketManager *socketManager, int argc, char **argv)
654 char *prog = argv[0];
657 while ((ret = options("c:p:v:q", argv, argc, &arg)) != -2)
681 yaz_log_init_level (yaz_log_mask_str(arg));
684 m_interactive_flag = 0;
703 int main(int argc, char **argv)
705 Yaz_SocketManager mySocketManager;
706 Yaz_PDU_Assoc *some = new Yaz_PDU_Assoc(&mySocketManager);
708 MyClient z(some, &mySocketManager);
710 if (z.args(&mySocketManager, argc, argv))
712 if (z.interactive(&mySocketManager))