Allow timeout to be specified for filter z3950_client
[metaproxy-moved-to-github.git] / src / filter_z3950_client.cpp
1 /* $Id: filter_z3950_client.cpp,v 1.17 2006-01-09 18:19:09 adam Exp $
2    Copyright (c) 2005, Index Data.
3
4 %LICENSE%
5  */
6
7 #include "config.hpp"
8
9 #include "xmlutil.hpp"
10 #include "filter.hpp"
11 #include "router.hpp"
12 #include "package.hpp"
13 #include "util.hpp"
14 #include "filter_z3950_client.hpp"
15
16 #include <map>
17 #include <stdexcept>
18 #include <list>
19 #include <iostream>
20
21 #include <boost/thread/mutex.hpp>
22 #include <boost/thread/condition.hpp>
23
24 #include <yaz/zgdu.h>
25 #include <yaz/log.h>
26 #include <yaz/otherinfo.h>
27 #include <yaz/diagbib1.h>
28
29 #include <yaz++/socket-manager.h>
30 #include <yaz++/pdu-assoc.h>
31 #include <yaz++/z-assoc.h>
32
33 namespace yf = yp2::filter;
34
35 namespace yp2 {
36     namespace filter {
37         class Z3950Client::Assoc : public yazpp_1::Z_Assoc{
38             friend class Rep;
39             Assoc(yazpp_1::SocketManager *socket_manager,
40                   yazpp_1::IPDU_Observable *PDU_Observable,
41                   std::string host, int timeout);
42             ~Assoc();
43             void connectNotify();
44             void failNotify();
45             void timeoutNotify();
46             void recv_GDU(Z_GDU *gdu, int len);
47             yazpp_1::IPDU_Observer* sessionNotify(
48                 yazpp_1::IPDU_Observable *the_PDU_Observable,
49                 int fd);
50
51             yazpp_1::SocketManager *m_socket_manager;
52             yazpp_1::IPDU_Observable *m_PDU_Observable;
53             Package *m_package;
54             bool m_in_use;
55             bool m_waiting;
56             bool m_destroyed;
57             bool m_connected;
58             int m_queue_len;
59             int m_time_elapsed;
60             int m_time_max;
61             std::string m_host;
62         };
63
64         class Z3950Client::Rep {
65         public:
66             int m_timeout_sec;
67             boost::mutex m_mutex;
68             boost::condition m_cond_session_ready;
69             std::map<yp2::Session,Z3950Client::Assoc *> m_clients;
70             Z3950Client::Assoc *get_assoc(Package &package);
71             void send_and_receive(Package &package,
72                                   yf::Z3950Client::Assoc *c);
73             void release_assoc(Package &package);
74         };
75     }
76 }
77
78 using namespace yp2;
79
80 yf::Z3950Client::Assoc::Assoc(yazpp_1::SocketManager *socket_manager,
81                               yazpp_1::IPDU_Observable *PDU_Observable,
82                               std::string host, int timeout_sec)
83     :  Z_Assoc(PDU_Observable),
84        m_socket_manager(socket_manager), m_PDU_Observable(PDU_Observable),
85        m_package(0), m_in_use(true), m_waiting(false), 
86        m_destroyed(false), m_connected(false), m_queue_len(1),
87        m_time_elapsed(0), m_time_max(timeout_sec), 
88        m_host(host)
89 {
90     // std::cout << "create assoc " << this << "\n";
91 }
92
93 yf::Z3950Client::Assoc::~Assoc()
94 {
95     // std::cout << "destroy assoc " << this << "\n";
96 }
97
98 void yf::Z3950Client::Assoc::connectNotify()
99 {
100     m_waiting = false;
101
102     m_connected = true;
103 }
104
105 void yf::Z3950Client::Assoc::failNotify()
106 {
107     m_waiting = false;
108
109     yp2::odr odr;
110
111     if (m_package)
112     {
113         m_package->response() = odr.create_close(Z_Close_peerAbort, 0);
114         m_package->session().close();
115     }
116 }
117
118 void yf::Z3950Client::Assoc::timeoutNotify()
119 {
120     m_time_elapsed++;
121     if (m_time_elapsed >= m_time_max)
122     {
123         m_waiting = false;
124
125         yp2::odr odr;
126         
127         if (m_package)
128         {
129             if (m_connected)
130                 m_package->response() = odr.create_close(Z_Close_lackOfActivity, 0);
131             else
132                 m_package->response() = odr.create_close(Z_Close_peerAbort, 0);
133                 
134             m_package->session().close();
135         }
136     }
137 }
138
139 void yf::Z3950Client::Assoc::recv_GDU(Z_GDU *gdu, int len)
140 {
141     m_waiting = false;
142
143     if (m_package)
144         m_package->response() = gdu;
145 }
146
147 yazpp_1::IPDU_Observer *yf::Z3950Client::Assoc::sessionNotify(
148     yazpp_1::IPDU_Observable *the_PDU_Observable,
149     int fd)
150 {
151     return 0;
152 }
153
154
155 yf::Z3950Client::Z3950Client() :  m_p(new yf::Z3950Client::Rep)
156 {
157     m_p->m_timeout_sec = 30;
158 }
159
160 yf::Z3950Client::~Z3950Client() {
161 }
162
163 yf::Z3950Client::Assoc *yf::Z3950Client::Rep::get_assoc(Package &package) 
164 {
165     // only one thread messes with the clients list at a time
166     boost::mutex::scoped_lock lock(m_mutex);
167
168     std::map<yp2::Session,yf::Z3950Client::Assoc *>::iterator it;
169     
170     Z_GDU *gdu = package.request().get();
171     // only deal with Z39.50
172     if (!gdu || gdu->which != Z_GDU_Z3950)
173     {
174         package.move();
175         return 0;
176     }
177     it = m_clients.find(package.session());
178     if (it != m_clients.end())
179     {
180         it->second->m_queue_len++;
181         while(true)
182         {
183 #if 0
184             if (gdu && gdu->which == Z_GDU_Z3950 &&
185                 gdu->u.z3950->which == Z_APDU_initRequest)
186             {
187                 yazpp_1::SocketManager *s = it->second->m_socket_manager;
188                 delete it->second;  // destroy Z_Assoc
189                 delete s;    // then manager
190                 m_clients.erase(it);
191                 break;
192             }
193 #endif
194             if (!it->second->m_in_use)
195             {
196                 it->second->m_in_use = true;
197                 return it->second;
198             }
199             m_cond_session_ready.wait(lock);
200         }
201     }
202     // new Z39.50 session ..
203     Z_APDU *apdu = gdu->u.z3950;
204     // check that it is init. If not, close
205     if (apdu->which != Z_APDU_initRequest)
206     {
207         yp2::odr odr;
208         
209         package.response() = odr.create_close(Z_Close_protocolError,
210                                               "First PDU was not an "
211                                               "Initialize Request");
212         package.session().close();
213         return 0;
214     }
215     // check virtual host
216     const char *vhost =
217         yaz_oi_get_string_oidval(&apdu->u.initRequest->otherInfo,
218                                  VAL_PROXY, 
219                                  /* categoryValue */ 1, /* delete */ 1);
220     if (!vhost)
221     {
222         yp2::odr odr;
223         package.response() = odr.create_initResponse(
224             YAZ_BIB1_INIT_NEGOTIATION_OPTION_REQUIRED,
225             "Virtual host not given");
226         
227         package.session().close();
228         return 0;
229     }
230                       
231     yazpp_1::SocketManager *sm = new yazpp_1::SocketManager;
232     yazpp_1::PDU_Assoc *pdu_as = new yazpp_1::PDU_Assoc(sm);
233     yf::Z3950Client::Assoc *as = new yf::Z3950Client::Assoc(sm, pdu_as, vhost,
234                                                             m_timeout_sec);
235     m_clients[package.session()] = as;
236     return as;
237 }
238
239 void yf::Z3950Client::Rep::send_and_receive(Package &package,
240                                             yf::Z3950Client::Assoc *c)
241 {
242     Z_GDU *gdu = package.request().get();
243
244     if (c->m_destroyed)
245         return;
246
247     if (!gdu || gdu->which != Z_GDU_Z3950)
248         return;
249
250     c->m_time_elapsed = 0;
251     c->m_package = &package;
252     c->m_waiting = true;
253     if (!c->m_connected)
254     {
255         c->client(c->m_host.c_str());
256         c->timeout(1);
257
258         while (!c->m_destroyed && c->m_waiting 
259                && c->m_socket_manager->processEvent() > 0)
260             ;
261     }
262     if (!c->m_connected)
263     {
264         return;
265     }
266
267     // prepare response
268     c->m_time_elapsed = 0;
269     c->m_waiting = true;
270     
271     // relay the package  ..
272     int len;
273     c->send_GDU(gdu, &len);
274
275     switch(gdu->u.z3950->which)
276     {
277     case Z_APDU_triggerResourceControlRequest:
278         // request only..
279         break;
280     default:
281         // for the rest: wait for a response PDU
282         while (!c->m_destroyed && c->m_waiting
283                && c->m_socket_manager->processEvent() > 0)
284             ;
285         break;
286     }
287 }
288
289 void yf::Z3950Client::Rep::release_assoc(Package &package)
290 {
291     boost::mutex::scoped_lock lock(m_mutex);
292     std::map<yp2::Session,yf::Z3950Client::Assoc *>::iterator it;
293     
294     it = m_clients.find(package.session());
295     if (it != m_clients.end())
296     {
297         Z_GDU *gdu = package.request().get();
298         if (gdu && gdu->which == Z_GDU_Z3950)
299         {   // only Z39.50 packages lock in get_assoc.. release it
300             it->second->m_in_use = false;
301             it->second->m_queue_len--;
302         }
303
304         if (package.session().is_closed())
305         {
306             // destroy hint (send_and_receive)
307             it->second->m_destroyed = true;
308             
309             // wait until no one is waiting for it.
310             while (it->second->m_queue_len)
311                 m_cond_session_ready.wait(lock);
312             
313             // the Z_Assoc and PDU_Assoc must be destroyed before
314             // the socket manager.. so pull that out.. first..
315             yazpp_1::SocketManager *s = it->second->m_socket_manager;
316             delete it->second;  // destroy Z_Assoc
317             delete s;    // then manager
318             m_clients.erase(it);
319         }
320         m_cond_session_ready.notify_all();
321     }
322 }
323
324 void yf::Z3950Client::process(Package &package) const
325 {
326     yf::Z3950Client::Assoc *c = m_p->get_assoc(package);
327     if (c)
328     {
329         m_p->send_and_receive(package, c);
330     }
331     m_p->release_assoc(package);
332 }
333
334 void yf::Z3950Client::configure(const xmlNode *ptr)
335 {
336     for (ptr = ptr->children; ptr; ptr = ptr->next)
337     {
338         if (ptr->type != XML_ELEMENT_NODE)
339             continue;
340         if (!strcmp((const char *) ptr->name, "timeout"))
341         {
342             std::string timeout_str = yp2::xml::get_text(ptr);
343             int timeout_sec = atoi(timeout_str.c_str());
344             if (timeout_sec < 2)
345                 throw yp2::filter::FilterException("Bad timeout value " 
346                                                    + timeout_str);
347             m_p->m_timeout_sec = timeout_sec;
348         }
349         else
350         {
351             throw yp2::filter::FilterException("Bad element " 
352                                                + std::string((const char *)
353                                                              ptr->name));
354         }
355     }
356 }
357
358 static yp2::filter::Base* filter_creator()
359 {
360     return new yp2::filter::Z3950Client;
361 }
362
363 extern "C" {
364     struct yp2_filter_struct yp2_filter_z3950_client = {
365         0,
366         "z3950_client",
367         filter_creator
368     };
369 }
370
371 /*
372  * Local variables:
373  * c-basic-offset: 4
374  * indent-tabs-mode: nil
375  * c-file-style: "stroustrup"
376  * End:
377  * vim: shiftwidth=4 tabstop=8 expandtab
378  */