|
1 | | -//NOLINTNEXTLINE(bugprone-reserved-identifier,cert-dcl37-c,cert-dcl51-cpp) |
2 | | -#define _GNU_SOURCE // needed for having accept4() |
3 | | - |
4 | 1 | #include <errno.h> |
5 | 2 | #include <fcntl.h> |
6 | 3 | #include <unistd.h> |
7 | 4 |
|
8 | 5 | #include "dns_server_tcp.h" |
9 | 6 | #include "logging.h" |
10 | 7 |
|
11 | | -// Portability wrapper for accept4 |
12 | | -#ifndef __linux__ |
13 | | -// Define constants if not available on non-Linux systems |
14 | | -#ifndef SOCK_NONBLOCK |
15 | | -#define SOCK_NONBLOCK 0x800 |
16 | | -#endif |
17 | | -#ifndef SOCK_CLOEXEC |
18 | | -#define SOCK_CLOEXEC 0x80000 |
19 | | -#endif |
20 | | - |
21 | | -// On non-Linux systems, implement accept4 using accept + fcntl |
22 | | -static int accept4(int sockfd, struct sockaddr *addr, socklen_t *addrlen, int flags) { |
23 | | - int fd = accept(sockfd, addr, addrlen); |
24 | | - if (fd == -1) { |
25 | | - return -1; |
26 | | - } |
27 | | - if (flags & SOCK_NONBLOCK) { |
28 | | - int fl = fcntl(fd, F_GETFL, 0); |
29 | | - if (fl == -1 || fcntl(fd, F_SETFL, fl | O_NONBLOCK) == -1) { |
30 | | - int saved_errno = errno; |
31 | | - close(fd); |
32 | | - errno = saved_errno; |
33 | | - return -1; |
34 | | - } |
35 | | - } |
36 | | - if (flags & SOCK_CLOEXEC) { |
37 | | - int fl = fcntl(fd, F_GETFD, 0); |
38 | | - if (fl == -1 || fcntl(fd, F_SETFD, fl | FD_CLOEXEC) == -1) { |
39 | | - int saved_errno = errno; |
40 | | - close(fd); |
41 | | - errno = saved_errno; |
42 | | - return -1; |
43 | | - } |
44 | | - } |
45 | | - return fd; |
46 | | -} |
47 | | -#endif |
48 | | - |
49 | 8 | // the following macros require to have client pointer to tcp_client_s structure |
50 | 9 | // else: compilation failure will occur |
51 | 10 | #define LOG_CLIENT(level, format, args...) LOG(level, "C-%u: " format, client->id, ## args) |
@@ -239,13 +198,19 @@ static void accept_cb(struct ev_loop __attribute__((unused)) *loop, |
239 | 198 | struct sockaddr_storage client_addr; |
240 | 199 | socklen_t client_addr_len = sizeof(client_addr); |
241 | 200 |
|
242 | | - int client_sock = accept4(w->fd, (struct sockaddr *)&client_addr, |
243 | | - &client_addr_len, SOCK_NONBLOCK); |
| 201 | + int client_sock = accept(w->fd, (struct sockaddr *)&client_addr, &client_addr_len); |
244 | 202 | if (client_sock == -1 && errno != EAGAIN && errno != EWOULDBLOCK) { |
245 | 203 | ELOG("Failed to accept TCP client: %s", strerror(errno)); |
246 | 204 | return; |
247 | 205 | } |
248 | 206 |
|
| 207 | + int flags = fcntl(client_sock, F_GETFL, 0); |
| 208 | + if (flags == -1 || fcntl(client_sock, F_SETFL, flags | O_NONBLOCK) == -1) { |
| 209 | + ELOG("Failed to set non-blocking on TCP client: %s", strerror(errno)); |
| 210 | + close(client_sock); |
| 211 | + return; |
| 212 | + } |
| 213 | + |
249 | 214 | d->client_id++; |
250 | 215 | d->client_count++; |
251 | 216 | if (d->client_count == d->client_limit) { |
|
0 commit comments