]> git.stg.codes - stg.git/blob - projects/stargazer/plugins/configuration/sgconfig/configproto.cpp
Handle failures in Conn ctor.
[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 "stg/common.h"
26 #include "stg/logger.h"
27
28 #include <algorithm>
29 #include <functional>
30 #include <csignal>
31 #include <cstring>
32 #include <cerrno>
33 #include <cassert>
34
35 #include <sys/types.h>
36 #include <sys/socket.h>
37 #include <netinet/in.h>
38 #include <arpa/inet.h>
39
40 namespace
41 {
42
43 struct IsFinished : public std::unary_function<STG::Conn *, bool>
44 {
45     result_type operator()(const argument_type & arg)
46     {
47         return (arg->IsDone() && !arg->IsKeepAlive()) || !arg->IsOk();
48     }
49 };
50
51 struct RemoveConn : public std::unary_function<STG::Conn *, void>
52 {
53     result_type operator()(const argument_type & arg)
54     {
55         delete arg;
56     }
57 };
58
59 }
60
61 CONFIGPROTO::CONFIGPROTO(PLUGIN_LOGGER & l)
62     : m_settings(NULL),
63       m_admins(NULL),
64       m_tariffs(NULL),
65       m_users(NULL),
66       m_port(0),
67       m_running(false),
68       m_stopped(true),
69       m_logger(l),
70       m_listenSocket(-1)
71 {
72     std::for_each(m_conns.begin(), m_conns.end(), RemoveConn());
73 }
74
75 int CONFIGPROTO::Prepare()
76 {
77     sigset_t sigmask, oldmask;
78     sigemptyset(&sigmask);
79     sigaddset(&sigmask, SIGINT);
80     sigaddset(&sigmask, SIGTERM);
81     sigaddset(&sigmask, SIGUSR1);
82     sigaddset(&sigmask, SIGHUP);
83     pthread_sigmask(SIG_BLOCK, &sigmask, &oldmask);
84
85     m_listenSocket = socket(PF_INET, SOCK_STREAM, 0);
86
87     if (m_listenSocket < 0)
88     {
89         m_errorStr = std::string("Cannot create listen socket: '") + strerror(errno) + "'.";
90         m_logger(m_errorStr);
91         return -1;
92     }
93
94     struct sockaddr_in listenAddr;
95     listenAddr.sin_family = PF_INET;
96     listenAddr.sin_port = htons(m_port);
97     listenAddr.sin_addr.s_addr = inet_addr("0.0.0.0"); // TODO: arbitrary address
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(m_listenSocket, reinterpret_cast<sockaddr *>(&listenAddr), sizeof(listenAddr)) == -1)
109     {
110         m_errorStr = std::string("Cannot bind listen socket: '") + strerror(errno) + "'.";
111         m_logger(m_errorStr);
112         return -1;
113     }
114
115     if (listen(m_listenSocket, 64) == -1) // TODO: backlog length
116     {
117         m_errorStr = std::string("Failed to start listening for connections: '") + strerror(errno) + "'.";
118         m_logger(m_errorStr);
119         return -1;
120     }
121
122     m_running = true;
123     m_stopped = false;
124     return 0;
125 }
126
127 int CONFIGPROTO::Stop()
128 {
129     m_running = false;
130     for (int i = 0; i < 5 && !m_stopped; ++i)
131     {
132         struct timespec ts = {0, 200000000};
133         nanosleep(&ts, NULL);
134     }
135
136     if (!m_stopped)
137     {
138         m_errorStr = "Cannot stop listenign thread.";
139         m_logger(m_errorStr);
140         return -1;
141     }
142
143     shutdown(m_listenSocket, SHUT_RDWR);
144     close(m_listenSocket);
145     return 0;
146 }
147
148 void CONFIGPROTO::Run()
149 {
150     while (m_running)
151     {
152         fd_set fds;
153
154         BuildFDSet(fds);
155
156         struct timeval tv;
157         tv.tv_sec = 0;
158         tv.tv_usec = 500000;
159
160         int res = select(MaxFD() + 1, &fds, NULL, NULL, &tv);
161         if (res < 0)
162         {
163             m_errorStr = std::string("'select' is failed: '") + strerror(errno) + "'.";
164             m_logger(m_errorStr);
165             break;
166         }
167         if (!m_running)
168             break;
169         if (res > 0)
170             HandleEvents(fds);
171
172         CleanupConns();
173     }
174     m_stopped = true;
175 }
176
177 int CONFIGPROTO::MaxFD() const
178 {
179     int maxFD = m_listenSocket;
180     for (size_t i = 0; i < m_conns.size(); ++i)
181         if (maxFD < m_conns[i]->Sock())
182             maxFD = m_conns[i]->Sock();
183     return maxFD;
184 }
185
186 void CONFIGPROTO::BuildFDSet(fd_set & fds) const
187 {
188     for (size_t i = 0; i < m_conns.size(); ++i)
189         FD_SET(m_conns[i]->Sock(), &fds);
190 }
191
192 void CONFIGPROTO::CleanupConns()
193 {
194     std::vector<STG::Conn *>::iterator pos;
195     pos = std::remove_if(m_conns.begin(), m_conns.end(), IsFinished());
196     if (pos == m_conns.end())
197         return;
198     std::for_each(pos, m_conns.end(), RemoveConn());
199     m_conns.erase(pos, m_conns.end());
200 }
201
202 void CONFIGPROTO::HandleEvents(const fd_set & fds)
203 {
204     if (FD_ISSET(m_listenSocket, &fds))
205         AcceptConnection();
206     else
207     {
208         for (size_t i = 0; i < m_conns.size(); ++i)
209             if (FD_ISSET(m_conns[i]->Sock(), &fds))
210                 m_conns[i]->Read();
211     }
212 }
213
214 void CONFIGPROTO::AcceptConnection()
215 {
216     struct sockaddr_in outerAddr;
217     socklen_t outerAddrLen(sizeof(outerAddr));
218     int sock = accept(m_listenSocket, reinterpret_cast<sockaddr *>(&outerAddr), &outerAddrLen);
219
220     if (sock < 0)
221     {
222         m_errorStr = std::string("Failed to accept connection: '") + strerror(errno) + "'.";
223         printfd(__FILE__, "%s", m_errorStr.c_str());
224         m_logger(m_errorStr);
225         return;
226     }
227
228     assert(m_settings != NULL);
229     assert(m_admins != NULL);
230     assert(m_users != NULL);
231     assert(m_tariffs != NULL);
232
233     try
234     {
235         m_conns.push_back(new STG::Conn(*m_settings, *m_admins, *m_users, *m_tariffs, sock, outerAddr));
236         printfd(__FILE__, "New connection from %s:%d\n", inet_ntostring(m_conns.back()->IP()).c_str(), m_conns.back()->Port());
237     }
238     catch (const STG::Conn::Error & error)
239     {
240         // Unlikely.
241         m_logger(std::string("Failed to create new client connection: '") + error.what() + "'.");
242     }
243 }
244 /*
245 void CONFIGPROTO::WriteLogAccessFailed(uint32_t ip)
246 {
247     m_logger("Admin's connection failed. IP %s", inet_ntostring(ip).c_str());
248 }
249 */