Fixed bug #2229:crash in Z39.50 client module
[metaproxy-moved-to-github.git] / src / filter_z3950_client.cpp
1 /* This file is part of Metaproxy.
2    Copyright (C) 2005-2008 Index Data
3
4 Metaproxy is free software; you can redistribute it and/or modify it under
5 the terms of the GNU General Public License as published by the Free
6 Software Foundation; either version 2, or (at your option) any later
7 version.
8
9 Metaproxy is distributed in the hope that it will be useful, but WITHOUT ANY
10 WARRANTY; without even the implied warranty of MERCHANTABILITY or
11 FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
12 for more details.
13
14 You should have received a copy of the GNU General Public License
15 along with this program; if not, write to the Free Software
16 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
17 */
18
19 #include "config.hpp"
20
21 #include "filter.hpp"
22 #include "package.hpp"
23 #include "util.hpp"
24 #include "filter_z3950_client.hpp"
25
26 #include <map>
27 #include <stdexcept>
28 #include <list>
29 #include <iostream>
30
31 #include <boost/thread/mutex.hpp>
32 #include <boost/thread/condition.hpp>
33 #include <boost/thread/xtime.hpp>
34
35 #include <yaz/zgdu.h>
36 #include <yaz/log.h>
37 #include <yaz/otherinfo.h>
38 #include <yaz/diagbib1.h>
39
40 #include <yazpp/socket-manager.h>
41 #include <yazpp/pdu-assoc.h>
42 #include <yazpp/z-assoc.h>
43
44 namespace mp = metaproxy_1;
45 namespace yf = mp::filter;
46
47 namespace metaproxy_1 {
48     namespace filter {
49         class Z3950Client::Assoc : public yazpp_1::Z_Assoc{
50             friend class Rep;
51             Assoc(yazpp_1::SocketManager *socket_manager,
52                   yazpp_1::IPDU_Observable *PDU_Observable,
53                   std::string host, int timeout);
54             ~Assoc();
55             void connectNotify();
56             void failNotify();
57             void timeoutNotify();
58             void recv_GDU(Z_GDU *gdu, int len);
59             yazpp_1::IPDU_Observer* sessionNotify(
60                 yazpp_1::IPDU_Observable *the_PDU_Observable,
61                 int fd);
62
63             yazpp_1::SocketManager *m_socket_manager;
64             yazpp_1::IPDU_Observable *m_PDU_Observable;
65             Package *m_package;
66             bool m_in_use;
67             bool m_waiting;
68             bool m_destroyed;
69             bool m_connected;
70             int m_queue_len;
71             int m_time_elapsed;
72             int m_time_max;
73             std::string m_host;
74         };
75
76         class Z3950Client::Rep {
77         public:
78             // number of seconds to wait before we give up request
79             int m_timeout_sec;
80             int m_max_sockets;
81             std::string m_default_target;
82             std::string m_force_target;
83             boost::mutex m_mutex;
84             boost::condition m_cond_session_ready;
85             std::map<mp::Session,Z3950Client::Assoc *> m_clients;
86             Z3950Client::Assoc *get_assoc(Package &package);
87             void send_and_receive(Package &package,
88                                   yf::Z3950Client::Assoc *c);
89             void release_assoc(Package &package);
90         };
91     }
92 }
93
94 using namespace mp;
95
96 yf::Z3950Client::Assoc::Assoc(yazpp_1::SocketManager *socket_manager,
97                               yazpp_1::IPDU_Observable *PDU_Observable,
98                               std::string host, int timeout_sec)
99     :  Z_Assoc(PDU_Observable),
100        m_socket_manager(socket_manager), m_PDU_Observable(PDU_Observable),
101        m_package(0), m_in_use(true), m_waiting(false), 
102        m_destroyed(false), m_connected(false), m_queue_len(1),
103        m_time_elapsed(0), m_time_max(timeout_sec), 
104        m_host(host)
105 {
106     // std::cout << "create assoc " << this << "\n";
107 }
108
109 yf::Z3950Client::Assoc::~Assoc()
110 {
111     // std::cout << "destroy assoc " << this << "\n";
112 }
113
114 void yf::Z3950Client::Assoc::connectNotify()
115 {
116     m_waiting = false;
117
118     m_connected = true;
119 }
120
121 void yf::Z3950Client::Assoc::failNotify()
122 {
123     m_waiting = false;
124
125     mp::odr odr;
126
127     if (m_package)
128     {
129         Z_GDU *gdu = m_package->request().get();
130         Z_APDU *apdu = 0;
131         if (gdu && gdu->which == Z_GDU_Z3950)
132             apdu = gdu->u.z3950;
133         
134         m_package->response() = odr.create_close(apdu, Z_Close_peerAbort, 0);
135         m_package->session().close();
136     }
137 }
138
139 void yf::Z3950Client::Assoc::timeoutNotify()
140 {
141     m_time_elapsed++;
142     if (m_time_elapsed >= m_time_max)
143     {
144         m_waiting = false;
145
146         mp::odr odr;
147         
148         if (m_package)
149         {
150             Z_GDU *gdu = m_package->request().get();
151             Z_APDU *apdu = 0;
152             if (gdu && gdu->which == Z_GDU_Z3950)
153                 apdu = gdu->u.z3950;
154         
155             if (m_connected)
156                 m_package->response() =
157                     odr.create_close(apdu, Z_Close_lackOfActivity, 0);
158             else
159                 m_package->response() = 
160                     odr.create_close(apdu, Z_Close_peerAbort, 0);
161                 
162             m_package->session().close();
163         }
164     }
165 }
166
167 void yf::Z3950Client::Assoc::recv_GDU(Z_GDU *gdu, int len)
168 {
169     m_waiting = false;
170
171     if (m_package)
172         m_package->response() = gdu;
173 }
174
175 yazpp_1::IPDU_Observer *yf::Z3950Client::Assoc::sessionNotify(
176     yazpp_1::IPDU_Observable *the_PDU_Observable,
177     int fd)
178 {
179     return 0;
180 }
181
182
183 yf::Z3950Client::Z3950Client() :  m_p(new yf::Z3950Client::Rep)
184 {
185     m_p->m_timeout_sec = 30;
186     m_p->m_max_sockets = 0;
187 }
188
189 yf::Z3950Client::~Z3950Client() {
190 }
191
192 yf::Z3950Client::Assoc *yf::Z3950Client::Rep::get_assoc(Package &package) 
193 {
194     // only one thread messes with the clients list at a time
195     boost::mutex::scoped_lock lock(m_mutex);
196
197     std::map<mp::Session,yf::Z3950Client::Assoc *>::iterator it;
198     
199     Z_GDU *gdu = package.request().get();
200     // only deal with Z39.50
201     if (!gdu || gdu->which != Z_GDU_Z3950)
202     {
203         package.move();
204         return 0;
205     }
206     
207     int max_sockets = package.origin().get_max_sockets();
208     if (max_sockets == 0)
209         max_sockets = m_max_sockets;
210     
211     std::string host;
212
213     it = m_clients.find(package.session());
214     if (it != m_clients.end())
215     {
216         it->second->m_queue_len++;
217         while (true)
218         {
219 #if 0
220             // double init .. NOT working yet
221             if (gdu && gdu->which == Z_GDU_Z3950 &&
222                 gdu->u.z3950->which == Z_APDU_initRequest)
223             {
224                 yazpp_1::SocketManager *s = it->second->m_socket_manager;
225                 delete it->second;  // destroy Z_Assoc
226                 delete s;    // then manager
227                 m_clients.erase(it);
228                 break;
229             }
230 #endif
231             if (!it->second->m_in_use)
232             {
233                 it->second->m_in_use = true;
234                 return it->second;
235             }
236             m_cond_session_ready.wait(lock);
237         }
238     }
239     // new Z39.50 session ..
240     Z_APDU *apdu = gdu->u.z3950;
241     // check that it is init. If not, close
242     if (apdu->which != Z_APDU_initRequest)
243     {
244         mp::odr odr;
245         
246         package.response() = odr.create_close(apdu,
247                                               Z_Close_protocolError,
248                                               "First PDU was not an "
249                                               "Initialize Request");
250         package.session().close();
251         return 0;
252     }
253     std::string target = m_force_target;
254     if (!target.length())
255     {
256         target = m_default_target;
257         std::list<std::string> vhosts;
258         mp::util::remove_vhost_otherinfo(&apdu->u.initRequest->otherInfo,
259                                              vhosts);
260         size_t no_vhosts = vhosts.size();
261         if (no_vhosts == 1)
262         {
263             std::list<std::string>::const_iterator v_it = vhosts.begin();
264             target = *v_it;
265         }
266         else if (no_vhosts == 0)
267         {
268             if (!target.length())
269             {
270                 // no default target. So we don't know where to connect
271                 mp::odr odr;
272                 package.response() = odr.create_initResponse(
273                     apdu,
274                     YAZ_BIB1_INIT_NEGOTIATION_OPTION_REQUIRED,
275                     "z3950_client: No virtal host given");
276                 
277                 package.session().close();
278                 return 0;
279             }
280         }
281         else if (no_vhosts > 1)
282         {
283             mp::odr odr;
284             package.response() = odr.create_initResponse(
285                 apdu,
286                 YAZ_BIB1_COMBI_OF_SPECIFIED_DATABASES_UNSUPP,
287                 "z3950_client: Can not cope with multiple vhosts");
288             package.session().close();
289             return 0;
290         }
291     }
292     
293     std::list<std::string> dblist;
294     mp::util::split_zurl(target, host, dblist);
295     
296     if (dblist.size())
297     {
298         ; // z3950_client: Databases in vhost ignored
299     }
300     
301     // see if we have reached max number of clients (max-sockets)
302
303     while (max_sockets)
304     {
305         int number = 0;
306         it = m_clients.begin();
307         for (; it != m_clients.end(); it++)
308         {
309             yf::Z3950Client::Assoc *as = it->second;
310             if (!strcmp(as->get_hostname(), host.c_str()))
311                 number++;
312         }
313         yaz_log(YLOG_LOG, "Found %d connections for %s", number, host.c_str());
314         if (number < max_sockets)
315             break;
316         boost::xtime xt;
317         xtime_get(&xt, boost::TIME_UTC);
318         
319         xt.sec += 15;
320         if (!m_cond_session_ready.timed_wait(lock, xt))
321         {
322             mp::odr odr;
323             
324             package.response() = odr.create_initResponse(
325                 apdu, YAZ_BIB1_TEMPORARY_SYSTEM_ERROR, "max sessions");
326             package.session().close();
327             return 0;
328         }
329     }
330
331     yazpp_1::SocketManager *sm = new yazpp_1::SocketManager;
332     yazpp_1::PDU_Assoc *pdu_as = new yazpp_1::PDU_Assoc(sm);
333     yf::Z3950Client::Assoc *as = new yf::Z3950Client::Assoc(sm, pdu_as,
334                                                             host.c_str(),
335                                                             m_timeout_sec);
336     m_clients[package.session()] = as;
337     return as;
338 }
339
340 void yf::Z3950Client::Rep::send_and_receive(Package &package,
341                                             yf::Z3950Client::Assoc *c)
342 {
343     Z_GDU *gdu = package.request().get();
344
345     if (c->m_destroyed)
346         return;
347
348     if (!gdu || gdu->which != Z_GDU_Z3950)
349         return;
350
351     c->m_time_elapsed = 0;
352     c->m_package = &package;
353     c->m_waiting = true;
354     if (!c->m_connected)
355     {
356         c->client(c->m_host.c_str());
357         c->timeout(1);  // so timeoutNotify gets called once per second
358
359         while (!c->m_destroyed && c->m_waiting 
360                && c->m_socket_manager->processEvent() > 0)
361             ;
362     }
363     if (!c->m_connected)
364     {
365         return;
366     }
367
368     // prepare response
369     c->m_time_elapsed = 0;
370     c->m_waiting = true;
371     
372     // relay the package  ..
373     int len;
374     c->send_GDU(gdu, &len);
375
376     switch(gdu->u.z3950->which)
377     {
378     case Z_APDU_triggerResourceControlRequest:
379         // request only..
380         break;
381     default:
382         // for the rest: wait for a response PDU
383         while (!c->m_destroyed && c->m_waiting
384                && c->m_socket_manager->processEvent() > 0)
385             ;
386         break;
387     }
388 }
389
390 void yf::Z3950Client::Rep::release_assoc(Package &package)
391 {
392     boost::mutex::scoped_lock lock(m_mutex);
393     std::map<mp::Session,yf::Z3950Client::Assoc *>::iterator it;
394     
395     it = m_clients.find(package.session());
396     if (it != m_clients.end())
397     {
398         Z_GDU *gdu = package.request().get();
399         if (gdu && gdu->which == Z_GDU_Z3950)
400         {   // only Z39.50 packages lock in get_assoc.. release it
401             it->second->m_in_use = false;
402             it->second->m_queue_len--;
403         }
404
405         if (package.session().is_closed())
406         {
407             // destroy hint (send_and_receive)
408             it->second->m_destroyed = true;
409             if (it->second->m_queue_len == 0)
410             {
411                 yazpp_1::SocketManager *s = it->second->m_socket_manager;
412                 delete it->second;  // destroy Z_Assoc
413                 delete s;    // then manager
414                 m_clients.erase(it);
415             }
416         }
417         yaz_log(YLOG_LOG, "Notify all release_assoc");
418         m_cond_session_ready.notify_all();
419     }
420 }
421
422 void yf::Z3950Client::process(Package &package) const
423 {
424     yf::Z3950Client::Assoc *c = m_p->get_assoc(package);
425     if (c)
426     {
427         m_p->send_and_receive(package, c);
428     }
429     m_p->release_assoc(package);
430 }
431
432 void yf::Z3950Client::configure(const xmlNode *ptr, bool test_only)
433 {
434     for (ptr = ptr->children; ptr; ptr = ptr->next)
435     {
436         if (ptr->type != XML_ELEMENT_NODE)
437             continue;
438         if (!strcmp((const char *) ptr->name, "timeout"))
439         {
440             m_p->m_timeout_sec = mp::xml::get_int(ptr->children, 30);
441         }
442         else if (!strcmp((const char *) ptr->name, "default_target"))
443         {
444             m_p->m_default_target = mp::xml::get_text(ptr);
445         }
446         else if (!strcmp((const char *) ptr->name, "force_target"))
447         {
448             m_p->m_force_target = mp::xml::get_text(ptr);
449         }
450         else if (!strcmp((const char *) ptr->name, "max-sockets"))
451         {
452             m_p->m_max_sockets = mp::xml::get_int(ptr->children, 0);
453         }
454         else
455         {
456             throw mp::filter::FilterException("Bad element " 
457                                                + std::string((const char *)
458                                                              ptr->name));
459         }
460     }
461 }
462
463 static mp::filter::Base* filter_creator()
464 {
465     return new mp::filter::Z3950Client;
466 }
467
468 extern "C" {
469     struct metaproxy_1_filter_struct metaproxy_1_filter_z3950_client = {
470         0,
471         "z3950_client",
472         filter_creator
473     };
474 }
475
476 /*
477  * Local variables:
478  * c-basic-offset: 4
479  * indent-tabs-mode: nil
480  * c-file-style: "stroustrup"
481  * End:
482  * vim: shiftwidth=4 tabstop=8 expandtab
483  */