2 * Copyright (c) 1998-2001, Index Data.
3 * See the file LICENSE for details.
5 * $Id: yaz-my-client.cpp,v 1.10 2001-11-04 22:36:21 adam Exp $
9 #include <yaz/options.h>
10 #include <yaz/diagbib1.h>
11 #include <yaz/marcdisp.h>
12 #include <yaz++/yaz-ir-assoc.h>
13 #include <yaz++/yaz-pdu-assoc.h>
14 #include <yaz++/yaz-socket-manager.h>
17 #include <yaz/zes-ursula.h>
21 #if HAVE_READLINE_READLINE_H
22 #include <readline/readline.h>
24 #if HAVE_READLINE_HISTORY_H
25 #include <readline/history.h>
29 class YAZ_EXPORT MyClient : public Yaz_IR_Assoc {
31 int m_interactive_flag;
32 char m_thisCommand[1024];
33 char m_lastCommand[1024];
35 Yaz_SocketManager *m_socketManager;
37 MyClient(IYaz_PDU_Observable *the_PDU_Observable,
38 Yaz_SocketManager *the_SocketManager);
39 IYaz_PDU_Observer *sessionNotify(
40 IYaz_PDU_Observable *the_PDU_Observable, int fd);
41 int args(Yaz_SocketManager *socketManager, int argc, char **argv);
42 int interactive(Yaz_SocketManager *socketManager);
44 void recv_initResponse(Z_InitResponse *initResponse);
45 void recv_searchResponse(Z_SearchResponse *searchResponse);
46 void recv_presentResponse(Z_PresentResponse *presentResponse);
47 void recv_records (Z_Records *records);
48 void recv_diagrecs(Z_DiagRec **pp, int num);
49 void recv_namePlusRecord (Z_NamePlusRecord *zpr, int offset);
50 void recv_record(Z_DatabaseRecord *record, int offset,
51 const char *databaseName);
52 void recv_textRecord(int type, const char *buf, size_t len);
53 void recv_genericRecord(Z_GenericRecord *r);
55 void recv_extendedServicesResponse(Z_ExtendedServicesResponse *extendedServicesResponse);
57 void display_genericRecord(Z_GenericRecord *r, int level);
58 void display_variant(Z_Variant *v, int level);
62 char *get_cookie (Z_OtherInformation **oi);
63 int processCommand(const char *cmd);
64 const char *MyClient::getCommand();
65 int cmd_open(char *host);
66 int cmd_connect(char *host);
67 int cmd_quit(char *args);
68 int cmd_close(char *args);
69 int cmd_find(char *args);
70 int cmd_show(char *args);
71 int cmd_cookie(char *args);
72 int cmd_init(char *args);
73 int cmd_format(char *args);
74 int cmd_proxy(char *args);
76 int cmd_ursula(char *args);
77 int cmd_ursula_renew(char *args);
82 void MyClient::connectNotify()
84 printf ("Connection accepted by target\n");
88 void MyClient::timeoutNotify()
90 printf ("Connection timeout\n");
94 void MyClient::failNotify()
96 printf ("Connection closed by target\n");
100 IYaz_PDU_Observer *MyClient::sessionNotify(
101 IYaz_PDU_Observable *the_PDU_Observable, int fd)
103 return new MyClient(the_PDU_Observable, m_socketManager);
106 MyClient::MyClient(IYaz_PDU_Observable *the_PDU_Observable,
107 Yaz_SocketManager *the_socketManager) :
108 Yaz_IR_Assoc (the_PDU_Observable)
111 m_interactive_flag = 1;
112 m_thisCommand[0] = '\0';
113 m_lastCommand[0] = '\0';
114 m_socketManager = the_socketManager;
117 void usage(char *prog)
119 fprintf (stderr, "%s: [-v log] [-c cookie] [-p proxy] [zurl]\n", prog);
123 char *MyClient::get_cookie(Z_OtherInformation **otherInfo)
126 Z_OtherInformationUnit *oi;
128 ent.proto = PROTO_Z3950;
129 ent.oclass = CLASS_USERINFO;
130 ent.value = (oid_value) VAL_COOKIE;
132 if (oid_ent_to_oid (&ent, oid) &&
133 (oi = update_otherInformation(otherInfo, 0, oid, 1, 1)) &&
134 oi->which == Z_OtherInfo_characterInfo)
135 return oi->information.characterInfo;
139 void MyClient::recv_initResponse(Z_InitResponse *initResponse)
141 printf ("Got InitResponse. Status ");
142 if (*initResponse->result)
146 const char *p = get_cookie (&initResponse->otherInfo);
149 printf ("cookie = %s\n", p);
157 void MyClient::recv_diagrecs(Z_DiagRec **pp, int num)
161 Z_DefaultDiagFormat *r;
163 printf("Diagnostic message(s) from database:\n");
164 for (i = 0; i<num; i++)
166 Z_DiagRec *p = pp[i];
167 if (p->which != Z_DiagRec_defaultFormat)
169 printf("Diagnostic record not in default format.\n");
173 r = p->u.defaultFormat;
174 if (!(ent = oid_getentbyoid(r->diagnosticSetId)) ||
175 ent->oclass != CLASS_DIAGSET || ent->value != VAL_BIB1)
176 printf("Missing or unknown diagset\n");
177 printf(" [%d] %s", *r->condition, diagbib1_str(*r->condition));
181 case Z_DefaultDiagFormat_v2Addinfo:
182 printf (" -- v2 addinfo '%s'\n", r->u.v2Addinfo);
184 case Z_DefaultDiagFormat_v3Addinfo:
185 printf (" -- v3 addinfo '%s'\n", r->u.v3Addinfo);
189 if (r->addinfo && *r->addinfo)
190 printf(" -- '%s'\n", r->addinfo);
197 void MyClient::recv_textRecord(int type, const char *buf, size_t len)
199 fwrite (buf, 1, len, stdout);
200 fputc ('\n', stdout);
203 void MyClient::display_variant(Z_Variant *v, int level)
207 for (i = 0; i < v->num_triples; i++)
209 printf("%*sclass=%d,type=%d", level * 4, "", *v->triples[i]->zclass,
210 *v->triples[i]->type);
211 if (v->triples[i]->which == Z_Triple_internationalString)
212 printf(",value=%s\n", v->triples[i]->value.internationalString);
218 void MyClient::display_genericRecord(Z_GenericRecord *r, int level)
224 for (i = 0; i < r->num_elements; i++)
228 printf("%*s", level * 4, "");
232 printf("%d,", *t->tagType);
235 if (t->tagValue->which == Z_StringOrNumeric_numeric)
236 printf("%d) ", *t->tagValue->u.numeric);
238 printf("%s) ", t->tagValue->u.string);
239 if (t->content->which == Z_ElementData_subtree)
242 display_genericRecord(t->content->u.subtree, level+1);
244 else if (t->content->which == Z_ElementData_string)
245 printf("%s\n", t->content->u.string);
246 else if (t->content->which == Z_ElementData_numeric)
247 printf("%d\n", *t->content->u.numeric);
248 else if (t->content->which == Z_ElementData_oid)
250 int *ip = t->content->u.oid;
253 if ((oent = oid_getentbyoid(t->content->u.oid)))
254 printf("OID: %s\n", oent->desc);
258 while (ip && *ip >= 0)
259 printf(" %d", *(ip++));
263 else if (t->content->which == Z_ElementData_noDataRequested)
264 printf("[No data requested]\n");
265 else if (t->content->which == Z_ElementData_elementEmpty)
266 printf("[Element empty]\n");
267 else if (t->content->which == Z_ElementData_elementNotThere)
268 printf("[Element not there]\n");
271 if (t->appliedVariant)
272 display_variant(t->appliedVariant, level+1);
273 if (t->metaData && t->metaData->supportedVariants)
277 printf("%*s---- variant list\n", (level+1)*4, "");
278 for (c = 0; c < t->metaData->num_supportedVariants; c++)
280 printf("%*svariant #%d\n", (level+1)*4, "", c);
281 display_variant(t->metaData->supportedVariants[c], level + 2);
287 void MyClient::recv_genericRecord(Z_GenericRecord *r)
289 display_genericRecord(r, 0);
292 void MyClient::recv_record(Z_DatabaseRecord *record, int offset,
293 const char *databaseName)
295 Z_External *r = (Z_External*) record;
296 oident *ent = oid_getentbyoid(r->direct_reference);
299 * Tell the user what we got.
301 if (r->direct_reference)
303 printf("Record type: ");
305 printf("%s\n", ent->desc);
307 /* Check if this is a known, ASN.1 type tucked away in an octet string */
308 Z_ext_typeent *etype = z_ext_getentbyref(ent->value);
309 if (ent && (r->which == Z_External_octet || r->which == Z_External_single)
310 && (etype = z_ext_getentbyref(ent->value)))
315 * Call the given decoder to process the record.
317 odr_setbuf(odr_decode(), (char*)record->u.octet_aligned->buf,
318 record->u.octet_aligned->len, 0);
319 if (!(*etype->fun)(odr_decode(), (char **)&rr, 0, 0))
321 odr_perror(odr_decode(), "Decoding constructed record.");
322 fprintf(stderr, "[Near %d]\n", odr_offset(odr_decode()));
323 fprintf(stderr, "Packet dump:\n---------\n");
324 odr_dumpBER(stderr, (char*)record->u.octet_aligned->buf,
325 record->u.octet_aligned->len);
326 fprintf(stderr, "---------\n");
328 if (etype->what == Z_External_sutrs)
330 Z_SUTRS *sutrs = (Z_SUTRS *) rr;
331 recv_textRecord ((int) VAL_SUTRS, (const char *) sutrs->buf,
332 (size_t) sutrs->len);
336 if (r->which == Z_External_octet && record->u.octet_aligned->len)
362 marc_display((char*) record->u.octet_aligned->buf,0);
365 recv_textRecord((int) ent->value,
366 (const char *) record->u.octet_aligned->buf,
367 (size_t) record->u.octet_aligned->len);
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);
449 #if HAVE_YAZ_URSULA_H
450 void MyClient::recv_extendedServicesResponse(Z_ExtendedServicesResponse *extendedServicesResponse)
452 printf("Got ESresponse\n");
453 printf(" OperationStatus=%d with %d diagnostics:\n",
454 *extendedServicesResponse->operationStatus,
455 extendedServicesResponse->num_diagnostics);
456 recv_diagrecs(extendedServicesResponse->diagnostics,
457 extendedServicesResponse->num_diagnostics);
458 //TODO: Add more info !
465 while (m_socketManager->processEvent() > 0)
467 if (get_lastReceived())
474 #define C_PROMPT "Z>"
476 int MyClient::cmd_connect(char *host)
485 int MyClient::cmd_open(char *host)
496 int MyClient::cmd_init(char *args)
498 if (send_initRequest() >= 0)
505 int MyClient::cmd_quit(char *args)
510 int MyClient::cmd_close(char *args)
516 int MyClient::cmd_find(char *args)
520 if (query.set_rpn(args) <= 0)
522 printf ("Bad RPN query\n");
525 if (send_searchRequest(&query) >= 0)
528 printf ("Not connected\n");
532 int MyClient::cmd_show(char *args)
534 int start = m_setOffset, number = 1;
536 sscanf (args, "%d %d", &start, &number);
538 if (send_presentRequest(start, number) >= 0)
541 printf ("Not connected\n");
545 int MyClient::cmd_cookie(char *args)
547 set_cookie(*args ? args : 0);
551 int MyClient::cmd_format(char *args)
553 set_preferredRecordSyntax(args);
557 int MyClient::cmd_proxy(char *args)
563 #if HAVE_YAZ_URSULA_H
564 int MyClient::cmd_ursula(char *args)
566 Z_APDU *apdu = create_Z_PDU(Z_APDU_extendedServicesRequest);
567 Z_ExtendedServicesRequest *req = apdu->u.extendedServicesRequest;
569 req->packageType = odr_getoidbystr(odr_encode(), "1.2.840.10003");
570 // req->packageType = odr_getoidbystr(odr_encode(), "1.2.840.10003.9.1000.105.3");
572 Z_External *ext = (Z_External *) odr_malloc(odr_encode(), sizeof(*ext));
573 req->taskSpecificParameters = ext;
574 ext->direct_reference = req->packageType;
576 ext->indirect_reference = 0;
578 ext->which = Z_External_octet;
579 ext->u.single_ASN1_type = (Odr_oct *)
580 odr_malloc (odr_encode(), sizeof(Odr_oct));
582 Z_UrsPDU *pdu = (Z_UrsPDU *) odr_malloc (odr_encode(), sizeof(*pdu));
583 pdu->which = Z_UrsPDU_request;
584 pdu->u.request = (Z_UrsRequest *)
585 odr_malloc (odr_encode(), sizeof(*pdu->u.request));
586 pdu->u.request->libraryNo = odr_strdup(odr_encode(), "000200");
587 pdu->u.request->borrowerTickerNo = odr_strdup(odr_encode(),"1234567973");
588 pdu->u.request->disposalType = 0;
589 pdu->u.request->lastUseDate = odr_strdup(odr_encode(),"20011224");
591 pdu->u.request->num_items = 0;
592 pdu->u.request->items = (Z_UrsRequestItem **) odr_nullval();
594 pdu->u.request->num_items = 1;
595 pdu->u.request->items = (Z_UrsRequestItem **)
596 odr_malloc(odr_encode(), 1 * sizeof(Z_UrsRequestItem*) );
597 pdu->u.request->items[0] = (Z_UrsRequestItem*)
598 odr_malloc(odr_encode(), sizeof(Z_UrsRequestItem) );
599 pdu->u.request->items[0]->id = odr_strdup(odr_encode(),"002231336x");
600 pdu->u.request->items[0]->titlePartNo=odr_strdup(odr_encode(),"31");
603 pdu->u.request->counter = odr_strdup(odr_encode(),"HB");
604 pdu->u.request->priority = 0;
605 pdu->u.request->disposalNote = 0;
606 pdu->u.request->overrule=(bool_t*)odr_malloc(odr_encode(),sizeof(bool_t));
607 *pdu->u.request->overrule = false;
609 if (!z_UrsPDU (odr_encode(), &pdu, 0, ""))
611 yaz_log (LOG_LOG, "ursula encoding failed");
615 odr_getbuf (odr_encode(), &ext->u.single_ASN1_type->len, 0);
617 ext->u.single_ASN1_type->buf = (unsigned char*)
618 odr_malloc (odr_encode(), ext->u.single_ASN1_type->len);
619 memcpy (ext->u.single_ASN1_type->buf, buf, ext->u.single_ASN1_type->len);
620 ext->u.single_ASN1_type->size = ext->u.single_ASN1_type->len;
622 if (send_Z_PDU(apdu) >= 0)
627 int MyClient::cmd_ursula_renew(char *args)
629 Z_APDU *apdu = create_Z_PDU(Z_APDU_extendedServicesRequest);
630 Z_ExtendedServicesRequest *req = apdu->u.extendedServicesRequest;
632 req->packageType = odr_getoidbystr(odr_encode(), "1.2.840.10003");
634 Z_External *ext = (Z_External *) odr_malloc(odr_encode(), sizeof(*ext));
635 req->taskSpecificParameters = ext;
636 ext->direct_reference = req->packageType;
638 ext->indirect_reference = 0;
640 ext->which = Z_External_octet;
641 ext->u.single_ASN1_type = (Odr_oct *)
642 odr_malloc (odr_encode(), sizeof(Odr_oct));
644 Z_UrsPDU *pdu = (Z_UrsPDU *) odr_malloc (odr_encode(), sizeof(*pdu));
645 pdu->which = Z_UrsPDU_renewal;
646 pdu->u.renewal = (Z_UrsRenewal *)
647 odr_malloc (odr_encode(), sizeof(*pdu->u.renewal));
648 pdu->u.renewal->libraryNo = odr_strdup(odr_encode(), "000200");
649 pdu->u.renewal->borrowerTicketNo = odr_strdup(odr_encode(),"1234567973");
650 pdu->u.renewal->num_copies=1;
651 pdu->u.renewal->copies = (Z_InternationalString **)
652 odr_malloc(odr_encode(),1* sizeof(Z_InternationalString *) );
653 pdu->u.renewal->copies[0]= odr_strdup(odr_encode(), "000035238");
654 pdu->u.renewal->newReturnDate=odr_strdup(odr_encode(), "20011224");
655 pdu->u.renewal->overrule=(bool_t*)odr_malloc(odr_encode(),sizeof(bool_t));
656 *pdu->u.renewal->overrule=false;
658 if (!z_UrsPDU (odr_encode(), &pdu, 0, ""))
660 yaz_log (LOG_LOG, "ursula encoding failed");
664 odr_getbuf (odr_encode(), &ext->u.single_ASN1_type->len, 0);
666 ext->u.single_ASN1_type->buf = (unsigned char*)
667 odr_malloc (odr_encode(), ext->u.single_ASN1_type->len);
668 memcpy (ext->u.single_ASN1_type->buf, buf, ext->u.single_ASN1_type->len);
669 ext->u.single_ASN1_type->size = ext->u.single_ASN1_type->len;
671 if (send_Z_PDU(apdu) >= 0)
679 int MyClient::processCommand(const char *commandLine)
681 char cmdStr[1024], cmdArgs[1024];
686 int (MyClient::*fun)(char *arg);
689 {"open", &MyClient::cmd_open, "<host>[':'<port>][/<database>]"},
690 {"connect", &MyClient::cmd_connect, "<host>[':'<port>][/<database>]"},
691 {"quit", &MyClient::cmd_quit, ""},
692 {"close", &MyClient::cmd_close, ""},
693 {"find", &MyClient::cmd_find, "<query>"},
694 {"show", &MyClient::cmd_show, "[<start> [<number>]]"},
695 {"cookie", &MyClient::cmd_cookie, "<cookie>"},
696 {"init", &MyClient::cmd_init, ""},
697 {"format", &MyClient::cmd_format, "<record-syntax>"},
698 {"proxy", &MyClient::cmd_proxy, "<host>:[':'<port>]"},
699 #if HAVE_YAZ_URSULA_H
700 {"ursula", &MyClient::cmd_ursula, ""},
701 {"ursula_request", &MyClient::cmd_ursula, ""},
702 {"ursreq", &MyClient::cmd_ursula, ""},
703 {"ursnew", &MyClient::cmd_ursula_renew, ""},
704 {"ursula_renew", &MyClient::cmd_ursula_renew, ""},
709 if (sscanf(commandLine, "%s %[^;]", cmdStr, cmdArgs) < 1)
712 for (i = 0; cmd[i].cmd; i++)
713 if (!strncmp(cmd[i].cmd, cmdStr, strlen(cmdStr)))
717 if (cmd[i].cmd) // Invoke command handler
718 res = (this->*cmd[i].fun)(cmdArgs);
719 else // Dump help screen
721 printf("Unknown command: %s.\n", cmdStr);
722 printf("Currently recognized commands:\n");
723 for (i = 0; cmd[i].cmd; i++)
724 printf(" %s %s\n", cmd[i].cmd, cmd[i].ad);
729 const char *MyClient::getCommand()
731 #if HAVE_READLINE_READLINE_H
732 // Read using GNU readline
734 line_in=readline(C_PROMPT);
737 #if HAVE_READLINE_HISTORY_H
739 add_history(line_in);
741 strncpy(m_thisCommand,line_in, 1023);
742 m_thisCommand[1023] = '\0';
745 // Read using fgets(3)
748 if (!fgets(m_thisCommand, 1023, stdin))
751 // Remove trailing whitespace
752 char *cp = m_thisCommand + strlen(m_thisCommand);
753 while (cp != m_thisCommand && strchr("\t \n", cp[-1]))
757 // Remove leading spaces...
758 while (*cp && strchr ("\t \n", *cp))
760 // Save command if non-empty
762 strcpy (m_lastCommand, cp);
763 return m_lastCommand;
766 int MyClient::interactive(Yaz_SocketManager *socketManager)
769 if (!m_interactive_flag)
771 while ((cmd = getCommand()))
773 if (!processCommand(cmd))
779 int MyClient::args(Yaz_SocketManager *socketManager, int argc, char **argv)
784 char *prog = argv[0];
787 while ((ret = options("c:p:v:q", argv, argc, &arg)) != -2)
811 yaz_log_init_level (yaz_log_mask_str(arg));
814 m_interactive_flag = 0;
833 int main(int argc, char **argv)
835 Yaz_SocketManager mySocketManager;
836 Yaz_PDU_Assoc *some = new Yaz_PDU_Assoc(&mySocketManager);
838 MyClient z(some, &mySocketManager);
840 if (z.args(&mySocketManager, argc, argv))
842 if (z.interactive(&mySocketManager))