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