2 * Copyright (c) 1998-2003, Index Data.
3 * See the file LICENSE for details.
5 * $Id: yaz-my-client.cpp,v 1.14 2003-10-16 10:26:58 adam Exp $
9 #include <yaz/options.h>
10 #include <yaz/diagbib1.h>
11 #include <yaz/marcdisp.h>
12 #include <yaz++/ir-assoc.h>
13 #include <yaz++/pdu-assoc.h>
14 #include <yaz++/socket-manager.h>
17 #if HAVE_READLINE_READLINE_H
18 #include <readline/readline.h>
20 #if HAVE_READLINE_HISTORY_H
21 #include <readline/history.h>
25 class YAZ_EXPORT MyClient : public Yaz_IR_Assoc {
27 int m_interactive_flag;
28 char m_thisCommand[1024];
29 char m_lastCommand[1024];
31 Yaz_SocketManager *m_socketManager;
33 MyClient(IYaz_PDU_Observable *the_PDU_Observable,
34 Yaz_SocketManager *the_SocketManager);
35 IYaz_PDU_Observer *sessionNotify(
36 IYaz_PDU_Observable *the_PDU_Observable, int fd);
37 int args(Yaz_SocketManager *socketManager, int argc, char **argv);
38 int interactive(Yaz_SocketManager *socketManager);
40 void recv_initResponse(Z_InitResponse *initResponse);
41 void recv_searchResponse(Z_SearchResponse *searchResponse);
42 void recv_presentResponse(Z_PresentResponse *presentResponse);
43 void recv_records (Z_Records *records);
44 void recv_diagrecs(Z_DiagRec **pp, int num);
45 void recv_namePlusRecord (Z_NamePlusRecord *zpr, int offset);
46 void recv_record(Z_DatabaseRecord *record, int offset,
47 const char *databaseName);
48 void recv_textRecord(int type, const char *buf, size_t len);
49 void recv_genericRecord(Z_GenericRecord *r);
50 void display_genericRecord(Z_GenericRecord *r, int level);
51 void display_variant(Z_Variant *v, int level);
55 char *get_cookie (Z_OtherInformation **oi);
56 int processCommand(const char *cmd);
57 const char *MyClient::getCommand();
58 int cmd_open(char *host);
59 int cmd_connect(char *host);
60 int cmd_quit(char *args);
61 int cmd_close(char *args);
62 int cmd_find(char *args);
63 int cmd_show(char *args);
64 int cmd_cookie(char *args);
65 int cmd_init(char *args);
66 int cmd_format(char *args);
67 int cmd_proxy(char *args);
71 void MyClient::connectNotify()
73 printf ("Connection accepted by target\n");
77 void MyClient::timeoutNotify()
79 printf ("Connection timeout\n");
83 void MyClient::failNotify()
85 printf ("Connection closed by target\n");
89 IYaz_PDU_Observer *MyClient::sessionNotify(
90 IYaz_PDU_Observable *the_PDU_Observable, int fd)
92 return new MyClient(the_PDU_Observable, m_socketManager);
95 MyClient::MyClient(IYaz_PDU_Observable *the_PDU_Observable,
96 Yaz_SocketManager *the_socketManager) :
97 Yaz_IR_Assoc (the_PDU_Observable)
100 m_interactive_flag = 1;
101 m_thisCommand[0] = '\0';
102 m_lastCommand[0] = '\0';
103 m_socketManager = the_socketManager;
106 void usage(char *prog)
108 fprintf (stderr, "%s: [-v log] [-c cookie] [-p proxy] [zurl]\n", prog);
112 char *MyClient::get_cookie(Z_OtherInformation **otherInfo)
115 Z_OtherInformationUnit *oi;
117 ent.proto = PROTO_Z3950;
118 ent.oclass = CLASS_USERINFO;
119 ent.value = (oid_value) VAL_COOKIE;
121 if (oid_ent_to_oid (&ent, oid) &&
122 (oi = update_otherInformation(otherInfo, 0, oid, 1, 1)) &&
123 oi->which == Z_OtherInfo_characterInfo)
124 return oi->information.characterInfo;
128 void MyClient::recv_initResponse(Z_InitResponse *initResponse)
130 printf ("Got InitResponse. Status ");
131 if (*initResponse->result)
135 const char *p = get_cookie (&initResponse->otherInfo);
138 printf ("cookie = %s\n", p);
146 void MyClient::recv_diagrecs(Z_DiagRec **pp, int num)
150 Z_DefaultDiagFormat *r;
152 printf("Diagnostic message(s) from database:\n");
153 for (i = 0; i<num; i++)
155 Z_DiagRec *p = pp[i];
156 if (p->which != Z_DiagRec_defaultFormat)
158 printf("Diagnostic record not in default format.\n");
162 r = p->u.defaultFormat;
163 if (!(ent = oid_getentbyoid(r->diagnosticSetId)) ||
164 ent->oclass != CLASS_DIAGSET || ent->value != VAL_BIB1)
165 printf("Missing or unknown diagset\n");
166 printf(" [%d] %s", *r->condition, diagbib1_str(*r->condition));
170 case Z_DefaultDiagFormat_v2Addinfo:
171 printf (" -- v2 addinfo '%s'\n", r->u.v2Addinfo);
173 case Z_DefaultDiagFormat_v3Addinfo:
174 printf (" -- v3 addinfo '%s'\n", r->u.v3Addinfo);
178 if (r->addinfo && *r->addinfo)
179 printf(" -- '%s'\n", r->addinfo);
186 void MyClient::recv_textRecord(int type, const char *buf, size_t len)
188 fwrite (buf, 1, len, stdout);
189 fputc ('\n', stdout);
192 void MyClient::display_variant(Z_Variant *v, int level)
196 for (i = 0; i < v->num_triples; i++)
198 printf("%*sclass=%d,type=%d", level * 4, "", *v->triples[i]->zclass,
199 *v->triples[i]->type);
200 if (v->triples[i]->which == Z_Triple_internationalString)
201 printf(",value=%s\n", v->triples[i]->value.internationalString);
207 void MyClient::display_genericRecord(Z_GenericRecord *r, int level)
213 for (i = 0; i < r->num_elements; i++)
217 printf("%*s", level * 4, "");
221 printf("%d,", *t->tagType);
224 if (t->tagValue->which == Z_StringOrNumeric_numeric)
225 printf("%d) ", *t->tagValue->u.numeric);
227 printf("%s) ", t->tagValue->u.string);
228 if (t->content->which == Z_ElementData_subtree)
231 display_genericRecord(t->content->u.subtree, level+1);
233 else if (t->content->which == Z_ElementData_string)
234 printf("%s\n", t->content->u.string);
235 else if (t->content->which == Z_ElementData_numeric)
236 printf("%d\n", *t->content->u.numeric);
237 else if (t->content->which == Z_ElementData_oid)
239 int *ip = t->content->u.oid;
242 if ((oent = oid_getentbyoid(t->content->u.oid)))
243 printf("OID: %s\n", oent->desc);
247 while (ip && *ip >= 0)
248 printf(" %d", *(ip++));
252 else if (t->content->which == Z_ElementData_noDataRequested)
253 printf("[No data requested]\n");
254 else if (t->content->which == Z_ElementData_elementEmpty)
255 printf("[Element empty]\n");
256 else if (t->content->which == Z_ElementData_elementNotThere)
257 printf("[Element not there]\n");
260 if (t->appliedVariant)
261 display_variant(t->appliedVariant, level+1);
262 if (t->metaData && t->metaData->supportedVariants)
266 printf("%*s---- variant list\n", (level+1)*4, "");
267 for (c = 0; c < t->metaData->num_supportedVariants; c++)
269 printf("%*svariant #%d\n", (level+1)*4, "", c);
270 display_variant(t->metaData->supportedVariants[c], level + 2);
276 void MyClient::recv_genericRecord(Z_GenericRecord *r)
278 display_genericRecord(r, 0);
281 void MyClient::recv_record(Z_DatabaseRecord *record, int offset,
282 const char *databaseName)
284 Z_External *r = (Z_External*) record;
285 oident *ent = oid_getentbyoid(r->direct_reference);
288 * Tell the user what we got.
290 if (r->direct_reference)
292 printf("Record type: ");
294 printf("%s\n", ent->desc);
296 /* Check if this is a known, ASN.1 type tucked away in an octet string */
297 Z_ext_typeent *etype = z_ext_getentbyref(ent->value);
298 if (ent && (r->which == Z_External_octet || r->which == Z_External_single)
299 && (etype = z_ext_getentbyref(ent->value)))
304 * Call the given decoder to process the record.
306 odr_setbuf(odr_decode(), (char*)record->u.octet_aligned->buf,
307 record->u.octet_aligned->len, 0);
308 if (!(*etype->fun)(odr_decode(), (char **)&rr, 0, 0))
310 odr_perror(odr_decode(), "Decoding constructed record.");
311 fprintf(stderr, "[Near %d]\n", odr_offset(odr_decode()));
312 fprintf(stderr, "Packet dump:\n---------\n");
313 odr_dumpBER(stderr, (char*)record->u.octet_aligned->buf,
314 record->u.octet_aligned->len);
315 fprintf(stderr, "---------\n");
317 if (etype->what == Z_External_sutrs)
319 Z_SUTRS *sutrs = (Z_SUTRS *) rr;
320 recv_textRecord ((int) VAL_SUTRS, (const char *) sutrs->buf,
321 (size_t) sutrs->len);
325 if (r->which == Z_External_octet && record->u.octet_aligned->len)
351 marc_display((char*) record->u.octet_aligned->buf,0);
354 recv_textRecord((int) ent->value,
355 (const char *) record->u.octet_aligned->buf,
356 (size_t) record->u.octet_aligned->len);
359 else if (ent && ent->value == VAL_SUTRS && r->which == Z_External_sutrs)
360 recv_textRecord((int) VAL_SUTRS, (const char *) r->u.sutrs->buf,
361 (size_t) r->u.sutrs->len);
362 else if (ent && ent->value == VAL_GRS1 && r->which == Z_External_grs1)
363 recv_genericRecord(r->u.grs1);
366 printf("Unknown record representation.\n");
367 if (!z_External(odr_print(), &r, 0, 0))
369 odr_perror(odr_print(), "Printing external");
370 odr_reset(odr_print());
375 void MyClient::recv_namePlusRecord (Z_NamePlusRecord *zpr, int offset)
377 if (zpr->databaseName)
378 printf("[%s]", zpr->databaseName);
379 if (zpr->which == Z_NamePlusRecord_surrogateDiagnostic)
380 recv_diagrecs(&zpr->u.surrogateDiagnostic, 1);
382 recv_record(zpr->u.databaseRecord, offset, zpr->databaseName);
385 void MyClient::recv_records (Z_Records *records)
388 Z_DiagRec dr, *dr_p = &dr;
393 switch (records->which)
395 case Z_Records_DBOSD:
396 for (i = 0; i < records->u.databaseOrSurDiagnostics->num_records; i++)
397 recv_namePlusRecord(records->u.databaseOrSurDiagnostics->
398 records[i], i + m_setOffset);
399 m_setOffset += records->u.databaseOrSurDiagnostics->num_records;
403 dr.which = Z_DiagRec_defaultFormat;
404 dr.u.defaultFormat = records->u.nonSurrogateDiagnostic;
405 recv_diagrecs (&dr_p, 1);
407 recv_diagrecs (&records->u.nonSurrogateDiagnostic, 1);
410 case Z_Records_multipleNSD:
411 recv_diagrecs (records->u.multipleNonSurDiagnostics->diagRecs,
412 records->u.multipleNonSurDiagnostics->num_diagRecs);
417 void MyClient::recv_searchResponse(Z_SearchResponse *searchResponse)
419 printf ("Got SearchResponse. Status ");
420 if (!*searchResponse->searchStatus)
427 printf ("Hits: %d\n", *searchResponse->resultCount);
429 recv_records (searchResponse->records);
432 void MyClient::recv_presentResponse(Z_PresentResponse *presentResponse)
434 printf ("Got PresentResponse\n");
435 recv_records (presentResponse->records);
441 while (m_socketManager->processEvent() > 0)
443 if (get_lastReceived())
450 #define C_PROMPT "Z>"
452 int MyClient::cmd_connect(char *host)
461 int MyClient::cmd_open(char *host)
472 int MyClient::cmd_init(char *args)
474 if (send_initRequest() >= 0)
481 int MyClient::cmd_quit(char *args)
486 int MyClient::cmd_close(char *args)
492 int MyClient::cmd_find(char *args)
496 if (query.set_rpn(args) <= 0)
498 printf ("Bad RPN query\n");
501 if (send_searchRequest(&query) >= 0)
504 printf ("Not connected\n");
508 int MyClient::cmd_show(char *args)
510 int start = m_setOffset, number = 1;
512 sscanf (args, "%d %d", &start, &number);
514 if (send_presentRequest(start, number) >= 0)
517 printf ("Not connected\n");
521 int MyClient::cmd_cookie(char *args)
523 set_cookie(*args ? args : 0);
527 int MyClient::cmd_format(char *args)
529 set_preferredRecordSyntax(args);
533 int MyClient::cmd_proxy(char *args)
539 int MyClient::processCommand(const char *commandLine)
541 char cmdStr[1024], cmdArgs[1024];
546 int (MyClient::*fun)(char *arg);
549 {"open", &MyClient::cmd_open, "<host>[':'<port>][/<database>]"},
550 {"connect", &MyClient::cmd_connect, "<host>[':'<port>][/<database>]"},
551 {"quit", &MyClient::cmd_quit, ""},
552 {"close", &MyClient::cmd_close, ""},
553 {"find", &MyClient::cmd_find, "<query>"},
554 {"show", &MyClient::cmd_show, "[<start> [<number>]]"},
555 {"cookie", &MyClient::cmd_cookie, "<cookie>"},
556 {"init", &MyClient::cmd_init, ""},
557 {"format", &MyClient::cmd_format, "<record-syntax>"},
558 {"proxy", &MyClient::cmd_proxy, "<host>:[':'<port>]"},
562 if (sscanf(commandLine, "%s %[^;]", cmdStr, cmdArgs) < 1)
565 for (i = 0; cmd[i].cmd; i++)
566 if (!strncmp(cmd[i].cmd, cmdStr, strlen(cmdStr)))
570 if (cmd[i].cmd) // Invoke command handler
571 res = (this->*cmd[i].fun)(cmdArgs);
572 else // Dump help screen
574 printf("Unknown command: %s.\n", cmdStr);
575 printf("Currently recognized commands:\n");
576 for (i = 0; cmd[i].cmd; i++)
577 printf(" %s %s\n", cmd[i].cmd, cmd[i].ad);
582 const char *MyClient::getCommand()
584 #if HAVE_READLINE_READLINE_H
585 // Read using GNU readline
587 line_in=readline(C_PROMPT);
590 #if HAVE_READLINE_HISTORY_H
592 add_history(line_in);
594 strncpy(m_thisCommand,line_in, 1023);
595 m_thisCommand[1023] = '\0';
598 // Read using fgets(3)
601 if (!fgets(m_thisCommand, 1023, stdin))
604 // Remove trailing whitespace
605 char *cp = m_thisCommand + strlen(m_thisCommand);
606 while (cp != m_thisCommand && strchr("\t \n", cp[-1]))
610 // Remove leading spaces...
611 while (*cp && strchr ("\t \n", *cp))
613 // Save command if non-empty
615 strcpy (m_lastCommand, cp);
616 return m_lastCommand;
619 int MyClient::interactive(Yaz_SocketManager *socketManager)
622 if (!m_interactive_flag)
624 while ((cmd = getCommand()))
626 if (!processCommand(cmd))
632 int MyClient::args(Yaz_SocketManager *socketManager, int argc, char **argv)
637 char *prog = argv[0];
640 while ((ret = options("c:p:v:q", argv, argc, &arg)) != -2)
664 yaz_log_init_level (yaz_log_mask_str(arg));
667 m_interactive_flag = 0;
686 int main(int argc, char **argv)
688 Yaz_SocketManager mySocketManager;
689 Yaz_PDU_Assoc *some = new Yaz_PDU_Assoc(&mySocketManager);
691 MyClient z(some, &mySocketManager);
693 if (z.args(&mySocketManager, argc, argv))
695 if (z.interactive(&mySocketManager))