9197ea3356ace4f0611d275e730a9217ca931f71
[yazproxy-moved-to-github.git] / src / limit-connect.cpp
1 /* $Id: limit-connect.cpp,v 1.1 2006-03-30 10:35:15 adam Exp $
2    Copyright (c) 1998-2006, Index Data.
3
4 This file is part of the yazproxy.
5
6 YAZ proxy is free software; you can redistribute it and/or modify it under
7 the terms of the GNU General Public License as published by the Free
8 Software Foundation; either version 2, or (at your option) any later
9 version.
10
11 YAZ proxy is distributed in the hope that it will be useful, but WITHOUT ANY
12 WARRANTY; without even the implied warranty of MERCHANTABILITY or
13 FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
14 for more details.
15
16 You should have received a copy of the GNU General Public License
17 along with YAZ proxy; see the file LICENSE.  If not, write to the
18 Free Software Foundation, 59 Temple Place - Suite 330, Boston, MA
19 02111-1307, USA.
20 */
21
22 #include <yazproxy/limit-connect.h>
23
24 #include <time.h>
25 #include <string.h>
26 #include <yaz/xmalloc.h>
27
28 struct LimitConnect::Peer {
29     friend class LimitConnect;
30     
31     Peer(int sz, const char *peername);
32     ~Peer();
33     void add_connect();
34     
35     char *m_peername;
36     Yaz_bw m_bw;
37     Peer *m_next;
38 };
39
40 LimitConnect::LimitConnect()
41 {
42     m_period = 60;
43     m_peers = 0;
44 }
45
46 LimitConnect::~LimitConnect()
47 {
48     cleanup(true);
49 }
50
51 LimitConnect::Peer::Peer(int sz, const char *peername) : m_bw(sz)
52 {
53     m_peername = xstrdup(peername);
54     m_next = 0;
55 }
56
57 LimitConnect::Peer::~Peer()
58 {
59     xfree(m_peername);
60 }
61
62 void LimitConnect::Peer::add_connect()
63 {
64     m_bw.add_bytes(1);
65 }
66
67 LimitConnect::Peer **LimitConnect::lookup(const char *peername)
68 {
69     Peer **p = &m_peers;
70     while (*p)
71     {
72         if (!strcmp((*p)->m_peername, peername))
73             break;
74         p = &(*p)->m_next;
75     }
76     return p;
77 }
78
79 void LimitConnect::add_connect(const char *peername)
80 {
81     Peer **p = lookup(peername);
82     if (!*p)
83         *p = new Peer(m_period, peername);
84     (*p)->add_connect();
85 }
86
87 int LimitConnect::get_total(const char *peername)
88 {
89     Peer **p = lookup(peername);
90     if (!*p)
91         return 0;
92     return (*p)->m_bw.get_total();
93 }
94
95 void LimitConnect::cleanup(bool all)
96 {
97     Peer **p = &m_peers;
98     while (*p)
99     {
100         Peer *tp = *p;
101         if (all || (tp->m_bw.get_total() == 0))
102         {
103             *p = tp->m_next;
104             delete tp;
105         }
106         else
107             p = &tp->m_next;
108     }
109 }
110
111 /*
112  * Local variables:
113  * c-basic-offset: 4
114  * indent-tabs-mode: nil
115  * End:
116  * vim: shiftwidth=4 tabstop=8 expandtab
117  */