2 * Copyright (c) 1998-2004, Index Data.
3 * See the file LICENSE for details.
5 * $Id: yaz-my-client.cpp,v 1.18 2005-01-17 09:55:58 adam Exp $
10 #include <yaz/options.h>
11 #include <yaz/diagbib1.h>
12 #include <yaz/marcdisp.h>
13 #include <yaz++/ir-assoc.h>
14 #include <yaz++/pdu-assoc.h>
15 #include <yaz++/socket-manager.h>
18 #if HAVE_READLINE_READLINE_H
19 #include <readline/readline.h>
21 #if HAVE_READLINE_HISTORY_H
22 #include <readline/history.h>
26 class YAZ_EXPORT MyClient : public Yaz_IR_Assoc {
28 int m_interactive_flag;
29 char m_thisCommand[1024];
30 char m_lastCommand[1024];
32 Yaz_SocketManager *m_socketManager;
34 MyClient(IYaz_PDU_Observable *the_PDU_Observable,
35 Yaz_SocketManager *the_SocketManager);
36 IYaz_PDU_Observer *sessionNotify(
37 IYaz_PDU_Observable *the_PDU_Observable, int fd);
38 int args(Yaz_SocketManager *socketManager, int argc, char **argv);
39 int interactive(Yaz_SocketManager *socketManager);
41 void recv_initResponse(Z_InitResponse *initResponse);
42 void recv_searchResponse(Z_SearchResponse *searchResponse);
43 void recv_presentResponse(Z_PresentResponse *presentResponse);
44 void recv_records (Z_Records *records);
45 void recv_diagrecs(Z_DiagRec **pp, int num);
46 void recv_namePlusRecord (Z_NamePlusRecord *zpr, int offset);
47 void recv_record(Z_DatabaseRecord *record, int offset,
48 const char *databaseName);
49 void recv_textRecord(int type, const char *buf, size_t len);
50 void recv_genericRecord(Z_GenericRecord *r);
51 void display_genericRecord(Z_GenericRecord *r, int level);
52 void display_variant(Z_Variant *v, int level);
56 char *get_cookie (Z_OtherInformation **oi);
57 int processCommand(const char *cmd);
58 const char *MyClient::getCommand();
59 int cmd_open(char *host);
60 int cmd_connect(char *host);
61 int cmd_quit(char *args);
62 int cmd_close(char *args);
63 int cmd_find(char *args);
64 int cmd_show(char *args);
65 int cmd_cookie(char *args);
66 int cmd_init(char *args);
67 int cmd_format(char *args);
68 int cmd_proxy(char *args);
72 void MyClient::connectNotify()
74 printf ("Connection accepted by target\n");
78 void MyClient::timeoutNotify()
80 printf ("Connection timeout\n");
84 void MyClient::failNotify()
86 printf ("Connection closed by target\n");
90 IYaz_PDU_Observer *MyClient::sessionNotify(
91 IYaz_PDU_Observable *the_PDU_Observable, int fd)
93 return new MyClient(the_PDU_Observable, m_socketManager);
96 MyClient::MyClient(IYaz_PDU_Observable *the_PDU_Observable,
97 Yaz_SocketManager *the_socketManager) :
98 Yaz_IR_Assoc (the_PDU_Observable)
101 m_interactive_flag = 1;
102 m_thisCommand[0] = '\0';
103 m_lastCommand[0] = '\0';
104 m_socketManager = the_socketManager;
107 void usage(char *prog)
109 fprintf (stderr, "%s: [-v log] [-c cookie] [-p proxy] [zurl]\n", prog);
113 char *MyClient::get_cookie(Z_OtherInformation **otherInfo)
116 Z_OtherInformationUnit *oi;
118 ent.proto = PROTO_Z3950;
119 ent.oclass = CLASS_USERINFO;
120 ent.value = (oid_value) VAL_COOKIE;
122 if (oid_ent_to_oid (&ent, oid) &&
123 (oi = update_otherInformation(otherInfo, 0, oid, 1, 1)) &&
124 oi->which == Z_OtherInfo_characterInfo)
125 return oi->information.characterInfo;
129 void MyClient::recv_initResponse(Z_InitResponse *initResponse)
131 printf ("Got InitResponse. Status ");
132 if (*initResponse->result)
136 const char *p = get_cookie (&initResponse->otherInfo);
139 printf ("cookie = %s\n", p);
147 void MyClient::recv_diagrecs(Z_DiagRec **pp, int num)
151 Z_DefaultDiagFormat *r;
153 printf("Diagnostic message(s) from database:\n");
154 for (i = 0; i<num; i++)
156 Z_DiagRec *p = pp[i];
157 if (p->which != Z_DiagRec_defaultFormat)
159 printf("Diagnostic record not in default format.\n");
163 r = p->u.defaultFormat;
164 if (!(ent = oid_getentbyoid(r->diagnosticSetId)) ||
165 ent->oclass != CLASS_DIAGSET || ent->value != VAL_BIB1)
166 printf("Missing or unknown diagset\n");
167 printf(" [%d] %s", *r->condition, diagbib1_str(*r->condition));
171 case Z_DefaultDiagFormat_v2Addinfo:
172 printf (" -- v2 addinfo '%s'\n", r->u.v2Addinfo);
174 case Z_DefaultDiagFormat_v3Addinfo:
175 printf (" -- v3 addinfo '%s'\n", r->u.v3Addinfo);
179 if (r->addinfo && *r->addinfo)
180 printf(" -- '%s'\n", r->addinfo);
187 void MyClient::recv_textRecord(int type, const char *buf, size_t len)
189 fwrite (buf, 1, len, stdout);
190 fputc ('\n', stdout);
193 void MyClient::display_variant(Z_Variant *v, int level)
197 for (i = 0; i < v->num_triples; i++)
199 printf("%*sclass=%d,type=%d", level * 4, "", *v->triples[i]->zclass,
200 *v->triples[i]->type);
201 if (v->triples[i]->which == Z_Triple_internationalString)
202 printf(",value=%s\n", v->triples[i]->value.internationalString);
208 void MyClient::display_genericRecord(Z_GenericRecord *r, int level)
214 for (i = 0; i < r->num_elements; i++)
218 printf("%*s", level * 4, "");
222 printf("%d,", *t->tagType);
225 if (t->tagValue->which == Z_StringOrNumeric_numeric)
226 printf("%d) ", *t->tagValue->u.numeric);
228 printf("%s) ", t->tagValue->u.string);
229 if (t->content->which == Z_ElementData_subtree)
232 display_genericRecord(t->content->u.subtree, level+1);
234 else if (t->content->which == Z_ElementData_string)
235 printf("%s\n", t->content->u.string);
236 else if (t->content->which == Z_ElementData_numeric)
237 printf("%d\n", *t->content->u.numeric);
238 else if (t->content->which == Z_ElementData_oid)
240 int *ip = t->content->u.oid;
243 if ((oent = oid_getentbyoid(t->content->u.oid)))
244 printf("OID: %s\n", oent->desc);
248 while (ip && *ip >= 0)
249 printf(" %d", *(ip++));
253 else if (t->content->which == Z_ElementData_noDataRequested)
254 printf("[No data requested]\n");
255 else if (t->content->which == Z_ElementData_elementEmpty)
256 printf("[Element empty]\n");
257 else if (t->content->which == Z_ElementData_elementNotThere)
258 printf("[Element not there]\n");
261 if (t->appliedVariant)
262 display_variant(t->appliedVariant, level+1);
263 if (t->metaData && t->metaData->supportedVariants)
267 printf("%*s---- variant list\n", (level+1)*4, "");
268 for (c = 0; c < t->metaData->num_supportedVariants; c++)
270 printf("%*svariant #%d\n", (level+1)*4, "", c);
271 display_variant(t->metaData->supportedVariants[c], level + 2);
277 void MyClient::recv_genericRecord(Z_GenericRecord *r)
279 display_genericRecord(r, 0);
282 void MyClient::recv_record(Z_DatabaseRecord *record, int offset,
283 const char *databaseName)
285 Z_External *r = (Z_External*) record;
286 oident *ent = oid_getentbyoid(r->direct_reference);
289 * Tell the user what we got.
291 if (r->direct_reference)
293 printf("Record type: ");
295 printf("%s\n", ent->desc);
297 /* Check if this is a known, ASN.1 type tucked away in an octet string */
298 Z_ext_typeent *etype = z_ext_getentbyref(ent->value);
299 if (ent && (r->which == Z_External_octet || r->which == Z_External_single)
300 && (etype = z_ext_getentbyref(ent->value)))
305 * Call the given decoder to process the record.
307 odr_setbuf(odr_decode(), (char*)record->u.octet_aligned->buf,
308 record->u.octet_aligned->len, 0);
309 if (!(*etype->fun)(odr_decode(), (char **)&rr, 0, 0))
311 odr_perror(odr_decode(), "Decoding constructed record.");
312 fprintf(stderr, "[Near %d]\n", odr_offset(odr_decode()));
313 fprintf(stderr, "Packet dump:\n---------\n");
314 odr_dumpBER(stderr, (char*)record->u.octet_aligned->buf,
315 record->u.octet_aligned->len);
316 fprintf(stderr, "---------\n");
318 if (etype->what == Z_External_sutrs)
320 Z_SUTRS *sutrs = (Z_SUTRS *) rr;
321 recv_textRecord ((int) VAL_SUTRS, (const char *) sutrs->buf,
322 (size_t) sutrs->len);
326 if (r->which == Z_External_octet && record->u.octet_aligned->len)
352 marc_display((char*) record->u.octet_aligned->buf,0);
355 recv_textRecord((int) ent->value,
356 (const char *) record->u.octet_aligned->buf,
357 (size_t) record->u.octet_aligned->len);
360 else if (ent && ent->value == VAL_SUTRS && r->which == Z_External_sutrs)
361 recv_textRecord((int) VAL_SUTRS, (const char *) r->u.sutrs->buf,
362 (size_t) r->u.sutrs->len);
363 else if (ent && ent->value == VAL_GRS1 && r->which == Z_External_grs1)
364 recv_genericRecord(r->u.grs1);
367 printf("Unknown record representation.\n");
368 if (!z_External(odr_print(), &r, 0, 0))
370 odr_perror(odr_print(), "Printing external");
371 odr_reset(odr_print());
376 void MyClient::recv_namePlusRecord (Z_NamePlusRecord *zpr, int offset)
378 if (zpr->databaseName)
379 printf("[%s]", zpr->databaseName);
380 if (zpr->which == Z_NamePlusRecord_surrogateDiagnostic)
381 recv_diagrecs(&zpr->u.surrogateDiagnostic, 1);
383 recv_record(zpr->u.databaseRecord, offset, zpr->databaseName);
386 void MyClient::recv_records (Z_Records *records)
389 Z_DiagRec dr, *dr_p = &dr;
394 switch (records->which)
396 case Z_Records_DBOSD:
397 for (i = 0; i < records->u.databaseOrSurDiagnostics->num_records; i++)
398 recv_namePlusRecord(records->u.databaseOrSurDiagnostics->
399 records[i], i + m_setOffset);
400 m_setOffset += records->u.databaseOrSurDiagnostics->num_records;
404 dr.which = Z_DiagRec_defaultFormat;
405 dr.u.defaultFormat = records->u.nonSurrogateDiagnostic;
406 recv_diagrecs (&dr_p, 1);
408 recv_diagrecs (&records->u.nonSurrogateDiagnostic, 1);
411 case Z_Records_multipleNSD:
412 recv_diagrecs (records->u.multipleNonSurDiagnostics->diagRecs,
413 records->u.multipleNonSurDiagnostics->num_diagRecs);
418 void MyClient::recv_searchResponse(Z_SearchResponse *searchResponse)
420 printf ("Got SearchResponse. Status ");
421 if (!*searchResponse->searchStatus)
428 printf ("Hits: %d\n", *searchResponse->resultCount);
430 recv_records (searchResponse->records);
433 void MyClient::recv_presentResponse(Z_PresentResponse *presentResponse)
435 printf ("Got PresentResponse\n");
436 recv_records (presentResponse->records);
442 while (m_socketManager->processEvent() > 0)
444 if (get_lastReceived())
451 #define C_PROMPT "Z>"
453 int MyClient::cmd_connect(char *host)
462 int MyClient::cmd_open(char *host)
473 int MyClient::cmd_init(char *args)
475 if (send_initRequest() >= 0)
482 int MyClient::cmd_quit(char *args)
487 int MyClient::cmd_close(char *args)
493 int MyClient::cmd_find(char *args)
497 if (query.set_rpn(args) <= 0)
499 printf ("Bad RPN query\n");
502 if (send_searchRequest(&query) >= 0)
505 printf ("Not connected\n");
509 int MyClient::cmd_show(char *args)
511 int start = m_setOffset, number = 1;
513 sscanf (args, "%d %d", &start, &number);
515 if (send_presentRequest(start, number) >= 0)
518 printf ("Not connected\n");
522 int MyClient::cmd_cookie(char *args)
524 set_cookie(*args ? args : 0);
528 int MyClient::cmd_format(char *args)
530 set_preferredRecordSyntax(args);
534 int MyClient::cmd_proxy(char *args)
540 int MyClient::processCommand(const char *commandLine)
542 char cmdStr[1024], cmdArgs[1024];
547 int (MyClient::*fun)(char *arg);
550 {"open", &MyClient::cmd_open, "<host>[':'<port>][/<database>]"},
551 {"connect", &MyClient::cmd_connect, "<host>[':'<port>][/<database>]"},
552 {"quit", &MyClient::cmd_quit, ""},
553 {"close", &MyClient::cmd_close, ""},
554 {"find", &MyClient::cmd_find, "<query>"},
555 {"show", &MyClient::cmd_show, "[<start> [<number>]]"},
556 {"cookie", &MyClient::cmd_cookie, "<cookie>"},
557 {"init", &MyClient::cmd_init, ""},
558 {"format", &MyClient::cmd_format, "<record-syntax>"},
559 {"proxy", &MyClient::cmd_proxy, "<host>:[':'<port>]"},
563 if (sscanf(commandLine, "%s %[^;]", cmdStr, cmdArgs) < 1)
566 for (i = 0; cmd[i].cmd; i++)
567 if (!strncmp(cmd[i].cmd, cmdStr, strlen(cmdStr)))
571 if (cmd[i].cmd) // Invoke command handler
572 res = (this->*cmd[i].fun)(cmdArgs);
573 else // Dump help screen
575 printf("Unknown command: %s.\n", cmdStr);
576 printf("Currently recognized commands:\n");
577 for (i = 0; cmd[i].cmd; i++)
578 printf(" %s %s\n", cmd[i].cmd, cmd[i].ad);
583 const char *MyClient::getCommand()
585 #if HAVE_READLINE_READLINE_H
586 // Read using GNU readline
588 line_in=readline(C_PROMPT);
591 #if HAVE_READLINE_HISTORY_H
593 add_history(line_in);
595 strncpy(m_thisCommand,line_in, 1023);
596 m_thisCommand[1023] = '\0';
599 // Read using fgets(3)
602 if (!fgets(m_thisCommand, 1023, stdin))
605 // Remove trailing whitespace
606 char *cp = m_thisCommand + strlen(m_thisCommand);
607 while (cp != m_thisCommand && strchr("\t \n", cp[-1]))
611 // Remove leading spaces...
612 while (*cp && strchr ("\t \n", *cp))
614 // Save command if non-empty
616 strcpy (m_lastCommand, cp);
617 return m_lastCommand;
620 int MyClient::interactive(Yaz_SocketManager *socketManager)
623 if (!m_interactive_flag)
625 while ((cmd = getCommand()))
627 if (!processCommand(cmd))
633 int MyClient::args(Yaz_SocketManager *socketManager, int argc, char **argv)
638 char *prog = argv[0];
641 while ((ret = options("c:p:v:q", argv, argc, &arg)) != -2)
665 yaz_log_init_level (yaz_log_mask_str(arg));
668 m_interactive_flag = 0;
687 int main(int argc, char **argv)
689 Yaz_SocketManager mySocketManager;
690 Yaz_PDU_Assoc *some = new Yaz_PDU_Assoc(&mySocketManager);
692 MyClient z(some, &mySocketManager);
694 if (z.args(&mySocketManager, argc, argv))
696 if (z.interactive(&mySocketManager))