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