metaproxy 1.22.1
filter_z3950_client.cpp
Go to the documentation of this file.
1/* This file is part of Metaproxy.
2 Copyright (C) Index Data
3
4Metaproxy is free software; you can redistribute it and/or modify it under
5the terms of the GNU General Public License as published by the Free
6Software Foundation; either version 2, or (at your option) any later
7version.
8
9Metaproxy is distributed in the hope that it will be useful, but WITHOUT ANY
10WARRANTY; without even the implied warranty of MERCHANTABILITY or
11FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
12for more details.
13
14You should have received a copy of the GNU General Public License
15along with this program; if not, write to the Free Software
16Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
17*/
18
19#include "config.hpp"
20
22#include <metaproxy/package.hpp>
23#include <metaproxy/util.hpp>
24
25#include <map>
26#include <stdexcept>
27#include <list>
28#include <iostream>
29
30#include <boost/thread/mutex.hpp>
31#include <boost/thread/condition.hpp>
32#include <boost/thread/xtime.hpp>
33
34#include <yaz/zgdu.h>
35#include <yaz/log.h>
36#include <yaz/otherinfo.h>
37#include <yaz/diagbib1.h>
38#include <yaz/oid_db.h>
39#include <yaz/charneg.h>
40
41#include <yazpp/socket-manager.h>
42#include <yazpp/pdu-assoc.h>
43#include <yazpp/z-assoc.h>
44
45namespace mp = metaproxy_1;
46namespace yf = mp::filter;
47
48namespace metaproxy_1 {
49 namespace filter {
50 class Z3950Client::Assoc : public yazpp_1::Z_Assoc{
51 friend class Rep;
52 Assoc(yazpp_1::SocketManager *socket_manager,
53 yazpp_1::IPDU_Observable *PDU_Observable,
54 std::string host, int connect_timeout,
55 int init_timeout, int max_sockets_timeout,
56 int general_timeout);
57 ~Assoc();
58 void connectNotify();
59 void failNotify();
60 void timeoutNotify();
61 void recv_GDU(Z_GDU *gdu, int len);
62 void fixup_nsd(ODR odr, Z_Records *records);
63 void fixup_nsd(ODR odr, Z_DefaultDiagFormat *nsd);
64 void fixup_init(ODR odr, Z_InitResponse *initrs);
65 yazpp_1::IPDU_Observer* sessionNotify(
66 yazpp_1::IPDU_Observable *the_PDU_Observable,
67 int fd);
68
69 yazpp_1::SocketManager *m_socket_manager;
70 yazpp_1::IPDU_Observable *m_PDU_Observable;
71 Package *m_package;
75 int m_connected; // 0=not connected, 1=init phase, 2=rest
83 std::string m_host;
84 };
85
87 public:
88 // number of seconds to wait before we give up request
97 std::string m_charset;
98 std::string m_default_target;
99 std::string m_force_target;
100 boost::mutex m_mutex;
101 boost::condition m_cond_session_ready;
102 std::map<mp::Session,Z3950Client::Assoc *> m_clients;
103 Z3950Client::Assoc *get_assoc(Package &package);
104 void send_and_receive(Package &package,
105 yf::Z3950Client::Assoc *c);
106 void release_assoc(Package &package);
107 };
108 }
109}
110
111using namespace mp;
112
113yf::Z3950Client::Assoc::Assoc(yazpp_1::SocketManager *socket_manager,
114 yazpp_1::IPDU_Observable *PDU_Observable,
115 std::string host,
116 int connect_timeout,
117 int init_timeout, int max_sockets_timeout,
118 int general_timeout)
119 : Z_Assoc(PDU_Observable),
120 m_socket_manager(socket_manager), m_PDU_Observable(PDU_Observable),
121 m_package(0), m_in_use(true), m_waiting(false),
122 m_destroyed(false), m_connected(0), m_has_closed(false),
123 m_queue_len(1),
124 m_time_elapsed(0),
125 m_connect_time_max(connect_timeout),
126 m_init_time_max(init_timeout),
127 m_max_sockets_timeout_sec(max_sockets_timeout),
128 m_general_time_max(general_timeout),
129 m_host(host)
130{
131}
132
133yf::Z3950Client::Assoc::~Assoc()
134{
135}
136
137void yf::Z3950Client::Assoc::connectNotify()
138{
139 m_waiting = false;
140
141 m_connected = 1;
142}
143
144void yf::Z3950Client::Assoc::failNotify()
145{
146 m_waiting = false;
147
148 mp::odr odr;
149
150 if (m_package)
151 {
152 Z_GDU *gdu = m_package->request().get();
153 Z_APDU *apdu = 0;
154 if (gdu && gdu->which == Z_GDU_Z3950)
155 apdu = gdu->u.z3950;
156
157 m_package->response() = odr.create_close(apdu, Z_Close_peerAbort, 0);
158 m_package->session().close();
159 }
160}
161
162void yf::Z3950Client::Assoc::timeoutNotify()
163{
164 m_time_elapsed++;
165 if ((m_connected == 0 && m_time_elapsed >= m_connect_time_max)
166 || (m_connected == 1 && m_time_elapsed >= m_init_time_max)
167 || (m_connected >= 2 && m_time_elapsed >= m_general_time_max))
168 {
169 m_waiting = false;
170
171 mp::odr odr;
172
173 if (m_package)
174 {
175 Z_GDU *gdu = m_package->request().get();
176 Z_APDU *apdu = 0;
177 if (gdu && gdu->which == Z_GDU_Z3950)
178 apdu = gdu->u.z3950;
179
180 if (m_connected == 2)
181 m_package->response() =
182 odr.create_close(apdu, Z_Close_lackOfActivity, 0);
183 else
184 m_package->response() =
185 odr.create_close(apdu, Z_Close_peerAbort, 0);
186
187 m_package->session().close();
188 }
189 }
190}
191
192void yf::Z3950Client::Assoc::fixup_nsd(ODR odr, Z_DefaultDiagFormat *nsd)
193{
194 std::string addinfo;
195
196 // should really check for nsd->which.. But union has two members
197 // containing almost same data
198 const char *v2Addinfo = nsd->u.v2Addinfo;
199 // Z_InternationalString *v3Addinfo;
200 if (v2Addinfo && *v2Addinfo)
201 {
202 addinfo.assign(nsd->u.v2Addinfo);
203 addinfo += " ";
204 }
205 addinfo += "(backend=" + m_host + ")";
206 nsd->u.v2Addinfo = odr_strdup(odr, addinfo.c_str());
207}
208
209void yf::Z3950Client::Assoc::fixup_nsd(ODR odr, Z_Records *records)
210{
211 if (records && records->which == Z_Records_NSD)
212 {
213 fixup_nsd(odr, records->u.nonSurrogateDiagnostic);
214 }
215 if (records && records->which == Z_Records_multipleNSD)
216 {
217 Z_DiagRecs *drecs = records->u.multipleNonSurDiagnostics;
218 int i;
219 for (i = 0; i < drecs->num_diagRecs; i++)
220 {
221 Z_DiagRec *dr = drecs->diagRecs[i];
222
223 if (dr->which == Z_DiagRec_defaultFormat)
224 fixup_nsd(odr, dr->u.defaultFormat);
225 }
226 }
227}
228
229void yf::Z3950Client::Assoc::fixup_init(ODR odr, Z_InitResponse *initrs)
230{
231 Z_External *uif = initrs->userInformationField;
232
233 if (uif && uif->which == Z_External_userInfo1)
234 {
235 Z_OtherInformation *ui = uif->u.userInfo1;
236 int i;
237 for (i = 0; i < ui->num_elements; i++)
238 {
239 Z_OtherInformationUnit *unit = ui->list[i];
240 if (unit->which == Z_OtherInfo_externallyDefinedInfo &&
241 unit->information.externallyDefinedInfo &&
242 unit->information.externallyDefinedInfo->which ==
243 Z_External_diag1)
244 {
245 Z_DiagnosticFormat *diag =
246 unit->information.externallyDefinedInfo->u.diag1;
247 int j;
248 for (j = 0; j < diag->num; j++)
249 {
250 Z_DiagnosticFormat_s *ds = diag->elements[j];
251 if (ds->which == Z_DiagnosticFormat_s_defaultDiagRec)
252 {
253 Z_DefaultDiagFormat *r = ds->u.defaultDiagRec;
254 char *oaddinfo = r->u.v2Addinfo;
255 char *naddinfo = (char *) odr_malloc(
256 odr,
257 (oaddinfo ? strlen(oaddinfo) : 0) + 20 +
258 m_host.length());
259 *naddinfo = '\0';
260 if (oaddinfo && *oaddinfo)
261 {
262 strcat(naddinfo, oaddinfo);
263 strcat(naddinfo, " ");
264 }
265 strcat(naddinfo, "(backend=");
266 strcat(naddinfo, m_host.c_str());
267 strcat(naddinfo, ")");
268
269 r->u.v2Addinfo = naddinfo;
270 }
271 }
272 }
273 }
274 }
275}
276
277void yf::Z3950Client::Assoc::recv_GDU(Z_GDU *gdu, int len)
278{
279 m_waiting = false;
280
281 if (m_package)
282 {
283 mp::odr odr; // must be in scope for response() = assignment
284 if (gdu && gdu->which == Z_GDU_Z3950)
285 {
286 Z_APDU *apdu = gdu->u.z3950;
287 switch (apdu->which)
288 {
289 case Z_APDU_searchResponse:
290 fixup_nsd(odr, apdu->u.searchResponse->records);
291 break;
292 case Z_APDU_presentResponse:
293 fixup_nsd(odr, apdu->u.presentResponse->records);
294 break;
295 case Z_APDU_initResponse:
296 fixup_init(odr, apdu->u.initResponse);
297 m_connected = 2;
298 break;
299 }
300 }
301 m_package->response() = gdu;
302 }
303}
304
305yazpp_1::IPDU_Observer *yf::Z3950Client::Assoc::sessionNotify(
306 yazpp_1::IPDU_Observable *the_PDU_Observable,
307 int fd)
308{
309 return 0;
310}
311
312
313yf::Z3950Client::Z3950Client() : m_p(new yf::Z3950Client::Rep)
314{
315 m_p->m_connect_timeout_sec = 10;
316 m_p->m_init_timeout_sec = 10;
317 m_p->m_general_timeout_sec = 30;
318 m_p->m_max_sockets = 0;
319 m_p->m_max_sockets_timeout_sec = 15;
320 m_p->m_force_close = false;
321 m_p->m_client_ip = false;
322 m_p->m_bind_host = false;
323}
324
325yf::Z3950Client::~Z3950Client() {
326}
327
328yf::Z3950Client::Assoc *yf::Z3950Client::Rep::get_assoc(Package &package)
329{
330 // only one thread messes with the clients list at a time
331 boost::mutex::scoped_lock lock(m_mutex);
332
333 std::map<mp::Session,yf::Z3950Client::Assoc *>::iterator it;
334
335 Z_GDU *gdu = package.request().get();
336
337 int max_sockets = package.origin().get_max_sockets();
338 if (max_sockets == 0)
339 max_sockets = m_max_sockets;
340
341 it = m_clients.find(package.session());
342 if (it != m_clients.end())
343 {
344 it->second->m_queue_len++;
345 while (true)
346 {
347#if 0
348 // double init .. NOT working yet
349 if (gdu && gdu->which == Z_GDU_Z3950 &&
350 gdu->u.z3950->which == Z_APDU_initRequest)
351 {
352 yazpp_1::SocketManager *s = it->second->m_socket_manager;
353 delete it->second; // destroy Z_Assoc
354 delete s; // then manager
355 m_clients.erase(it);
356 break;
357 }
358#endif
359 if (!it->second->m_in_use)
360 {
361 it->second->m_in_use = true;
362 return it->second;
363 }
364 m_cond_session_ready.wait(lock);
365 }
366 }
367 if (!gdu || gdu->which != Z_GDU_Z3950)
368 {
369 package.move();
370 return 0;
371 }
372 // new Z39.50 session ..
373 Z_APDU *apdu = gdu->u.z3950;
374 // check that it is init. If not, close
375 if (apdu->which != Z_APDU_initRequest)
376 {
377 mp::odr odr;
378
379 package.response() = odr.create_close(apdu,
380 Z_Close_protocolError,
381 "First PDU was not an "
382 "Initialize Request");
383 package.session().close();
384 return 0;
385 }
386 std::string target = m_force_target;
387 if (!target.length())
388 {
389 target = m_default_target;
390 std::list<std::string> vhosts;
391 mp::util::remove_vhost_otherinfo(&apdu->u.initRequest->otherInfo,
392 vhosts);
393 size_t no_vhosts = vhosts.size();
394 if (no_vhosts == 1)
395 {
396 std::list<std::string>::const_iterator v_it = vhosts.begin();
397 target = *v_it;
398 }
399 else if (no_vhosts == 0)
400 {
401 if (!target.length())
402 {
403 // no default target. So we don't know where to connect
404 mp::odr odr;
405 package.response() = odr.create_initResponse(
406 apdu,
407 YAZ_BIB1_INIT_NEGOTIATION_OPTION_REQUIRED,
408 "z3950_client: No vhost given");
409
410 package.session().close();
411 return 0;
412 }
413 }
414 else if (no_vhosts > 1)
415 {
416 mp::odr odr;
417 package.response() = odr.create_initResponse(
418 apdu,
419 YAZ_BIB1_COMBI_OF_SPECIFIED_DATABASES_UNSUPP,
420 "z3950_client: Can not cope with multiple vhosts");
421 package.session().close();
422 return 0;
423 }
424 }
425
426 // see if we have reached max number of clients (max-sockets)
427 boost::xtime xt;
428 xtime_get(&xt,
429#if BOOST_VERSION >= 105000
430 boost::TIME_UTC_
431#else
432 boost::TIME_UTC
433#endif
434 );
435 xt.sec += m_max_sockets_timeout_sec;
436 while (max_sockets)
437 {
438 int no_not_in_use = 0;
439 int number = 0;
440 it = m_clients.begin();
441 for (; it != m_clients.end(); it++)
442 {
443 yf::Z3950Client::Assoc *as = it->second;
444 if (!strcmp(as->m_host.c_str(), target.c_str()))
445 {
446 number++;
447 if (!as->m_in_use)
448 no_not_in_use++;
449 }
450 }
451 yaz_log(YLOG_LOG, "Found num=%d/max=%d/idle=%d connections for %s",
452 number, max_sockets, no_not_in_use, target.c_str());
453 if (number < max_sockets)
454 break;
455 if (no_not_in_use == 0) // all in use..
456 {
457 mp::odr odr;
458
459 package.response() = odr.create_initResponse(
460 apdu, YAZ_BIB1_TEMPORARY_SYSTEM_ERROR,
461 "z3950_client: max sessions");
462 package.session().close();
463 return 0;
464 }
465 if (!m_cond_session_ready.timed_wait(lock, xt))
466 {
467 mp::odr odr;
468
469 package.response() = odr.create_initResponse(
470 apdu, YAZ_BIB1_TEMPORARY_SYSTEM_ERROR,
471 "z3950_client: max sessions");
472 package.session().close();
473 return 0;
474 }
475 }
476
477 yazpp_1::SocketManager *sm = new yazpp_1::SocketManager;
478 yazpp_1::PDU_Assoc *pdu_as = new yazpp_1::PDU_Assoc(sm);
479 yf::Z3950Client::Assoc *as =
480 new yf::Z3950Client::Assoc(sm, pdu_as, target.c_str(),
481 m_connect_timeout_sec,
482 m_init_timeout_sec,
483 m_max_sockets_timeout_sec,
484 m_general_timeout_sec);
485 m_clients[package.session()] = as;
486 return as;
487}
488
489static void set_charset_proposal(ODR odr, Z_InitRequest *req, const char *charset)
490{
491 Z_OtherInformation **p = &req->otherInfo;
492 Z_OtherInformationUnit *oi;
493
494 if (*p)
495 {
496 int i;
497 for (i = 0; i < (*p)->num_elements; i++)
498 {
499 Z_External *ext = (*p)->list[i]->information.externallyDefinedInfo;
500 if ((*p)->list[i]->which == Z_OtherInfo_externallyDefinedInfo
501 && ext &&
502 ext->which == Z_External_charSetandLanguageNegotiation)
503 return;
504 }
505 }
506 if ((oi = yaz_oi_update(p, odr, 0, 0, 0)))
507 {
508 ODR_MASK_SET(req->options, Z_Options_negotiationModel);
509 oi->which = Z_OtherInfo_externallyDefinedInfo;
510 oi->information.externallyDefinedInfo =
511 yaz_set_proposal_charneg_list(odr, ",",
512 charset,
513 0 /* lang */,
514 1 /* records included */);
515 }
516}
517
518void yf::Z3950Client::Rep::send_and_receive(Package &package,
519 yf::Z3950Client::Assoc *c)
520{
521 if (c->m_destroyed)
522 return;
523
524 c->m_package = &package;
525
526 if (package.session().is_closed() && c->m_connected && !c->m_has_closed
527 && m_force_close)
528 {
529 mp::odr odr;
530
531 package.request() = odr.create_close(
532 0, Z_Close_finished, "z3950_client");
533 c->m_package = 0; // don't inspect response
534 }
535 Z_GDU *gdu = package.request().get();
536
537 if (!gdu || gdu->which != Z_GDU_Z3950)
538 return;
539
540 if (gdu->u.z3950->which == Z_APDU_close)
541 c->m_has_closed = true;
542
543 Z_APDU *apdu = gdu->u.z3950;
544
545 // prepare connect
546 c->m_time_elapsed = 0;
547 c->m_waiting = true;
548 if (!c->m_connected)
549 {
550 std::string host(c->m_host);
551
552 if (m_bind_host)
553 {
554 std::string bind_host = package.origin().get_bind_address();
555 if (bind_host.length())
556 {
557 host.append(" ");
558 host.append(bind_host);
559 }
560 }
561 if (c->client(host.c_str()))
562 {
563 mp::odr odr;
564 package.response() =
565 odr.create_close(gdu->u.z3950, Z_Close_peerAbort, 0);
566 package.session().close();
567 return;
568 }
569 c->timeout(1); // so timeoutNotify gets called once per second
570
571
572 while (!c->m_destroyed && c->m_waiting
573 && c->m_socket_manager->processEvent() > 0)
574 ;
575 }
576 if (!c->m_connected)
577 {
578 return;
579 }
580 mp::odr odr;
581 if (m_client_ip)
582 {
583 std::string peer_name2 = package.origin().get_address();
584 if (apdu->which == Z_APDU_initRequest && peer_name2.length())
585 {
586 Z_OtherInformation **oi = &apdu->u.initRequest->otherInfo;
587 char *peer_name1 =
588 yaz_oi_get_string_oid(oi, yaz_oid_userinfo_client_ip, 1, 1);
589 std::string pcomb;
590 if (peer_name1)
591 {
592 pcomb.append(peer_name1);
593 pcomb.append(", ");
594 }
595 pcomb.append(peer_name2);
596 yaz_oi_set_string_oid(&apdu->u.initRequest->otherInfo,
597 odr, yaz_oid_userinfo_client_ip,
598 1, pcomb.c_str());
599 }
600 }
601 if (apdu->which == Z_APDU_initRequest && m_charset.length() > 0)
602 set_charset_proposal(odr, apdu->u.initRequest, m_charset.c_str());
603
604 // prepare response
605 c->m_time_elapsed = 0;
606 c->m_waiting = true;
607
608 // relay the package ..
609 int len;
610 c->send_GDU(gdu, &len);
611
612 switch (gdu->u.z3950->which)
613 {
614 case Z_APDU_triggerResourceControlRequest:
615 // request only..
616 break;
617 default:
618 // for the rest: wait for a response PDU
619 while (!c->m_destroyed && c->m_waiting
620 && c->m_socket_manager->processEvent() > 0)
621 ;
622 break;
623 }
624}
625
626void yf::Z3950Client::Rep::release_assoc(Package &package)
627{
628 boost::mutex::scoped_lock lock(m_mutex);
629 std::map<mp::Session,yf::Z3950Client::Assoc *>::iterator it;
630
631 it = m_clients.find(package.session());
632 if (it != m_clients.end())
633 {
634 it->second->m_in_use = false;
635 it->second->m_queue_len--;
636
637 if (package.session().is_closed())
638 {
639 // destroy hint (send_and_receive)
640 it->second->m_destroyed = true;
641 if (it->second->m_queue_len == 0)
642 {
643 yazpp_1::SocketManager *s = it->second->m_socket_manager;
644 delete it->second; // destroy Z_Assoc
645 delete s; // then manager
646 m_clients.erase(it);
647 }
648 }
649 m_cond_session_ready.notify_all();
650 }
651}
652
653void yf::Z3950Client::process(Package &package) const
654{
655 yf::Z3950Client::Assoc *c = m_p->get_assoc(package);
656 if (c)
657 {
658 m_p->send_and_receive(package, c);
659 m_p->release_assoc(package);
660 }
661}
662
663void yf::Z3950Client::configure(const xmlNode *ptr, bool test_only,
664 const char *path)
665{
666 for (ptr = ptr->children; ptr; ptr = ptr->next)
667 {
668 if (ptr->type != XML_ELEMENT_NODE)
669 continue;
670 if (!strcmp((const char *) ptr->name, "timeout"))
671 {
672 m_p->m_general_timeout_sec = mp::xml::get_int(ptr, 30);
673 }
674 else if (!strcmp((const char *) ptr->name, "connect-timeout"))
675 {
676 m_p->m_connect_timeout_sec = mp::xml::get_int(ptr, 10);
677 }
678 else if (!strcmp((const char *) ptr->name, "init-timeout"))
679 {
680 m_p->m_init_timeout_sec = mp::xml::get_int(ptr, 10);
681 }
682 else if (!strcmp((const char *) ptr->name, "max-sockets-timeout"))
683 {
684 m_p->m_max_sockets_timeout_sec = mp::xml::get_int(ptr, 15);
685 }
686 else if (!strcmp((const char *) ptr->name, "default_target"))
687 {
688 m_p->m_default_target = mp::xml::get_text(ptr);
689 }
690 else if (!strcmp((const char *) ptr->name, "force_target"))
691 {
692 m_p->m_force_target = mp::xml::get_text(ptr);
693 }
694 else if (!strcmp((const char *) ptr->name, "max-sockets"))
695 {
696 m_p->m_max_sockets = mp::xml::get_int(ptr, 0);
697 }
698 else if (!strcmp((const char *) ptr->name, "force_close"))
699 {
700 m_p->m_force_close = mp::xml::get_bool(ptr, 0);
701 }
702 else if (!strcmp((const char *) ptr->name, "client_ip"))
703 {
704 m_p->m_client_ip = mp::xml::get_bool(ptr, 0);
705 }
706 else if (!strcmp((const char *) ptr->name, "charset"))
707 {
708 m_p->m_charset = mp::xml::get_text(ptr);
709 }
710 else if (!strcmp((const char *) ptr->name, "bind_host"))
711 {
712 m_p->m_bind_host = mp::xml::get_bool(ptr, 0);
713 }
714 else
715 {
716 throw mp::filter::FilterException("Bad element "
717 + std::string((const char *)
718 ptr->name));
719 }
720 }
721}
722
723static mp::filter::Base* filter_creator()
724{
725 return new mp::filter::Z3950Client;
726}
727
728extern "C" {
729 struct metaproxy_1_filter_struct metaproxy_1_filter_z3950_client = {
730 0,
731 "z3950_client",
733 };
734}
735
736/*
737 * Local variables:
738 * c-basic-offset: 4
739 * c-file-style: "Stroustrup"
740 * indent-tabs-mode: nil
741 * End:
742 * vim: shiftwidth=4 tabstop=8 expandtab
743 */
744
void fixup_nsd(ODR odr, Z_Records *records)
void fixup_init(ODR odr, Z_InitResponse *initrs)
yazpp_1::IPDU_Observer * sessionNotify(yazpp_1::IPDU_Observable *the_PDU_Observable, int fd)
void send_and_receive(Package &package, yf::Z3950Client::Assoc *c)
std::map< mp::Session, Z3950Client::Assoc * > m_clients
Z3950Client::Assoc * get_assoc(Package &package)
static mp::filter::Base * filter_creator()
struct metaproxy_1_filter_struct metaproxy_1_filter_z3950_client
static void set_charset_proposal(ODR odr, Z_InitRequest *req, const char *charset)