Windows: use Boost 1.59, msvc 14.0
[metaproxy-moved-to-github.git] / src / filter_frontend_net.cpp
1 /* This file is part of Metaproxy.
2    Copyright (C) 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 #if HAVE_GETRLIMIT
22 #include <sys/resource.h>
23 #endif
24 #include <sstream>
25 #include <iomanip>
26 #include <metaproxy/util.hpp>
27 #include "pipe.hpp"
28 #include <metaproxy/filter.hpp>
29 #include <metaproxy/package.hpp>
30 #include "thread_pool_observer.hpp"
31 #include "filter_frontend_net.hpp"
32 #include <yazpp/z-assoc.h>
33 #include <yazpp/pdu-assoc.h>
34 #include <yazpp/socket-manager.h>
35 #include <yazpp/limit-connect.h>
36 #include <yaz/timing.h>
37 #include <yaz/log.h>
38 #include <yaz/daemon.h>
39 #include "gduutil.hpp"
40 #include <signal.h>
41
42 #include <iostream>
43
44 namespace mp = metaproxy_1;
45 namespace yf = metaproxy_1::filter;
46
47 namespace metaproxy_1 {
48     namespace filter {
49         class FrontendNet::Port {
50             friend class Rep;
51             friend class FrontendNet;
52             std::string port;
53             std::string route;
54             std::string cert_fname;
55             int max_recv_bytes;
56         };
57         class FrontendNet::IP_Pattern {
58             friend class Rep;
59             friend class FrontendNet;
60             std::string pattern;
61             int verbose;
62             int value;
63         };
64         class FrontendNet::Rep {
65             friend class FrontendNet;
66
67             int m_no_threads;
68             int m_max_threads;
69             int m_stack_size;
70             std::vector<Port> m_ports;
71             int m_listen_duration;
72             int m_session_timeout;
73             std::list<IP_Pattern> connect_max;
74             std::list<IP_Pattern> http_req_max;
75             std::string m_msg_config;
76             std::string m_stat_req;
77             yazpp_1::SocketManager mySocketManager;
78             ZAssocServer **az;
79             yazpp_1::PDU_Assoc **pdu;
80             int m_duration_freq[22];
81             double m_duration_lim[22];
82             double m_duration_max;
83             double m_duration_min;
84             double m_duration_total;
85             int m_stop_signo;
86         public:
87             Rep();
88             ~Rep();
89         };
90         class FrontendNet::My_Timer_Thread : public yazpp_1::ISocketObserver {
91         private:
92             yazpp_1::ISocketObservable *m_obs;
93             Pipe m_pipe;
94             bool m_timeout;
95         public:
96             My_Timer_Thread(yazpp_1::ISocketObservable *obs, int duration);
97             void socketNotify(int event);
98             bool timeout();
99         };
100         class FrontendNet::ZAssocChild : public yazpp_1::Z_Assoc {
101         public:
102             ~ZAssocChild();
103             ZAssocChild(yazpp_1::IPDU_Observable *the_PDU_Observable,
104                         mp::ThreadPoolSocketObserver *m_thread_pool_observer,
105                         const mp::Package *package,
106                         Port *port,
107                         Rep *rep,
108                         yazpp_1::LimitConnect &limit,
109                         const char *peername);
110             int m_no_requests;
111             Port *m_port;
112         private:
113             yazpp_1::IPDU_Observer* sessionNotify(
114                 yazpp_1::IPDU_Observable *the_PDU_Observable,
115                 int fd);
116             void recv_GDU(Z_GDU *apdu, int len);
117             void report(Z_HTTP_Request *hreq);
118             void failNotify();
119             void timeoutNotify();
120             void connectNotify();
121         private:
122             mp::ThreadPoolSocketObserver *m_thread_pool_observer;
123             mp::Session m_session;
124             mp::Origin m_origin;
125             bool m_delete_flag;
126             const mp::Package *m_package;
127             Rep *m_p;
128             yazpp_1::LimitConnect &m_limit_http_req;
129         };
130         class FrontendNet::ThreadPoolPackage : public mp::IThreadPoolMsg {
131         public:
132             ThreadPoolPackage(mp::Package *package,
133                               yf::FrontendNet::ZAssocChild *ses,
134                               Rep *rep);
135             ~ThreadPoolPackage();
136             IThreadPoolMsg *handle();
137             void result(const char *t_info);
138             bool cleanup(void *info);
139         private:
140             yaz_timing_t timer;
141             ZAssocChild *m_assoc_child;
142             mp::Package *m_package;
143             Rep *m_p;
144         };
145         class FrontendNet::ZAssocServer : public yazpp_1::Z_Assoc {
146         public:
147             ~ZAssocServer();
148             ZAssocServer(yazpp_1::IPDU_Observable *PDU_Observable,
149                          FrontendNet::Port *port,
150                          Rep *rep);
151             void set_package(const mp::Package *package);
152             void set_thread_pool(ThreadPoolSocketObserver *observer);
153         private:
154             yazpp_1::IPDU_Observer* sessionNotify(
155                 yazpp_1::IPDU_Observable *the_PDU_Observable,
156                 int fd);
157             void recv_GDU(Z_GDU *apdu, int len);
158
159             void failNotify();
160             void timeoutNotify();
161             void connectNotify();
162         private:
163             mp::ThreadPoolSocketObserver *m_thread_pool_observer;
164             const mp::Package *m_package;
165             yazpp_1::LimitConnect limit_connect;
166             yazpp_1::LimitConnect limit_http_req;
167             Port *m_port;
168             Rep *m_p;
169         };
170     }
171 }
172
173 yf::FrontendNet::ThreadPoolPackage::ThreadPoolPackage(mp::Package *package,
174                                                       ZAssocChild *ses,
175                                                       Rep *rep) :
176     m_assoc_child(ses), m_package(package), m_p(rep)
177 {
178     timer = yaz_timing_create();
179 }
180
181 yf::FrontendNet::ThreadPoolPackage::~ThreadPoolPackage()
182 {
183     yaz_timing_destroy(&timer); // timer may be NULL
184     delete m_package;
185 }
186
187 bool yf::FrontendNet::ThreadPoolPackage::cleanup(void *info)
188 {
189     mp::Session *ses = (mp::Session *) info;
190
191     return *ses == m_package->session();
192 }
193
194 void yf::FrontendNet::ThreadPoolPackage::result(const char *t_info)
195 {
196     m_assoc_child->m_no_requests--;
197
198     yazpp_1::GDU *gdu = &m_package->response();
199
200     if (gdu->get())
201     {
202         int len;
203         m_assoc_child->send_GDU(gdu->get(), &len);
204
205         yaz_timing_stop(timer);
206         double duration = yaz_timing_get_real(timer);
207
208         size_t ent = 0;
209         while (m_p->m_duration_lim[ent] != 0.0 && duration > m_p->m_duration_lim[ent])
210             ent++;
211         m_p->m_duration_freq[ent]++;
212
213         m_p->m_duration_total += duration;
214
215         if (m_p->m_duration_max < duration)
216             m_p->m_duration_max = duration;
217
218         if (m_p->m_duration_min == 0.0 || m_p->m_duration_min > duration)
219             m_p->m_duration_min = duration;
220
221         if (m_p->m_msg_config.length())
222         {
223             Z_GDU *z_gdu = gdu->get();
224
225             std::ostringstream os;
226             os  << m_p->m_msg_config << " "
227                 << *m_package << " "
228                 << std::fixed << std::setprecision (6) << duration << " ";
229
230             if (z_gdu)
231                 os << *z_gdu;
232             else
233                 os << "-";
234
235             yaz_log(YLOG_LOG, "%s %s", os.str().c_str(), t_info);
236         }
237     }
238     else if (!m_package->session().is_closed())
239     {
240         // no response package and yet the session is still open..
241         // means that request is unhandled..
242         yazpp_1::GDU *gdu_req = &m_package->request();
243         Z_GDU *z_gdu = gdu_req->get();
244         if (z_gdu && z_gdu->which == Z_GDU_Z3950)
245         {
246             // For Z39.50, response with a Close and shutdown
247             mp::odr odr;
248             int len;
249             Z_APDU *apdu_response = odr.create_close(
250                 z_gdu->u.z3950, Z_Close_systemProblem,
251                 "unhandled Z39.50 request");
252
253             m_assoc_child->send_Z_PDU(apdu_response, &len);
254         }
255         else if (z_gdu && z_gdu->which == Z_GDU_HTTP_Request)
256         {
257             // For HTTP, respond with Server Error
258             int len;
259             mp::odr odr;
260             Z_GDU *zgdu_res
261                 = odr.create_HTTP_Response(m_package->session(),
262                                            z_gdu->u.HTTP_Request, 500);
263             m_assoc_child->send_GDU(zgdu_res, &len);
264         }
265         m_package->session().close();
266     }
267
268     if (m_assoc_child->m_no_requests == 0 && m_package->session().is_closed())
269     {
270         m_assoc_child->close();
271     }
272
273
274     delete this;
275 }
276
277 mp::IThreadPoolMsg *yf::FrontendNet::ThreadPoolPackage::handle()
278 {
279     m_package->move(m_assoc_child->m_port->route);
280     return this;
281 }
282
283 yf::FrontendNet::ZAssocChild::ZAssocChild(
284     yazpp_1::IPDU_Observable *PDU_Observable,
285     mp::ThreadPoolSocketObserver *my_thread_pool,
286     const mp::Package *package,
287     Port *port, Rep *rep,
288     yazpp_1::LimitConnect &limit_http_req,
289     const char *peername)
290     :  Z_Assoc(PDU_Observable), m_p(rep), m_limit_http_req(limit_http_req)
291 {
292     m_thread_pool_observer = my_thread_pool;
293     m_no_requests = 0;
294     m_delete_flag = false;
295     m_package = package;
296     m_port = port;
297     std::string addr;
298     addr.append(peername);
299     addr.append(" ");
300     addr.append(port->port);
301     m_origin.set_tcpip_address(addr, m_session.id());
302     timeout(m_p->m_session_timeout);
303 }
304
305 yazpp_1::IPDU_Observer *yf::FrontendNet::ZAssocChild::sessionNotify(
306     yazpp_1::IPDU_Observable *the_PDU_Observable, int fd)
307 {
308     return 0;
309 }
310
311 yf::FrontendNet::ZAssocChild::~ZAssocChild()
312 {
313 }
314
315 void yf::FrontendNet::ZAssocChild::report(Z_HTTP_Request *hreq)
316 {
317     mp::odr o;
318
319     Z_GDU *gdu_res = o.create_HTTP_Response(m_session, hreq, 200);
320
321     Z_HTTP_Response *hres = gdu_res->u.HTTP_Response;
322
323     mp::wrbuf w;
324     size_t i;
325     int number_total = 0;
326
327     for (i = 0; m_p->m_duration_lim[i] != 0.0; i++)
328         number_total += m_p->m_duration_freq[i];
329     number_total += m_p->m_duration_freq[i];
330
331     wrbuf_puts(w, "<?xml version=\"1.0\"?>\n");
332     wrbuf_puts(w, "<frontend_net>\n");
333     wrbuf_printf(w, "  <responses frequency=\"%d\">\n", number_total);
334     for (i = 0; m_p->m_duration_lim[i] != 0.0; i++)
335     {
336         if (m_p->m_duration_freq[i] > 0)
337             wrbuf_printf(
338                 w, "    <response duration_start=\"%f\" "
339                 "duration_end=\"%f\" frequency=\"%d\"/>\n",
340                 i > 0 ? m_p->m_duration_lim[i - 1] : 0.0,
341                 m_p->m_duration_lim[i], m_p->m_duration_freq[i]);
342     }
343
344     if (m_p->m_duration_freq[i] > 0)
345         wrbuf_printf(
346             w, "    <response duration_start=\"%f\" frequency=\"%d\"/>\n",
347             m_p->m_duration_lim[i - 1], m_p->m_duration_freq[i]);
348
349     if (m_p->m_duration_max != 0.0)
350         wrbuf_printf(
351             w, "    <response duration_max=\"%f\"/>\n",
352             m_p->m_duration_max);
353     if (m_p->m_duration_min != 0.0)
354         wrbuf_printf(
355             w, "    <response duration_min=\"%f\"/>\n",
356             m_p->m_duration_min);
357     if (m_p->m_duration_total != 0.0)
358         wrbuf_printf(
359             w, "    <response duration_average=\"%f\"/>\n",
360             m_p->m_duration_total / number_total);
361
362     wrbuf_puts(w, " </responses>\n");
363
364     int thread_busy;
365     int thread_total;
366     m_thread_pool_observer->get_thread_info(thread_busy, thread_total);
367
368     wrbuf_printf(w, " <thread_info busy=\"%d\" total=\"%d\"/>\n",
369                  thread_busy, thread_total);
370
371     wrbuf_puts(w, "</frontend_net>\n");
372
373     hres->content_len = w.len();
374     hres->content_buf = (char *) w.buf();
375
376     int len;
377     send_GDU(gdu_res, &len);
378 }
379
380 void yf::FrontendNet::ZAssocChild::recv_GDU(Z_GDU *z_pdu, int len)
381 {
382     m_no_requests++;
383
384     mp::Package *p = new mp::Package(m_session, m_origin);
385
386     if (z_pdu && z_pdu->which == Z_GDU_HTTP_Request)
387     {
388         Z_HTTP_Request *hreq = z_pdu->u.HTTP_Request;
389
390         const char *f = z_HTTP_header_lookup(hreq->headers, "X-Forwarded-For");
391         if (f)
392             p->origin().set_tcpip_address(std::string(f), m_session.id());
393
394         if (m_p->m_stat_req.length()
395             && !strcmp(hreq->path, m_p->m_stat_req.c_str()))
396         {
397             report(hreq);
398             delete p;
399             return;
400         }
401     }
402
403     p->copy_route(*m_package);
404     p->request() = yazpp_1::GDU(z_pdu);
405
406     if (m_p->m_msg_config.length())
407     {
408         if (z_pdu)
409         {
410             std::ostringstream os;
411             os  << m_p->m_msg_config << " "
412                 << *p << " "
413                 << "0.000000" << " "
414                 << *z_pdu;
415             yaz_log(YLOG_LOG, "%s", os.str().c_str());
416         }
417     }
418     if (z_pdu && z_pdu->which == Z_GDU_HTTP_Request)
419     {
420         Z_HTTP_Request *hreq = z_pdu->u.HTTP_Request;
421         std::string peername = p->origin().get_address();
422
423         m_limit_http_req.cleanup(false);
424         int con_sz = m_limit_http_req.get_total(peername.c_str());
425         std::list<IP_Pattern>::const_iterator it = m_p->http_req_max.begin();
426         for (; it != m_p->http_req_max.end(); it++)
427         {
428             if (mp::util::match_ip(it->pattern, peername))
429             {
430                 if (it->verbose > 1 ||
431                     (it->value && con_sz >= it->value && it->verbose > 0))
432                     yaz_log(YLOG_LOG, "http-req-max pattern=%s ip=%s con_sz=%d value=%d", it->pattern.c_str(), peername.c_str(), con_sz, it->value);
433                 if (it->value == 0 || con_sz < it->value)
434                     break;
435                 mp::odr o;
436                 Z_GDU *gdu_res = o.create_HTTP_Response(m_session, hreq, 500);
437                 int len;
438                 send_GDU(gdu_res, &len);
439                 delete p;
440                 return;
441             }
442         }
443         m_limit_http_req.add_connect(peername.c_str());
444     }
445     ThreadPoolPackage *tp = new ThreadPoolPackage(p, this, m_p);
446     m_thread_pool_observer->put(tp);
447 }
448
449 void yf::FrontendNet::ZAssocChild::failNotify()
450 {
451     // TODO: send Package to signal "close"
452     if (m_session.is_closed())
453     {
454         if (m_no_requests == 0)
455             delete this;
456         return;
457     }
458     m_no_requests++;
459
460     m_session.close();
461
462     mp::Package *p = new mp::Package(m_session, m_origin);
463
464     ThreadPoolPackage *tp = new ThreadPoolPackage(p, this, m_p);
465     p->copy_route(*m_package);
466     m_thread_pool_observer->cleanup(tp, &m_session);
467     m_thread_pool_observer->put(tp);
468 }
469
470 void yf::FrontendNet::ZAssocChild::timeoutNotify()
471 {
472     failNotify();
473 }
474
475 void yf::FrontendNet::ZAssocChild::connectNotify()
476 {
477
478 }
479
480 yf::FrontendNet::ZAssocServer::ZAssocServer(
481     yazpp_1::IPDU_Observable *PDU_Observable,
482     Port *port,
483     Rep *rep)
484     :
485     Z_Assoc(PDU_Observable), m_port(port), m_p(rep)
486 {
487     m_package = 0;
488 }
489
490
491 void yf::FrontendNet::ZAssocServer::set_package(const mp::Package *package)
492 {
493     m_package = package;
494 }
495
496 void yf::FrontendNet::ZAssocServer::set_thread_pool(
497     mp::ThreadPoolSocketObserver *observer)
498 {
499     m_thread_pool_observer = observer;
500 }
501
502 yazpp_1::IPDU_Observer *yf::FrontendNet::ZAssocServer::sessionNotify(
503     yazpp_1::IPDU_Observable *the_PDU_Observable, int fd)
504 {
505
506     const char *peername = the_PDU_Observable->getpeername();
507     if (!peername)
508         peername = "unknown";
509     else
510     {
511         const char *cp = strchr(peername, ':');
512         if (cp)
513             peername = cp + 1;
514     }
515     if (peername)
516     {
517         limit_connect.cleanup(false);
518         int con_sz = limit_connect.get_total(peername);
519         std::list<IP_Pattern>::const_iterator it = m_p->connect_max.begin();
520         for (; it != m_p->connect_max.end(); it++)
521         {
522             if (mp::util::match_ip(it->pattern, peername))
523             {
524                 if (it->verbose > 1 ||
525                     (it->value && con_sz >= it->value && it->verbose > 0))
526                     yaz_log(YLOG_LOG, "connect-max pattern=%s ip=%s con_sz=%d value=%d", it->pattern.c_str(), peername, con_sz, it->value);
527                 if (it->value == 0 || con_sz < it->value)
528                     break;
529                 return 0;
530             }
531         }
532         limit_connect.add_connect(peername);
533     }
534     ZAssocChild *my = new ZAssocChild(the_PDU_Observable,
535                                       m_thread_pool_observer,
536                                       m_package, m_port, m_p, limit_http_req,
537                                       peername);
538     return my;
539 }
540
541 yf::FrontendNet::ZAssocServer::~ZAssocServer()
542 {
543 }
544
545 void yf::FrontendNet::ZAssocServer::recv_GDU(Z_GDU *apdu, int len)
546 {
547 }
548
549 void yf::FrontendNet::ZAssocServer::failNotify()
550 {
551 }
552
553 void yf::FrontendNet::ZAssocServer::timeoutNotify()
554 {
555 }
556
557 void yf::FrontendNet::ZAssocServer::connectNotify()
558 {
559 }
560
561 yf::FrontendNet::FrontendNet() : m_p(new Rep)
562 {
563 }
564
565 yf::FrontendNet::Rep::Rep()
566 {
567     m_max_threads = m_no_threads = 5;
568     m_stack_size = 0;
569     m_listen_duration = 0;
570     m_session_timeout = 300; // 5 minutes
571     az = 0;
572     size_t i;
573     for (i = 0; i < 22; i++)
574         m_duration_freq[i] = 0;
575     m_duration_lim[0] = 0.000001;
576     m_duration_lim[1] = 0.00001;
577     m_duration_lim[2] = 0.0001;
578     m_duration_lim[3] = 0.001;
579     m_duration_lim[4] = 0.01;
580     m_duration_lim[5] = 0.1;
581     m_duration_lim[6] = 0.2;
582     m_duration_lim[7] = 0.3;
583     m_duration_lim[8] = 0.5;
584     m_duration_lim[9] = 1.0;
585     m_duration_lim[10] = 1.5;
586     m_duration_lim[11] = 2.0;
587     m_duration_lim[12] = 3.0;
588     m_duration_lim[13] = 4.0;
589     m_duration_lim[14] = 5.0;
590     m_duration_lim[15] = 6.0;
591     m_duration_lim[16] = 8.0;
592     m_duration_lim[17] = 10.0;
593     m_duration_lim[18] = 15.0;
594     m_duration_lim[19] = 20.0;
595     m_duration_lim[20] = 30.0;
596     m_duration_lim[21] = 0.0;
597     m_duration_max = 0.0;
598     m_duration_min = 0.0;
599     m_duration_total = 0.0;
600     m_stop_signo = 0;
601 }
602
603 yf::FrontendNet::Rep::~Rep()
604 {
605     if (az)
606     {
607         size_t i;
608         for (i = 0; i < m_ports.size(); i++)
609             delete az[i];
610         delete [] az;
611         delete [] pdu;
612     }
613     az = 0;
614 }
615
616 yf::FrontendNet::~FrontendNet()
617 {
618 }
619
620 void yf::FrontendNet::stop(int signo) const
621 {
622     m_p->m_stop_signo = signo;
623 }
624
625 void yf::FrontendNet::start() const
626 {
627 #if HAVE_GETRLIMIT
628     struct rlimit limit_data;
629     getrlimit(RLIMIT_NOFILE, &limit_data);
630     yaz_log(YLOG_LOG, "getrlimit NOFILE cur=%ld max=%ld",
631             (long) limit_data.rlim_cur, (long) limit_data.rlim_max);
632 #endif
633 }
634
635 bool yf::FrontendNet::My_Timer_Thread::timeout()
636 {
637     return m_timeout;
638 }
639
640 yf::FrontendNet::My_Timer_Thread::My_Timer_Thread(
641     yazpp_1::ISocketObservable *obs,
642     int duration) :
643     m_obs(obs), m_pipe(9123), m_timeout(false)
644 {
645     obs->addObserver(m_pipe.read_fd(), this);
646     obs->maskObserver(this, yazpp_1::SOCKET_OBSERVE_READ);
647     obs->timeoutObserver(this, duration);
648 }
649
650 void yf::FrontendNet::My_Timer_Thread::socketNotify(int event)
651 {
652     m_timeout = true;
653     m_obs->deleteObserver(this);
654 }
655
656 void yf::FrontendNet::process(mp::Package &package) const
657 {
658     if (m_p->az == 0)
659         return;
660     size_t i;
661     My_Timer_Thread *tt = 0;
662
663     if (m_p->m_listen_duration)
664         tt = new My_Timer_Thread(&m_p->mySocketManager,
665                                  m_p->m_listen_duration);
666
667     ThreadPoolSocketObserver tp(&m_p->mySocketManager, m_p->m_no_threads,
668                                 m_p->m_max_threads,
669                                 m_p->m_stack_size);
670
671     for (i = 0; i<m_p->m_ports.size(); i++)
672     {
673         m_p->az[i]->set_package(&package);
674         m_p->az[i]->set_thread_pool(&tp);
675     }
676     while (m_p->mySocketManager.processEvent() > 0)
677     {
678         if (m_p->m_stop_signo == SIGTERM)
679         {
680             yaz_log(YLOG_LOG, "metaproxy received SIGTERM");
681             if (m_p->az)
682             {
683                 size_t i;
684                 for (i = 0; i < m_p->m_ports.size(); i++)
685                 {
686                     m_p->pdu[i]->shutdown();
687                     m_p->az[i]->server("");
688                 }
689                 yaz_daemon_stop();
690             }
691             break; /* stop right away */
692         }
693 #ifndef WIN32
694         if (m_p->m_stop_signo == SIGUSR1)
695         {    /* just stop listeners and cont till all sessions are done*/
696             yaz_log(YLOG_LOG, "metaproxy received SIGUSR1");
697             m_p->m_stop_signo = 0;
698             if (m_p->az)
699             {
700                 size_t i;
701                 for (i = 0; i < m_p->m_ports.size(); i++)
702                     m_p->az[i]->server("");
703                 yaz_daemon_stop();
704             }
705         }
706 #endif
707         int no = m_p->mySocketManager.getNumberOfObservers();
708         if (no <= 1)
709             break;
710         if (tt && tt->timeout())
711             break;
712     }
713     delete tt;
714 }
715
716 void yf::FrontendNet::configure(const xmlNode * ptr, bool test_only,
717                                 const char *path)
718 {
719     if (!ptr || !ptr->children)
720     {
721         throw yf::FilterException("No ports for Frontend");
722     }
723     std::vector<Port> ports;
724     for (ptr = ptr->children; ptr; ptr = ptr->next)
725     {
726         if (ptr->type != XML_ELEMENT_NODE)
727             continue;
728         if (!strcmp((const char *) ptr->name, "port"))
729         {
730             Port port;
731
732             const char *names[5] = {"route", "max_recv_bytes", "port",
733                                     "cert_fname", 0};
734             std::string values[4];
735
736             mp::xml::parse_attr(ptr, names, values);
737             port.route = values[0];
738             if (values[1].length() > 0)
739                 port.max_recv_bytes = atoi(values[1].c_str());
740             else
741                 port.max_recv_bytes = 0;
742             if (values[2].length() > 0)
743                 port.port = values[2];
744             else
745                 port.port = mp::xml::get_text(ptr);
746             port.cert_fname = values[3];
747             ports.push_back(port);
748         }
749         else if (!strcmp((const char *) ptr->name, "threads"))
750         {
751             std::string threads_str = mp::xml::get_text(ptr);
752             int threads = atoi(threads_str.c_str());
753             if (threads < 1)
754                 throw yf::FilterException("Bad value for threads: "
755                                                    + threads_str);
756             m_p->m_no_threads = threads;
757         }
758         else if (!strcmp((const char *) ptr->name, "max-threads"))
759         {
760             std::string threads_str = mp::xml::get_text(ptr);
761             int threads = atoi(threads_str.c_str());
762             if (threads < 1)
763                 throw yf::FilterException("Bad value for max-threads: "
764                                                    + threads_str);
765             m_p->m_max_threads = threads;
766         }
767         else if (!strcmp((const char *) ptr->name, "stack-size"))
768         {
769             std::string sz_str = mp::xml::get_text(ptr);
770             int sz = atoi(sz_str.c_str());
771             if (sz < 0)
772                 throw yf::FilterException("Bad value for stack-size: "
773                                                    + sz_str);
774             m_p->m_stack_size = sz * 1024;
775         }
776         else if (!strcmp((const char *) ptr->name, "timeout"))
777         {
778             std::string timeout_str = mp::xml::get_text(ptr);
779             int timeout = atoi(timeout_str.c_str());
780             if (timeout < 1)
781                 throw yf::FilterException("Bad value for timeout: "
782                                                    + timeout_str);
783             m_p->m_session_timeout = timeout;
784         }
785         else if (!strcmp((const char *) ptr->name, "connect-max"))
786         {
787             const char *names[3] = {"ip", "verbose", 0};
788             std::string values[2];
789
790             mp::xml::parse_attr(ptr, names, values);
791             IP_Pattern m;
792             m.value = mp::xml::get_int(ptr, 0);
793             m.pattern = values[0];
794             m.verbose = values[1].length() ? atoi(values[1].c_str()) : 1;
795             m_p->connect_max.push_back(m);
796         }
797         else if (!strcmp((const char *) ptr->name, "http-req-max"))
798         {
799             const char *names[3] = {"ip", "verbose", 0};
800             std::string values[2];
801
802             mp::xml::parse_attr(ptr, names, values);
803             IP_Pattern m;
804             m.value = mp::xml::get_int(ptr, 0);
805             m.pattern = values[0];
806             m.verbose = values[1].length() ? atoi(values[1].c_str()) : 1;
807             m_p->http_req_max.push_back(m);
808         }
809         else if (!strcmp((const char *) ptr->name, "message"))
810         {
811             m_p->m_msg_config = mp::xml::get_text(ptr);
812         }
813         else if (!strcmp((const char *) ptr->name, "stat-req"))
814         {
815             m_p->m_stat_req = mp::xml::get_text(ptr);
816         }
817         else
818         {
819             throw yf::FilterException("Bad element "
820                                       + std::string((const char *)
821                                                     ptr->name));
822         }
823     }
824     if (test_only)
825         return;
826     set_ports(ports);
827 }
828
829 void yf::FrontendNet::set_ports(std::vector<std::string> &ports)
830 {
831     std::vector<Port> nports;
832     size_t i;
833
834     for (i = 0; i < ports.size(); i++)
835     {
836         Port nport;
837
838         nport.port = ports[i];
839
840         nports.push_back(nport);
841     }
842     set_ports(nports);
843 }
844
845
846 void yf::FrontendNet::set_ports(std::vector<Port> &ports)
847 {
848     m_p->m_ports = ports;
849
850     m_p->az = new yf::FrontendNet::ZAssocServer *[m_p->m_ports.size()];
851     m_p->pdu = new yazpp_1::PDU_Assoc *[m_p->m_ports.size()];
852
853     // Create yf::FrontendNet::ZAssocServer for each port
854     size_t i;
855     for (i = 0; i < m_p->m_ports.size(); i++)
856         m_p->az[i] = 0;
857     for (i = 0; i < m_p->m_ports.size(); i++)
858     {
859         // create a PDU assoc object (one per yf::FrontendNet::ZAssocServer)
860         yazpp_1::PDU_Assoc *as = new yazpp_1::PDU_Assoc(&m_p->mySocketManager);
861
862         if (m_p->m_ports[i].cert_fname.length())
863             as->set_cert_fname(m_p->m_ports[i].cert_fname.c_str());
864         // create ZAssoc with PDU Assoc
865         m_p->pdu[i] = as;
866         m_p->az[i] = new yf::FrontendNet::ZAssocServer(
867             as, &m_p->m_ports[i], m_p.get());
868         if (m_p->az[i]->server(m_p->m_ports[i].port.c_str()))
869         {
870             throw yf::FilterException("Unable to bind to address "
871                                       + std::string(m_p->m_ports[i].port));
872         }
873         COMSTACK cs = as->get_comstack();
874
875         if (cs && m_p->m_ports[i].max_recv_bytes)
876             cs_set_max_recv_bytes(cs, m_p->m_ports[i].max_recv_bytes);
877
878     }
879 }
880
881 void yf::FrontendNet::set_listen_duration(int d)
882 {
883     m_p->m_listen_duration = d;
884 }
885
886 static yf::Base* filter_creator()
887 {
888     return new yf::FrontendNet;
889 }
890
891 extern "C" {
892     struct metaproxy_1_filter_struct metaproxy_1_filter_frontend_net = {
893         0,
894         "frontend_net",
895         filter_creator
896     };
897 }
898
899 /*
900  * Local variables:
901  * c-basic-offset: 4
902  * c-file-style: "Stroustrup"
903  * indent-tabs-mode: nil
904  * End:
905  * vim: shiftwidth=4 tabstop=8 expandtab
906  */
907