Updated footer comment
[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         if (m_no_requests == 0)
223             delete this;
224         return;
225     }
226     m_no_requests++;
227
228     m_session.close();
229
230     mp::Package *p = new mp::Package(m_session, m_origin);
231
232     mp::ThreadPoolPackage *tp = new mp::ThreadPoolPackage(p, this);
233     p->copy_filter(*m_package);
234     m_thread_pool_observer->put(tp);  
235 }
236
237 void mp::ZAssocChild::timeoutNotify()
238 {
239     failNotify();
240 }
241
242 void mp::ZAssocChild::connectNotify()
243 {
244
245 }
246
247 mp::ZAssocServer::ZAssocServer(yazpp_1::IPDU_Observable *PDU_Observable,
248                                int timeout)
249     :  Z_Assoc(PDU_Observable), m_session_timeout(timeout)
250 {
251     m_package = 0;
252 }
253
254
255 void mp::ZAssocServer::set_package(const mp::Package *package)
256 {
257     m_package = package;
258 }
259
260 void mp::ZAssocServer::set_thread_pool(ThreadPoolSocketObserver *observer)
261 {
262     m_thread_pool_observer = observer;
263 }
264
265 yazpp_1::IPDU_Observer *mp::ZAssocServer::sessionNotify(yazpp_1::IPDU_Observable
266                                                  *the_PDU_Observable, int fd)
267 {
268     mp::ZAssocChild *my =
269         new mp::ZAssocChild(the_PDU_Observable, m_thread_pool_observer,
270                              m_package);
271     my->timeout(m_session_timeout);
272     return my;
273 }
274
275 mp::ZAssocServer::~ZAssocServer()
276 {
277 }
278
279 void mp::ZAssocServer::recv_GDU(Z_GDU *apdu, int len)
280 {
281 }
282
283 void mp::ZAssocServer::failNotify()
284 {
285 }
286
287 void mp::ZAssocServer::timeoutNotify()
288 {
289 }
290
291 void mp::ZAssocServer::connectNotify()
292 {
293 }
294
295 mp::filter::FrontendNet::FrontendNet() : m_p(new Rep)
296 {
297     m_p->m_no_threads = 5;
298     m_p->m_listen_duration = 0;
299     m_p->m_session_timeout = 300; // 5 minutes
300     m_p->az = 0;
301 }
302
303 mp::filter::FrontendNet::~FrontendNet()
304 {
305     if (m_p->az)
306     {
307         size_t i;
308         for (i = 0; i<m_p->m_ports.size(); i++)
309             delete m_p->az[i];
310         delete [] m_p->az;
311     }
312 }
313
314 bool mp::My_Timer_Thread::timeout()
315 {
316     return m_timeout;
317 }
318
319 mp::My_Timer_Thread::My_Timer_Thread(yazpp_1::ISocketObservable *obs,
320                                  int duration) : 
321     m_obs(obs), m_pipe(9123), m_timeout(false)
322 {
323     obs->addObserver(m_pipe.read_fd(), this);
324     obs->maskObserver(this, yazpp_1::SOCKET_OBSERVE_READ);
325     obs->timeoutObserver(this, duration);
326 }
327
328 void mp::My_Timer_Thread::socketNotify(int event)
329 {
330     m_timeout = true;
331     m_obs->deleteObserver(this);
332 }
333
334 void mp::filter::FrontendNet::process(Package &package) const
335 {
336     if (m_p->az == 0)
337         return;
338     size_t i;
339     My_Timer_Thread *tt = 0;
340
341     if (m_p->m_listen_duration)
342         tt = new My_Timer_Thread(&m_p->mySocketManager,
343                                  m_p->m_listen_duration);
344     
345     ThreadPoolSocketObserver tp(&m_p->mySocketManager, m_p->m_no_threads);
346
347     for (i = 0; i<m_p->m_ports.size(); i++)
348     {
349         m_p->az[i]->set_package(&package);
350         m_p->az[i]->set_thread_pool(&tp);
351     }
352     while (m_p->mySocketManager.processEvent() > 0)
353     {
354         if (tt && tt->timeout())
355             break;
356     }
357     delete tt;
358 }
359
360 void mp::filter::FrontendNet::configure(const xmlNode * ptr, bool test_only)
361 {
362     if (!ptr || !ptr->children)
363     {
364         throw mp::filter::FilterException("No ports for Frontend");
365     }
366     std::vector<std::string> ports;
367     for (ptr = ptr->children; ptr; ptr = ptr->next)
368     {
369         if (ptr->type != XML_ELEMENT_NODE)
370             continue;
371         if (!strcmp((const char *) ptr->name, "port"))
372         {
373             std::string port = mp::xml::get_text(ptr);
374             ports.push_back(port);
375             
376         }
377         else if (!strcmp((const char *) ptr->name, "threads"))
378         {
379             std::string threads_str = mp::xml::get_text(ptr);
380             int threads = atoi(threads_str.c_str());
381             if (threads < 1)
382                 throw mp::filter::FilterException("Bad value for threads: " 
383                                                    + threads_str);
384             m_p->m_no_threads = threads;
385         }
386         else if (!strcmp((const char *) ptr->name, "timeout"))
387         {
388             std::string timeout_str = mp::xml::get_text(ptr);
389             int timeout = atoi(timeout_str.c_str());
390             if (timeout < 1)
391                 throw mp::filter::FilterException("Bad value for timeout: " 
392                                                    + timeout_str);
393             m_p->m_session_timeout = timeout;
394         }
395         else
396         {
397             throw mp::filter::FilterException("Bad element " 
398                                                + std::string((const char *)
399                                                              ptr->name));
400         }
401     }
402     if (test_only)
403         return;
404     set_ports(ports);
405 }
406
407 void mp::filter::FrontendNet::set_ports(std::vector<std::string> &ports)
408 {
409     m_p->m_ports = ports;
410     
411     m_p->az = new mp::ZAssocServer *[m_p->m_ports.size()];
412     
413     // Create mp::ZAssocServer for each port
414     size_t i;
415     for (i = 0; i<m_p->m_ports.size(); i++)
416     {
417         // create a PDU assoc object (one per mp::ZAssocServer)
418         yazpp_1::PDU_Assoc *as = new yazpp_1::PDU_Assoc(&m_p->mySocketManager);
419         
420         // create ZAssoc with PDU Assoc
421         m_p->az[i] = new mp::ZAssocServer(as, 
422                                           m_p->m_session_timeout);
423         if (m_p->az[i]->server(m_p->m_ports[i].c_str()))
424         {
425             throw mp::filter::FilterException("Unable to bind to address " 
426                                               + std::string(m_p->m_ports[i]));
427         }
428     }
429 }
430
431 void mp::filter::FrontendNet::set_listen_duration(int d)
432 {
433     m_p->m_listen_duration = d;
434 }
435
436 static mp::filter::Base* filter_creator()
437 {
438     return new mp::filter::FrontendNet;
439 }
440
441 extern "C" {
442     struct metaproxy_1_filter_struct metaproxy_1_filter_frontend_net = {
443         0,
444         "frontend_net",
445         filter_creator
446     };
447 }
448
449 /*
450  * Local variables:
451  * c-basic-offset: 4
452  * c-file-style: "Stroustrup"
453  * indent-tabs-mode: nil
454  * End:
455  * vim: shiftwidth=4 tabstop=8 expandtab
456  */
457