Debian Codegraph @

src/listener.cpp

raw
1 // Copyright © 2002-2004 Rob Kaper <[email protected]>.
2 // 2010-2015 Sylvain Rochet <[email protected]>
3 //
4 // This program is free software; you can redistribute it and/or
5 // modify it under the terms of the GNU General Public License
6 // version 2 as published by the Free Software Foundation.
7 //
8 // This program is distributed in the hope that it will be useful,
9 // but WITHOUT ANY WARRANTY; without even the implied warranty of
10 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
11 // General Public License for more details.
12 //
13 // You should have received a copy of the GNU General Public License
14 // along with this program; see the file COPYING. If not, see
15 // <http://www.gnu.org/licenses/>.
16
17 #include "config.h"
18
19 #include <stdio.h>
20 #include <string.h>
21 #include <errno.h>
22 #include <sys/types.h>
23 #include <sys/socket.h>
24 #include <sys/time.h>
25
26 #include <netinet/in.h>
27 #include <netinet/tcp.h>
28 #include <arpa/inet.h>
29
30 #include <netdb.h>
31 #include <unistd.h>
32 #include <stdlib.h>
33 #include <fcntl.h>
34 #include <syslog.h>
35 #include <signal.h>
36
37 #if USE_SYSTEMD_DAEMON
38 #include <systemd/sd-daemon.h>
39 #endif /* USE_SYSTEMD_DAEMON */
40
41 #include "listener.h"
42 #include "listenport.h"
43 #include "socket.h"
44 #include "server.h"
45
46 #define MAXLINE 1024
47
48 Listener::Listener(MonopdServer *server, const int port)
49 {
50 int err;
51
52 m_server = server;
53
54 signal(SIGPIPE, SIG_IGN);
55
56 #if USE_SYSTEMD_DAEMON
57 int socket_count = sd_listen_fds(0);
58 if (socket_count > 0) {
59 for (int fd = SD_LISTEN_FDS_START; socket_count--; fd++) {
60 if ((err = addListenFd(fd))) {
61 sd_notifyf(1, "STATUS=Failed to start: could not add listening socket: %s\nERRNO=%d", strerror(err), err);
62 usleep(100000);
63 exit(-2);
64 }
65 }
66 syslog(LOG_NOTICE, "listener: systemd");
67 } else
68 #endif /* USE_SYSTEMD_DAEMON */
69
70 if ((err = addListenPort(port))) {
71 syslog(LOG_ERR, "could not bind port %d: %s, exiting", port, strerror(err));
72 #if USE_SYSTEMD_DAEMON
73 sd_notifyf(1, "STATUS=Failed to start: could not bind port %d: %s\nERRNO=%d", port, strerror(err), err);
74 usleep(100000);
75 #endif /* USE_SYSTEMD_DAEMON */
76 exit(-2);
77 }
78 else
79 syslog(LOG_NOTICE, "listener: port=[%d]", port);
80 }
81
82 Listener::~Listener()
83 {
84 while (!m_listenPorts.empty()) { delete *m_listenPorts.begin(); m_listenPorts.erase(m_listenPorts.begin()); }
85 while (!m_sockets.empty()) { delete *m_sockets.begin(); m_sockets.erase(m_sockets.begin()); }
86 }
87
88 int Listener::addListenPort(const int port)
89 {
90 ListenPort *listenPort;
91 int err;
92
93 listenPort = new ListenPort(AF_INET6, "::", port);
94 if ( listenPort->error() ) {
95 delete listenPort;
96 } else {
97 m_listenPorts.push_back(listenPort);
98 }
99
100 listenPort = new ListenPort(AF_INET, "0.0.0.0", port);
101 if ( (err = listenPort->error()) ) {
102 delete listenPort;
103 return err;
104 }
105 m_listenPorts.push_back(listenPort);
106 return 0;
107 }
108
109 int Listener::addListenFd(const int fd) {
110 ListenPort *listenPort;
111 int err;
112
113 listenPort = new ListenPort(fd);
114 if ( (err = listenPort->error()) ) {
115 delete listenPort;
116 return err;
117 }
118 m_listenPorts.push_back(listenPort);
119 return 0;
120 }
121
122 void Listener::checkActivity()
123 {
124 // Construct file descriptor set for new events
125 FD_ZERO(&m_readfdset);
126 FD_ZERO(&m_writefdset);
127 int highestFd = 0;
128
129 ListenPort *listenPort = 0;
130 for(std::vector<ListenPort *>::iterator it = m_listenPorts.begin() ; it != m_listenPorts.end() && (listenPort = *it) ; ++it)
131 {
132 if ( !listenPort->error() )
133 {
134 FD_SET(listenPort->fd(), &m_readfdset);
135 if (listenPort->fd() > highestFd)
136 highestFd = listenPort->fd();
137 }
138 }
139
140 for (std::vector<Socket *>::iterator it = m_sockets.begin() ; it != m_sockets.end() && (*it) ;)
141 {
142 switch ((*it)->status()) {
143 case Socket::Connect:
144 // Connection in progress.
145 FD_SET( (*it)->fd(), &m_writefdset );
146 if ( (*it)->fd() > highestFd )
147 highestFd = (*it)->fd();
148 break;
149 case Socket::Ok:
150 FD_SET( (*it)->fd(), &m_readfdset );
151 if ((*it)->sendBufNotEmpty())
152 FD_SET( (*it)->fd(), &m_writefdset );
153 if ( (*it)->fd() > highestFd )
154 highestFd = (*it)->fd();
155 break;
156 case Socket::Close:
157 // Notify socket close events and delete them.
158 if ((*it)->type() == Socket::Player) {
159 syslog(LOG_INFO, "disconnect: fd=[%d], ip=[%s]", (*it)->fd(), (*it)->ipAddr().c_str());
160 m_server->closedSocket((*it));
161 } else {
162 m_server->closedMetaserver((*it));
163 }
164 shutdown((*it)->fd(), SHUT_RDWR);
165 close((*it)->fd());
166 delete *it;
167 it = m_sockets.erase(it);
168 continue;
169 }
170 ++it;
171 }
172
173 // No file descriptors are opened, exit.
174 if ( !highestFd )
175 {
176 // FIXME: try to (re)bind unbound listenports
177 sleep(1);
178 exit(1);
179 return;
180 }
181
182 struct timeval tv, *tvp = NULL;
183 int timeout = m_server->timeleftEvent();
184 if (timeout >= 0) {
185 // timeout is in ms
186 tv.tv_sec = timeout/1000;
187 tv.tv_usec = (timeout%1000)*1000;
188 tvp = &tv;
189 }
190
191 // Check filedescriptors for input.
192 if ( (select(highestFd+1, &m_readfdset, &m_writefdset, NULL, tvp)) <= 0 )
193 return;
194
195 // Check for new connections
196 for(std::vector<ListenPort *>::iterator it = m_listenPorts.begin() ; it != m_listenPorts.end() && (listenPort = *it) ; ++it)
197 if (FD_ISSET(listenPort->fd(), &m_readfdset))
198 {
199 acceptSocket( listenPort->fd() );
200 }
201
202 // Check socket data.
203 for ( std::vector<Socket *>::iterator it = m_sockets.begin() ; it != m_sockets.end() && (*it) ; ++it )
204 {
205 if ( FD_ISSET( (*it)->fd(), &m_readfdset ) )
206 {
207 char *readBuf = new char[MAXLINE+1]; // MAXLINE + '\0'
208 int n = read((*it)->fd(), readBuf, MAXLINE);
209 if (n <= 0) // socket was closed
210 {
211 (*it)->setStatus(Socket::Close);
212 delete[] readBuf;
213 continue;
214 }
215 readBuf[n] = 0;
216 (*it)->fillBuffer(readBuf);
217 delete[] readBuf;
218
219 while ( (*it)->hasReadLine() )
220 {
221 std::string data = (*it)->readLine();
222
223 // Return activity if we have a line
224 if (data.size() > 0 && (*it)->status() == Socket::Ok && (*it)->type() == Socket::Player)
225 {
226 m_server->processInput((*it), data);
227 }
228 }
229 }
230
231 if ( FD_ISSET( (*it)->fd(), &m_writefdset ) ) {
232 if ( (*it)->status() == Socket::Ok ) {
233 (*it)->sendMore();
234 }
235 else if ( (*it)->status() == Socket::Connect ) {
236 int err;
237 int sockerr;
238 socklen_t len = sizeof(sockerr);
239 err = getsockopt((*it)->fd(), SOL_SOCKET, SO_ERROR, &sockerr, &len);
240 if (err == 0 && sockerr == 0) {
241 (*it)->setStatus(Socket::Ok);
242 m_server->welcomeMetaserver((*it));
243 } else {
244 int socketFd;
245 char ip_str[INET6_ADDRSTRLEN];
246 syslog( LOG_INFO, "connect() failed: ip=[%s], error=[%s]", (*it)->ipAddr().c_str(), strerror(sockerr) );
247
248 /* Try next */
249 struct addrinfo *addrinfo = (*it)->addrinfoNext();
250 for (; addrinfo != NULL; addrinfo = addrinfo->ai_next) {
251 socketFd = socket(addrinfo->ai_family, addrinfo->ai_socktype, addrinfo->ai_protocol);
252 if (socketFd < 0)
253 continue;
254
255 // get current socket flags
256 int flags = fcntl(socketFd, F_GETFL);
257 if (flags < 0)
258 goto non_blocking_failed;
259
260 // set socket to non-blocking
261 flags |= O_NDELAY;
262 if (fcntl(socketFd, F_SETFL, flags) < 0)
263 goto non_blocking_failed;
264
265 #ifdef TCP_CORK
266 flags = 1;
267 setsockopt(socketFd, IPPROTO_TCP, TCP_CORK, &flags, sizeof(int));
268 #endif /* TCP_CORK */
269
270 ip_str[0] = '\0';
271 if (addrinfo->ai_family == AF_INET) {
272 inet_ntop(addrinfo->ai_family, &(((struct sockaddr_in *)addrinfo->ai_addr)->sin_addr), ip_str, INET6_ADDRSTRLEN);
273 } else if(addrinfo->ai_family == AF_INET6) {
274 inet_ntop(addrinfo->ai_family, &(((struct sockaddr_in6 *)addrinfo->ai_addr)->sin6_addr), ip_str, INET6_ADDRSTRLEN);
275 }
276
277 err = connect(socketFd, addrinfo->ai_addr, addrinfo->ai_addrlen);
278 if (err < 0 && errno != EINPROGRESS) {
279 syslog(LOG_INFO, "connect() failed: ip=[%s], error=[%s]", ip_str, strerror(errno));
280 goto connect_failed;
281 }
282 break;
283
284 connect_failed:
285 non_blocking_failed:
286 close(socketFd);
287 }
288
289 // Connect failed
290 if (addrinfo == NULL) {
291 (*it)->setStatus(Socket::Close);
292 continue;
293 }
294
295 close((*it)->fd());
296 (*it)->setFd(socketFd);
297 (*it)->setAddrinfoNext(addrinfo->ai_next);
298 (*it)->setIpAddr(ip_str);
299 }
300 }
301 }
302 }
303 }
304
305 Socket *Listener::acceptSocket(int fd)
306 {
307 struct sockaddr_storage clientaddr;
308 char ip_str[INET6_ADDRSTRLEN];
309 int flags;
310
311 int len = sizeof(clientaddr);
312 int socketFd = accept(fd, (struct sockaddr *) &clientaddr, (socklen_t *) &len);
313 if (socketFd == -1) {
314 if (errno == EINVAL) {
315 syslog(LOG_INFO, "accept() failed: %s, probably because systemd socket activation [Socket] configuration use Accept=yes, that must be set to no", strerror(errno));
316 exit(-2);
317 }
318 return 0;
319 }
320
321 Socket *socket = new Socket(socketFd);
322 if(clientaddr.ss_family == AF_INET) {
323 inet_ntop(clientaddr.ss_family, &(((struct sockaddr_in *)&clientaddr)->sin_addr), ip_str, INET6_ADDRSTRLEN);
324 socket->setIpAddr(ip_str);
325 } else if(clientaddr.ss_family == AF_INET6) {
326 inet_ntop(clientaddr.ss_family, &(((struct sockaddr_in6 *)&clientaddr)->sin6_addr), ip_str, INET6_ADDRSTRLEN);
327 socket->setIpAddr(ip_str);
328 }
329
330 // set socket to non-blocking
331 flags = fcntl(socketFd, F_GETFL);
332 if (flags >= 0) {
333 flags |= O_NDELAY;
334 fcntl(socketFd, F_SETFL, flags);
335 }
336
337 #ifdef TCP_CORK
338 flags = 1;
339 setsockopt(socketFd, IPPROTO_TCP, TCP_CORK, &flags, sizeof(int));
340 #endif /* TCP_CORK */
341
342 m_sockets.push_back(socket);
343 syslog(LOG_INFO, "connection: fd=[%d], ip=[%s]", socket->fd(), socket->ipAddr().c_str());
344 m_server->welcomeNew(socket);
345
346 return socket;
347 }
348
349 Socket *Listener::connectSocket(struct addrinfo *addrinfo) {
350 int socketFd;
351 int err;
352 Socket *sock;
353 int flags;
354 char ip_str[INET6_ADDRSTRLEN];
355
356 for (; addrinfo != NULL; addrinfo = addrinfo->ai_next) {
357 socketFd = socket(addrinfo->ai_family, addrinfo->ai_socktype, addrinfo->ai_protocol);
358 if (socketFd < 0)
359 continue;
360
361 // get current socket flags
362 flags = fcntl(socketFd, F_GETFL);
363 if (flags < 0)
364 goto non_blocking_failed;
365
366 // set socket to non-blocking
367 flags |= O_NDELAY;
368 if (fcntl(socketFd, F_SETFL, flags) < 0)
369 goto non_blocking_failed;
370
371 #ifdef TCP_CORK
372 flags = 1;
373 setsockopt(socketFd, IPPROTO_TCP, TCP_CORK, &flags, sizeof(int));
374 #endif /* TCP_CORK */
375
376 ip_str[0] = '\0';
377 if (addrinfo->ai_family == AF_INET) {
378 inet_ntop(addrinfo->ai_family, &(((struct sockaddr_in *)addrinfo->ai_addr)->sin_addr), ip_str, INET6_ADDRSTRLEN);
379 } else if(addrinfo->ai_family == AF_INET6) {
380 inet_ntop(addrinfo->ai_family, &(((struct sockaddr_in6 *)addrinfo->ai_addr)->sin6_addr), ip_str, INET6_ADDRSTRLEN);
381 }
382
383 err = connect(socketFd, addrinfo->ai_addr, addrinfo->ai_addrlen);
384 if (err < 0 && errno != EINPROGRESS) {
385 syslog(LOG_INFO, "connect() failed: ip=[%s], error=[%s]", ip_str, strerror(errno));
386 goto connect_failed;
387 }
388 break;
389
390 connect_failed:
391 non_blocking_failed:
392 close(socketFd);
393 }
394
395 if (addrinfo == NULL) {
396 return NULL;
397 }
398
399 sock = new Socket(socketFd);
400 sock->setType( Socket::Metaserver );
401 sock->setStatus( Socket::Connect );
402 sock->setAddrinfoNext(addrinfo->ai_next);
403 sock->setIpAddr(ip_str);
404 m_sockets.push_back(sock);
405 return sock;
406 }
407
408 Socket *Listener::findSocket(int fd)
409 {
410 Socket *socket = 0;
411 for (std::vector<Socket *>::iterator it = m_sockets.begin() ; it != m_sockets.end() && (socket = *it) ; ++it)
412 if (socket->fd() == fd)
413 return socket;
414
415 return 0;
416 }