-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathsocket.c
153 lines (122 loc) · 2.46 KB
/
socket.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
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
144
145
146
147
148
149
150
151
152
153
/* Copyright (c) 2019 by Erik Larsson
SPDX-License-Identifier: GPL-3.0-or-later
*/
#include <sys/socket.h>
#include <sys/epoll.h>
#include <sys/stat.h>
#include <sys/un.h>
#include <string.h>
#include <unistd.h>
#include <errno.h>
#include "agent.h"
#ifdef WITH_SYSTEMD
#include <systemd/sd-daemon.h>
int setup_systemd(context_t *ctx) {
int sfd, n;
n = sd_listen_fds(0);
if (n < 0) {
errno = n;
return -1;
}
if (!n) {
return 0;
}
if (n > 1) {
FATAL("Too many systemd sockets");
}
sfd = SD_LISTEN_FDS_START;
n = sd_is_socket_unix(sfd, SOCK_STREAM, 1, NULL, 0);
if (n < 0) {
errno = n;
return -1;
}
else if (!n) {
FATAL("Bad systemd socket type");
}
return sfd;
}
#endif
int setup_socket(context_t *ctx, const char *path) {
int r, sfd;
struct sockaddr_un sname = { .sun_family = AF_UNIX };
#ifdef WITH_SYSTEMD
sfd = setup_systemd(ctx);
if (sfd) {
return sfd;
}
#endif
if (!path) {
FATAL("missing socket path");
}
if (strlen(path) > (sizeof(sname.sun_path) - 1)) {
errno = EOVERFLOW;
return -1;
}
strncpy(sname.sun_path, path, sizeof(sname.sun_path) - 1);
sfd = socket(AF_UNIX, SOCK_STREAM, 0);
if (sfd == -1) {
return -1;
}
r = fchmod(sfd, S_IRUSR | S_IWUSR);
if (r) {
return r;
}
r = bind(sfd, (const struct sockaddr *) &sname, sizeof(struct sockaddr_un));
if (r) {
return r;
}
ctx->socketpath = path;
r = listen(sfd, 10);
if (r) {
return r;
}
return sfd;
}
int epoll_setup(int sfd) {
int r, pfd;
struct epoll_event ev = { .events = EPOLLIN };
pfd = epoll_create1(0);
if (pfd == -1) {
return -1;
}
ev.data.fd = sfd;
r = epoll_ctl(pfd, EPOLL_CTL_ADD, sfd, &ev);
if (r == -1) {
return -1;
}
return pfd;
}
int epoll_close(int pfd, int fd) {
int r;
r = epoll_ctl(pfd, EPOLL_CTL_DEL, fd, NULL);
close(fd);
return r;
}
int epoll_loop(int pfd, int sfd) {
int r, fd;
struct epoll_event rev, ev = { .events = EPOLLIN };
r = epoll_wait(pfd, &rev, 1, -1);
if (r == -1) {
return -1;
}
if (rev.data.fd == sfd) {
fd = accept(sfd, NULL, NULL);
if (fd == -1) {
return -1;
}
ev.data.fd = fd;
r = epoll_ctl(pfd, EPOLL_CTL_ADD, fd, &ev);
if (r == -1) {
return -1;
}
return 0;
}
else if (rev.events & EPOLLHUP) {
r = epoll_close(pfd, rev.data.fd);
return r;
}
else if (rev.events & EPOLLIN) {
return rev.data.fd;
}
return 0;
}