-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathutils.c
82 lines (63 loc) · 1.45 KB
/
utils.c
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
#include <stdlib.h>
#include <netinet/tcp.h>
#include <string.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <err.h>
#include "utils.h"
inline void *
xmalloc(const size_t size)
{
void *ptr = malloc(size);
if (!ptr) {
err(1, "malloc(), can't allocate %zu bytes", size);
}
return ptr;
}
inline void *
xrealloc(void *ptr, const size_t size)
{
ptr = realloc(ptr, size);
if (!ptr) {
err(1, "realloc(), can't reallocate %zu bytes", size);
}
return ptr;
}
inline void
xchdir(const char *dir)
{
if (chdir(dir) < 0) {
err(1, "chdir(), `%s'", dir);
}
}
inline void
xchroot(const char *dir)
{
if (chroot(dir) < 0) {
err(1, "chroot(), `%s'", dir);
}
}
int
create_listen_socket(const char *listen_addr, int port)
{
int opt, listenfd;
struct sockaddr_in addr;
if ((listenfd = socket(AF_INET, SOCK_STREAM | SOCK_NONBLOCK, 0)) < 0) {
err(1, "socket()");
}
opt = 1;
if (setsockopt(listenfd, SOL_SOCKET, SO_REUSEPORT, &opt, sizeof(opt))) {
err(1, "setsockopt(), SOL_SOCKET, SO_REUSEPORT");
}
memset(&addr, 0, sizeof(addr));
addr.sin_family = AF_INET;
addr.sin_port = htons(port);
addr.sin_addr.s_addr = inet_addr(listen_addr);
if (bind(listenfd, (struct sockaddr *)&addr, sizeof(addr)) < 0) {
err(1, "bind(), `%d'", port);
}
if (listen(listenfd, -1) < 0) {
err(1, "listen()");
}
return listenfd;
}