]> git.stg.codes - stg.git/blob - projects/stargazer/plugins/configuration/sgconfig/configproto.cpp
Various fixes of issues reported by static analyzers.
[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_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_store(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     {
69     std::deque<STG::Conn *>::iterator it;
70     for (it = m_conns.begin(); it != m_conns.end(); ++it)
71         delete *it;
72     }
73     {
74     BASE_PARSER::REGISTRY::iterator it;
75     for (it = m_registry.begin(); it != m_registry.end(); ++it)
76         delete it->second;
77     }
78 }
79
80 int CONFIGPROTO::Prepare()
81 {
82     sigset_t sigmask, oldmask;
83     sigemptyset(&sigmask);
84     sigaddset(&sigmask, SIGINT);
85     sigaddset(&sigmask, SIGTERM);
86     sigaddset(&sigmask, SIGUSR1);
87     sigaddset(&sigmask, SIGHUP);
88     pthread_sigmask(SIG_BLOCK, &sigmask, &oldmask);
89
90     m_listenSocket = socket(PF_INET, SOCK_STREAM, 0);
91
92     if (m_listenSocket < 0)
93     {
94         m_errorStr = std::string("Cannot create listen socket: '") + strerror(errno) + "'.";
95         m_logger(m_errorStr);
96         return -1;
97     }
98
99     int dummy = 1;
100
101     if (setsockopt(m_listenSocket, SOL_SOCKET, SO_REUSEADDR, &dummy, 4) != 0)
102     {
103         m_errorStr = std::string("Failed to set SO_REUSEADDR to the listen socket: '") + strerror(errno) + "'.";
104         m_logger(m_errorStr);
105         return -1;
106     }
107
108     if (!Bind())
109         return -1;
110
111     if (listen(m_listenSocket, 64) == -1) // TODO: backlog length
112     {
113         m_errorStr = std::string("Failed to start listening for connections: '") + strerror(errno) + "'.";
114         m_logger(m_errorStr);
115         return -1;
116     }
117
118     RegisterParsers();
119
120     m_running = true;
121     m_stopped = false;
122     return 0;
123 }
124
125 int CONFIGPROTO::Stop()
126 {
127     m_running = false;
128     for (int i = 0; i < 5 && !m_stopped; ++i)
129     {
130         struct timespec ts = {0, 200000000};
131         nanosleep(&ts, NULL);
132     }
133
134     if (!m_stopped)
135     {
136         m_errorStr = "Cannot stop listenign thread.";
137         m_logger(m_errorStr);
138         return -1;
139     }
140
141     shutdown(m_listenSocket, SHUT_RDWR);
142     close(m_listenSocket);
143     return 0;
144 }
145
146 void CONFIGPROTO::Run()
147 {
148     while (m_running)
149     {
150         fd_set fds;
151
152         BuildFDSet(fds);
153
154         struct timeval tv;
155         tv.tv_sec = 0;
156         tv.tv_usec = 500000;
157
158         int res = select(MaxFD() + 1, &fds, NULL, NULL, &tv);
159         if (res < 0)
160         {
161             m_errorStr = std::string("'select' is failed: '") + strerror(errno) + "'.";
162             printfd(__FILE__, "%s\n", m_errorStr.c_str());
163             m_logger(m_errorStr);
164             break;
165         }
166         if (!m_running)
167             break;
168         if (res > 0)
169             HandleEvents(fds);
170
171         CleanupConns();
172     }
173     m_stopped = true;
174 }
175
176 bool CONFIGPROTO::Bind()
177 {
178     const hostent * he = gethostbyname(m_bindAddress.c_str());
179     if (he == NULL)
180     {
181         m_errorStr = "Failed to resolve name '" + m_bindAddress + "': '" + hstrerror(h_errno) + "'.";
182         printfd(__FILE__, "%s\n", m_errorStr.c_str());
183         m_logger(m_errorStr);
184         return false;
185     }
186
187     char ** ptr = he->h_addr_list;
188     while (*ptr != NULL)
189     {
190         struct sockaddr_in listenAddr;
191         listenAddr.sin_family = PF_INET;
192         listenAddr.sin_port = htons(m_port);
193         listenAddr.sin_addr.s_addr = *reinterpret_cast<in_addr_t *>(*ptr);
194
195         printfd(__FILE__, "Trying to bind to %s:%d\n", inet_ntostring(listenAddr.sin_addr.s_addr).c_str(), m_port);
196
197         if (bind(m_listenSocket, reinterpret_cast<sockaddr *>(&listenAddr), sizeof(listenAddr)) == 0)
198             return true;
199
200         m_errorStr = std::string("Cannot bind listen socket: '") + strerror(errno) + "'.";
201         printfd(__FILE__, "%s\n", m_errorStr.c_str());
202         m_logger(m_errorStr);
203
204         ++ptr;
205     }
206
207     return false;
208 }
209
210 void CONFIGPROTO::RegisterParsers()
211 {
212     assert(m_settings != NULL);
213     assert(m_store != NULL);
214     assert(m_admins != NULL);
215     assert(m_users != NULL);
216     assert(m_tariffs != NULL);
217
218     SP::GET_SERVER_INFO::FACTORY::Register(m_registry, *m_settings, *m_users, *m_tariffs);
219
220     SP::GET_ADMINS::FACTORY::Register(m_registry, *m_admins);
221     SP::ADD_ADMIN::FACTORY::Register(m_registry, *m_admins);
222     SP::DEL_ADMIN::FACTORY::Register(m_registry, *m_admins);
223     SP::CHG_ADMIN::FACTORY::Register(m_registry, *m_admins);
224
225     SP::GET_TARIFFS::FACTORY::Register(m_registry, *m_tariffs);
226     SP::ADD_TARIFF::FACTORY::Register(m_registry, *m_tariffs);
227     SP::DEL_TARIFF::FACTORY::Register(m_registry, *m_tariffs, *m_users);
228     SP::CHG_TARIFF::FACTORY::Register(m_registry, *m_tariffs);
229
230     SP::GET_USERS::FACTORY::Register(m_registry, *m_users);
231     SP::GET_USER::FACTORY::Register(m_registry, *m_users);
232     SP::ADD_USER::FACTORY::Register(m_registry, *m_users);
233     SP::DEL_USER::FACTORY::Register(m_registry, *m_users);
234     SP::CHG_USER::FACTORY::Register(m_registry, *m_users, *m_store, *m_tariffs);
235     SP::CHECK_USER::FACTORY::Register(m_registry, *m_users);
236
237     SP::SEND_MESSAGE::FACTORY::Register(m_registry, *m_users);
238
239     SP::AUTH_BY::FACTORY::Register(m_registry, *m_users);
240 }
241
242 int CONFIGPROTO::MaxFD() const
243 {
244     int maxFD = m_listenSocket;
245     std::deque<STG::Conn *>::const_iterator it;
246     for (it = m_conns.begin(); it != m_conns.end(); ++it)
247         if (maxFD < (*it)->Sock())
248             maxFD = (*it)->Sock();
249     return maxFD;
250 }
251
252 void CONFIGPROTO::BuildFDSet(fd_set & fds) const
253 {
254     FD_ZERO(&fds);
255     FD_SET(m_listenSocket, &fds);
256     std::deque<STG::Conn *>::const_iterator it;
257     for (it = m_conns.begin(); it != m_conns.end(); ++it)
258         FD_SET((*it)->Sock(), &fds);
259 }
260
261 void CONFIGPROTO::CleanupConns()
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
275 void CONFIGPROTO::HandleEvents(const fd_set & fds)
276 {
277     if (FD_ISSET(m_listenSocket, &fds))
278         AcceptConnection();
279     else
280     {
281         std::deque<STG::Conn *>::iterator it;
282         for (it = m_conns.begin(); it != m_conns.end(); ++it)
283             if (FD_ISSET((*it)->Sock(), &fds))
284                 (*it)->Read();
285     }
286 }
287
288 void CONFIGPROTO::AcceptConnection()
289 {
290     struct sockaddr_in outerAddr;
291     socklen_t outerAddrLen(sizeof(outerAddr));
292     int sock = accept(m_listenSocket, reinterpret_cast<sockaddr *>(&outerAddr), &outerAddrLen);
293
294     if (sock < 0)
295     {
296         m_errorStr = std::string("Failed to accept connection: '") + strerror(errno) + "'.";
297         printfd(__FILE__, "%s\n", m_errorStr.c_str());
298         m_logger(m_errorStr);
299         return;
300     }
301
302     assert(m_admins != NULL);
303
304     try
305     {
306         m_conns.push_back(new STG::Conn(m_registry, *m_admins, sock, outerAddr, m_logger));
307         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());
308     }
309     catch (const STG::Conn::Error & error)
310     {
311         // Unlikely.
312         m_logger(std::string("Failed to create new client connection: '") + error.what() + "'.");
313     }
314 }