summaryrefslogtreecommitdiff
path: root/src/sabridge/sabridge.c
blob: 058987187008fc681f580c5cb8ee0485081264e8 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/

/***
  This file is part of systemd.

  Copyright 2013 David Strauss

  systemd is free software; you can redistribute it and/or modify it
  under the terms of the GNU Lesser General Public License as published by
  the Free Software Foundation; either version 2.1 of the License, or
  (at your option) any later version.

  systemd is distributed in the hope that it will be useful, but
  WITHOUT ANY WARRANTY; without even the implied warranty of
  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  Lesser General Public License for more details.

  You should have received a copy of the GNU Lesser General Public License
  along with systemd; If not, see <http://www.gnu.org/licenses/>.
 ***/

#include <arpa/inet.h>
#include <errno.h>
#include <getopt.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <netdb.h>
#include <sys/fcntl.h>
#include <sys/socket.h>
#include <sys/un.h>
#include <unistd.h>

#include "log.h"
#include "sd-daemon.h"
#include "sd-event.h"
#include "socket-util.h"
#include "util.h"

#define BUFFER_SIZE 4096
#define _cleanup_freeaddrinfo_ _cleanup_(freeaddrinfop)

unsigned int total_clients = 0;

DEFINE_TRIVIAL_CLEANUP_FUNC(struct addrinfo *, freeaddrinfo);

struct proxy {
        int listen_fd;
        bool ignore_env;
        bool remote_is_inet;
        const char *remote_host;
        const char *remote_service;
};

struct connection {
        int fd;
        sd_event_source *w_recv;
        sd_event_source *w_send;
        struct connection *c_destination;
        size_t buffer_filled_len;
        size_t buffer_sent_len;
        char buffer[BUFFER_SIZE];
};

static void free_connection(struct connection *c) {
        log_debug("Freeing fd=%d (conn %p).", c->fd, c);
        sd_event_source_unref(c->w_recv);
        sd_event_source_unref(c->w_send);
        close(c->fd);
        free(c);
}

static int send_buffer(struct connection *sender) {
        struct connection *receiver = sender->c_destination;
        ssize_t len;
        int r = 0;

        /* We cannot assume that even a partial send() indicates that
         * the next send() will block. Loop until it does. */
        while (sender->buffer_filled_len > sender->buffer_sent_len) {
                len = send(receiver->fd, sender->buffer + sender->buffer_sent_len, sender->buffer_filled_len - sender->buffer_sent_len, 0);
                log_debug("send(%d, ...)=%ld", receiver->fd, len);
                if (len < 0) {
                        if (errno != EWOULDBLOCK && errno != EAGAIN) {
                                log_error("Error %d in send to fd=%d: %m", errno, receiver->fd);
                                return -errno;
                        }
                        else {
                                /* send() is in a blocking state. */
                                break;
                        }
                }

                /* len < 0 can't occur here. len == 0 is possible but
                 * undefined behavior for nonblocking send(). */
                assert(len > 0);
                sender->buffer_sent_len += len;
        }

        log_debug("send(%d, ...) completed with %lu bytes still buffered.", receiver->fd, sender->buffer_filled_len - sender->buffer_sent_len);

        /* Detect a would-block state or partial send. */
        if (sender->buffer_filled_len > sender->buffer_sent_len) {

                /* If the buffer is full, disable events coming for recv. */
                if (sender->buffer_filled_len == BUFFER_SIZE) {
                    r = sd_event_source_set_enabled(sender->w_recv, SD_EVENT_OFF);
                    if (r < 0) {
                            log_error("Error %d disabling recv for fd=%d: %s", r, sender->fd, strerror(-r));
                            return r;
                    }
                }

                /* Watch for when the recipient can be sent data again. */
                r = sd_event_source_set_enabled(receiver->w_send, SD_EVENT_ON);
                if (r < 0) {
                        log_error("Error %d enabling send for fd=%d: %s", r, receiver->fd, strerror(-r));
                        return r;
                }
                log_debug("Done with recv for fd=%d. Waiting on send for fd=%d.", sender->fd, receiver->fd);
                return r;
        }

        /* If we sent everything without blocking, the buffer is now empty. */
        sender->buffer_filled_len = 0;
        sender->buffer_sent_len = 0;

        /* Unmute the sender, in case the buffer was full. */
        r = sd_event_source_set_enabled(sender->w_recv, SD_EVENT_ON);
        if (r < 0) {
                log_error("Error %d enabling recv for fd=%d: %s", r, sender->fd, strerror(-r));
                return r;
        }

        /* Mute the recipient, as we have no data to send now. */
        r = sd_event_source_set_enabled(receiver->w_send, SD_EVENT_OFF);
        if (r < 0) {
                log_error("Error %d disabling send for fd=%d: %s", r, receiver->fd, strerror(-r));
                return r;
        }

        return 0;
}

static int transfer_data_cb(sd_event_source *s, int fd, uint32_t revents, void *userdata) {
        struct connection *c = (struct connection *) userdata;
        int r = 0;
        ssize_t len;

        assert(revents & (EPOLLIN | EPOLLOUT));
        assert(fd == c->fd);

        log_debug("Got event revents=%d from fd=%d (conn %p).", revents, fd, c);

        if (revents & EPOLLIN) {
                log_debug("About to recv up to %lu bytes from fd=%d (%lu/BUFFER_SIZE).", BUFFER_SIZE - c->buffer_filled_len, fd, c->buffer_filled_len);

                assert(s == c->w_recv);

                /* Receive until the buffer's full, there's no more data,
                 * or the client/server disconnects. */
                while (c->buffer_filled_len < BUFFER_SIZE) {
                        len = recv(fd, c->buffer + c->buffer_filled_len, BUFFER_SIZE - c->buffer_filled_len, 0);
                        log_debug("recv(%d, ...)=%ld", fd, len);
                        if (len < 0) {
                                if (errno != EWOULDBLOCK && errno != EAGAIN) {
                                        log_error("Error %d in recv from fd=%d: %m", errno, fd);
                                        return -errno;
                                }
                                else {
                                        /* recv() is in a blocking state. */
                                        break;
                                }
                        }
                        else if (len == 0) {
                                log_debug("Clean disconnection from fd=%d", fd);
                                total_clients--;
                                free_connection(c->c_destination);
                                free_connection(c);
                                return 0;
                        }

                        assert(len > 0);
                        log_debug("Recording that the buffer got %ld more bytes full.", len);
                        c->buffer_filled_len += len;
                        log_debug("Buffer now has %ld bytes full.", c->buffer_filled_len);
                }

                /* Try sending the data immediately. */
                return send_buffer(c);
        }
        else {
                assert(s == c->w_send);
                return send_buffer(c->c_destination);
        }

        return r;
}

/* Once sending to the server is unblocked, set up the real watchers. */
static int connected_to_server_cb(sd_event_source *s, int fd, uint32_t revents, void *userdata) {
        struct sd_event *e = NULL;
        struct connection *c_server_to_client = (struct connection *) userdata;
        struct connection *c_client_to_server = c_server_to_client->c_destination;
        int r;

        assert(revents & EPOLLOUT);

        e = sd_event_get(s);

        /* Cancel the initial write watcher for the server. */
        sd_event_source_unref(s);

        log_debug("Connected to server. Initializing watchers for receiving data.");

        /* A disabled send watcher for the server. */
        r = sd_event_add_io(e, c_server_to_client->fd, EPOLLOUT, transfer_data_cb, c_server_to_client, &c_server_to_client->w_send);
        if (r < 0) {
                log_error("Error %d creating send watcher for fd=%d: %s", r, c_server_to_client->fd, strerror(-r));
                goto fail;
        }
        r = sd_event_source_set_enabled(c_server_to_client->w_send, SD_EVENT_OFF);
        if (r < 0) {
                log_error("Error %d muting send for fd=%d: %s", r, c_server_to_client->fd, strerror(-r));
                goto finish;
        }

        /* A recv watcher for the server. */
        r = sd_event_add_io(e, c_server_to_client->fd, EPOLLIN, transfer_data_cb, c_server_to_client, &c_server_to_client->w_recv);
        if (r < 0) {
                log_error("Error %d creating recv watcher for fd=%d: %s", r, c_server_to_client->fd, strerror(-r));
                goto fail;
        }

        /* A disabled send watcher for the client. */
        r = sd_event_add_io(e, c_client_to_server->fd, EPOLLOUT, transfer_data_cb, c_client_to_server, &c_client_to_server->w_send);
        if (r < 0) {
                log_error("Error %d creating send watcher for fd=%d: %s", r, c_client_to_server->fd, strerror(-r));
                goto fail;
        }
        r = sd_event_source_set_enabled(c_client_to_server->w_send, SD_EVENT_OFF);
        if (r < 0) {
                log_error("Error %d muting send for fd=%d: %s", r, c_client_to_server->fd, strerror(-r));
                goto finish;
        }

        /* A recv watcher for the client. */
        r = sd_event_add_io(e, c_client_to_server->fd, EPOLLIN, transfer_data_cb, c_client_to_server, &c_client_to_server->w_recv);
        if (r < 0) {
                log_error("Error %d creating recv watcher for fd=%d: %s", r, c_client_to_server->fd, strerror(-r));
                goto fail;
        }

goto finish;

fail:
        free_connection(c_client_to_server);
        free_connection(c_server_to_client);

finish:
        return r;
}

static int get_server_connection_fd(const struct proxy *proxy) {
        int server_fd;
        int r = -EBADF;
        int len;

        if (proxy->remote_is_inet) {
                int s;
                _cleanup_freeaddrinfo_ struct addrinfo *result = NULL;
                struct addrinfo hints = {.ai_family = AF_UNSPEC,
                                         .ai_socktype = SOCK_STREAM,
                                         .ai_flags = AI_PASSIVE};

                log_debug("Looking up address info for %s:%s", proxy->remote_host, proxy->remote_service);
                s = getaddrinfo(proxy->remote_host, proxy->remote_service, &hints, &result);
                if (s != 0) {
                        log_error("getaddrinfo error (%d): %s", s, gai_strerror(s));
                        return r;
                }

                if (result == NULL) {
                        log_error("getaddrinfo: no result");
                        return r;
                }

                /* @TODO: Try connecting to all results instead of just the first. */
                server_fd = socket(result->ai_family, result->ai_socktype | SOCK_NONBLOCK, result->ai_protocol);
                if (server_fd < 0) {
                        log_error("Error %d creating socket: %m", errno);
                        return r;
                }

                r = connect(server_fd, result->ai_addr, result->ai_addrlen);
                /* Ignore EINPROGRESS errors because they're expected for a nonblocking socket. */
                if (r < 0 && errno != EINPROGRESS) {
                        log_error("Error %d while connecting to socket %s:%s: %m", errno, proxy->remote_host, proxy->remote_service);
                        return r;
                }
        }
        else {
                struct sockaddr_un remote;

                server_fd = socket(AF_UNIX, SOCK_STREAM | SOCK_NONBLOCK, 0);
                if (server_fd < 0) {
                        log_error("Error %d creating socket: %m", errno);
                        return -EBADFD;
                }

                remote.sun_family = AF_UNIX;
                strncpy(remote.sun_path, proxy->remote_host, sizeof(remote.sun_path));
                len = strlen(remote.sun_path) + sizeof(remote.sun_family);
                r = connect(server_fd, (struct sockaddr *) &remote, len);
                if (r < 0 && errno != EINPROGRESS) {
                        log_error("Error %d while connecting to Unix domain socket %s: %m", errno, proxy->remote_host);
                        return -EBADFD;
                }
        }

        log_debug("Server connection is fd=%d", server_fd);
        return server_fd;
}

static int accept_cb(sd_event_source *s, int fd, uint32_t revents, void *userdata) {
        struct proxy *proxy = (struct proxy *) userdata;
        struct connection *c_server_to_client;
        struct connection *c_client_to_server;
        int r = 0;
        union sockaddr_union sa;
        socklen_t salen = sizeof(sa);

        assert(revents & EPOLLIN);

        c_server_to_client = malloc0(sizeof(struct connection));
        if (c_server_to_client == NULL) {
                log_oom();
                goto fail;
        }

        c_client_to_server = malloc0(sizeof(struct connection));
        if (c_client_to_server == NULL) {
                log_oom();
                goto fail;
        }

        c_server_to_client->fd = get_server_connection_fd(proxy);
        if (c_server_to_client->fd < 0) {
                log_error("Error initiating server connection.");
                goto fail;
        }

        c_client_to_server->fd = accept(fd, (struct sockaddr *) &sa, &salen);
        if (c_client_to_server->fd < 0) {
                log_error("Error accepting client connection.");
                goto fail;
        }

        /* Unlike on BSD, client sockets do not inherit nonblocking status
         * from the listening socket. */
        r = fd_nonblock(c_client_to_server->fd, true);
        if (r < 0) {
                log_error("Error %d marking client connection as nonblocking: %s", r, strerror(-r));
                goto fail;
        }

        if (sa.sa.sa_family == AF_INET || sa.sa.sa_family == AF_INET6) {
                char sa_str[INET6_ADDRSTRLEN];
                const char *success;

                success = inet_ntop(sa.sa.sa_family, &sa.in6.sin6_addr, sa_str, INET6_ADDRSTRLEN);
                if (success == NULL)
                        log_warning("Error %d calling inet_ntop: %m", errno);
                else
                        log_debug("Accepted client connection from %s as fd=%d", sa_str, c_client_to_server->fd);
        }
        else {
                log_debug("Accepted client connection (non-IP) as fd=%d", c_client_to_server->fd);
        }

        total_clients++;
        log_debug("Client fd=%d (conn %p) successfully connected. Total clients: %u", c_client_to_server->fd, c_client_to_server, total_clients);
        log_debug("Server fd=%d (conn %p) successfully initialized.", c_server_to_client->fd, c_server_to_client);

        /* Initialize watcher for send to server; this shows connectivity. */
        r = sd_event_add_io(sd_event_get(s), c_server_to_client->fd, EPOLLOUT, connected_to_server_cb, c_server_to_client, &c_server_to_client->w_send);
        if (r < 0) {
                log_error("Error %d creating connectivity watcher for fd=%d: %s", r, c_server_to_client->fd, strerror(-r));
                goto fail;
        }

        /* Allow lookups of the opposite connection. */
        c_server_to_client->c_destination = c_client_to_server;
        c_client_to_server->c_destination = c_server_to_client;

        goto finish;

fail:
        log_warning("Accepting a client connection or connecting to the server failed.");
        free_connection(c_client_to_server);
        free_connection(c_server_to_client);

finish:
        /* Preserve the main loop even if a single proxy setup fails. */
        return 0;
}

static int run_main_loop(struct proxy *proxy) {
        int r = EXIT_SUCCESS;
        struct sd_event *e = NULL;
        sd_event_source *w_accept = NULL;

        r = sd_event_new(&e);
        if (r < 0)
                goto finish;

        r = fd_nonblock(proxy->listen_fd, true);
        if (r < 0)
                goto finish;

        log_debug("Initializing main listener fd=%d", proxy->listen_fd);

        sd_event_add_io(e, proxy->listen_fd, EPOLLIN, accept_cb, proxy, &w_accept);

        log_debug("Initialized main listener. Entering loop.");

        sd_event_loop(e);

finish:
        sd_event_source_unref(w_accept);
        sd_event_unref(e);

        return r;
}

static int help(void) {

        printf("%s hostname-or-ip port-or-service\n"
               "%s unix-domain-socket-path\n\n"
               "Inherit a socket. Bidirectionally proxy.\n\n"
               "  -h --help       Show this help\n"
               "  --version       Print version and exit\n"
               "  --ignore-env    Ignore expected systemd environment\n",
               program_invocation_short_name,
               program_invocation_short_name);

        return 0;
}

static void version(void) {
        puts(PACKAGE_STRING " sabridge");
}

static int parse_argv(int argc, char *argv[], struct proxy *p) {

        enum {
                ARG_VERSION = 0x100,
                ARG_IGNORE_ENV
        };

        static const struct option options[] = {
                { "help",       no_argument, NULL, 'h'           },
                { "version",    no_argument, NULL, ARG_VERSION   },
                { "ignore-env", no_argument, NULL, ARG_IGNORE_ENV},
                { NULL,         0,           NULL, 0             }
        };

        int c;

        assert(argc >= 0);
        assert(argv);

        while ((c = getopt_long(argc, argv, "h", options, NULL)) >= 0) {

                switch (c) {

                case 'h':
                        help();
                        return 0;

                case '?':
                        return -EINVAL;

                case ARG_VERSION:
                        version();
                        return 0;

                case ARG_IGNORE_ENV:
                        p->ignore_env = true;
                        continue;

                default:
                        log_error("Unknown option code %c", c);
                        return -EINVAL;
                }
        }

        if (optind + 1 != argc && optind + 2 != argc) {
                log_error("Incorrect number of positional arguments.");
                help();
                return -EINVAL;
        }

        p->remote_host = argv[optind];
        assert(p->remote_host);

        p->remote_is_inet = p->remote_host[0] != '/';

        if (optind == argc - 2) {
                if (!p->remote_is_inet) {
                        log_error("A port or service is not allowed for Unix socket destinations.");
                        help();
                        return -EINVAL;
                }
                p->remote_service = argv[optind + 1];
                assert(p->remote_service);
        } else if (p->remote_is_inet) {
                log_error("A port or service is required for IP destinations.");
                help();
                return -EINVAL;
        }

        return 1;
}

int main(int argc, char *argv[]) {
        struct proxy p = {};
        int r;

        log_parse_environment();
        log_open();

        r = parse_argv(argc, argv, &p);
        if (r <= 0)
                goto finish;

        p.listen_fd = SD_LISTEN_FDS_START;

        if (!p.ignore_env) {
            int n;
            n = sd_listen_fds(1);
            if (n == 0) {
                    log_error("Found zero inheritable sockets. Are you sure this is running as a socket-activated service?");
                    r = EXIT_FAILURE;
                    goto finish;
            } else if (n < 0) {
                    log_error("Error %d while finding inheritable sockets: %s", n, strerror(-n));
                    r = EXIT_FAILURE;
                    goto finish;
            } else if (n > 1) {
                    log_error("Can't listen on more than one socket.");
                    r = EXIT_FAILURE;
                    goto finish;
            }
        }

        /* @TODO: Check if this proxy can work with datagram sockets. */
        r = sd_is_socket(p.listen_fd, 0, SOCK_STREAM, 1);
        if (r < 0) {
                log_error("Error %d while checking inherited socket: %s", r, strerror(-r));
                goto finish;
        }

        log_info("Starting the socket activation bridge with listener fd=%d.", p.listen_fd);

        r = run_main_loop(&p);
        if (r < 0) {
                log_error("Error %d from main loop.", r);
                goto finish;
        }

finish:
        log_close();
        return r < 0 ? EXIT_FAILURE : EXIT_SUCCESS;
}