Filter frontend_net honors connect-max
[metaproxy-moved-to-github.git] / src / filter_frontend_net.cpp
1 /* This file is part of Metaproxy.
2    Copyright (C) 2005-2009 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 "util.hpp"
22 #include "pipe.hpp"
23 #include "filter.hpp"
24 #include "package.hpp"
25 #include "thread_pool_observer.hpp"
26 #include "filter_frontend_net.hpp"
27 #include <yazpp/z-assoc.h>
28 #include <yazpp/pdu-assoc.h>
29 #include <yazpp/socket-manager.h>
30 #include <yazpp/limit-connect.h>
31 #include <yaz/log.h>
32
33 #include <iostream>
34
35 namespace mp = metaproxy_1;
36
37 namespace metaproxy_1 {
38     class My_Timer_Thread;
39     class ZAssocServer;
40     namespace filter {
41         class FrontendNet::Rep {
42             friend class FrontendNet;
43             int m_no_threads;
44             std::vector<std::string> m_ports;
45             int m_listen_duration;
46             int m_session_timeout;
47             int m_connect_max;
48             yazpp_1::SocketManager mySocketManager;
49             ZAssocServer **az;
50         };
51     }
52     class My_Timer_Thread : public yazpp_1::ISocketObserver {
53     private:
54         yazpp_1::ISocketObservable *m_obs;
55         Pipe m_pipe;
56         bool m_timeout;
57     public:
58         My_Timer_Thread(yazpp_1::ISocketObservable *obs, int duration);
59         void socketNotify(int event);
60         bool timeout();
61     };
62     class ZAssocChild : public yazpp_1::Z_Assoc {
63     public:
64         ~ZAssocChild();
65         ZAssocChild(yazpp_1::IPDU_Observable *the_PDU_Observable,
66                           mp::ThreadPoolSocketObserver *m_thread_pool_observer,
67                           const mp::Package *package);
68         int m_no_requests;
69     private:
70         yazpp_1::IPDU_Observer* sessionNotify(
71             yazpp_1::IPDU_Observable *the_PDU_Observable,
72             int fd);
73         void recv_GDU(Z_GDU *apdu, int len);
74         
75         void failNotify();
76         void timeoutNotify();
77         void connectNotify();
78     private:
79         mp::ThreadPoolSocketObserver *m_thread_pool_observer;
80         mp::Session m_session;
81         mp::Origin m_origin;
82         bool m_delete_flag;
83         const mp::Package *m_package;
84     };
85     class ThreadPoolPackage : public mp::IThreadPoolMsg {
86     public:
87         ThreadPoolPackage(mp::Package *package, mp::ZAssocChild *ses) :
88             m_assoc_child(ses), m_package(package) { };
89         ~ThreadPoolPackage();
90         IThreadPoolMsg *handle();
91         void result();
92         
93     private:
94         mp::ZAssocChild *m_assoc_child;
95         mp::Package *m_package;
96         
97     };
98     class ZAssocServer : public yazpp_1::Z_Assoc {
99     public:
100         ~ZAssocServer();
101         ZAssocServer(yazpp_1::IPDU_Observable *PDU_Observable, int timeout,
102                      int connect_max);
103         void set_package(const mp::Package *package);
104         void set_thread_pool(ThreadPoolSocketObserver *m_thread_pool_observer);
105     private:
106         yazpp_1::IPDU_Observer* sessionNotify(
107             yazpp_1::IPDU_Observable *the_PDU_Observable,
108             int fd);
109         void recv_GDU(Z_GDU *apdu, int len);
110         
111         void failNotify();
112         void timeoutNotify();
113     void connectNotify();
114     private:
115         mp::ThreadPoolSocketObserver *m_thread_pool_observer;
116         const mp::Package *m_package;
117         int m_session_timeout;
118         int m_connect_max;
119         yazpp_1::LimitConnect limit_connect;
120     };
121 }
122
123 mp::ThreadPoolPackage::~ThreadPoolPackage()
124 {
125     delete m_package;
126 }
127
128 void mp::ThreadPoolPackage::result()
129 {
130     m_assoc_child->m_no_requests--;
131
132     yazpp_1::GDU *gdu = &m_package->response();
133
134     if (gdu->get())
135     {
136         int len;
137         m_assoc_child->send_GDU(gdu->get(), &len);
138     }
139     else if (!m_package->session().is_closed())
140     {
141         // no response package and yet the session is still open..
142         // means that request is unhandled..
143         yazpp_1::GDU *gdu_req = &m_package->request();
144         Z_GDU *z_gdu = gdu_req->get();
145         if (z_gdu && z_gdu->which == Z_GDU_Z3950)
146         {
147             // For Z39.50, response with a Close and shutdown
148             mp::odr odr;
149             int len;
150             Z_APDU *apdu_response = odr.create_close(
151                 z_gdu->u.z3950, Z_Close_systemProblem, 
152                 "unhandled Z39.50 request");
153
154             m_assoc_child->send_Z_PDU(apdu_response, &len);
155         }
156         else if (z_gdu && z_gdu->which == Z_GDU_HTTP_Request)
157         {
158             // For HTTP, respond with Server Error
159             int len;
160             mp::odr odr;
161             Z_GDU *zgdu_res 
162                 = odr.create_HTTP_Response(m_package->session(), 
163                                            z_gdu->u.HTTP_Request, 500);
164             m_assoc_child->send_GDU(zgdu_res, &len);
165         }
166         m_package->session().close();
167     }
168
169     if (m_assoc_child->m_no_requests == 0 && m_package->session().is_closed())
170     {
171         m_assoc_child->close();
172     }
173     delete this;
174 }
175
176 mp::IThreadPoolMsg *mp::ThreadPoolPackage::handle() 
177 {
178     m_package->move();
179     return this;
180 }
181
182
183 mp::ZAssocChild::ZAssocChild(yazpp_1::IPDU_Observable *PDU_Observable,
184                                      mp::ThreadPoolSocketObserver *my_thread_pool,
185                                      const mp::Package *package)
186     :  Z_Assoc(PDU_Observable)
187 {
188     m_thread_pool_observer = my_thread_pool;
189     m_no_requests = 0;
190     m_delete_flag = false;
191     m_package = package;
192     const char *peername = PDU_Observable->getpeername();
193     if (!peername)
194         peername = "unknown";
195     m_origin.set_tcpip_address(std::string(peername), m_session.id());
196 }
197
198
199 yazpp_1::IPDU_Observer *mp::ZAssocChild::sessionNotify(yazpp_1::IPDU_Observable
200                                                   *the_PDU_Observable, int fd)
201 {
202     return 0;
203 }
204
205 mp::ZAssocChild::~ZAssocChild()
206 {
207 }
208
209 void mp::ZAssocChild::recv_GDU(Z_GDU *z_pdu, int len)
210 {
211     m_no_requests++;
212
213     mp::Package *p = new mp::Package(m_session, m_origin);
214
215     mp::ThreadPoolPackage *tp = new mp::ThreadPoolPackage(p, this);
216     p->copy_filter(*m_package);
217     p->request() = yazpp_1::GDU(z_pdu);
218     m_thread_pool_observer->put(tp);  
219 }
220
221 void mp::ZAssocChild::failNotify()
222 {
223     // TODO: send Package to signal "close"
224     if (m_session.is_closed())
225     {
226         if (m_no_requests == 0)
227             delete this;
228         return;
229     }
230     m_no_requests++;
231
232     m_session.close();
233
234     mp::Package *p = new mp::Package(m_session, m_origin);
235
236     mp::ThreadPoolPackage *tp = new mp::ThreadPoolPackage(p, this);
237     p->copy_filter(*m_package);
238     m_thread_pool_observer->put(tp);  
239 }
240
241 void mp::ZAssocChild::timeoutNotify()
242 {
243     failNotify();
244 }
245
246 void mp::ZAssocChild::connectNotify()
247 {
248
249 }
250
251 mp::ZAssocServer::ZAssocServer(yazpp_1::IPDU_Observable *PDU_Observable,
252                                int timeout, int connect_max)
253     :  Z_Assoc(PDU_Observable), m_session_timeout(timeout),
254        m_connect_max(connect_max)
255 {
256     m_package = 0;
257 }
258
259
260 void mp::ZAssocServer::set_package(const mp::Package *package)
261 {
262     m_package = package;
263 }
264
265 void mp::ZAssocServer::set_thread_pool(ThreadPoolSocketObserver *observer)
266 {
267     m_thread_pool_observer = observer;
268 }
269
270 yazpp_1::IPDU_Observer *mp::ZAssocServer::sessionNotify(yazpp_1::IPDU_Observable
271                                                  *the_PDU_Observable, int fd)
272 {
273
274     const char *peername = the_PDU_Observable->getpeername();
275     if (peername)
276     {
277         limit_connect.add_connect(peername);
278         limit_connect.cleanup(false);
279         int con_sz = limit_connect.get_total(peername);
280         if (m_connect_max && con_sz > m_connect_max)
281             return 0;
282     }
283     mp::ZAssocChild *my =
284         new mp::ZAssocChild(the_PDU_Observable, m_thread_pool_observer,
285                              m_package);
286     my->timeout(m_session_timeout);
287     return my;
288 }
289
290 mp::ZAssocServer::~ZAssocServer()
291 {
292 }
293
294 void mp::ZAssocServer::recv_GDU(Z_GDU *apdu, int len)
295 {
296 }
297
298 void mp::ZAssocServer::failNotify()
299 {
300 }
301
302 void mp::ZAssocServer::timeoutNotify()
303 {
304 }
305
306 void mp::ZAssocServer::connectNotify()
307 {
308 }
309
310 mp::filter::FrontendNet::FrontendNet() : m_p(new Rep)
311 {
312     m_p->m_no_threads = 5;
313     m_p->m_listen_duration = 0;
314     m_p->m_session_timeout = 300; // 5 minutes
315     m_p->az = 0;
316 }
317
318 mp::filter::FrontendNet::~FrontendNet()
319 {
320     if (m_p->az)
321     {
322         size_t i;
323         for (i = 0; i<m_p->m_ports.size(); i++)
324             delete m_p->az[i];
325         delete [] m_p->az;
326     }
327 }
328
329 bool mp::My_Timer_Thread::timeout()
330 {
331     return m_timeout;
332 }
333
334 mp::My_Timer_Thread::My_Timer_Thread(yazpp_1::ISocketObservable *obs,
335                                  int duration) : 
336     m_obs(obs), m_pipe(9123), m_timeout(false)
337 {
338     obs->addObserver(m_pipe.read_fd(), this);
339     obs->maskObserver(this, yazpp_1::SOCKET_OBSERVE_READ);
340     obs->timeoutObserver(this, duration);
341 }
342
343 void mp::My_Timer_Thread::socketNotify(int event)
344 {
345     m_timeout = true;
346     m_obs->deleteObserver(this);
347 }
348
349 void mp::filter::FrontendNet::process(Package &package) const
350 {
351     if (m_p->az == 0)
352         return;
353     size_t i;
354     My_Timer_Thread *tt = 0;
355
356     if (m_p->m_listen_duration)
357         tt = new My_Timer_Thread(&m_p->mySocketManager,
358                                  m_p->m_listen_duration);
359     
360     ThreadPoolSocketObserver tp(&m_p->mySocketManager, m_p->m_no_threads);
361
362     for (i = 0; i<m_p->m_ports.size(); i++)
363     {
364         m_p->az[i]->set_package(&package);
365         m_p->az[i]->set_thread_pool(&tp);
366     }
367     while (m_p->mySocketManager.processEvent() > 0)
368     {
369         if (tt && tt->timeout())
370             break;
371     }
372     delete tt;
373 }
374
375 void mp::filter::FrontendNet::configure(const xmlNode * ptr, bool test_only)
376 {
377     if (!ptr || !ptr->children)
378     {
379         throw mp::filter::FilterException("No ports for Frontend");
380     }
381     std::vector<std::string> ports;
382     for (ptr = ptr->children; ptr; ptr = ptr->next)
383     {
384         if (ptr->type != XML_ELEMENT_NODE)
385             continue;
386         if (!strcmp((const char *) ptr->name, "port"))
387         {
388             std::string port = mp::xml::get_text(ptr);
389             ports.push_back(port);
390             
391         }
392         else if (!strcmp((const char *) ptr->name, "threads"))
393         {
394             std::string threads_str = mp::xml::get_text(ptr);
395             int threads = atoi(threads_str.c_str());
396             if (threads < 1)
397                 throw mp::filter::FilterException("Bad value for threads: " 
398                                                    + threads_str);
399             m_p->m_no_threads = threads;
400         }
401         else if (!strcmp((const char *) ptr->name, "timeout"))
402         {
403             std::string timeout_str = mp::xml::get_text(ptr);
404             int timeout = atoi(timeout_str.c_str());
405             if (timeout < 1)
406                 throw mp::filter::FilterException("Bad value for timeout: " 
407                                                    + timeout_str);
408             m_p->m_session_timeout = timeout;
409         }
410         else if (!strcmp((const char *) ptr->name, "connect-max"))
411         {
412             m_p->m_connect_max = mp::xml::get_int(ptr->children, 0);
413         }
414         else
415         {
416             throw mp::filter::FilterException("Bad element " 
417                                                + std::string((const char *)
418                                                              ptr->name));
419         }
420     }
421     if (test_only)
422         return;
423     set_ports(ports);
424 }
425
426 void mp::filter::FrontendNet::set_ports(std::vector<std::string> &ports)
427 {
428     m_p->m_ports = ports;
429     
430     m_p->az = new mp::ZAssocServer *[m_p->m_ports.size()];
431     
432     // Create mp::ZAssocServer for each port
433     size_t i;
434     for (i = 0; i<m_p->m_ports.size(); i++)
435     {
436         // create a PDU assoc object (one per mp::ZAssocServer)
437         yazpp_1::PDU_Assoc *as = new yazpp_1::PDU_Assoc(&m_p->mySocketManager);
438         
439         // create ZAssoc with PDU Assoc
440         m_p->az[i] = new mp::ZAssocServer(as, 
441                                           m_p->m_session_timeout,
442                                           m_p->m_connect_max);
443         if (m_p->az[i]->server(m_p->m_ports[i].c_str()))
444         {
445             throw mp::filter::FilterException("Unable to bind to address " 
446                                               + std::string(m_p->m_ports[i]));
447         }
448     }
449 }
450
451 void mp::filter::FrontendNet::set_listen_duration(int d)
452 {
453     m_p->m_listen_duration = d;
454 }
455
456 static mp::filter::Base* filter_creator()
457 {
458     return new mp::filter::FrontendNet;
459 }
460
461 extern "C" {
462     struct metaproxy_1_filter_struct metaproxy_1_filter_frontend_net = {
463         0,
464         "frontend_net",
465         filter_creator
466     };
467 }
468
469 /*
470  * Local variables:
471  * c-basic-offset: 4
472  * c-file-style: "Stroustrup"
473  * indent-tabs-mode: nil
474  * End:
475  * vim: shiftwidth=4 tabstop=8 expandtab
476  */
477