Updated copyright headers. Omit CVS ID.
[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_session(ses), m_package(package) { };
88         ~ThreadPoolPackage();
89         IThreadPoolMsg *handle();
90         void result();
91         
92     private:
93         mp::ZAssocChild *m_session;
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_session->m_no_requests--;
127
128     yazpp_1::GDU *gdu = &m_package->response();
129
130     if (gdu->get())
131     {
132         int len;
133         m_session->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_session->send_Z_PDU(apdu_response, &len);
151             m_package->session().close();
152         }
153     }
154
155     if (m_session->m_no_requests == 0 && m_package->session().is_closed())
156     {
157         m_session->close();
158     }
159     delete this;
160 }
161
162 mp::IThreadPoolMsg *mp::ThreadPoolPackage::handle() 
163 {
164     m_package->move();
165     return this;
166 }
167
168
169 mp::ZAssocChild::ZAssocChild(yazpp_1::IPDU_Observable *PDU_Observable,
170                                      mp::ThreadPoolSocketObserver *my_thread_pool,
171                                      const mp::Package *package)
172     :  Z_Assoc(PDU_Observable)
173 {
174     m_thread_pool_observer = my_thread_pool;
175     m_no_requests = 0;
176     m_delete_flag = false;
177     m_package = package;
178     const char *peername = PDU_Observable->getpeername();
179     if (!peername)
180         peername = "unknown";
181     m_origin.set_tcpip_address(std::string(peername), m_session.id());
182 }
183
184
185 yazpp_1::IPDU_Observer *mp::ZAssocChild::sessionNotify(yazpp_1::IPDU_Observable
186                                                   *the_PDU_Observable, int fd)
187 {
188     return 0;
189 }
190
191 mp::ZAssocChild::~ZAssocChild()
192 {
193 }
194
195 void mp::ZAssocChild::recv_GDU(Z_GDU *z_pdu, int len)
196 {
197     m_no_requests++;
198
199     mp::Package *p = new mp::Package(m_session, m_origin);
200
201     mp::ThreadPoolPackage *tp = new mp::ThreadPoolPackage(p, this);
202     p->copy_filter(*m_package);
203     p->request() = yazpp_1::GDU(z_pdu);
204     m_thread_pool_observer->put(tp);  
205 }
206
207 void mp::ZAssocChild::failNotify()
208 {
209     // TODO: send Package to signal "close"
210     if (m_session.is_closed())
211     {
212         delete this;
213         return;
214     }
215     m_no_requests++;
216
217     m_session.close();
218
219     mp::Package *p = new mp::Package(m_session, m_origin);
220
221     mp::ThreadPoolPackage *tp = new mp::ThreadPoolPackage(p, this);
222     p->copy_filter(*m_package);
223     m_thread_pool_observer->put(tp);  
224 }
225
226 void mp::ZAssocChild::timeoutNotify()
227 {
228     failNotify();
229 }
230
231 void mp::ZAssocChild::connectNotify()
232 {
233
234 }
235
236 mp::ZAssocServer::ZAssocServer(yazpp_1::IPDU_Observable *PDU_Observable,
237                                int timeout)
238     :  Z_Assoc(PDU_Observable), m_session_timeout(timeout)
239 {
240     m_package = 0;
241 }
242
243
244 void mp::ZAssocServer::set_package(const mp::Package *package)
245 {
246     m_package = package;
247 }
248
249 void mp::ZAssocServer::set_thread_pool(ThreadPoolSocketObserver *observer)
250 {
251     m_thread_pool_observer = observer;
252 }
253
254 yazpp_1::IPDU_Observer *mp::ZAssocServer::sessionNotify(yazpp_1::IPDU_Observable
255                                                  *the_PDU_Observable, int fd)
256 {
257     mp::ZAssocChild *my =
258         new mp::ZAssocChild(the_PDU_Observable, m_thread_pool_observer,
259                              m_package);
260     my->timeout(m_session_timeout);
261     return my;
262 }
263
264 mp::ZAssocServer::~ZAssocServer()
265 {
266 }
267
268 void mp::ZAssocServer::recv_GDU(Z_GDU *apdu, int len)
269 {
270 }
271
272 void mp::ZAssocServer::failNotify()
273 {
274 }
275
276 void mp::ZAssocServer::timeoutNotify()
277 {
278 }
279
280 void mp::ZAssocServer::connectNotify()
281 {
282 }
283
284 mp::filter::FrontendNet::FrontendNet() : m_p(new Rep)
285 {
286     m_p->m_no_threads = 5;
287     m_p->m_listen_duration = 0;
288     m_p->m_session_timeout = 300; // 5 minutes
289     m_p->az = 0;
290 }
291
292 mp::filter::FrontendNet::~FrontendNet()
293 {
294     if (m_p->az)
295     {
296         size_t i;
297         for (i = 0; i<m_p->m_ports.size(); i++)
298             delete m_p->az[i];
299         delete [] m_p->az;
300     }
301 }
302
303 bool mp::My_Timer_Thread::timeout()
304 {
305     return m_timeout;
306 }
307
308 mp::My_Timer_Thread::My_Timer_Thread(yazpp_1::ISocketObservable *obs,
309                                  int duration) : 
310     m_obs(obs), m_pipe(9123), m_timeout(false)
311 {
312     obs->addObserver(m_pipe.read_fd(), this);
313     obs->maskObserver(this, yazpp_1::SOCKET_OBSERVE_READ);
314     obs->timeoutObserver(this, duration);
315 }
316
317 void mp::My_Timer_Thread::socketNotify(int event)
318 {
319     m_timeout = true;
320     m_obs->deleteObserver(this);
321 }
322
323 void mp::filter::FrontendNet::process(Package &package) const
324 {
325     if (m_p->az == 0)
326         return;
327     size_t i;
328     My_Timer_Thread *tt = 0;
329
330     if (m_p->m_listen_duration)
331         tt = new My_Timer_Thread(&m_p->mySocketManager,
332                                  m_p->m_listen_duration);
333     
334     ThreadPoolSocketObserver tp(&m_p->mySocketManager, m_p->m_no_threads);
335
336     for (i = 0; i<m_p->m_ports.size(); i++)
337     {
338         m_p->az[i]->set_package(&package);
339         m_p->az[i]->set_thread_pool(&tp);
340     }
341     while (m_p->mySocketManager.processEvent() > 0)
342     {
343         if (tt && tt->timeout())
344             break;
345     }
346     delete tt;
347 }
348
349 void mp::filter::FrontendNet::configure(const xmlNode * ptr, bool test_only)
350 {
351     if (!ptr || !ptr->children)
352     {
353         throw mp::filter::FilterException("No ports for Frontend");
354     }
355     std::vector<std::string> ports;
356     for (ptr = ptr->children; ptr; ptr = ptr->next)
357     {
358         if (ptr->type != XML_ELEMENT_NODE)
359             continue;
360         if (!strcmp((const char *) ptr->name, "port"))
361         {
362             std::string port = mp::xml::get_text(ptr);
363             ports.push_back(port);
364             
365         }
366         else if (!strcmp((const char *) ptr->name, "threads"))
367         {
368             std::string threads_str = mp::xml::get_text(ptr);
369             int threads = atoi(threads_str.c_str());
370             if (threads < 1)
371                 throw mp::filter::FilterException("Bad value for threads: " 
372                                                    + threads_str);
373             m_p->m_no_threads = threads;
374         }
375         else if (!strcmp((const char *) ptr->name, "timeout"))
376         {
377             std::string timeout_str = mp::xml::get_text(ptr);
378             int timeout = atoi(timeout_str.c_str());
379             if (timeout < 1)
380                 throw mp::filter::FilterException("Bad value for timeout: " 
381                                                    + timeout_str);
382             m_p->m_session_timeout = timeout;
383         }
384         else
385         {
386             throw mp::filter::FilterException("Bad element " 
387                                                + std::string((const char *)
388                                                              ptr->name));
389         }
390     }
391     if (test_only)
392         return;
393     set_ports(ports);
394 }
395
396 void mp::filter::FrontendNet::set_ports(std::vector<std::string> &ports)
397 {
398     m_p->m_ports = ports;
399     
400     m_p->az = new mp::ZAssocServer *[m_p->m_ports.size()];
401     
402     // Create mp::ZAssocServer for each port
403     size_t i;
404     for (i = 0; i<m_p->m_ports.size(); i++)
405     {
406         // create a PDU assoc object (one per mp::ZAssocServer)
407         yazpp_1::PDU_Assoc *as = new yazpp_1::PDU_Assoc(&m_p->mySocketManager);
408         
409         // create ZAssoc with PDU Assoc
410         m_p->az[i] = new mp::ZAssocServer(as, 
411                                           m_p->m_session_timeout);
412         if (m_p->az[i]->server(m_p->m_ports[i].c_str()))
413         {
414             throw mp::filter::FilterException("Unable to bind to address " 
415                                               + std::string(m_p->m_ports[i]));
416         }
417     }
418 }
419
420 void mp::filter::FrontendNet::set_listen_duration(int d)
421 {
422     m_p->m_listen_duration = d;
423 }
424
425 static mp::filter::Base* filter_creator()
426 {
427     return new mp::filter::FrontendNet;
428 }
429
430 extern "C" {
431     struct metaproxy_1_filter_struct metaproxy_1_filter_frontend_net = {
432         0,
433         "frontend_net",
434         filter_creator
435     };
436 }
437
438 /*
439  * Local variables:
440  * c-basic-offset: 4
441  * indent-tabs-mode: nil
442  * c-file-style: "stroustrup"
443  * End:
444  * vim: shiftwidth=4 tabstop=8 expandtab
445  */