]> git.stg.codes - stg.git/blob - projects/stargazer/plugins/configuration/sgconfig/configproto.cpp
Finished new implementation of sgconfig plugin.
[stg.git] / projects / stargazer / plugins / configuration / sgconfig / configproto.cpp
1 /*
2  *    This program is free software; you can redistribute it and/or modify
3  *    it under the terms of the GNU General Public License as published by
4  *    the Free Software Foundation; either version 2 of the License, or
5  *    (at your option) any later version.
6  *
7  *    This program is distributed in the hope that it will be useful,
8  *    but WITHOUT ANY WARRANTY; without even the implied warranty of
9  *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
10  *    GNU General Public License for more details.
11  *
12  *    You should have received a copy of the GNU General Public License
13  *    along with this program; if not, write to the Free Software
14  *    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
15  */
16
17 /*
18  *    Author : Boris Mikhailenko <stg34@stargazer.dp.ua>
19  *    Author : Maxim Mamontov <faust@stargazer.dp.ua>
20  */
21
22
23 #include "conn.h"
24
25 #include "parser_server_info.h"
26 #include "parser_admins.h"
27 #include "parser_tariffs.h"
28 #include "parser_users.h"
29 #include "parser_message.h"
30 #include "parser_user_info.h"
31 #include "parser_auth_by.h"
32
33 #include "stg/common.h"
34 #include "stg/logger.h"
35
36 #include <algorithm>
37 #include <functional>
38 #include <vector>
39 #include <csignal>
40 #include <cstring>
41 #include <cerrno>
42 #include <cassert>
43
44 #include <sys/types.h>
45 #include <sys/socket.h>
46 #include <netinet/in.h>
47 #include <netdb.h>
48
49 namespace SP = STG::PARSER;
50
51 CONFIGPROTO::CONFIGPROTO(PLUGIN_LOGGER & l)
52     : m_settings(NULL),
53       m_admins(NULL),
54       m_tariffs(NULL),
55       m_users(NULL),
56       m_port(0),
57       m_bindAddress("0.0.0.0"),
58       m_running(false),
59       m_stopped(true),
60       m_logger(l),
61       m_listenSocket(-1)
62 {
63 }
64
65 CONFIGPROTO::~CONFIGPROTO()
66 {
67     std::deque<STG::Conn *>::iterator it;
68     for (it = m_conns.begin(); it != m_conns.end(); ++it)
69         delete *it;
70 }
71
72 int CONFIGPROTO::Prepare()
73 {
74     sigset_t sigmask, oldmask;
75     sigemptyset(&sigmask);
76     sigaddset(&sigmask, SIGINT);
77     sigaddset(&sigmask, SIGTERM);
78     sigaddset(&sigmask, SIGUSR1);
79     sigaddset(&sigmask, SIGHUP);
80     pthread_sigmask(SIG_BLOCK, &sigmask, &oldmask);
81
82     m_listenSocket = socket(PF_INET, SOCK_STREAM, 0);
83
84     if (m_listenSocket < 0)
85     {
86         m_errorStr = std::string("Cannot create listen socket: '") + strerror(errno) + "'.";
87         m_logger(m_errorStr);
88         return -1;
89     }
90
91     int dummy = 1;
92
93     if (setsockopt(m_listenSocket, SOL_SOCKET, SO_REUSEADDR, &dummy, 4) != 0)
94     {
95         m_errorStr = std::string("Failed to set SO_REUSEADDR to the listen socket: '") + strerror(errno) + "'.";
96         m_logger(m_errorStr);
97         return -1;
98     }
99
100     if (!Bind())
101         return -1;
102
103     if (listen(m_listenSocket, 64) == -1) // TODO: backlog length
104     {
105         m_errorStr = std::string("Failed to start listening for connections: '") + strerror(errno) + "'.";
106         m_logger(m_errorStr);
107         return -1;
108     }
109
110     RegisterParsers();
111
112     m_running = true;
113     m_stopped = false;
114     return 0;
115 }
116
117 int CONFIGPROTO::Stop()
118 {
119     m_running = false;
120     for (int i = 0; i < 5 && !m_stopped; ++i)
121     {
122         struct timespec ts = {0, 200000000};
123         nanosleep(&ts, NULL);
124     }
125
126     if (!m_stopped)
127     {
128         m_errorStr = "Cannot stop listenign thread.";
129         m_logger(m_errorStr);
130         return -1;
131     }
132
133     shutdown(m_listenSocket, SHUT_RDWR);
134     close(m_listenSocket);
135     return 0;
136 }
137
138 void CONFIGPROTO::Run()
139 {
140     while (m_running)
141     {
142         fd_set fds;
143
144         BuildFDSet(fds);
145
146         struct timeval tv;
147         tv.tv_sec = 0;
148         tv.tv_usec = 500000;
149
150         int res = select(MaxFD() + 1, &fds, NULL, NULL, &tv);
151         if (res < 0)
152         {
153             m_errorStr = std::string("'select' is failed: '") + strerror(errno) + "'.";
154             printfd(__FILE__, "%s\n", m_errorStr.c_str());
155             m_logger(m_errorStr);
156             break;
157         }
158         if (!m_running)
159             break;
160         if (res > 0)
161         {
162             printfd(__FILE__, "Something happend - received %d events.\n", res);
163             HandleEvents(fds);
164         }
165
166         CleanupConns();
167     }
168     m_stopped = true;
169 }
170
171 bool CONFIGPROTO::Bind()
172 {
173     const hostent * he = gethostbyname(m_bindAddress.c_str());
174     if (he == NULL)
175     {
176         m_errorStr = "Failed to resolve name '" + m_bindAddress + "': '" + hstrerror(h_errno) + "'.";
177         printfd(__FILE__, "%s\n", m_errorStr.c_str());
178         m_logger(m_errorStr);
179         return false;
180     }
181
182     char ** ptr = he->h_addr_list;
183     while (*ptr != NULL)
184     {
185         struct sockaddr_in listenAddr;
186         listenAddr.sin_family = PF_INET;
187         listenAddr.sin_port = htons(m_port);
188         listenAddr.sin_addr.s_addr = *reinterpret_cast<in_addr_t *>(*ptr);
189
190         printfd(__FILE__, "Trying to bind to %s:%d\n", inet_ntostring(listenAddr.sin_addr.s_addr).c_str(), m_port);
191
192         if (bind(m_listenSocket, reinterpret_cast<sockaddr *>(&listenAddr), sizeof(listenAddr)) == 0)
193             return true;
194
195         m_errorStr = std::string("Cannot bind listen socket: '") + strerror(errno) + "'.";
196         printfd(__FILE__, "%s\n", m_errorStr.c_str());
197         m_logger(m_errorStr);
198
199         ++ptr;
200     }
201
202     return false;
203 }
204
205 void CONFIGPROTO::RegisterParsers()
206 {
207     assert(m_settings != NULL);
208     assert(m_store != NULL);
209     assert(m_admins != NULL);
210     assert(m_users != NULL);
211     assert(m_tariffs != NULL);
212
213     SP::GET_SERVER_INFO::FACTORY::Register(m_registry, *m_settings, *m_users, *m_tariffs);
214
215     SP::GET_ADMINS::FACTORY::Register(m_registry, *m_admins);
216     SP::ADD_ADMIN::FACTORY::Register(m_registry, *m_admins);
217     SP::DEL_ADMIN::FACTORY::Register(m_registry, *m_admins);
218     SP::CHG_ADMIN::FACTORY::Register(m_registry, *m_admins);
219
220     SP::GET_TARIFFS::FACTORY::Register(m_registry, *m_tariffs);
221     SP::ADD_TARIFF::FACTORY::Register(m_registry, *m_tariffs);
222     SP::DEL_TARIFF::FACTORY::Register(m_registry, *m_tariffs, *m_users);
223     SP::CHG_TARIFF::FACTORY::Register(m_registry, *m_tariffs);
224
225     SP::GET_USERS::FACTORY::Register(m_registry, *m_users);
226     SP::GET_USER::FACTORY::Register(m_registry, *m_users);
227     SP::ADD_USER::FACTORY::Register(m_registry, *m_users);
228     SP::DEL_USER::FACTORY::Register(m_registry, *m_users);
229     SP::CHG_USER::FACTORY::Register(m_registry, *m_users, *m_store, *m_tariffs);
230     SP::CHECK_USER::FACTORY::Register(m_registry, *m_users);
231
232     SP::SEND_MESSAGE::FACTORY::Register(m_registry, *m_users);
233
234     SP::AUTH_BY::FACTORY::Register(m_registry, *m_users);
235
236     SP::USER_INFO::FACTORY::Register(m_registry, *m_users);
237 }
238
239 int CONFIGPROTO::MaxFD() const
240 {
241     int maxFD = m_listenSocket;
242     std::deque<STG::Conn *>::const_iterator it;
243     for (it = m_conns.begin(); it != m_conns.end(); ++it)
244         if (maxFD < (*it)->Sock())
245             maxFD = (*it)->Sock();
246     return maxFD;
247 }
248
249 void CONFIGPROTO::BuildFDSet(fd_set & fds) const
250 {
251     printfd(__FILE__, "Building fd set for %d connections.\n", m_conns.size());
252     FD_ZERO(&fds);
253     FD_SET(m_listenSocket, &fds);
254     std::deque<STG::Conn *>::const_iterator it;
255     for (it = m_conns.begin(); it != m_conns.end(); ++it)
256         FD_SET((*it)->Sock(), &fds);
257 }
258
259 void CONFIGPROTO::CleanupConns()
260 {
261     size_t old = m_conns.size();
262
263     std::deque<STG::Conn *>::iterator pos;
264     for (pos = m_conns.begin(); pos != m_conns.end(); ++pos)
265         if (((*pos)->IsDone() && !(*pos)->IsKeepAlive()) || !(*pos)->IsOk())
266         {
267             delete *pos;
268             *pos = NULL;
269         }
270
271     pos = std::remove(m_conns.begin(), m_conns.end(), static_cast<STG::Conn *>(NULL));
272     m_conns.erase(pos, m_conns.end());
273
274     if (m_conns.size() < old)
275         printfd(__FILE__, "Cleaned up %d connections.\n", old - m_conns.size());
276 }
277
278 void CONFIGPROTO::HandleEvents(const fd_set & fds)
279 {
280     if (FD_ISSET(m_listenSocket, &fds))
281         AcceptConnection();
282     else
283     {
284         std::deque<STG::Conn *>::iterator it;
285         for (it = m_conns.begin(); it != m_conns.end(); ++it)
286             if (FD_ISSET((*it)->Sock(), &fds))
287             {
288                 printfd(__FILE__, "Reading data from %s:%d.\n", inet_ntostring((*it)->IP()).c_str(), (*it)->Port());
289                 (*it)->Read();
290             }
291     }
292 }
293
294 void CONFIGPROTO::AcceptConnection()
295 {
296     printfd(__FILE__, "Accepting new connection.\n");
297
298     struct sockaddr_in outerAddr;
299     socklen_t outerAddrLen(sizeof(outerAddr));
300     int sock = accept(m_listenSocket, reinterpret_cast<sockaddr *>(&outerAddr), &outerAddrLen);
301
302     if (sock < 0)
303     {
304         m_errorStr = std::string("Failed to accept connection: '") + strerror(errno) + "'.";
305         printfd(__FILE__, "%s\n", m_errorStr.c_str());
306         m_logger(m_errorStr);
307         return;
308     }
309
310     assert(m_admins != NULL);
311
312     try
313     {
314         m_conns.push_back(new STG::Conn(m_registry, *m_admins, sock, outerAddr));
315         printfd(__FILE__, "New connection from %s:%d. Total connections: %d\n", inet_ntostring(m_conns.back()->IP()).c_str(), m_conns.back()->Port(), m_conns.size());
316     }
317     catch (const STG::Conn::Error & error)
318     {
319         // Unlikely.
320         m_logger(std::string("Failed to create new client connection: '") + error.what() + "'.");
321     }
322 }
323 /*
324 void CONFIGPROTO::WriteLogAccessFailed(uint32_t ip)
325 {
326     m_logger("Admin's connection failed. IP %s", inet_ntostring(ip).c_str());
327 }
328 */