1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
|
/* BSD-2-Clause license
*
* Copyright (c) 2018-2023 NST <www.newinfosec.ru>, sss <sss at dark-alexandr dot net>.
*
*/
#include <errno.h>
#include <unistd.h>
#include <fcntl.h>
#include <netdb.h>
#include <stdlib.h>
#include <stdio.h>
#include <netinet/tcp.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <sys/un.h>
#include <sys/stat.h>
#include <stdbool.h>
#include "webrdp_core_api.h"
#include "log.h"
void
socket_make_non_block(int sock)
{
int flags, r;
while ((flags = fcntl(sock, F_GETFL, 0)) == -1 && errno == EINTR)
{
}
if (flags == -1)
{
perror("fcntl");
exit(EXIT_FAILURE);
}
while ((r = fcntl(sock, F_SETFL, flags | O_NONBLOCK)) == -1
&& errno == EINTR)
{
}
if (r == -1)
{
perror("fcntl");
exit(EXIT_FAILURE);
}
}
int
create_listen_socket_tcp(uint32_t port)
{
/* TODO: ipv6 */
struct addrinfo hints, *res, *rp;
int sfd = -1;
int r;
memset(&hints, 0, sizeof(struct addrinfo));
hints.ai_family = AF_UNSPEC;
hints.ai_socktype = SOCK_STREAM;
hints.ai_flags = AI_PASSIVE | AI_ADDRCONFIG;
{
char sport[10];
snprintf(sport, 9, "%d", port);
r = getaddrinfo(0, sport, &hints, &res);
}
if (r != 0)
{
uint8_t buf[64];
snprintf((char *)buf, 63, "getaddrinfo: %s", gai_strerror(r));
log_msg(
buf, strlen((const char *)buf), wrdp_log_level_error, 0);
exit(EXIT_FAILURE);
}
for (rp = res; rp; rp = rp->ai_next)
{
int val = 1;
sfd = socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol);
if (sfd == -1)
{
continue;
}
if (setsockopt(sfd, SOL_SOCKET, SO_REUSEADDR, &val,
(socklen_t)sizeof(val))
== -1)
{
continue;
}
if (bind(sfd, rp->ai_addr, rp->ai_addrlen) == 0)
{
break;
}
close(sfd);
}
freeaddrinfo(res);
if (listen(sfd, 16) == -1)
{
perror("listen");
close(sfd);
exit(EXIT_FAILURE);
}
return sfd;
}
int
create_listen_socket_unix(const char *path)
{
struct sockaddr_un saddr;
int sfd = socket(AF_UNIX, SOCK_STREAM, 0);
bzero(&saddr, sizeof(struct sockaddr_un));
saddr.sun_family = AF_UNIX;
strcpy(saddr.sun_path, path);
/* this will delete file on disk, beware ) */
unlink(path);
if (bind(sfd, &saddr, sizeof(struct sockaddr_un)))
{
perror("bind");
exit(EXIT_FAILURE);
}
/* set permissive access to socket */
chmod(path, 0777);
if (listen(sfd, 16) == -1)
{
perror("listen");
close(sfd);
exit(EXIT_FAILURE);
}
return sfd;
}
int
accept_new_connection(int socket)
{
int fd = -1;
fd = accept(socket, NULL, NULL);
if (fd == -1 && errno != EINTR && errno != EAGAIN
&& errno != EWOULDBLOCK)
{
perror("accept");
}
else
{
socket_make_non_block(fd);
}
return fd;
}
|