Merge branch 'master' of ssh://git.indexdata.com/home/git/pub/yazproxy
[yazproxy-moved-to-github.git] / src / limit-connect.cpp
1 /* This file is part of YAZ proxy
2    Copyright (C) 1998-2009 Index Data
3
4 YAZ proxy 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 YAZ proxy 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 <yazproxy/limit-connect.h>
20
21 #include <time.h>
22 #include <string.h>
23 #include <yaz/xmalloc.h>
24
25 struct LimitConnect::Peer {
26     friend class LimitConnect;
27     
28     Peer(int sz, const char *peername);
29     ~Peer();
30     void add_connect();
31     
32     char *m_peername;
33     Yaz_bw m_bw;
34     Peer *m_next;
35 };
36
37 LimitConnect::LimitConnect()
38 {
39     m_period = 60;
40     m_peers = 0;
41 }
42
43
44 LimitConnect::~LimitConnect()
45 {
46     cleanup(true);
47 }
48
49 void LimitConnect::set_period(int sec)
50 {
51     m_period = sec;
52 }
53
54 LimitConnect::Peer::Peer(int sz, const char *peername) : m_bw(sz)
55 {
56     m_peername = xstrdup(peername);
57     m_next = 0;
58 }
59
60 LimitConnect::Peer::~Peer()
61 {
62     xfree(m_peername);
63 }
64
65 void LimitConnect::Peer::add_connect()
66 {
67     m_bw.add_bytes(1);
68 }
69
70 LimitConnect::Peer **LimitConnect::lookup(const char *peername)
71 {
72     Peer **p = &m_peers;
73     while (*p)
74     {
75         if (!strcmp((*p)->m_peername, peername))
76             break;
77         p = &(*p)->m_next;
78     }
79     return p;
80 }
81
82 void LimitConnect::add_connect(const char *peername)
83 {
84     Peer **p = lookup(peername);
85     if (!*p)
86         *p = new Peer(m_period, peername);
87     (*p)->add_connect();
88 }
89
90 int LimitConnect::get_total(const char *peername)
91 {
92     Peer **p = lookup(peername);
93     if (!*p)
94         return 0;
95     return (*p)->m_bw.get_total();
96 }
97
98 void LimitConnect::cleanup(bool all)
99 {
100     Peer **p = &m_peers;
101     while (*p)
102     {
103         Peer *tp = *p;
104         if (all || (tp->m_bw.get_total() == 0))
105         {
106             *p = tp->m_next;
107             delete tp;
108         }
109         else
110             p = &tp->m_next;
111     }
112 }
113
114 /*
115  * Local variables:
116  * c-basic-offset: 4
117  * c-file-style: "Stroustrup"
118  * indent-tabs-mode: nil
119  * End:
120  * vim: shiftwidth=4 tabstop=8 expandtab
121  */
122