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