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