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