Updated footer comment
[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             int m_time_connect_max;
74             std::string m_host;
75         };
76
77         class Z3950Client::Rep {
78         public:
79             // number of seconds to wait before we give up request
80             int m_timeout_sec;
81             int m_max_sockets;
82             std::string m_default_target;
83             std::string m_force_target;
84             boost::mutex m_mutex;
85             boost::condition m_cond_session_ready;
86             std::map<mp::Session,Z3950Client::Assoc *> m_clients;
87             Z3950Client::Assoc *get_assoc(Package &package);
88             void send_and_receive(Package &package,
89                                   yf::Z3950Client::Assoc *c);
90             void release_assoc(Package &package);
91         };
92     }
93 }
94
95 using namespace mp;
96
97 yf::Z3950Client::Assoc::Assoc(yazpp_1::SocketManager *socket_manager,
98                               yazpp_1::IPDU_Observable *PDU_Observable,
99                               std::string host, int timeout_sec)
100     :  Z_Assoc(PDU_Observable),
101        m_socket_manager(socket_manager), m_PDU_Observable(PDU_Observable),
102        m_package(0), m_in_use(true), m_waiting(false), 
103        m_destroyed(false), m_connected(false), m_queue_len(1),
104        m_time_elapsed(0), m_time_max(timeout_sec),  m_time_connect_max(10),
105        m_host(host)
106 {
107     // std::cout << "create assoc " << this << "\n";
108 }
109
110 yf::Z3950Client::Assoc::~Assoc()
111 {
112     // std::cout << "destroy assoc " << this << "\n";
113 }
114
115 void yf::Z3950Client::Assoc::connectNotify()
116 {
117     m_waiting = false;
118
119     m_connected = true;
120 }
121
122 void yf::Z3950Client::Assoc::failNotify()
123 {
124     m_waiting = false;
125
126     mp::odr odr;
127
128     if (m_package)
129     {
130         Z_GDU *gdu = m_package->request().get();
131         Z_APDU *apdu = 0;
132         if (gdu && gdu->which == Z_GDU_Z3950)
133             apdu = gdu->u.z3950;
134         
135         m_package->response() = odr.create_close(apdu, Z_Close_peerAbort, 0);
136         m_package->session().close();
137     }
138 }
139
140 void yf::Z3950Client::Assoc::timeoutNotify()
141 {
142     m_time_elapsed++;
143     if ((m_connected && m_time_elapsed >= m_time_max)
144         || (!m_connected && m_time_elapsed >= m_time_connect_max))
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             if (m_connected)
158                 m_package->response() =
159                     odr.create_close(apdu, Z_Close_lackOfActivity, 0);
160             else
161                 m_package->response() = 
162                     odr.create_close(apdu, Z_Close_peerAbort, 0);
163                 
164             m_package->session().close();
165         }
166     }
167 }
168
169 void yf::Z3950Client::Assoc::recv_GDU(Z_GDU *gdu, int len)
170 {
171     m_waiting = false;
172
173     if (m_package)
174         m_package->response() = gdu;
175 }
176
177 yazpp_1::IPDU_Observer *yf::Z3950Client::Assoc::sessionNotify(
178     yazpp_1::IPDU_Observable *the_PDU_Observable,
179     int fd)
180 {
181     return 0;
182 }
183
184
185 yf::Z3950Client::Z3950Client() :  m_p(new yf::Z3950Client::Rep)
186 {
187     m_p->m_timeout_sec = 30;
188     m_p->m_max_sockets = 0;
189 }
190
191 yf::Z3950Client::~Z3950Client() {
192 }
193
194 yf::Z3950Client::Assoc *yf::Z3950Client::Rep::get_assoc(Package &package) 
195 {
196     // only one thread messes with the clients list at a time
197     boost::mutex::scoped_lock lock(m_mutex);
198
199     std::map<mp::Session,yf::Z3950Client::Assoc *>::iterator it;
200     
201     Z_GDU *gdu = package.request().get();
202     // only deal with Z39.50
203     if (!gdu || gdu->which != Z_GDU_Z3950)
204     {
205         package.move();
206         return 0;
207     }
208     
209     int max_sockets = package.origin().get_max_sockets();
210     if (max_sockets == 0)
211         max_sockets = m_max_sockets;
212     
213     std::string host;
214
215     it = m_clients.find(package.session());
216     if (it != m_clients.end())
217     {
218         it->second->m_queue_len++;
219         while (true)
220         {
221 #if 0
222             // double init .. NOT working yet
223             if (gdu && gdu->which == Z_GDU_Z3950 &&
224                 gdu->u.z3950->which == Z_APDU_initRequest)
225             {
226                 yazpp_1::SocketManager *s = it->second->m_socket_manager;
227                 delete it->second;  // destroy Z_Assoc
228                 delete s;    // then manager
229                 m_clients.erase(it);
230                 break;
231             }
232 #endif
233             if (!it->second->m_in_use)
234             {
235                 it->second->m_in_use = true;
236                 return it->second;
237             }
238             m_cond_session_ready.wait(lock);
239         }
240     }
241     // new Z39.50 session ..
242     Z_APDU *apdu = gdu->u.z3950;
243     // check that it is init. If not, close
244     if (apdu->which != Z_APDU_initRequest)
245     {
246         mp::odr odr;
247         
248         package.response() = odr.create_close(apdu,
249                                               Z_Close_protocolError,
250                                               "First PDU was not an "
251                                               "Initialize Request");
252         package.session().close();
253         return 0;
254     }
255     std::string target = m_force_target;
256     if (!target.length())
257     {
258         target = m_default_target;
259         std::list<std::string> vhosts;
260         mp::util::remove_vhost_otherinfo(&apdu->u.initRequest->otherInfo,
261                                              vhosts);
262         size_t no_vhosts = vhosts.size();
263         if (no_vhosts == 1)
264         {
265             std::list<std::string>::const_iterator v_it = vhosts.begin();
266             target = *v_it;
267         }
268         else if (no_vhosts == 0)
269         {
270             if (!target.length())
271             {
272                 // no default target. So we don't know where to connect
273                 mp::odr odr;
274                 package.response() = odr.create_initResponse(
275                     apdu,
276                     YAZ_BIB1_INIT_NEGOTIATION_OPTION_REQUIRED,
277                     "z3950_client: No virtal host given");
278                 
279                 package.session().close();
280                 return 0;
281             }
282         }
283         else if (no_vhosts > 1)
284         {
285             mp::odr odr;
286             package.response() = odr.create_initResponse(
287                 apdu,
288                 YAZ_BIB1_COMBI_OF_SPECIFIED_DATABASES_UNSUPP,
289                 "z3950_client: Can not cope with multiple vhosts");
290             package.session().close();
291             return 0;
292         }
293     }
294     
295     std::list<std::string> dblist;
296     mp::util::split_zurl(target, host, dblist);
297     
298     if (dblist.size())
299     {
300         ; // z3950_client: Databases in vhost ignored
301     }
302     
303     // see if we have reached max number of clients (max-sockets)
304
305     while (max_sockets)
306     {
307         int number = 0;
308         it = m_clients.begin();
309         for (; it != m_clients.end(); it++)
310         {
311             yf::Z3950Client::Assoc *as = it->second;
312             if (!strcmp(as->get_hostname(), host.c_str()))
313                 number++;
314         }
315         yaz_log(YLOG_LOG, "Found %d connections for %s", number, host.c_str());
316         if (number < max_sockets)
317             break;
318         boost::xtime xt;
319         xtime_get(&xt, boost::TIME_UTC);
320         
321         xt.sec += 15;
322         if (!m_cond_session_ready.timed_wait(lock, xt))
323         {
324             mp::odr odr;
325             
326             package.response() = odr.create_initResponse(
327                 apdu, YAZ_BIB1_TEMPORARY_SYSTEM_ERROR, "max sessions");
328             package.session().close();
329             return 0;
330         }
331     }
332
333     yazpp_1::SocketManager *sm = new yazpp_1::SocketManager;
334     yazpp_1::PDU_Assoc *pdu_as = new yazpp_1::PDU_Assoc(sm);
335     yf::Z3950Client::Assoc *as = new yf::Z3950Client::Assoc(sm, pdu_as,
336                                                             host.c_str(),
337                                                             m_timeout_sec);
338     m_clients[package.session()] = as;
339     return as;
340 }
341
342 void yf::Z3950Client::Rep::send_and_receive(Package &package,
343                                             yf::Z3950Client::Assoc *c)
344 {
345     Z_GDU *gdu = package.request().get();
346
347     if (c->m_destroyed)
348         return;
349
350     if (!gdu || gdu->which != Z_GDU_Z3950)
351         return;
352
353     c->m_time_elapsed = 0;
354     c->m_package = &package;
355     c->m_waiting = true;
356     if (!c->m_connected)
357     {
358         c->client(c->m_host.c_str());
359         c->timeout(1);  // so timeoutNotify gets called once per second
360
361         while (!c->m_destroyed && c->m_waiting 
362                && c->m_socket_manager->processEvent() > 0)
363             ;
364     }
365     if (!c->m_connected)
366     {
367         return;
368     }
369
370     // prepare response
371     c->m_time_elapsed = 0;
372     c->m_waiting = true;
373     
374     // relay the package  ..
375     int len;
376     c->send_GDU(gdu, &len);
377
378     switch(gdu->u.z3950->which)
379     {
380     case Z_APDU_triggerResourceControlRequest:
381         // request only..
382         break;
383     default:
384         // for the rest: wait for a response PDU
385         while (!c->m_destroyed && c->m_waiting
386                && c->m_socket_manager->processEvent() > 0)
387             ;
388         break;
389     }
390 }
391
392 void yf::Z3950Client::Rep::release_assoc(Package &package)
393 {
394     boost::mutex::scoped_lock lock(m_mutex);
395     std::map<mp::Session,yf::Z3950Client::Assoc *>::iterator it;
396     
397     it = m_clients.find(package.session());
398     if (it != m_clients.end())
399     {
400         Z_GDU *gdu = package.request().get();
401         if (gdu && gdu->which == Z_GDU_Z3950)
402         {   // only Z39.50 packages lock in get_assoc.. release it
403             it->second->m_in_use = false;
404             it->second->m_queue_len--;
405         }
406
407         if (package.session().is_closed())
408         {
409             // destroy hint (send_and_receive)
410             it->second->m_destroyed = true;
411             if (it->second->m_queue_len == 0)
412             {
413                 yazpp_1::SocketManager *s = it->second->m_socket_manager;
414                 delete it->second;  // destroy Z_Assoc
415                 delete s;    // then manager
416                 m_clients.erase(it);
417             }
418         }
419         m_cond_session_ready.notify_all();
420     }
421 }
422
423 void yf::Z3950Client::process(Package &package) const
424 {
425     yf::Z3950Client::Assoc *c = m_p->get_assoc(package);
426     if (c)
427     {
428         m_p->send_and_receive(package, c);
429     }
430     m_p->release_assoc(package);
431 }
432
433 void yf::Z3950Client::configure(const xmlNode *ptr, bool test_only)
434 {
435     for (ptr = ptr->children; ptr; ptr = ptr->next)
436     {
437         if (ptr->type != XML_ELEMENT_NODE)
438             continue;
439         if (!strcmp((const char *) ptr->name, "timeout"))
440         {
441             m_p->m_timeout_sec = mp::xml::get_int(ptr->children, 30);
442         }
443         else if (!strcmp((const char *) ptr->name, "default_target"))
444         {
445             m_p->m_default_target = mp::xml::get_text(ptr);
446         }
447         else if (!strcmp((const char *) ptr->name, "force_target"))
448         {
449             m_p->m_force_target = mp::xml::get_text(ptr);
450         }
451         else if (!strcmp((const char *) ptr->name, "max-sockets"))
452         {
453             m_p->m_max_sockets = mp::xml::get_int(ptr->children, 0);
454         }
455         else
456         {
457             throw mp::filter::FilterException("Bad element " 
458                                                + std::string((const char *)
459                                                              ptr->name));
460         }
461     }
462 }
463
464 static mp::filter::Base* filter_creator()
465 {
466     return new mp::filter::Z3950Client;
467 }
468
469 extern "C" {
470     struct metaproxy_1_filter_struct metaproxy_1_filter_z3950_client = {
471         0,
472         "z3950_client",
473         filter_creator
474     };
475 }
476
477 /*
478  * Local variables:
479  * c-basic-offset: 4
480  * c-file-style: "Stroustrup"
481  * indent-tabs-mode: nil
482  * End:
483  * vim: shiftwidth=4 tabstop=8 expandtab
484  */
485