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