]> git.ipfire.org Git - thirdparty/systemd.git/blob - src/socket-proxy/socket-proxyd.c
Merge pull request #11232 from yuwata/fix-9130-alternative
[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 <string.h>
10 #include <sys/socket.h>
11 #include <sys/un.h>
12 #include <unistd.h>
13
14 #include "sd-daemon.h"
15 #include "sd-event.h"
16 #include "sd-resolve.h"
17
18 #include "alloc-util.h"
19 #include "fd-util.h"
20 #include "log.h"
21 #include "main-func.h"
22 #include "parse-util.h"
23 #include "path-util.h"
24 #include "pretty-print.h"
25 #include "resolve-private.h"
26 #include "set.h"
27 #include "socket-util.h"
28 #include "string-util.h"
29 #include "util.h"
30
31 #define BUFFER_SIZE (256 * 1024)
32 static unsigned arg_connections_max = 256;
33
34 static const char *arg_remote_host = NULL;
35
36 typedef struct Context {
37 sd_event *event;
38 sd_resolve *resolve;
39
40 Set *listen;
41 Set *connections;
42 } Context;
43
44 typedef struct Connection {
45 Context *context;
46
47 int server_fd, client_fd;
48 int server_to_client_buffer[2]; /* a pipe */
49 int client_to_server_buffer[2]; /* a pipe */
50
51 size_t server_to_client_buffer_full, client_to_server_buffer_full;
52 size_t server_to_client_buffer_size, client_to_server_buffer_size;
53
54 sd_event_source *server_event_source, *client_event_source;
55
56 sd_resolve_query *resolve_query;
57 } Connection;
58
59 static void connection_free(Connection *c) {
60 assert(c);
61
62 if (c->context)
63 set_remove(c->context->connections, c);
64
65 sd_event_source_unref(c->server_event_source);
66 sd_event_source_unref(c->client_event_source);
67
68 safe_close(c->server_fd);
69 safe_close(c->client_fd);
70
71 safe_close_pair(c->server_to_client_buffer);
72 safe_close_pair(c->client_to_server_buffer);
73
74 sd_resolve_query_unref(c->resolve_query);
75
76 free(c);
77 }
78
79 static void context_clear(Context *context) {
80 assert(context);
81
82 set_free_with_destructor(context->listen, sd_event_source_unref);
83 set_free_with_destructor(context->connections, connection_free);
84
85 sd_event_unref(context->event);
86 sd_resolve_unref(context->resolve);
87 }
88
89 static int connection_create_pipes(Connection *c, int buffer[static 2], size_t *sz) {
90 int r;
91
92 assert(c);
93 assert(buffer);
94 assert(sz);
95
96 if (buffer[0] >= 0)
97 return 0;
98
99 r = pipe2(buffer, O_CLOEXEC|O_NONBLOCK);
100 if (r < 0)
101 return log_error_errno(errno, "Failed to allocate pipe buffer: %m");
102
103 (void) fcntl(buffer[0], F_SETPIPE_SZ, BUFFER_SIZE);
104
105 r = fcntl(buffer[0], F_GETPIPE_SZ);
106 if (r < 0)
107 return log_error_errno(errno, "Failed to get pipe buffer size: %m");
108
109 assert(r > 0);
110 *sz = r;
111
112 return 0;
113 }
114
115 static int connection_shovel(
116 Connection *c,
117 int *from, int buffer[2], int *to,
118 size_t *full, size_t *sz,
119 sd_event_source **from_source, sd_event_source **to_source) {
120
121 bool shoveled;
122
123 assert(c);
124 assert(from);
125 assert(buffer);
126 assert(buffer[0] >= 0);
127 assert(buffer[1] >= 0);
128 assert(to);
129 assert(full);
130 assert(sz);
131 assert(from_source);
132 assert(to_source);
133
134 do {
135 ssize_t z;
136
137 shoveled = false;
138
139 if (*full < *sz && *from >= 0 && *to >= 0) {
140 z = splice(*from, NULL, buffer[1], NULL, *sz - *full, SPLICE_F_MOVE|SPLICE_F_NONBLOCK);
141 if (z > 0) {
142 *full += z;
143 shoveled = true;
144 } else if (z == 0 || IN_SET(errno, EPIPE, ECONNRESET)) {
145 *from_source = sd_event_source_unref(*from_source);
146 *from = safe_close(*from);
147 } else if (!IN_SET(errno, EAGAIN, EINTR))
148 return log_error_errno(errno, "Failed to splice: %m");
149 }
150
151 if (*full > 0 && *to >= 0) {
152 z = splice(buffer[0], NULL, *to, NULL, *full, SPLICE_F_MOVE|SPLICE_F_NONBLOCK);
153 if (z > 0) {
154 *full -= z;
155 shoveled = true;
156 } else if (z == 0 || IN_SET(errno, EPIPE, ECONNRESET)) {
157 *to_source = sd_event_source_unref(*to_source);
158 *to = safe_close(*to);
159 } else if (!IN_SET(errno, EAGAIN, EINTR))
160 return log_error_errno(errno, "Failed to splice: %m");
161 }
162 } while (shoveled);
163
164 return 0;
165 }
166
167 static int connection_enable_event_sources(Connection *c);
168
169 static int traffic_cb(sd_event_source *s, int fd, uint32_t revents, void *userdata) {
170 Connection *c = userdata;
171 int r;
172
173 assert(s);
174 assert(fd >= 0);
175 assert(c);
176
177 r = connection_shovel(c,
178 &c->server_fd, c->server_to_client_buffer, &c->client_fd,
179 &c->server_to_client_buffer_full, &c->server_to_client_buffer_size,
180 &c->server_event_source, &c->client_event_source);
181 if (r < 0)
182 goto quit;
183
184 r = connection_shovel(c,
185 &c->client_fd, c->client_to_server_buffer, &c->server_fd,
186 &c->client_to_server_buffer_full, &c->client_to_server_buffer_size,
187 &c->client_event_source, &c->server_event_source);
188 if (r < 0)
189 goto quit;
190
191 /* EOF on both sides? */
192 if (c->server_fd == -1 && c->client_fd == -1)
193 goto quit;
194
195 /* Server closed, and all data written to client? */
196 if (c->server_fd == -1 && c->server_to_client_buffer_full <= 0)
197 goto quit;
198
199 /* Client closed, and all data written to server? */
200 if (c->client_fd == -1 && c->client_to_server_buffer_full <= 0)
201 goto quit;
202
203 r = connection_enable_event_sources(c);
204 if (r < 0)
205 goto quit;
206
207 return 1;
208
209 quit:
210 connection_free(c);
211 return 0; /* ignore errors, continue serving */
212 }
213
214 static int connection_enable_event_sources(Connection *c) {
215 uint32_t a = 0, b = 0;
216 int r;
217
218 assert(c);
219
220 if (c->server_to_client_buffer_full > 0)
221 b |= EPOLLOUT;
222 if (c->server_to_client_buffer_full < c->server_to_client_buffer_size)
223 a |= EPOLLIN;
224
225 if (c->client_to_server_buffer_full > 0)
226 a |= EPOLLOUT;
227 if (c->client_to_server_buffer_full < c->client_to_server_buffer_size)
228 b |= EPOLLIN;
229
230 if (c->server_event_source)
231 r = sd_event_source_set_io_events(c->server_event_source, a);
232 else if (c->server_fd >= 0)
233 r = sd_event_add_io(c->context->event, &c->server_event_source, c->server_fd, a, traffic_cb, c);
234 else
235 r = 0;
236
237 if (r < 0)
238 return log_error_errno(r, "Failed to set up server event source: %m");
239
240 if (c->client_event_source)
241 r = sd_event_source_set_io_events(c->client_event_source, b);
242 else if (c->client_fd >= 0)
243 r = sd_event_add_io(c->context->event, &c->client_event_source, c->client_fd, b, traffic_cb, c);
244 else
245 r = 0;
246
247 if (r < 0)
248 return log_error_errno(r, "Failed to set up client event source: %m");
249
250 return 0;
251 }
252
253 static int connection_complete(Connection *c) {
254 int r;
255
256 assert(c);
257
258 r = connection_create_pipes(c, c->server_to_client_buffer, &c->server_to_client_buffer_size);
259 if (r < 0)
260 goto fail;
261
262 r = connection_create_pipes(c, c->client_to_server_buffer, &c->client_to_server_buffer_size);
263 if (r < 0)
264 goto fail;
265
266 r = connection_enable_event_sources(c);
267 if (r < 0)
268 goto fail;
269
270 return 0;
271
272 fail:
273 connection_free(c);
274 return 0; /* ignore errors, continue serving */
275 }
276
277 static int connect_cb(sd_event_source *s, int fd, uint32_t revents, void *userdata) {
278 Connection *c = userdata;
279 socklen_t solen;
280 int error, r;
281
282 assert(s);
283 assert(fd >= 0);
284 assert(c);
285
286 solen = sizeof(error);
287 r = getsockopt(fd, SOL_SOCKET, SO_ERROR, &error, &solen);
288 if (r < 0) {
289 log_error_errno(errno, "Failed to issue SO_ERROR: %m");
290 goto fail;
291 }
292
293 if (error != 0) {
294 log_error_errno(error, "Failed to connect to remote host: %m");
295 goto fail;
296 }
297
298 c->client_event_source = sd_event_source_unref(c->client_event_source);
299
300 return connection_complete(c);
301
302 fail:
303 connection_free(c);
304 return 0; /* ignore errors, continue serving */
305 }
306
307 static int connection_start(Connection *c, struct sockaddr *sa, socklen_t salen) {
308 int r;
309
310 assert(c);
311 assert(sa);
312 assert(salen);
313
314 c->client_fd = socket(sa->sa_family, SOCK_STREAM|SOCK_NONBLOCK|SOCK_CLOEXEC, 0);
315 if (c->client_fd < 0) {
316 log_error_errno(errno, "Failed to get remote socket: %m");
317 goto fail;
318 }
319
320 r = connect(c->client_fd, sa, salen);
321 if (r < 0) {
322 if (errno == EINPROGRESS) {
323 r = sd_event_add_io(c->context->event, &c->client_event_source, c->client_fd, EPOLLOUT, connect_cb, c);
324 if (r < 0) {
325 log_error_errno(r, "Failed to add connection socket: %m");
326 goto fail;
327 }
328
329 r = sd_event_source_set_enabled(c->client_event_source, SD_EVENT_ONESHOT);
330 if (r < 0) {
331 log_error_errno(r, "Failed to enable oneshot event source: %m");
332 goto fail;
333 }
334 } else {
335 log_error_errno(errno, "Failed to connect to remote host: %m");
336 goto fail;
337 }
338 } else {
339 r = connection_complete(c);
340 if (r < 0)
341 goto fail;
342 }
343
344 return 0;
345
346 fail:
347 connection_free(c);
348 return 0; /* ignore errors, continue serving */
349 }
350
351 static int resolve_handler(sd_resolve_query *q, int ret, const struct addrinfo *ai, Connection *c) {
352 assert(q);
353 assert(c);
354
355 if (ret != 0) {
356 log_error("Failed to resolve host: %s", gai_strerror(ret));
357 goto fail;
358 }
359
360 c->resolve_query = sd_resolve_query_unref(c->resolve_query);
361
362 return connection_start(c, ai->ai_addr, ai->ai_addrlen);
363
364 fail:
365 connection_free(c);
366 return 0; /* ignore errors, continue serving */
367 }
368
369 static int resolve_remote(Connection *c) {
370
371 static const struct addrinfo hints = {
372 .ai_family = AF_UNSPEC,
373 .ai_socktype = SOCK_STREAM,
374 .ai_flags = AI_ADDRCONFIG
375 };
376
377 union sockaddr_union sa = {};
378 const char *node, *service;
379 int r;
380
381 if (IN_SET(arg_remote_host[0], '/', '@')) {
382 int salen;
383
384 salen = sockaddr_un_set_path(&sa.un, arg_remote_host);
385 if (salen < 0) {
386 log_error_errno(salen, "Specified address doesn't fit in an AF_UNIX address, refusing: %m");
387 goto fail;
388 }
389
390 return connection_start(c, &sa.sa, salen);
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 != -EAGAIN)
470 log_warning_errno(errno, "Failed to accept() socket: %m");
471 } else {
472 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);