Debian Codegraph @

src/socket-proxy/socket-proxyd.c

raw
1 /* SPDX-License-Identifier: LGPL-2.1-or-later */
2
3 #include <netdb.h>
4 #include <stdio.h>
5 #include <unistd.h>
6
7 #include "sd-daemon.h"
8 #include "sd-event.h"
9 #include "sd-resolve.h"
10
11 #include "alloc-util.h"
12 #include "build.h"
13 #include "daemon-util.h"
14 #include "errno-util.h"
15 #include "event-util.h"
16 #include "fd-util.h"
17 #include "format-table.h"
18 #include "in-addr-util.h"
19 #include "io-util.h"
20 #include "log.h"
21 #include "main-func.h"
22 #include "options.h"
23 #include "parse-util.h"
24 #include "pretty-print.h"
25 #include "resolve-private.h"
26 #include "set.h"
27 #include "socket-forward.h"
28 #include "socket-util.h"
29 #include "string-table.h"
30 #include "string-util.h"
31 #include "strv.h"
32 #include "time-util.h"
33
34 static unsigned arg_connections_max = 256;
35 static const char *arg_remote_host = NULL;
36 static usec_t arg_exit_idle_time = USEC_INFINITY;
37
38 typedef enum ProxyProtocol {
39 PROXY_NONE,
40 PROXY_V1,
41 _PROXY_PROTOCOL_MAX,
42 _PROXY_PROTOCOL_INVALID = -EINVAL,
43 } ProxyProtocol;
44
45 static const char* const proxy_protocol_table[_PROXY_PROTOCOL_MAX] = {
46 [PROXY_V1] = "v1",
47 };
48
49 static ProxyProtocol arg_proxy_protocol = PROXY_NONE;
50
51 DEFINE_PRIVATE_STRING_TABLE_LOOKUP_FROM_STRING(proxy_protocol, ProxyProtocol);
52
53 typedef struct Context {
54 sd_event *event;
55 sd_resolve *resolve;
56 sd_event_source *idle_time;
57
58 Set *listen;
59 Set *connections;
60 } Context;
61
62 typedef struct Connection {
63 Context *context;
64
65 int server_fd, client_fd;
66
67 sd_event_source *connect_event_source;
68
69 SocketForward *forward;
70
71 sd_resolve_query *resolve_query;
72 } Connection;
73
74 static Connection* connection_free(Connection *c) {
75 if (!c)
76 return NULL;
77
78 if (c->context)
79 set_remove(c->context->connections, c);
80
81 sd_event_source_unref(c->connect_event_source);
82 socket_forward_free(c->forward);
83
84 safe_close(c->server_fd);
85 safe_close(c->client_fd);
86
87 sd_resolve_query_unref(c->resolve_query);
88
89 return mfree(c);
90 }
91
92 DEFINE_TRIVIAL_CLEANUP_FUNC(Connection*, connection_free);
93
94 DEFINE_PRIVATE_HASH_OPS_WITH_VALUE_DESTRUCTOR(
95 connection_hash_ops,
96 void, trivial_hash_func, trivial_compare_func,
97 Connection, connection_free);
98
99 static void context_done(Context *context) {
100 assert(context);
101
102 set_free(context->listen);
103 set_free(context->connections);
104
105 sd_event_unref(context->event);
106 sd_resolve_unref(context->resolve);
107 sd_event_source_unref(context->idle_time);
108 }
109
110 static int idle_time_cb(sd_event_source *s, uint64_t usec, void *userdata) {
111 Context *c = userdata;
112 int r;
113
114 if (!set_isempty(c->connections)) {
115 log_warning("Idle timer fired even though there are connections, ignoring");
116 return 0;
117 }
118
119 r = sd_event_exit(c->event, 0);
120 if (r < 0) {
121 log_warning_errno(r, "Error while stopping event loop, ignoring: %m");
122 return 0;
123 }
124 return 0;
125 }
126
127 static void context_reset_timer(Context *context) {
128 int r;
129
130 assert(context);
131
132 if (arg_exit_idle_time < USEC_INFINITY && set_isempty(context->connections)) {
133 r = event_reset_time_relative(
134 context->event, &context->idle_time, CLOCK_MONOTONIC,
135 arg_exit_idle_time, 0, idle_time_cb, context,
136 SD_EVENT_PRIORITY_NORMAL, "idle-timer", /* force_reset= */ true);
137 if (r < 0)
138 log_warning_errno(r, "Failed to reset idle timer, ignoring: %m");
139 }
140 }
141
142 static void connection_release(Connection *c) {
143 Context *context = ASSERT_PTR(ASSERT_PTR(c)->context);
144
145 connection_free(c);
146 context_reset_timer(context);
147 }
148
149 static int connection_forward_done(SocketForward *sf, int error, void *userdata) {
150 Connection *c = ASSERT_PTR(userdata);
151
152 if (error < 0)
153 log_error_errno(error, "Forwarding failed: %m");
154
155 connection_release(c);
156 return 0; /* ignore errors, continue serving */
157 }
158
159 static int send_proxy_protocol_v1(Connection *c) {
160 _cleanup_free_ char *header = NULL;
161 int r, header_len;
162 union sockaddr_union local_sa, remote_sa;
163 socklen_t sa_len;
164
165 assert(c);
166
167 r = sd_is_socket(c->server_fd, AF_UNSPEC, SOCK_STREAM, /* listening= */ 0);
168 if (r < 0) {
169 log_warning_errno(r, "Failed to issue SO_TYPE, reporting fallback proxy data 'UNKNOWN': %m");
170 goto unknown;
171 }
172 if (r == 0) {
173 log_warning("Only TCP is supported by the PROXY protocol, reporting fallback proxy data 'UNKNOWN'.");
174 goto unknown;
175 }
176
177 sa_len = sizeof(local_sa);
178 if (getsockname(c->server_fd, &local_sa.sa, &sa_len) < 0) {
179 log_warning_errno(errno, "Failed to get local address (getsockname), reporting fallback proxy data 'UNKNOWN': %m");
180 goto unknown;
181 }
182
183 sa_len = sizeof(remote_sa);
184 if (getpeername(c->server_fd, &remote_sa.sa, &sa_len) < 0) {
185 log_warning_errno(errno, "Failed to get remote address (getpeername), reporting fallback proxy data 'UNKNOWN': %m");
186 goto unknown;
187 }
188
189 const char *proto = NULL;
190 switch (remote_sa.sa.sa_family) {
191
192 case AF_INET:
193 proto = "TCP4";
194 break;
195
196 case AF_INET6:
197 proto = "TCP6";
198 break;
199
200 default:
201 log_warning("Only TCP over IPv4 and IPv6 are supported, reporting fallback proxy data 'UNKNOWN'.");
202 goto unknown;
203 }
204
205 const union in_addr_union *remote_addr = sockaddr_in_addr(&remote_sa.sa);
206 const union in_addr_union *local_addr = sockaddr_in_addr(&local_sa.sa);
207
208 unsigned remote_port, local_port;
209 assert_se(sockaddr_port(&remote_sa.sa, &remote_port) >= 0);
210 assert_se(sockaddr_port(&local_sa.sa, &local_port) >= 0);
211
212 header_len = asprintf(
213 &header, "PROXY %s %s %s %u %u\r\n",
214 proto,
215 IN_ADDR_TO_STRING(remote_sa.sa.sa_family, remote_addr),
216 IN_ADDR_TO_STRING(local_sa.sa.sa_family, local_addr),
217 remote_port,
218 local_port);
219 if (header_len < 0)
220 return log_oom();
221
222 r = loop_write_full(c->client_fd, header, header_len, 10 * USEC_PER_SEC);
223 if (r < 0)
224 return log_error_errno(r, "Failed to write to backend host: %m");
225
226 /* success */
227 return 0;
228
229 unknown:
230 /* ignore previous errors - server can decide to deny UNKNOWN connections */
231 r = loop_write_full(c->client_fd, "PROXY UNKNOWN\r\n", SIZE_MAX, 10 * USEC_PER_SEC);
232 if (r < 0)
233 return log_error_errno(r, "Failed to write to backend host: %m");
234
235 return 0;
236 }
237
238 static int connection_complete(Connection *c) {
239 int r;
240
241 assert(c);
242
243 if (arg_proxy_protocol == PROXY_V1) {
244 r = send_proxy_protocol_v1(c);
245 if (r < 0)
246 return r;
247 }
248
249 r = socket_forward_new(
250 c->context->event,
251 TAKE_FD(c->server_fd),
252 TAKE_FD(c->client_fd),
253 connection_forward_done, c,
254 &c->forward);
255 if (r < 0)
256 return log_error_errno(r, "Failed to set up forwarding: %m");
257
258 return 0;
259 }
260
261 static int connect_cb(sd_event_source *s, int fd, uint32_t revents, void *userdata) {
262 Connection *c = ASSERT_PTR(userdata);
263 socklen_t solen;
264 int error;
265
266 assert(s);
267 assert(fd >= 0);
268
269 solen = sizeof(error);
270 if (getsockopt(fd, SOL_SOCKET, SO_ERROR, &error, &solen) < 0) {
271 log_error_errno(errno, "Failed to issue SO_ERROR: %m");
272 goto fail;
273 }
274
275 if (error != 0) {
276 log_error_errno(error, "Failed to connect to remote host: %m");
277 goto fail;
278 }
279
280 c->connect_event_source = sd_event_source_unref(c->connect_event_source);
281
282 if (connection_complete(c) < 0)
283 goto fail;
284
285 return 0;
286
287 fail:
288 connection_release(c);
289 return 0; /* ignore errors, continue serving */
290 }
291
292 static int connection_start(Connection *c, struct sockaddr *sa, socklen_t salen) {
293 int r;
294
295 assert(c);
296 assert(sa);
297 assert(salen);
298
299 c->client_fd = socket(sa->sa_family, SOCK_STREAM|SOCK_NONBLOCK|SOCK_CLOEXEC, 0);
300 if (c->client_fd < 0)
301 return log_error_errno(errno, "Failed to get remote socket: %m");
302
303 r = connect(c->client_fd, sa, salen);
304 if (r < 0) {
305 if (errno != EINPROGRESS)
306 return log_error_errno(errno, "Failed to connect to remote host: %m");
307
308 r = sd_event_add_io(c->context->event, &c->connect_event_source, c->client_fd, EPOLLOUT, connect_cb, c);
309 if (r < 0)
310 return log_error_errno(r, "Failed to add connection socket: %m");
311
312 r = sd_event_source_set_enabled(c->connect_event_source, SD_EVENT_ONESHOT);
313 if (r < 0)
314 return log_error_errno(r, "Failed to enable oneshot event source: %m");
315
316 return 0;
317 }
318
319 return connection_complete(c);
320 }
321
322 static int resolve_handler(sd_resolve_query *q, int ret, const struct addrinfo *ai, Connection *c) {
323 assert(q);
324 assert(c);
325
326 if (ret != 0) {
327 log_error("Failed to resolve host: %s", gai_strerror(ret));
328 goto fail;
329 }
330
331 c->resolve_query = sd_resolve_query_unref(c->resolve_query);
332
333 if (connection_start(c, ai->ai_addr, ai->ai_addrlen) < 0)
334 goto fail;
335
336 return 0;
337
338 fail:
339 connection_release(c);
340 return 0; /* ignore errors, continue serving */
341 }
342
343 static int resolve_remote(Connection *c) {
344
345 static const struct addrinfo hints = {
346 .ai_family = AF_UNSPEC,
347 .ai_socktype = SOCK_STREAM,
348 };
349
350 const char *node, *service;
351 int r;
352
353 if (IN_SET(arg_remote_host[0], '/', '@')) {
354 union sockaddr_union sa;
355 int sa_len;
356
357 r = sockaddr_un_set_path(&sa.un, arg_remote_host);
358 if (r < 0)
359 return log_error_errno(r, "Specified address doesn't fit in an AF_UNIX address, refusing: %m");
360 sa_len = r;
361
362 return connection_start(c, &sa.sa, sa_len);
363 }
364
365 service = strrchr(arg_remote_host, ':');
366 if (service) {
367 node = strndupa_safe(arg_remote_host,
368 service - arg_remote_host);
369 service++;
370 } else {
371 node = arg_remote_host;
372 service = "80";
373 }
374
375 log_debug("Looking up address info for %s:%s", node, service);
376 r = resolve_getaddrinfo(c->context->resolve, &c->resolve_query, node, service, &hints, resolve_handler, NULL, c);
377 if (r < 0)
378 return log_error_errno(r, "Failed to resolve remote host: %m");
379
380 return 0;
381 }
382
383 static int context_add_connection(Context *context, int fd) {
384 int r;
385
386 assert(context);
387
388 _cleanup_close_ int nfd = accept4(fd, NULL, NULL, SOCK_NONBLOCK|SOCK_CLOEXEC);
389 if (nfd < 0) {
390 if (!ERRNO_IS_ACCEPT_AGAIN(errno))
391 log_warning_errno(errno, "Failed to accept() socket, ignoring: %m");
392
393 return -errno;
394 }
395
396 if (DEBUG_LOGGING) {
397 _cleanup_free_ char *peer = NULL;
398 (void) getpeername_pretty(nfd, true, &peer);
399 log_debug("New connection from %s", strna(peer));
400 }
401
402 if (set_size(context->connections) > arg_connections_max)
403 return log_warning_errno(SYNTHETIC_ERRNO(EBUSY), "Hit connection limit, refusing connection.");
404
405 r = sd_event_source_set_enabled(context->idle_time, SD_EVENT_OFF);
406 if (r < 0)
407 log_warning_errno(r, "Unable to disable idle timer, continuing: %m");
408
409 _cleanup_(connection_freep) Connection *c = new(Connection, 1);
410 if (!c)
411 return log_oom();
412
413 *c = (Connection) {
414 .server_fd = TAKE_FD(nfd),
415 .client_fd = -EBADF,
416 };
417
418 r = set_ensure_put(&context->connections, &connection_hash_ops, c);
419 if (r < 0)
420 return log_oom();
421
422 c->context = context;
423
424 r = resolve_remote(c);
425 if (r < 0)
426 return r;
427
428 TAKE_PTR(c);
429 return 0;
430 }
431
432 static int accept_cb(sd_event_source *s, int fd, uint32_t revents, void *userdata) {
433 Context *context = ASSERT_PTR(userdata);
434 int r;
435
436 assert(s);
437 assert(fd >= 0);
438 assert(revents & EPOLLIN);
439
440 if (context_add_connection(context, fd) < 0)
441 context_reset_timer(context);
442
443 r = sd_event_source_set_enabled(s, SD_EVENT_ONESHOT);
444 if (r < 0)
445 return log_error_errno(r, "Error while re-enabling listener with ONESHOT: %m");
446
447 return 1;
448 }
449
450 static int add_listen_socket(Context *context, int fd) {
451 int r;
452
453 assert(context);
454 assert(fd >= 0);
455
456 r = sd_is_socket(fd, 0, SOCK_STREAM, 1);
457 if (r < 0)
458 return log_error_errno(r, "Failed to determine socket type: %m");
459 if (r == 0)
460 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
461 "Passed in socket is not a stream socket.");
462
463 r = fd_nonblock(fd, true);
464 if (r < 0)
465 return log_error_errno(r, "Failed to mark file descriptor non-blocking: %m");
466
467 _cleanup_(sd_event_source_unrefp) sd_event_source *source = NULL;
468 r = sd_event_add_io(context->event, &source, fd, EPOLLIN, accept_cb, context);
469 if (r < 0)
470 return log_error_errno(r, "Failed to add event source: %m");
471
472 r = sd_event_source_set_exit_on_failure(source, true);
473 if (r < 0)
474 return log_error_errno(r, "Failed to enable exit-on-failure logic: %m");
475
476 /* Set the watcher to oneshot in case other processes are also
477 * watching to accept(). */
478 r = sd_event_source_set_enabled(source, SD_EVENT_ONESHOT);
479 if (r < 0)
480 return log_error_errno(r, "Failed to enable oneshot mode: %m");
481
482 r = set_ensure_consume(&context->listen, &event_source_hash_ops, TAKE_PTR(source));
483 if (r < 0)
484 return log_error_errno(r, "Failed to add source to set: %m");
485
486 return 0;
487 }
488
489 static int help(void) {
490 _cleanup_free_ char *link = NULL, *time_link = NULL;
491 _cleanup_(table_unrefp) Table *options = NULL;
492 int r;
493
494 r = terminal_urlify_man("systemd-socket-proxyd", "8", &link);
495 if (r < 0)
496 return log_oom();
497 r = terminal_urlify_man("systemd.time", "7", &time_link);
498 if (r < 0)
499 return log_oom();
500
501 r = option_parser_get_help_table(&options);
502 if (r < 0)
503 return r;
504
505 printf("%1$s [HOST:PORT]\n"
506 "%1$s [SOCKET]\n"
507 "\n%2$sBidirectionally proxy local sockets to another (possibly remote) socket.%3$s\n\n",
508 program_invocation_short_name,
509 ansi_highlight(),
510 ansi_normal());
511
512 r = table_print_or_warn(options);
513 if (r < 0)
514 return r;
515
516 printf("\nSee %s for --exit-idle-time= time span format.\n"
517 "See the %s for details.\n",
518 time_link, link);
519 return 0;
520 }
521
522 static int parse_argv(int argc, char *argv[]) {
523 assert(argc >= 0);
524 assert(argv);
525
526 OptionParser opts = { argc, argv };
527 int r;
528
529 FOREACH_OPTION_OR_RETURN(c, &opts)
530 switch (c) {
531
532 OPTION_COMMON_HELP:
533 return help();
534
535 OPTION_COMMON_VERSION:
536 return version();
537
538 OPTION('c', "connections-max", "NUMBER",
539 "Set the maximum number of connections to be accepted"):
540 r = safe_atou(opts.arg, &arg_connections_max);
541 if (r < 0)
542 return log_error_errno(r, "Failed to parse --connections-max= argument: %s", opts.arg);
543
544 if (arg_connections_max < 1)
545 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
546 "Connection limit is too low.");
547
548 break;
549
550 OPTION_LONG("exit-idle-time", "TIME",
551 "Exit when without a connection for this duration"):
552 r = parse_sec(opts.arg, &arg_exit_idle_time);
553 if (r < 0)
554 return log_error_errno(r, "Failed to parse --exit-idle-time= argument: %s", opts.arg);
555 break;
556
557 OPTION_LONG("proxy-protocol", "v1",
558 "Enable PROXY protocol: v1"):
559 arg_proxy_protocol = proxy_protocol_from_string(opts.arg);
560 if (arg_proxy_protocol < 0)
561 return log_error_errno(arg_proxy_protocol, "Failed to parse --proxy-protocol= argument: %s", opts.arg);
562 break;
563 }
564
565 char **args = option_parser_get_args(&opts);
566 size_t n = strv_length(args);
567 if (n < 1)
568 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Not enough parameters.");
569 if (n > 1)
570 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Too many parameters.");
571
572 arg_remote_host = args[0];
573 return 1;
574 }
575
576 static int run(int argc, char *argv[]) {
577 _cleanup_(context_done) Context context = {};
578 _unused_ _cleanup_(notify_on_cleanup) const char *notify_stop = NULL;
579 int r, n, fd;
580
581 log_setup();
582
583 r = parse_argv(argc, argv);
584 if (r <= 0)
585 return r;
586
587 r = sd_event_default(&context.event);
588 if (r < 0)
589 return log_error_errno(r, "Failed to allocate event loop: %m");
590
591 r = sd_resolve_default(&context.resolve);
592 if (r < 0)
593 return log_error_errno(r, "Failed to allocate resolver: %m");
594
595 r = sd_resolve_attach_event(context.resolve, context.event, 0);
596 if (r < 0)
597 return log_error_errno(r, "Failed to attach resolver: %m");
598
599 sd_event_set_watchdog(context.event, true);
600
601 r = sd_listen_fds(1);
602 if (r < 0)
603 return log_error_errno(r, "Failed to receive sockets from parent.");
604 if (r == 0)
605 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Didn't get any sockets passed in.");
606
607 n = r;
608
609 for (fd = SD_LISTEN_FDS_START; fd < SD_LISTEN_FDS_START + n; fd++) {
610 r = add_listen_socket(&context, fd);
611 if (r < 0)
612 return r;
613 }
614
615 notify_stop = notify_start(NOTIFY_READY_MESSAGE, NOTIFY_STOPPING_MESSAGE);
616 r = sd_event_loop(context.event);
617 if (r < 0)
618 return log_error_errno(r, "Failed to run event loop: %m");
619
620 return 0;
621 }
622
623 DEFINE_MAIN_FUNCTION(run);