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