Happy new year
[metaproxy-moved-to-github.git] / src / filter_z3950_client.cpp
1 /* This file is part of Metaproxy.
2    Copyright (C) 2005-2011 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_z3950_client.hpp"
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
39 #include <yazpp/socket-manager.h>
40 #include <yazpp/pdu-assoc.h>
41 #include <yazpp/z-assoc.h>
42
43 namespace mp = metaproxy_1;
44 namespace yf = mp::filter;
45
46 namespace metaproxy_1 {
47     namespace filter {
48         class Z3950Client::Assoc : public yazpp_1::Z_Assoc{
49             friend class Rep;
50             Assoc(yazpp_1::SocketManager *socket_manager,
51                   yazpp_1::IPDU_Observable *PDU_Observable,
52                   std::string host, int timeout);
53             ~Assoc();
54             void connectNotify();
55             void failNotify();
56             void timeoutNotify();
57             void recv_GDU(Z_GDU *gdu, int len);
58             yazpp_1::IPDU_Observer* sessionNotify(
59                 yazpp_1::IPDU_Observable *the_PDU_Observable,
60                 int fd);
61
62             yazpp_1::SocketManager *m_socket_manager;
63             yazpp_1::IPDU_Observable *m_PDU_Observable;
64             Package *m_package;
65             bool m_in_use;
66             bool m_waiting;
67             bool m_destroyed;
68             bool m_connected;
69             int m_queue_len;
70             int m_time_elapsed;
71             int m_time_max;
72             int m_time_connect_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),  m_time_connect_max(10),
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_connected && m_time_elapsed >= m_time_max)
143         || (!m_connected && m_time_elapsed >= m_time_connect_max))
144     {
145         m_waiting = false;
146
147         mp::odr odr;
148         
149         if (m_package)
150         {
151             Z_GDU *gdu = m_package->request().get();
152             Z_APDU *apdu = 0;
153             if (gdu && gdu->which == Z_GDU_Z3950)
154                 apdu = gdu->u.z3950;
155         
156             if (m_connected)
157                 m_package->response() =
158                     odr.create_close(apdu, Z_Close_lackOfActivity, 0);
159             else
160                 m_package->response() = 
161                     odr.create_close(apdu, Z_Close_peerAbort, 0);
162                 
163             m_package->session().close();
164         }
165     }
166 }
167
168 void yf::Z3950Client::Assoc::recv_GDU(Z_GDU *gdu, int len)
169 {
170     m_waiting = false;
171
172     if (m_package)
173         m_package->response() = gdu;
174 }
175
176 yazpp_1::IPDU_Observer *yf::Z3950Client::Assoc::sessionNotify(
177     yazpp_1::IPDU_Observable *the_PDU_Observable,
178     int fd)
179 {
180     return 0;
181 }
182
183
184 yf::Z3950Client::Z3950Client() :  m_p(new yf::Z3950Client::Rep)
185 {
186     m_p->m_timeout_sec = 30;
187     m_p->m_max_sockets = 0;
188 }
189
190 yf::Z3950Client::~Z3950Client() {
191 }
192
193 yf::Z3950Client::Assoc *yf::Z3950Client::Rep::get_assoc(Package &package) 
194 {
195     // only one thread messes with the clients list at a time
196     boost::mutex::scoped_lock lock(m_mutex);
197
198     std::map<mp::Session,yf::Z3950Client::Assoc *>::iterator it;
199     
200     Z_GDU *gdu = package.request().get();
201     // only deal with Z39.50
202     if (!gdu || gdu->which != Z_GDU_Z3950)
203     {
204         package.move();
205         return 0;
206     }
207     
208     int max_sockets = package.origin().get_max_sockets();
209     if (max_sockets == 0)
210         max_sockets = m_max_sockets;
211     
212     std::string host;
213
214     it = m_clients.find(package.session());
215     if (it != m_clients.end())
216     {
217         it->second->m_queue_len++;
218         while (true)
219         {
220 #if 0
221             // double init .. NOT working yet
222             if (gdu && gdu->which == Z_GDU_Z3950 &&
223                 gdu->u.z3950->which == Z_APDU_initRequest)
224             {
225                 yazpp_1::SocketManager *s = it->second->m_socket_manager;
226                 delete it->second;  // destroy Z_Assoc
227                 delete s;    // then manager
228                 m_clients.erase(it);
229                 break;
230             }
231 #endif
232             if (!it->second->m_in_use)
233             {
234                 it->second->m_in_use = true;
235                 return it->second;
236             }
237             m_cond_session_ready.wait(lock);
238         }
239     }
240     // new Z39.50 session ..
241     Z_APDU *apdu = gdu->u.z3950;
242     // check that it is init. If not, close
243     if (apdu->which != Z_APDU_initRequest)
244     {
245         mp::odr odr;
246         
247         package.response() = odr.create_close(apdu,
248                                               Z_Close_protocolError,
249                                               "First PDU was not an "
250                                               "Initialize Request");
251         package.session().close();
252         return 0;
253     }
254     std::string target = m_force_target;
255     if (!target.length())
256     {
257         target = m_default_target;
258         std::list<std::string> vhosts;
259         mp::util::remove_vhost_otherinfo(&apdu->u.initRequest->otherInfo,
260                                              vhosts);
261         size_t no_vhosts = vhosts.size();
262         if (no_vhosts == 1)
263         {
264             std::list<std::string>::const_iterator v_it = vhosts.begin();
265             target = *v_it;
266         }
267         else if (no_vhosts == 0)
268         {
269             if (!target.length())
270             {
271                 // no default target. So we don't know where to connect
272                 mp::odr odr;
273                 package.response() = odr.create_initResponse(
274                     apdu,
275                     YAZ_BIB1_INIT_NEGOTIATION_OPTION_REQUIRED,
276                     "z3950_client: No vhost given");
277                 
278                 package.session().close();
279                 return 0;
280             }
281         }
282         else if (no_vhosts > 1)
283         {
284             mp::odr odr;
285             package.response() = odr.create_initResponse(
286                 apdu,
287                 YAZ_BIB1_COMBI_OF_SPECIFIED_DATABASES_UNSUPP,
288                 "z3950_client: Can not cope with multiple vhosts");
289             package.session().close();
290             return 0;
291         }
292     }
293     
294     std::list<std::string> dblist;
295     mp::util::split_zurl(target, host, dblist);
296     
297     if (dblist.size())
298     {
299         ; // z3950_client: Databases in vhost ignored
300     }
301     
302     // see if we have reached max number of clients (max-sockets)
303
304     while (max_sockets)
305     {
306         int no_not_in_use = 0;
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->m_host.c_str(), host.c_str()))
313             {
314                 number++;
315                 if (!as->m_in_use)
316                     no_not_in_use++;
317             }
318         }
319         yaz_log(YLOG_LOG, "Found %d/%d connections for %s", number, max_sockets,
320                 host.c_str());
321         if (number < max_sockets)
322             break;
323         if (no_not_in_use == 0) // all in use..
324         {
325             mp::odr odr;
326             
327             package.response() = odr.create_initResponse(
328                 apdu, YAZ_BIB1_TEMPORARY_SYSTEM_ERROR, "max sessions");
329             package.session().close();
330             return 0;
331         }
332         boost::xtime xt;
333         xtime_get(&xt, boost::TIME_UTC);
334         
335         xt.sec += 15;
336         if (!m_cond_session_ready.timed_wait(lock, xt))
337         {
338             mp::odr odr;
339             
340             package.response() = odr.create_initResponse(
341                 apdu, YAZ_BIB1_TEMPORARY_SYSTEM_ERROR, "max sessions");
342             package.session().close();
343             return 0;
344         }
345     }
346
347     yazpp_1::SocketManager *sm = new yazpp_1::SocketManager;
348     yazpp_1::PDU_Assoc *pdu_as = new yazpp_1::PDU_Assoc(sm);
349     yf::Z3950Client::Assoc *as = new yf::Z3950Client::Assoc(sm, pdu_as,
350                                                             host.c_str(),
351                                                             m_timeout_sec);
352     m_clients[package.session()] = as;
353     return as;
354 }
355
356 void yf::Z3950Client::Rep::send_and_receive(Package &package,
357                                             yf::Z3950Client::Assoc *c)
358 {
359     Z_GDU *gdu = package.request().get();
360
361     if (c->m_destroyed)
362         return;
363
364     if (!gdu || gdu->which != Z_GDU_Z3950)
365         return;
366
367     c->m_time_elapsed = 0;
368     c->m_package = &package;
369     c->m_waiting = true;
370     if (!c->m_connected)
371     {
372         c->client(c->m_host.c_str());
373         c->timeout(1);  // so timeoutNotify gets called once per second
374
375         while (!c->m_destroyed && c->m_waiting 
376                && c->m_socket_manager->processEvent() > 0)
377             ;
378     }
379     if (!c->m_connected)
380     {
381         return;
382     }
383
384     // prepare response
385     c->m_time_elapsed = 0;
386     c->m_waiting = true;
387     
388     // relay the package  ..
389     int len;
390     c->send_GDU(gdu, &len);
391
392     switch(gdu->u.z3950->which)
393     {
394     case Z_APDU_triggerResourceControlRequest:
395         // request only..
396         break;
397     default:
398         // for the rest: wait for a response PDU
399         while (!c->m_destroyed && c->m_waiting
400                && c->m_socket_manager->processEvent() > 0)
401             ;
402         break;
403     }
404 }
405
406 void yf::Z3950Client::Rep::release_assoc(Package &package)
407 {
408     boost::mutex::scoped_lock lock(m_mutex);
409     std::map<mp::Session,yf::Z3950Client::Assoc *>::iterator it;
410     
411     it = m_clients.find(package.session());
412     if (it != m_clients.end())
413     {
414         Z_GDU *gdu = package.request().get();
415         if (gdu && gdu->which == Z_GDU_Z3950)
416         {   // only Z39.50 packages lock in get_assoc.. release it
417             it->second->m_in_use = false;
418             it->second->m_queue_len--;
419         }
420
421         if (package.session().is_closed())
422         {
423             // destroy hint (send_and_receive)
424             it->second->m_destroyed = true;
425             if (it->second->m_queue_len == 0)
426             {
427                 yazpp_1::SocketManager *s = it->second->m_socket_manager;
428                 delete it->second;  // destroy Z_Assoc
429                 delete s;    // then manager
430                 m_clients.erase(it);
431             }
432         }
433         m_cond_session_ready.notify_all();
434     }
435 }
436
437 void yf::Z3950Client::process(Package &package) const
438 {
439     yf::Z3950Client::Assoc *c = m_p->get_assoc(package);
440     if (c)
441     {
442         m_p->send_and_receive(package, c);
443     }
444     m_p->release_assoc(package);
445 }
446
447 void yf::Z3950Client::configure(const xmlNode *ptr, bool test_only)
448 {
449     for (ptr = ptr->children; ptr; ptr = ptr->next)
450     {
451         if (ptr->type != XML_ELEMENT_NODE)
452             continue;
453         if (!strcmp((const char *) ptr->name, "timeout"))
454         {
455             m_p->m_timeout_sec = mp::xml::get_int(ptr->children, 30);
456         }
457         else if (!strcmp((const char *) ptr->name, "default_target"))
458         {
459             m_p->m_default_target = mp::xml::get_text(ptr);
460         }
461         else if (!strcmp((const char *) ptr->name, "force_target"))
462         {
463             m_p->m_force_target = mp::xml::get_text(ptr);
464         }
465         else if (!strcmp((const char *) ptr->name, "max-sockets"))
466         {
467             m_p->m_max_sockets = mp::xml::get_int(ptr->children, 0);
468         }
469         else
470         {
471             throw mp::filter::FilterException("Bad element " 
472                                                + std::string((const char *)
473                                                              ptr->name));
474         }
475     }
476 }
477
478 static mp::filter::Base* filter_creator()
479 {
480     return new mp::filter::Z3950Client;
481 }
482
483 extern "C" {
484     struct metaproxy_1_filter_struct metaproxy_1_filter_z3950_client = {
485         0,
486         "z3950_client",
487         filter_creator
488     };
489 }
490
491 /*
492  * Local variables:
493  * c-basic-offset: 4
494  * c-file-style: "Stroustrup"
495  * indent-tabs-mode: nil
496  * End:
497  * vim: shiftwidth=4 tabstop=8 expandtab
498  */
499