2 * Copyright (c) 1998-2004, Index Data.
3 * See the file LICENSE for details.
5 * $Id: yaz-my-client.cpp,v 1.25 2007-03-20 07:54:11 adam Exp $
10 #include <yaz/options.h>
11 #include <yaz/diagbib1.h>
12 #include <yaz/marcdisp.h>
13 #include <yazpp/ir-assoc.h>
14 #include <yazpp/pdu-assoc.h>
15 #include <yazpp/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 using namespace yazpp_1;
28 class YAZ_EXPORT MyClient : public IR_Assoc {
30 int m_interactive_flag;
31 char m_thisCommand[1024];
32 char m_lastCommand[1024];
34 SocketManager *m_socketManager;
36 MyClient(IPDU_Observable *the_PDU_Observable,
37 SocketManager *the_SocketManager);
38 IPDU_Observer *sessionNotify(
39 IPDU_Observable *the_PDU_Observable, int fd);
40 int args(SocketManager *socketManager, int argc, char **argv);
41 int interactive(SocketManager *socketManager);
43 void recv_initResponse(Z_InitResponse *initResponse);
44 void recv_searchResponse(Z_SearchResponse *searchResponse);
45 void recv_presentResponse(Z_PresentResponse *presentResponse);
46 void recv_records (Z_Records *records);
47 void recv_diagrecs(Z_DiagRec **pp, int num);
48 void recv_namePlusRecord (Z_NamePlusRecord *zpr, int offset);
49 void recv_record(Z_DatabaseRecord *record, int offset,
50 const char *databaseName);
51 void recv_textRecord(int type, const char *buf, size_t len);
52 void recv_genericRecord(Z_GenericRecord *r);
53 void display_genericRecord(Z_GenericRecord *r, int level);
54 void display_variant(Z_Variant *v, int level);
58 char *get_cookie (Z_OtherInformation **oi);
59 int processCommand(const char *cmd);
60 const char *getCommand();
61 int cmd_open(char *host);
62 int cmd_connect(char *host);
63 int cmd_quit(char *args);
64 int cmd_close(char *args);
65 int cmd_find(char *args);
66 int cmd_show(char *args);
67 int cmd_cookie(char *args);
68 int cmd_init(char *args);
69 int cmd_format(char *args);
70 int cmd_proxy(char *args);
74 void MyClient::connectNotify()
76 printf ("Connection accepted by target\n");
80 void MyClient::timeoutNotify()
82 printf ("Connection timeout\n");
86 void MyClient::failNotify()
88 printf ("Connection closed by target\n");
92 IPDU_Observer *MyClient::sessionNotify(IPDU_Observable *the_PDU_Observable,
95 return new MyClient(the_PDU_Observable, m_socketManager);
98 MyClient::MyClient(IPDU_Observable *the_PDU_Observable,
99 SocketManager *the_socketManager) :
100 IR_Assoc (the_PDU_Observable)
103 m_interactive_flag = 1;
104 m_thisCommand[0] = '\0';
105 m_lastCommand[0] = '\0';
106 m_socketManager = the_socketManager;
109 void usage(char *prog)
111 fprintf (stderr, "%s: [-v log] [-c cookie] [-p proxy] [zurl]\n", prog);
115 char *MyClient::get_cookie(Z_OtherInformation **otherInfo)
118 Z_OtherInformationUnit *oi;
120 ent.proto = PROTO_Z3950;
121 ent.oclass = CLASS_USERINFO;
122 ent.value = (oid_value) VAL_COOKIE;
124 if (oid_ent_to_oid (&ent, oid) &&
125 (oi = update_otherInformation(otherInfo, 0, oid, 1, 1)) &&
126 oi->which == Z_OtherInfo_characterInfo)
127 return oi->information.characterInfo;
131 void MyClient::recv_initResponse(Z_InitResponse *initResponse)
133 printf ("Got InitResponse. Status ");
134 if (*initResponse->result)
138 const char *p = get_cookie (&initResponse->otherInfo);
141 printf ("cookie = %s\n", p);
149 void MyClient::recv_diagrecs(Z_DiagRec **pp, int num)
153 Z_DefaultDiagFormat *r;
155 printf("Diagnostic message(s) from database:\n");
156 for (i = 0; i<num; i++)
158 Z_DiagRec *p = pp[i];
159 if (p->which != Z_DiagRec_defaultFormat)
161 printf("Diagnostic record not in default format.\n");
165 r = p->u.defaultFormat;
166 if (!(ent = oid_getentbyoid(r->diagnosticSetId)) ||
167 ent->oclass != CLASS_DIAGSET || ent->value != VAL_BIB1)
168 printf("Missing or unknown diagset\n");
169 printf(" [%d] %s", *r->condition, diagbib1_str(*r->condition));
173 case Z_DefaultDiagFormat_v2Addinfo:
174 printf (" -- v2 addinfo '%s'\n", r->u.v2Addinfo);
176 case Z_DefaultDiagFormat_v3Addinfo:
177 printf (" -- v3 addinfo '%s'\n", r->u.v3Addinfo);
181 if (r->addinfo && *r->addinfo)
182 printf(" -- '%s'\n", r->addinfo);
189 void MyClient::recv_textRecord(int type, const char *buf, size_t len)
191 fwrite (buf, 1, len, stdout);
192 fputc ('\n', stdout);
195 void MyClient::display_variant(Z_Variant *v, int level)
199 for (i = 0; i < v->num_triples; i++)
201 printf("%*sclass=%d,type=%d", level * 4, "", *v->triples[i]->zclass,
202 *v->triples[i]->type);
203 if (v->triples[i]->which == Z_Triple_internationalString)
204 printf(",value=%s\n", v->triples[i]->value.internationalString);
210 void MyClient::display_genericRecord(Z_GenericRecord *r, int level)
216 for (i = 0; i < r->num_elements; i++)
220 printf("%*s", level * 4, "");
224 printf("%d,", *t->tagType);
227 if (t->tagValue->which == Z_StringOrNumeric_numeric)
228 printf("%d) ", *t->tagValue->u.numeric);
230 printf("%s) ", t->tagValue->u.string);
231 if (t->content->which == Z_ElementData_subtree)
234 display_genericRecord(t->content->u.subtree, level+1);
236 else if (t->content->which == Z_ElementData_string)
237 printf("%s\n", t->content->u.string);
238 else if (t->content->which == Z_ElementData_numeric)
239 printf("%d\n", *t->content->u.numeric);
240 else if (t->content->which == Z_ElementData_oid)
242 int *ip = t->content->u.oid;
245 if ((oent = oid_getentbyoid(t->content->u.oid)))
246 printf("OID: %s\n", oent->desc);
250 while (ip && *ip >= 0)
251 printf(" %d", *(ip++));
255 else if (t->content->which == Z_ElementData_noDataRequested)
256 printf("[No data requested]\n");
257 else if (t->content->which == Z_ElementData_elementEmpty)
258 printf("[Element empty]\n");
259 else if (t->content->which == Z_ElementData_elementNotThere)
260 printf("[Element not there]\n");
263 if (t->appliedVariant)
264 display_variant(t->appliedVariant, level+1);
265 if (t->metaData && t->metaData->supportedVariants)
269 printf("%*s---- variant list\n", (level+1)*4, "");
270 for (c = 0; c < t->metaData->num_supportedVariants; c++)
272 printf("%*svariant #%d\n", (level+1)*4, "", c);
273 display_variant(t->metaData->supportedVariants[c], level + 2);
279 void MyClient::recv_genericRecord(Z_GenericRecord *r)
281 display_genericRecord(r, 0);
284 void MyClient::recv_record(Z_DatabaseRecord *record, int offset,
285 const char *databaseName)
287 Z_External *r = (Z_External*) record;
288 oident *ent = oid_getentbyoid(r->direct_reference);
291 * Tell the user what we got.
293 if (r->direct_reference)
295 printf("Record type: ");
297 printf("%s\n", ent->desc);
299 /* Check if this is a known, ASN.1 type tucked away in an octet string */
300 Z_ext_typeent *etype = z_ext_getentbyref(ent->value);
301 if (ent && (r->which == Z_External_octet || r->which == Z_External_single)
302 && (etype = z_ext_getentbyref(ent->value)))
307 * Call the given decoder to process the record.
309 odr_setbuf(odr_decode(), (char*)record->u.octet_aligned->buf,
310 record->u.octet_aligned->len, 0);
311 if (!(*etype->fun)(odr_decode(), (char **)&rr, 0, 0))
313 odr_perror(odr_decode(), "Decoding constructed record.");
314 fprintf(stderr, "[Near %ld]\n", (long) odr_offset(odr_decode()));
315 fprintf(stderr, "Packet dump:\n---------\n");
316 odr_dumpBER(stderr, (char*)record->u.octet_aligned->buf,
317 record->u.octet_aligned->len);
318 fprintf(stderr, "---------\n");
320 if (etype->what == Z_External_sutrs)
322 Z_SUTRS *sutrs = (Z_SUTRS *) rr;
323 recv_textRecord ((int) VAL_SUTRS, (const char *) sutrs->buf,
324 (size_t) sutrs->len);
328 if (r->which == Z_External_octet && record->u.octet_aligned->len)
330 yaz_marc_t mt = yaz_marc_create();
355 const char *result_buf;
357 yaz_marc_decode_buf(mt, (const char *)
358 record->u.octet_aligned->buf,
359 record->u.octet_aligned->len,
360 &result_buf, &result_size);
361 fwrite(result_buf, 1, result_size, stdout);
364 recv_textRecord((int) ent->value,
365 (const char *) record->u.octet_aligned->buf,
366 (size_t) record->u.octet_aligned->len);
368 yaz_marc_destroy(mt);
370 else if (ent && ent->value == VAL_SUTRS && r->which == Z_External_sutrs)
371 recv_textRecord((int) VAL_SUTRS, (const char *) r->u.sutrs->buf,
372 (size_t) r->u.sutrs->len);
373 else if (ent && ent->value == VAL_GRS1 && r->which == Z_External_grs1)
374 recv_genericRecord(r->u.grs1);
377 printf("Unknown record representation.\n");
378 if (!z_External(odr_print(), &r, 0, 0))
380 odr_perror(odr_print(), "Printing external");
381 odr_reset(odr_print());
386 void MyClient::recv_namePlusRecord (Z_NamePlusRecord *zpr, int offset)
388 if (zpr->databaseName)
389 printf("[%s]", zpr->databaseName);
390 if (zpr->which == Z_NamePlusRecord_surrogateDiagnostic)
391 recv_diagrecs(&zpr->u.surrogateDiagnostic, 1);
393 recv_record(zpr->u.databaseRecord, offset, zpr->databaseName);
396 void MyClient::recv_records (Z_Records *records)
399 Z_DiagRec dr, *dr_p = &dr;
404 switch (records->which)
406 case Z_Records_DBOSD:
407 for (i = 0; i < records->u.databaseOrSurDiagnostics->num_records; i++)
408 recv_namePlusRecord(records->u.databaseOrSurDiagnostics->
409 records[i], i + m_setOffset);
410 m_setOffset += records->u.databaseOrSurDiagnostics->num_records;
414 dr.which = Z_DiagRec_defaultFormat;
415 dr.u.defaultFormat = records->u.nonSurrogateDiagnostic;
416 recv_diagrecs (&dr_p, 1);
418 recv_diagrecs (&records->u.nonSurrogateDiagnostic, 1);
421 case Z_Records_multipleNSD:
422 recv_diagrecs (records->u.multipleNonSurDiagnostics->diagRecs,
423 records->u.multipleNonSurDiagnostics->num_diagRecs);
428 void MyClient::recv_searchResponse(Z_SearchResponse *searchResponse)
430 printf ("Got SearchResponse. Status ");
431 if (!*searchResponse->searchStatus)
438 printf ("Hits: %d\n", *searchResponse->resultCount);
440 recv_records (searchResponse->records);
443 void MyClient::recv_presentResponse(Z_PresentResponse *presentResponse)
445 printf ("Got PresentResponse\n");
446 recv_records (presentResponse->records);
452 while (m_socketManager->processEvent() > 0)
454 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(SocketManager *socketManager)
633 if (!m_interactive_flag)
635 while ((cmd = getCommand()))
637 if (!processCommand(cmd))
643 int MyClient::args(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 SocketManager mySocketManager;
700 PDU_Assoc *some = new PDU_Assoc(&mySocketManager);
702 MyClient z(some, &mySocketManager);
704 if (z.args(&mySocketManager, argc, argv))
706 if (z.interactive(&mySocketManager))
713 * indent-tabs-mode: nil
715 * vim: shiftwidth=4 tabstop=8 expandtab