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