2 * Copyright (c) 1998-1999, Index Data.
3 * See the file LICENSE for details.
4 * Sebastian Hammer, Adam Dickmeiss
6 * $Log: yaz-client.cpp,v $
7 * Revision 1.10 2000-05-30 03:12:27 ian
8 * minor change to stop g++ 2.95.2 complaining about taking the address
9 * of a member function.
11 * Revision 1.9 1999/12/06 13:52:45 adam
12 * Modified for new location of YAZ header files. Experimental threaded
15 * Revision 1.8 1999/11/10 10:02:34 adam
18 * Revision 1.7 1999/04/21 12:09:01 adam
19 * Many improvements. Modified to proxy server to work with "sessions"
22 * Revision 1.6 1999/04/20 10:30:05 adam
23 * Implemented various stuff for client and proxy. Updated calls
24 * to ODR to reflect new name parameter.
26 * Revision 1.5 1999/04/09 11:46:57 adam
27 * Added object Yaz_Z_Assoc. Much more functional client.
29 * Revision 1.4 1999/03/23 14:17:57 adam
30 * More work on timeout handling. Work on yaz-client.
32 * Revision 1.3 1999/02/02 14:01:18 adam
33 * First WIN32 port of YAZ++.
35 * Revision 1.2 1999/01/28 13:08:42 adam
36 * Yaz_PDU_Assoc better encapsulated. Memory leak fix in
37 * yaz-socket-manager.cc.
39 * Revision 1.1.1.1 1999/01/28 09:41:07 adam
40 * First implementation of YAZ++.
45 #include <yaz/options.h>
46 #include <yaz/diagbib1.h>
47 #include <yaz-ir-assoc.h>
48 #include <yaz-pdu-assoc.h>
49 #include <yaz-socket-manager.h>
52 #if HAVE_READLINE_READLINE_H
53 #include <readline/readline.h>
55 #if HAVE_READLINE_HISTORY_H
56 #include <readline/history.h>
60 class YAZ_EXPORT MyClient : public Yaz_IR_Assoc {
62 int m_interactive_flag;
63 char m_thisCommand[1024];
64 char m_lastCommand[1024];
66 Yaz_SocketManager *m_socketManager;
68 MyClient(IYaz_PDU_Observable *the_PDU_Observable,
69 Yaz_SocketManager *the_SocketManager);
70 IYaz_PDU_Observer *clone(IYaz_PDU_Observable *the_PDU_Observable);
71 int args(Yaz_SocketManager *socketManager, int argc, char **argv);
72 int interactive(Yaz_SocketManager *socketManager);
74 void recv_initResponse(Z_InitResponse *initResponse);
75 void recv_searchResponse(Z_SearchResponse *searchResponse);
76 void recv_presentResponse(Z_PresentResponse *presentResponse);
77 void recv_records (Z_Records *records);
78 void recv_diagrecs(Z_DiagRec **pp, int num);
79 void recv_namePlusRecord (Z_NamePlusRecord *zpr, int offset);
80 void recv_record(Z_DatabaseRecord *record, int offset,
81 const char *databaseName);
82 void recv_textRecord(int type, const char *buf, size_t len);
83 void recv_genericRecord(Z_GenericRecord *r);
84 void display_genericRecord(Z_GenericRecord *r, int level);
85 void display_variant(Z_Variant *v, int level);
89 int processCommand(const char *cmd);
90 const char *MyClient::getCommand();
91 int cmd_open(char *host);
92 int cmd_connect(char *host);
93 int cmd_quit(char *args);
94 int cmd_close(char *args);
95 int cmd_find(char *args);
96 int cmd_show(char *args);
97 int cmd_cookie(char *args);
98 int cmd_init(char *args);
99 int cmd_format(char *args);
100 int cmd_proxy(char *args);
104 void MyClient::connectNotify()
106 printf ("Connection accepted by target\n");
107 set_lastReceived(-1);
110 void MyClient::timeoutNotify()
112 printf ("Connection timeout\n");
116 void MyClient::failNotify()
118 printf ("Connection closed by target\n");
119 set_lastReceived(-1);
122 IYaz_PDU_Observer *MyClient::clone(IYaz_PDU_Observable *the_PDU_Observable)
124 return new MyClient(the_PDU_Observable, m_socketManager);
127 MyClient::MyClient(IYaz_PDU_Observable *the_PDU_Observable,
128 Yaz_SocketManager *the_socketManager) :
129 Yaz_IR_Assoc (the_PDU_Observable)
132 m_interactive_flag = 1;
133 m_thisCommand[0] = '\0';
134 m_lastCommand[0] = '\0';
135 m_socketManager = the_socketManager;
138 void usage(char *prog)
140 fprintf (stderr, "%s: [-v log] [-p proxy] [zurl]\n", prog);
144 void MyClient::recv_initResponse(Z_InitResponse *initResponse)
146 printf ("Got InitResponse. Status ");
147 if (*initResponse->result)
153 void MyClient::recv_diagrecs(Z_DiagRec **pp, int num)
157 Z_DefaultDiagFormat *r;
159 printf("Diagnostic message(s) from database:\n");
160 for (i = 0; i<num; i++)
162 Z_DiagRec *p = pp[i];
163 if (p->which != Z_DiagRec_defaultFormat)
165 printf("Diagnostic record not in default format.\n");
169 r = p->u.defaultFormat;
170 if (!(ent = oid_getentbyoid(r->diagnosticSetId)) ||
171 ent->oclass != CLASS_DIAGSET || ent->value != VAL_BIB1)
172 printf("Missing or unknown diagset\n");
173 printf(" [%d] %s", *r->condition, diagbib1_str(*r->condition));
177 case Z_DefaultDiagFormat_v2Addinfo:
178 printf (" -- v2 addinfo '%s'\n", r->u.v2Addinfo);
180 case Z_DefaultDiagFormat_v3Addinfo:
181 printf (" -- v3 addinfo '%s'\n", r->u.v3Addinfo);
185 if (r->addinfo && *r->addinfo)
186 printf(" -- '%s'\n", r->addinfo);
193 void MyClient::recv_textRecord(int type, const char *buf, size_t len)
195 fwrite (buf, 1, len, stdout);
196 fputc ('\n', stdout);
199 void MyClient::display_variant(Z_Variant *v, int level)
203 for (i = 0; i < v->num_triples; i++)
205 printf("%*sclass=%d,type=%d", level * 4, "", *v->triples[i]->zclass,
206 *v->triples[i]->type);
207 if (v->triples[i]->which == Z_Triple_internationalString)
208 printf(",value=%s\n", v->triples[i]->value.internationalString);
214 void MyClient::display_genericRecord(Z_GenericRecord *r, int level)
220 for (i = 0; i < r->num_elements; i++)
224 printf("%*s", level * 4, "");
228 printf("%d,", *t->tagType);
231 if (t->tagValue->which == Z_StringOrNumeric_numeric)
232 printf("%d) ", *t->tagValue->u.numeric);
234 printf("%s) ", t->tagValue->u.string);
235 if (t->content->which == Z_ElementData_subtree)
238 display_genericRecord(t->content->u.subtree, level+1);
240 else if (t->content->which == Z_ElementData_string)
241 printf("%s\n", t->content->u.string);
242 else if (t->content->which == Z_ElementData_numeric)
243 printf("%d\n", *t->content->u.numeric);
244 else if (t->content->which == Z_ElementData_oid)
246 int *ip = t->content->u.oid;
249 if ((oent = oid_getentbyoid(t->content->u.oid)))
250 printf("OID: %s\n", oent->desc);
254 while (ip && *ip >= 0)
255 printf(" %d", *(ip++));
259 else if (t->content->which == Z_ElementData_noDataRequested)
260 printf("[No data requested]\n");
261 else if (t->content->which == Z_ElementData_elementEmpty)
262 printf("[Element empty]\n");
263 else if (t->content->which == Z_ElementData_elementNotThere)
264 printf("[Element not there]\n");
267 if (t->appliedVariant)
268 display_variant(t->appliedVariant, level+1);
269 if (t->metaData && t->metaData->supportedVariants)
273 printf("%*s---- variant list\n", (level+1)*4, "");
274 for (c = 0; c < t->metaData->num_supportedVariants; c++)
276 printf("%*svariant #%d\n", (level+1)*4, "", c);
277 display_variant(t->metaData->supportedVariants[c], level + 2);
283 void MyClient::recv_genericRecord(Z_GenericRecord *r)
285 display_genericRecord(r, 0);
288 void MyClient::recv_record(Z_DatabaseRecord *record, int offset,
289 const char *databaseName)
291 Z_External *r = (Z_External*) record;
292 oident *ent = oid_getentbyoid(r->direct_reference);
295 * Tell the user what we got.
297 if (r->direct_reference)
299 printf("Record type: ");
301 printf("%s\n", ent->desc);
303 /* Check if this is a known, ASN.1 type tucked away in an octet string */
304 Z_ext_typeent *etype = z_ext_getentbyref(ent->value);
305 if (ent && (r->which == Z_External_octet || r->which == Z_External_single)
306 && (etype = z_ext_getentbyref(ent->value)))
311 * Call the given decoder to process the record.
313 odr_setbuf(odr_decode(), (char*)record->u.octet_aligned->buf,
314 record->u.octet_aligned->len, 0);
315 if (!(*etype->fun)(odr_decode(), (char **)&rr, 0, 0))
317 odr_perror(odr_decode(), "Decoding constructed record.");
318 fprintf(stderr, "[Near %d]\n", odr_offset(odr_decode()));
319 fprintf(stderr, "Packet dump:\n---------\n");
320 odr_dumpBER(stderr, (char*)record->u.octet_aligned->buf,
321 record->u.octet_aligned->len);
322 fprintf(stderr, "---------\n");
324 if (etype->what == Z_External_sutrs)
326 Z_SUTRS *sutrs = (Z_SUTRS *) rr;
327 recv_textRecord ((int) VAL_SUTRS, (const char *) sutrs->buf,
328 (size_t) sutrs->len);
332 if (r->which == Z_External_octet && record->u.octet_aligned->len)
334 recv_textRecord((int) ent->value,
335 (const char *) record->u.octet_aligned->buf,
336 (size_t) record->u.octet_aligned->len);
338 else if (ent && ent->value == VAL_SUTRS && r->which == Z_External_sutrs)
339 recv_textRecord((int) VAL_SUTRS, (const char *) r->u.sutrs->buf,
340 (size_t) r->u.sutrs->len);
341 else if (ent && ent->value == VAL_GRS1 && r->which == Z_External_grs1)
342 recv_genericRecord(r->u.grs1);
345 printf("Unknown record representation.\n");
346 if (!z_External(odr_print(), &r, 0, 0))
348 odr_perror(odr_print(), "Printing external");
349 odr_reset(odr_print());
354 void MyClient::recv_namePlusRecord (Z_NamePlusRecord *zpr, int offset)
356 if (zpr->databaseName)
357 printf("[%s]", zpr->databaseName);
358 if (zpr->which == Z_NamePlusRecord_surrogateDiagnostic)
359 recv_diagrecs(&zpr->u.surrogateDiagnostic, 1);
361 recv_record(zpr->u.databaseRecord, offset, zpr->databaseName);
364 void MyClient::recv_records (Z_Records *records)
367 Z_DiagRec dr, *dr_p = &dr;
372 switch (records->which)
374 case Z_Records_DBOSD:
375 for (i = 0; i < records->u.databaseOrSurDiagnostics->num_records; i++)
376 recv_namePlusRecord(records->u.databaseOrSurDiagnostics->
377 records[i], i + m_setOffset);
378 m_setOffset += records->u.databaseOrSurDiagnostics->num_records;
382 dr.which = Z_DiagRec_defaultFormat;
383 dr.u.defaultFormat = records->u.nonSurrogateDiagnostic;
384 recv_diagrecs (&dr_p, 1);
386 recv_diagrecs (&records->u.nonSurrogateDiagnostic, 1);
389 case Z_Records_multipleNSD:
390 recv_diagrecs (records->u.multipleNonSurDiagnostics->diagRecs,
391 records->u.multipleNonSurDiagnostics->num_diagRecs);
396 void MyClient::recv_searchResponse(Z_SearchResponse *searchResponse)
398 printf ("Got SearchResponse. Status ");
399 if (!*searchResponse->searchStatus)
405 printf ("Hits: %d\n", *searchResponse->resultCount);
406 recv_records (searchResponse->records);
409 void MyClient::recv_presentResponse(Z_PresentResponse *presentResponse)
411 printf ("Got PresentResponse\n");
412 recv_records (presentResponse->records);
418 while (m_socketManager->processEvent() > 0)
420 if (get_lastReceived())
426 #define C_PROMPT "Z>"
428 int MyClient::cmd_connect(char *host)
437 int MyClient::cmd_open(char *host)
448 int MyClient::cmd_init(char *args)
450 if (send_initRequest() >= 0)
457 int MyClient::cmd_quit(char *args)
462 int MyClient::cmd_close(char *args)
468 int MyClient::cmd_find(char *args)
472 if (query.set_rpn(args) <= 0)
474 printf ("Bad RPN query\n");
477 if (send_searchRequest(&query) >= 0)
480 printf ("Not connected\n");
484 int MyClient::cmd_show(char *args)
486 int start = m_setOffset, number = 1;
488 sscanf (args, "%d %d", &start, &number);
490 if (send_presentRequest(start, number) >= 0)
493 printf ("Not connected\n");
497 int MyClient::cmd_cookie(char *args)
499 set_cookie(*args ? args : 0);
503 int MyClient::cmd_format(char *args)
505 set_preferredRecordSyntax(args);
509 int MyClient::cmd_proxy(char *args)
515 int MyClient::processCommand(const char *commandLine)
517 char cmdStr[1024], cmdArgs[1024];
522 int (MyClient::*fun)(char *arg);
525 {"open", &MyClient::cmd_open, "<host>[':'<port>][/<database>]"},
526 {"connect", &MyClient::cmd_connect, "<host>[':'<port>][/<database>]"},
527 {"quit", &MyClient::cmd_quit, ""},
528 {"close", &MyClient::cmd_close, ""},
529 {"find", &MyClient::cmd_find, "<query>"},
530 {"show", &MyClient::cmd_show, "[<start> [<number>]]"},
531 {"cookie", &MyClient::cmd_cookie, "<cookie>"},
532 {"init", &MyClient::cmd_init, ""},
533 {"format", &MyClient::cmd_format, "<record-syntax>"},
534 {"proxy", &MyClient::cmd_proxy, "<host>:[':'<port>]"},
538 if (sscanf(commandLine, "%s %[^;]", cmdStr, cmdArgs) < 1)
541 for (i = 0; cmd[i].cmd; i++)
542 if (!strncmp(cmd[i].cmd, cmdStr, strlen(cmdStr)))
546 if (cmd[i].cmd) // Invoke command handler
547 res = (this->*cmd[i].fun)(cmdArgs);
548 else // Dump help screen
550 printf("Unknown command: %s.\n", cmdStr);
551 printf("Currently recognized commands:\n");
552 for (i = 0; cmd[i].cmd; i++)
553 printf(" %s %s\n", cmd[i].cmd, cmd[i].ad);
558 const char *MyClient::getCommand()
560 #if HAVE_READLINE_READLINE_H
561 // Read using GNU readline
563 line_in=readline(C_PROMPT);
566 #if HAVE_READLINE_HISTORY_H
568 add_history(line_in);
570 strncpy(m_thisCommand,line_in, 1023);
571 m_thisCommand[1023] = '\0';
574 // Read using fgets(3)
577 if (!fgets(m_thisCommand, 1023, stdin))
580 // Remove trailing whitespace
581 char *cp = m_thisCommand + strlen(m_thisCommand);
582 while (cp != m_thisCommand && strchr("\t \n", cp[-1]))
586 // Remove leading spaces...
587 while (*cp && strchr ("\t \n", *cp))
589 // Save command if non-empty
591 strcpy (m_lastCommand, cp);
592 return m_lastCommand;
595 int MyClient::interactive(Yaz_SocketManager *socketManager)
598 if (!m_interactive_flag)
600 while ((cmd = getCommand()))
602 if (!processCommand(cmd))
608 int MyClient::args(Yaz_SocketManager *socketManager, int argc, char **argv)
613 char *prog = argv[0];
616 while ((ret = options("c:p:v:q", argv, argc, &arg)) != -2)
640 log_init_level (log_mask_str(arg));
643 m_interactive_flag = 0;
662 int main(int argc, char **argv)
664 Yaz_SocketManager mySocketManager;
665 Yaz_PDU_Assoc *some = new Yaz_PDU_Assoc(&mySocketManager);
667 MyClient z(some, &mySocketManager);
669 if (z.args(&mySocketManager, argc, argv))
671 if (z.interactive(&mySocketManager))