Debian Codegraph @

src/socket-activate.c

raw symbols SCIP
1 /*
2 * standalone-socket-activate
3 *
4 * Copyright (c) 2019 Peter Pentchev
5 * Copyright (c) 2023- Mark Hindley
6 *
7 * License: GPL-3.0+
8 *
9 * This program is free software: you can redistribute it and/or modify
10 * it under the terms of the GNU General Public License as published by
11 * the Free Software Foundation, either version 3 of the License, or
12 * (at your option) any later version.
13 *
14 * This program is distributed in the hope that it will be useful,
15 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 * GNU General Public License for more details.
18 *
19 * You should have received a copy of the GNU General Public License
20 * along with this program. If not, see <http://www.gnu.org/licenses/>.
21 */
22
23 #include <sys/types.h>
24 #include <sys/socket.h>
25 #include <sys/stat.h>
26 #include <sys/un.h>
27
28 #include <err.h>
29 #include <errno.h>
30 #include <fcntl.h>
31 #include <inttypes.h>
32 #include <limits.h>
33 #include <netdb.h>
34 #include <poll.h>
35 #include <stdarg.h>
36 #include <stdbool.h>
37 #include <stdio.h>
38 #include <stdlib.h>
39 #include <string.h>
40 #include <unistd.h>
41
42 #include <arpa/inet.h>
43 #include <netinet/in.h>
44
45 #define SD_LISTEN_FDS_START 3
46
47 #ifndef __printflike
48 #if defined(__GNUC__) && __GNUC__ >= 3
49 #define __printflike(x, y) __attribute__((format(printf, (x), (y))))
50 #define __unused __attribute__((unused))
51 #else
52 #define __printflike(x, y)
53 #define __unused
54 #endif
55 #endif
56
57 #define VERSION_STRING "0.4unreleased"
58
59 enum option_id_t {
60 OPT_LABEL,
61 OPT_MODE,
62 OPT_USER,
63 OPT_GROUP,
64 OPT_BACKLOG,
65 OPTIONS_COUNT
66 };
67
68 struct option_t {
69 const char *value;
70 bool handled;
71 };
72
73 static const char * const option_names[OPTIONS_COUNT] = {
74 "label",
75 "mode",
76 "user",
77 "group",
78 "backlog",
79 };
80
81 static bool verbose;
82
83 static void
84 usage(const bool _ferr)
85 {
86 const char * const s =
87 "Usage:\tsocket-activate [-v | --verbose] --family:[options,...]:address... [--] program [arg...]\n"
88 "\tsocket-activate -V | -h | --version | --help\n"
89 "\tsocket-activate --features\n"
90 "\n"
91 "\t-h\tdisplay program usage information and exit\n"
92 "\t-V\tdisplay program version information and exit\n"
93 "\t-v\tverbose operation; display diagnostic output\n";
94
95 fprintf(_ferr? stderr: stdout, "%s", s);
96 if (_ferr)
97 exit(1);
98 }
99
100 static void
101 version(void)
102 {
103 puts("socket-activate " VERSION_STRING);
104 }
105
106 static void
107 features(void)
108 {
109 puts("Features: socket-activate=" VERSION_STRING);
110 }
111
112 __printflike(1, 2)
113 static void
114 debug(const char * const fmt, ...)
115 {
116 va_list v;
117
118 va_start(v, fmt);
119 if (verbose)
120 vfprintf(stderr, fmt, v);
121 va_end(v);
122 }
123
124 static long
125 strtolong_fatal(const char * const s, const int base)
126 {
127 errno = 0;
128 char *endp;
129 const long value = strtol(s, &endp, base);
130 if (*endp != '\0' ||
131 (errno == ERANGE && (value == LONG_MIN || value == LONG_MAX)))
132 errx(1, "Invalid base %d numeric value '%s'", base, s);
133 return value;
134 }
135
136 static int
137 connect_unix(const int socktype, struct option_t * const options,
138 char * const address)
139 {
140 const int sock = socket(AF_UNIX, socktype, 0);
141 if (sock == -1)
142 err(EXIT_FAILURE, "Could not create a Unix-domain socket");
143
144 mode_t oldmask = 0;
145 long mode = 0;
146 struct sockaddr_un addr = { 0 };
147 addr.sun_family = AF_UNIX;
148 const int written = snprintf(addr.sun_path, sizeof(addr.sun_path),
149 "%s", address);
150 if (written < 0 || (size_t)written >= sizeof(addr.sun_path))
151 err(EXIT_FAILURE, "Path too long for a Unix-domain socket");
152 if (unlink(address) == -1 && errno != ENOENT)
153 err(EXIT_FAILURE, "Failed to remove existing Unix-domain socket %s", address);
154 /* Set umask for bind */
155 if (options[OPT_MODE].value != NULL) {
156 options[OPT_MODE].handled = true;
157 mode = strtolong_fatal(options[OPT_MODE].value, 8);
158 if (mode < 0)
159 errx(1, "Invalid access mode '%s' for '%s'",
160 options[OPT_MODE].value, address);
161 oldmask = umask(~mode);
162 }
163 if (bind(sock, (const struct sockaddr *)&addr, sizeof(addr)) == -1)
164 err(EXIT_FAILURE, "Could not bind the Unix-domain socket to %s", address);
165 if (options[OPT_MODE].value != NULL)
166 umask(oldmask);
167
168 uid_t uid = 0;
169 gid_t gid = 0;
170 if (options[OPT_USER].value != NULL) {
171 options[OPT_USER].handled = true;
172 const long luid = strtolong_fatal(options[OPT_USER].value, 10);
173 if (luid < 0)
174 errx(1, "The user id must be non-negative");
175 uid = (uid_t)luid;
176
177 if (options[OPT_GROUP].value == NULL)
178 gid = getgid();
179 }
180 if (options[OPT_GROUP].value != NULL) {
181 options[OPT_GROUP].handled = true;
182 const long lgid = strtolong_fatal(options[OPT_GROUP].value, 10);
183 if (lgid < 0)
184 errx(1, "The group id must be non-negative");
185 gid = (gid_t)lgid;
186
187 if (options[OPT_USER].value == NULL)
188 uid = getuid();
189 }
190 if (options[OPT_USER].value != NULL ||
191 options[OPT_GROUP].value != NULL)
192 if (chown(address, uid, gid) == -1)
193 err(EXIT_FAILURE, "Could not set the Unix socket ownership to "
194 "%jd:%jd", (intmax_t)uid, (intmax_t)gid);
195
196 return sock;
197 }
198
199 static int
200 connect_inet(const int socktype, struct option_t * const options __unused,
201 char * const address)
202 {
203 const int proto = socktype == SOCK_STREAM ? IPPROTO_TCP : IPPROTO_UDP;
204 char *next = address;
205 const char * const first = strsep(&next, "/");
206 const char * const addrstr = next == NULL ? "0.0.0.0" : first;
207 const char * const portstr = next == NULL ? first : next;
208 struct addrinfo hints = {
209 .ai_family = next == NULL ? AF_INET : AF_UNSPEC,
210 .ai_socktype = socktype,
211 .ai_protocol = proto,
212 .ai_flags = AI_NUMERICHOST | AI_NUMERICSERV | AI_PASSIVE,
213 };
214 struct addrinfo *res;
215 const int ret = getaddrinfo(addrstr, portstr, &hints, &res);
216 if (ret != 0)
217 errx(1, "Could not parse the %s address: %s",
218 address, gai_strerror(ret));
219 if (res == NULL)
220 errx(1, "Could not parse the %s address", address);
221
222 if (verbose) {
223 char buf[200];
224 short port;
225 const void *vaddr;
226 if (res->ai_family == AF_INET) {
227 const struct sockaddr_in * const iaddr =
228 (const struct sockaddr_in *)res->ai_addr;
229 vaddr = &iaddr->sin_addr;
230 port = iaddr->sin_port;
231 } else {
232 const struct sockaddr_in6 * const iaddr =
233 (const struct sockaddr_in6 *)res->ai_addr;
234 vaddr = &iaddr->sin6_addr;
235 port = iaddr->sin6_port;
236 }
237 debug("got family %d type %d proto %d len %d "
238 "address %s port %d\n",
239 res->ai_family, res->ai_socktype, res->ai_protocol,
240 res->ai_addrlen,
241 inet_ntop(res->ai_family, vaddr, buf, res->ai_addrlen),
242 ntohs(port));
243 }
244
245 const int sock = socket(res->ai_family, res->ai_socktype,
246 res->ai_protocol);
247 if (sock == -1)
248 err(EXIT_FAILURE, "Could not create a %s socket",
249 socktype == SOCK_STREAM ? "tcp" : "udp");
250 const int optval = 1;
251 if (setsockopt(sock, SOL_SOCKET, SO_REUSEADDR,
252 &optval, sizeof(optval)) == -1
253 #ifndef __gnu_hurd__
254 || setsockopt(sock, SOL_SOCKET, SO_REUSEPORT,
255 &optval, sizeof(optval)) == -1
256 #endif
257 )
258 err(EXIT_FAILURE, "Could not set the socket options for %s:%s",
259 addrstr, portstr);
260 if (bind(sock, res->ai_addr, res->ai_addrlen) == -1)
261 err(EXIT_FAILURE, "Could not bind to %s:%s", addrstr, portstr);
262
263 return sock;
264 }
265
266
267 struct connect_func_t {
268 const char * const family;
269 int (* const func)(int, struct option_t * const options, char *);
270 const int socktype;
271 };
272
273 static const struct connect_func_t connect_functions[] = {
274 {"unix", connect_unix, SOCK_STREAM},
275 {"unix-dgram", connect_unix, SOCK_DGRAM},
276 {"tcp", connect_inet, SOCK_STREAM},
277 {"udp", connect_inet, SOCK_DGRAM},
278 };
279
280 static inline const struct connect_func_t *
281 get_connect_function(const char * const family)
282 {
283 for (size_t idx = 0; idx < sizeof(connect_functions) / sizeof(connect_functions[0]); idx++)
284 if (strcmp(family, connect_functions[idx].family) == 0)
285 return &connect_functions[idx];
286 errx(1, "Invalid socket family '%s'", family);
287 }
288
289 static inline enum option_id_t
290 get_option_id(const char * const name)
291 {
292 for (size_t idx = 0; idx < (size_t)OPTIONS_COUNT; idx++)
293 if (strcmp(option_names[idx], name) == 0)
294 return (enum option_id_t)idx;
295 return OPTIONS_COUNT;
296 }
297
298 static const char *
299 add_listener(const char * const optarg, const int nextfd)
300 {
301 char *next = strdup(optarg);
302 if (next == NULL)
303 err(EXIT_FAILURE, "Could not allocate memory");
304
305 const char * const family = strsep(&next, ":");
306 const struct connect_func_t * const func = get_connect_function(family);
307
308 struct option_t * const options = calloc(OPTIONS_COUNT, sizeof(*options));
309 char *optstr = strsep(&next, ":");
310 char *current;
311 while (current = strsep(&optstr, ","), current != NULL && strlen(current)) {
312 const char * const name = strsep(&current, "=");
313 if (name[0] == '\0')
314 errx(1, "Empty option name in '%s'", optarg);
315 const enum option_id_t idx = get_option_id(name);
316 if (idx == OPTIONS_COUNT)
317 errx(1, "Unknown option '%s' in '%s'", name, optarg);
318
319 if (current[0] == '\0')
320 errx(1, "No value for option '%s' in '%s'",
321 name, optarg);
322 options[idx].value = current;
323 }
324
325 const char * const label = options[OPT_LABEL].value;
326 options[OPT_LABEL].handled = true;
327 char * const address = next;
328 const int fd = func->func(func->socktype, options, address);
329 if (fd != nextfd) {
330 debug("moving %s fd %d to %d\n", optarg, fd, nextfd);
331 if (dup2(fd, nextfd) == -1)
332 err(EXIT_FAILURE, "Could not move %s fd %d to %d",
333 optarg, fd, nextfd);
334 if (close(fd) == -1)
335 err(EXIT_FAILURE, "Could not close %s fd %d after "
336 "moving it to %d",
337 optarg, fd, nextfd);
338 /* fd now closed, don't use anymore */
339 } else {
340 debug("no need to move %s fd %d\n", optarg, fd);
341 }
342 debug("fd %d: label %s, family %s, address %s\n",
343 nextfd, label, family, address);
344
345 if (func->socktype == SOCK_STREAM) {
346 int backlog = SOMAXCONN;
347 if (options[OPT_BACKLOG].value != NULL) {
348 options[OPT_BACKLOG].handled = true;
349 long value = strtolong_fatal(
350 options[OPT_BACKLOG].value, 10);
351 if (value < 1)
352 err(EXIT_FAILURE, "The listen backlog for %s must be "
353 "a positive number", optarg);
354 #if LONG_MAX > INT_MAX
355 if (value > INT_MAX)
356 err(EXIT_FAILURE, "The listen backlog for %s must be "
357 "no more than %d", optarg, INT_MAX);
358 #endif
359 backlog = value;
360 }
361 if (listen(nextfd, backlog) == -1)
362 err(EXIT_FAILURE, "Could not listen for %s", optarg);
363 }
364
365 for (size_t idx = 0; idx < OPTIONS_COUNT; idx++)
366 if (options[idx].value != NULL && !options[idx].handled)
367 errx(1, "Unexpected option '%s' in '%s'",
368 option_names[idx], optarg);
369 free(options);
370
371 return label != NULL ? label : "";
372 }
373
374 int
375 main(int argc, char * const argv[])
376 {
377 char *fdnames = NULL;
378 bool hflag = false, Vflag = false, show_features = false;
379 int ch;
380 int nextfd = SD_LISTEN_FDS_START;
381 while ((ch = getopt(argc, argv, "hVv-:")) != -1) {
382 switch ((char)ch) {
383 case 'h':
384 hflag = true;
385 break;
386
387 case 'V':
388 Vflag = true;
389 break;
390
391 case 'v':
392 verbose = true;
393 break;
394
395 case '-':
396 if (strcmp(optarg, "help") == 0)
397 hflag = true;
398 else if (strcmp(optarg, "version") == 0)
399 Vflag = true;
400 else if (strcmp(optarg, "verbose") == 0)
401 verbose = true;
402 else if (strcmp(optarg, "features") == 0)
403 show_features = true;
404 else {
405 const char * const label =
406 add_listener(optarg, nextfd);
407 nextfd++;
408 char *newnames = NULL;
409 const int res = asprintf(&newnames,
410 "%s%s%s",
411 fdnames == NULL ? "" : fdnames,
412 fdnames == NULL ? "" : ":",
413 label);
414 if (res < 0 || newnames == NULL)
415 err(EXIT_FAILURE, "Could not allocate "
416 "the names list");
417 if (fdnames == NULL || strcmp(newnames,fdnames) != 0) {
418 free(fdnames);
419 fdnames = newnames;
420 } else {
421 free(newnames);
422 }
423 }
424 break;
425
426 default:
427 usage(true);
428 /* NOTREACHED */
429 }
430 }
431 if (Vflag)
432 version();
433 if (hflag)
434 usage(false);
435 if (show_features)
436 features();
437 if (Vflag || hflag || show_features)
438 return (0);
439
440 argc -= optind;
441 argv += optind;
442 if (argc < 1)
443 usage(true);
444
445 struct pollfd *pfds;
446 pid_t pid;
447 nfds_t nfds = nextfd - SD_LISTEN_FDS_START;
448 nfds_t j = 0;
449 pfds = calloc(nfds, sizeof(struct pollfd));
450 if (pfds == NULL)
451 err(EXIT_FAILURE, "Malloc failed");
452
453 for (int fd = SD_LISTEN_FDS_START; fd < nextfd; fd++) {
454 pfds[j].events = POLLIN;
455 pfds[j++].fd = fd;
456 }
457
458 debug("Polling %ld fds\n", nfds);
459 const int n = poll(pfds, nfds, -1);
460 if (n == -1)
461 err(EXIT_FAILURE, "Could not wait for incoming connections");
462 debug("got %d fds from poll()\n", n);
463 char buf[20];
464 pid = getpid();
465 snprintf(buf, sizeof(buf), "%d", pid);
466 setenv("LISTEN_PID", buf, 1);
467 snprintf(buf, sizeof(buf), "%d", nextfd - SD_LISTEN_FDS_START);
468 setenv("LISTEN_FDS", buf, 1);
469 setenv("LISTEN_FDNAMES", fdnames, 1);
470 debug("Exec %s, PID %d\n", argv[0], pid);
471 execvp(argv[0], argv);
472 err(EXIT_FAILURE, "Could not execute '%s'", argv[0]);
473 }