]> git.ipfire.org Git - thirdparty/systemd.git/blob - src/socket-proxy/socket-proxyd.c
Merge pull request #14956 from ssahani/delegated-prefix-14474
[thirdparty/systemd.git] / src / socket-proxy / socket-proxyd.c
1 /* SPDX-License-Identifier: LGPL-2.1+ */
2
3 #include <errno.h>
4 #include <fcntl.h>
5 #include <getopt.h>
6 #include <netdb.h>
7 #include <stdio.h>
8 #include <stdlib.h>
9 #include <sys/un.h>
10 #include <unistd.h>
11
12 #include "sd-daemon.h"
13 #include "sd-event.h"
14 #include "sd-resolve.h"
15
16 #include "alloc-util.h"
17 #include "errno-util.h"
18 #include "fd-util.h"
19 #include "log.h"
20 #include "main-func.h"
21 #include "parse-util.h"
22 #include "path-util.h"
23 #include "pretty-print.h"
24 #include "resolve-private.h"
25 #include "set.h"
26 #include "socket-util.h"
27 #include "string-util.h"
28 #include "util.h"
29
30 #define BUFFER_SIZE (256 * 1024)
31
32 static unsigned arg_connections_max = 256;
33 static const char *arg_remote_host = NULL;
34
35 typedef struct Context {
36 sd_event *event;
37 sd_resolve *resolve;
38
39 Set *listen;
40 Set *connections;
41 } Context;
42
43 typedef struct Connection {
44 Context *context;
45
46 int server_fd, client_fd;
47 int server_to_client_buffer[2]; /* a pipe */
48 int client_to_server_buffer[2]; /* a pipe */
49
50 size_t server_to_client_buffer_full, client_to_server_buffer_full;
51 size_t server_to_client_buffer_size, client_to_server_buffer_size;
52
53 sd_event_source *server_event_source, *client_event_source;
54
55 sd_resolve_query *resolve_query;
56 } Connection;
57
58 static void connection_free(Connection *c) {
59 assert(c);
60
61 if (c->context)
62 set_remove(c->context->connections, c);
63
64 sd_event_source_unref(c->server_event_source);
65 sd_event_source_unref(c->client_event_source);
66
67 safe_close(c->server_fd);
68 safe_close(c->client_fd);
69
70 safe_close_pair(c->server_to_client_buffer);
71 safe_close_pair(c->client_to_server_buffer);
72
73 sd_resolve_query_unref(c->resolve_query);
74
75 free(c);
76 }
77
78 static void context_clear(Context *context) {
79 assert(context);
80
81 set_free_with_destructor(context->listen, sd_event_source_unref);
82 set_free_with_destructor(context->connections, connection_free);
83
84 sd_event_unref(context->event);
85 sd_resolve_unref(context->resolve);
86 }
87
88 static int connection_create_pipes(Connection *c, int buffer[static 2], size_t *sz) {
89 int r;
90
91 assert(c);
92 assert(buffer);
93 assert(sz);
94
95 if (buffer[0] >= 0)
96 return 0;
97
98 r = pipe2(buffer, O_CLOEXEC|O_NONBLOCK);
99 if (r < 0)
100 return log_error_errno(errno, "Failed to allocate pipe buffer: %m");
101
102 (void) fcntl(buffer[0], F_SETPIPE_SZ, BUFFER_SIZE);
103
104 r = fcntl(buffer[0], F_GETPIPE_SZ);
105 if (r < 0)
106 return log_error_errno(errno, "Failed to get pipe buffer size: %m");
107
108 assert(r > 0);
109 *sz = r;
110
111 return 0;
112 }
113
114 static int connection_shovel(
115 Connection *c,
116 int *from, int buffer[2], int *to,
117 size_t *full, size_t *sz,
118 sd_event_source **from_source, sd_event_source **to_source) {
119
120 bool shoveled;
121
122 assert(c);
123 assert(from);
124 assert(buffer);
125 assert(buffer[0] >= 0);
126 assert(buffer[1] >= 0);
127 assert(to);
128 assert(full);
129 assert(sz);
130 assert(from_source);
131 assert(to_source);
132
133 do {
134 ssize_t z;
135
136 shoveled = false;
137
138 if (*full < *sz && *from >= 0 && *to >= 0) {
139 z = splice(*from, NULL, buffer[1], NULL, *sz - *full, SPLICE_F_MOVE|SPLICE_F_NONBLOCK);
140 if (z > 0) {
141 *full += z;
142 shoveled = true;
143 } else if (z == 0 || ERRNO_IS_DISCONNECT(errno)) {
144 *from_source = sd_event_source_unref(*from_source);
145 *from = safe_close(*from);
146 } else if (!IN_SET(errno, EAGAIN, EINTR))
147 return log_error_errno(errno, "Failed to splice: %m");
148 }
149
150 if (*full > 0 && *to >= 0) {
151 z = splice(buffer[0], NULL, *to, NULL, *full, SPLICE_F_MOVE|SPLICE_F_NONBLOCK);
152 if (z > 0) {
153 *full -= z;
154 shoveled = true;
155 } else if (z == 0 || ERRNO_IS_DISCONNECT(errno)) {
156 *to_source = sd_event_source_unref(*to_source);
157 *to = safe_close(*to);
158 } else if (!IN_SET(errno, EAGAIN, EINTR))
159 return log_error_errno(errno, "Failed to splice: %m");
160 }
161 } while (shoveled);
162
163 return 0;
164 }
165
166 static int connection_enable_event_sources(Connection *c);
167
168 static int traffic_cb(sd_event_source *s, int fd, uint32_t revents, void *userdata) {
169 Connection *c = userdata;
170 int r;
171
172 assert(s);
173 assert(fd >= 0);
174 assert(c);
175
176 r = connection_shovel(c,
177 &c->server_fd, c->server_to_client_buffer, &c->client_fd,
178 &c->server_to_client_buffer_full, &c->server_to_client_buffer_size,
179 &c->server_event_source, &c->client_event_source);
180 if (r < 0)
181 goto quit;
182
183 r = connection_shovel(c,
184 &c->client_fd, c->client_to_server_buffer, &c->server_fd,
185 &c->client_to_server_buffer_full, &c->client_to_server_buffer_size,
186 &c->client_event_source, &c->server_event_source);
187 if (r < 0)
188 goto quit;
189
190 /* EOF on both sides? */
191 if (c->server_fd == -1 && c->client_fd == -1)
192 goto quit;
193
194 /* Server closed, and all data written to client? */
195 if (c->server_fd == -1 && c->server_to_client_buffer_full <= 0)
196 goto quit;
197
198 /* Client closed, and all data written to server? */
199 if (c->client_fd == -1 && c->client_to_server_buffer_full <= 0)
200 goto quit;
201
202 r = connection_enable_event_sources(c);
203 if (r < 0)
204 goto quit;
205
206 return 1;
207
208 quit:
209 connection_free(c);
210 return 0; /* ignore errors, continue serving */
211 }
212
213 static int connection_enable_event_sources(Connection *c) {
214 uint32_t a = 0, b = 0;
215 int r;
216
217 assert(c);
218
219 if (c->server_to_client_buffer_full > 0)
220 b |= EPOLLOUT;
221 if (c->server_to_client_buffer_full < c->server_to_client_buffer_size)
222 a |= EPOLLIN;
223
224 if (c->client_to_server_buffer_full > 0)
225 a |= EPOLLOUT;
226 if (c->client_to_server_buffer_full < c->client_to_server_buffer_size)
227 b |= EPOLLIN;
228
229 if (c->server_event_source)
230 r = sd_event_source_set_io_events(c->server_event_source, a);
231 else if (c->server_fd >= 0)
232 r = sd_event_add_io(c->context->event, &c->server_event_source, c->server_fd, a, traffic_cb, c);
233 else
234 r = 0;
235
236 if (r < 0)
237 return log_error_errno(r, "Failed to set up server event source: %m");
238
239 if (c->client_event_source)
240 r = sd_event_source_set_io_events(c->client_event_source, b);
241 else if (c->client_fd >= 0)
242 r = sd_event_add_io(c->context->event, &c->client_event_source, c->client_fd, b, traffic_cb, c);
243 else
244 r = 0;
245
246 if (r < 0)
247 return log_error_errno(r, "Failed to set up client event source: %m");
248
249 return 0;
250 }
251
252 static int connection_complete(Connection *c) {
253 int r;
254
255 assert(c);
256
257 r = connection_create_pipes(c, c->server_to_client_buffer, &c->server_to_client_buffer_size);
258 if (r < 0)
259 goto fail;
260
261 r = connection_create_pipes(c, c->client_to_server_buffer, &c->client_to_server_buffer_size);
262 if (r < 0)
263 goto fail;
264
265 r = connection_enable_event_sources(c);
266 if (r < 0)
267 goto fail;
268
269 return 0;
270
271 fail:
272 connection_free(c);
273 return 0; /* ignore errors, continue serving */
274 }
275
276 static int connect_cb(sd_event_source *s, int fd, uint32_t revents, void *userdata) {
277 Connection *c = userdata;
278 socklen_t solen;
279 int error, r;
280
281 assert(s);
282 assert(fd >= 0);
283 assert(c);
284
285 solen = sizeof(error);
286 r = getsockopt(fd, SOL_SOCKET, SO_ERROR, &error, &solen);
287 if (r < 0) {
288 log_error_errno(errno, "Failed to issue SO_ERROR: %m");
289 goto fail;
290 }
291
292 if (error != 0) {
293 log_error_errno(error, "Failed to connect to remote host: %m");
294 goto fail;
295 }
296
297 c->client_event_source = sd_event_source_unref(c->client_event_source);
298
299 return connection_complete(c);
300
301 fail:
302 connection_free(c);
303 return 0; /* ignore errors, continue serving */
304 }
305
306 static int connection_start(Connection *c, struct sockaddr *sa, socklen_t salen) {
307 int r;
308
309 assert(c);
310 assert(sa);
311 assert(salen);
312
313 c->client_fd = socket(sa->sa_family, SOCK_STREAM|SOCK_NONBLOCK|SOCK_CLOEXEC, 0);
314 if (c->client_fd < 0) {
315 log_error_errno(errno, "Failed to get remote socket: %m");
316 goto fail;
317 }
318
319 r = connect(c->client_fd, sa, salen);
320 if (r < 0) {
321 if (errno == EINPROGRESS) {
322 r = sd_event_add_io(c->context->event, &c->client_event_source, c->client_fd, EPOLLOUT, connect_cb, c);
323 if (r < 0) {
324 log_error_errno(r, "Failed to add connection socket: %m");
325 goto fail;
326 }
327
328 r = sd_event_source_set_enabled(c->client_event_source, SD_EVENT_ONESHOT);
329 if (r < 0) {
330 log_error_errno(r, "Failed to enable oneshot event source: %m");
331 goto fail;
332 }
333 } else {
334 log_error_errno(errno, "Failed to connect to remote host: %m");
335 goto fail;
336 }
337 } else {
338 r = connection_complete(c);
339 if (r < 0)
340 goto fail;
341 }
342
343 return 0;
344
345 fail:
346 connection_free(c);
347 return 0; /* ignore errors, continue serving */
348 }
349
350 static int resolve_handler(sd_resolve_query *q, int ret, const struct addrinfo *ai, Connection *c) {
351 assert(q);
352 assert(c);
353
354 if (ret != 0) {
355 log_error("Failed to resolve host: %s", gai_strerror(ret));
356 goto fail;
357 }
358
359 c->resolve_query = sd_resolve_query_unref(c->resolve_query);
360
361 return connection_start(c, ai->ai_addr, ai->ai_addrlen);
362
363 fail:
364 connection_free(c);
365 return 0; /* ignore errors, continue serving */
366 }
367
368 static int resolve_remote(Connection *c) {
369
370 static const struct addrinfo hints = {
371 .ai_family = AF_UNSPEC,
372 .ai_socktype = SOCK_STREAM,
373 .ai_flags = AI_ADDRCONFIG
374 };
375
376 const char *node, *service;
377 int r;
378
379 if (IN_SET(arg_remote_host[0], '/', '@')) {
380 union sockaddr_union sa;
381 int sa_len;
382
383 r = sockaddr_un_set_path(&sa.un, arg_remote_host);
384 if (r < 0) {
385 log_error_errno(r, "Specified address doesn't fit in an AF_UNIX address, refusing: %m");
386 goto fail;
387 }
388 sa_len = r;
389
390 return connection_start(c, &sa.sa, sa_len);
391 }
392
393 service = strrchr(arg_remote_host, ':');
394 if (service) {
395 node = strndupa(arg_remote_host, service - arg_remote_host);
396 service++;
397 } else {
398 node = arg_remote_host;
399 service = "80";
400 }
401
402 log_debug("Looking up address info for %s:%s", node, service);
403 r = resolve_getaddrinfo(c->context->resolve, &c->resolve_query, node, service, &hints, resolve_handler, NULL, c);
404 if (r < 0) {
405 log_error_errno(r, "Failed to resolve remote host: %m");
406 goto fail;
407 }
408
409 return 0;
410
411 fail:
412 connection_free(c);
413 return 0; /* ignore errors, continue serving */
414 }
415
416 static int add_connection_socket(Context *context, int fd) {
417 Connection *c;
418 int r;
419
420 assert(context);
421 assert(fd >= 0);
422
423 if (set_size(context->connections) > arg_connections_max) {
424 log_warning("Hit connection limit, refusing connection.");
425 safe_close(fd);
426 return 0;
427 }
428
429 r = set_ensure_allocated(&context->connections, NULL);
430 if (r < 0) {
431 log_oom();
432 return 0;
433 }
434
435 c = new0(Connection, 1);
436 if (!c) {
437 log_oom();
438 return 0;
439 }
440
441 c->context = context;
442 c->server_fd = fd;
443 c->client_fd = -1;
444 c->server_to_client_buffer[0] = c->server_to_client_buffer[1] = -1;
445 c->client_to_server_buffer[0] = c->client_to_server_buffer[1] = -1;
446
447 r = set_put(context->connections, c);
448 if (r < 0) {
449 free(c);
450 log_oom();
451 return 0;
452 }
453
454 return resolve_remote(c);
455 }
456
457 static int accept_cb(sd_event_source *s, int fd, uint32_t revents, void *userdata) {
458 _cleanup_free_ char *peer = NULL;
459 Context *context = userdata;
460 int nfd = -1, r;
461
462 assert(s);
463 assert(fd >= 0);
464 assert(revents & EPOLLIN);
465 assert(context);
466
467 nfd = accept4(fd, NULL, NULL, SOCK_NONBLOCK|SOCK_CLOEXEC);
468 if (nfd < 0) {
469 if (!ERRNO_IS_ACCEPT_AGAIN(errno))
470 log_warning_errno(errno, "Failed to accept() socket: %m");
471 } else {
472 (void) getpeername_pretty(nfd, true, &peer);
473 log_debug("New connection from %s", strna(peer));
474
475 r = add_connection_socket(context, nfd);
476 if (r < 0) {
477 log_error_errno(r, "Failed to accept connection, ignoring: %m");
478 safe_close(fd);
479 }
480 }
481
482 r = sd_event_source_set_enabled(s, SD_EVENT_ONESHOT);
483 if (r < 0) {
484 log_error_errno(r, "Error while re-enabling listener with ONESHOT: %m");
485 sd_event_exit(context->event, r);
486 return r;
487 }
488
489 return 1;
490 }
491
492 static int add_listen_socket(Context *context, int fd) {
493 sd_event_source *source;
494 int r;
495
496 assert(context);
497 assert(fd >= 0);
498
499 r = set_ensure_allocated(&context->listen, NULL);
500 if (r < 0) {
501 log_oom();
502 return r;
503 }
504
505 r = sd_is_socket(fd, 0, SOCK_STREAM, 1);
506 if (r < 0)
507 return log_error_errno(r, "Failed to determine socket type: %m");
508 if (r == 0)
509 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
510 "Passed in socket is not a stream socket.");
511
512 r = fd_nonblock(fd, true);
513 if (r < 0)
514 return log_error_errno(r, "Failed to mark file descriptor non-blocking: %m");
515
516 r = sd_event_add_io(context->event, &source, fd, EPOLLIN, accept_cb, context);
517 if (r < 0)
518 return log_error_errno(r, "Failed to add event source: %m");
519
520 r = set_put(context->listen, source);
521 if (r < 0) {
522 log_error_errno(r, "Failed to add source to set: %m");
523 sd_event_source_unref(source);
524 return r;
525 }
526
527 /* Set the watcher to oneshot in case other processes are also
528 * watching to accept(). */
529 r = sd_event_source_set_enabled(source, SD_EVENT_ONESHOT);
530 if (r < 0)
531 return log_error_errno(r, "Failed to enable oneshot mode: %m");
532
533 return 0;
534 }
535
536 static int help(void) {
537 _cleanup_free_ char *link = NULL;
538 int r;
539
540 r = terminal_urlify_man("systemd-socket-proxyd", "8", &link);
541 if (r < 0)
542 return log_oom();
543
544 printf("%1$s [HOST:PORT]\n"
545 "%1$s [SOCKET]\n\n"
546 "Bidirectionally proxy local sockets to another (possibly remote) socket.\n\n"
547 " -c --connections-max= Set the maximum number of connections to be accepted\n"
548 " -h --help Show this help\n"
549 " --version Show package version\n"
550 "\nSee the %2$s for details.\n"
551 , program_invocation_short_name
552 , link
553 );
554
555 return 0;
556 }
557
558 static int parse_argv(int argc, char *argv[]) {
559
560 enum {
561 ARG_VERSION = 0x100,
562 ARG_IGNORE_ENV
563 };
564
565 static const struct option options[] = {
566 { "connections-max", required_argument, NULL, 'c' },
567 { "help", no_argument, NULL, 'h' },
568 { "version", no_argument, NULL, ARG_VERSION },
569 {}
570 };
571
572 int c, r;
573
574 assert(argc >= 0);
575 assert(argv);
576
577 while ((c = getopt_long(argc, argv, "c:h", options, NULL)) >= 0)
578
579 switch (c) {
580
581 case 'h':
582 return help();
583
584 case ARG_VERSION:
585 return version();
586
587 case 'c':
588 r = safe_atou(optarg, &arg_connections_max);
589 if (r < 0) {
590 log_error("Failed to parse --connections-max= argument: %s", optarg);
591 return r;
592 }
593
594 if (arg_connections_max < 1)
595 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
596 "Connection limit is too low.");
597
598 break;
599
600 case '?':
601 return -EINVAL;
602
603 default:
604 assert_not_reached("Unhandled option");
605 }
606
607 if (optind >= argc)
608 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
609 "Not enough parameters.");
610
611 if (argc != optind+1)
612 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
613 "Too many parameters.");
614
615 arg_remote_host = argv[optind];
616 return 1;
617 }
618
619 static int run(int argc, char *argv[]) {
620 _cleanup_(context_clear) Context context = {};
621 int r, n, fd;
622
623 log_parse_environment();
624 log_open();
625
626 r = parse_argv(argc, argv);
627 if (r <= 0)
628 return r;
629
630 r = sd_event_default(&context.event);
631 if (r < 0)
632 return log_error_errno(r, "Failed to allocate event loop: %m");
633
634 r = sd_resolve_default(&context.resolve);
635 if (r < 0)
636 return log_error_errno(r, "Failed to allocate resolver: %m");
637
638 r = sd_resolve_attach_event(context.resolve, context.event, 0);
639 if (r < 0)
640 return log_error_errno(r, "Failed to attach resolver: %m");
641
642 sd_event_set_watchdog(context.event, true);
643
644 r = sd_listen_fds(1);
645 if (r < 0)
646 return log_error_errno(r, "Failed to receive sockets from parent.");
647 if (r == 0)
648 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Didn't get any sockets passed in.");
649
650 n = r;
651
652 for (fd = SD_LISTEN_FDS_START; fd < SD_LISTEN_FDS_START + n; fd++) {
653 r = add_listen_socket(&context, fd);
654 if (r < 0)
655 return r;
656 }
657
658 r = sd_event_loop(context.event);
659 if (r < 0)
660 return log_error_errno(r, "Failed to run event loop: %m");
661
662 return 0;
663 }
664
665 DEFINE_MAIN_FUNCTION(run);