Blob


1 /*
2 * Copyright (c) 2021 Omar Polo <op@omarpolo.com>
3 *
4 * Permission to use, copy, modify, and distribute this software for any
5 * purpose with or without fee is hereby granted, provided that the above
6 * copyright notice and this permission notice appear in all copies.
7 *
8 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
9 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
10 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
11 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
12 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
13 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
14 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
15 */
17 #include <sys/types.h>
18 #include <sys/socket.h>
19 #include <sys/wait.h>
21 #include <ctype.h>
22 #include <err.h>
23 #include <errno.h>
24 #include <event.h>
25 #include <limits.h>
26 #include <netdb.h>
27 #include <signal.h>
28 #include <stdio.h>
29 #include <stdlib.h>
30 #include <string.h>
31 #include <unistd.h>
33 #include <stdint.h>
35 #ifndef SSH_PATH
36 #define SSH_PATH "/usr/bin/ssh"
37 #endif
39 #define MAXSOCK 4
40 #define MAXCONN 16
41 #define BACKOFF 1
42 #define RETRIES 8
44 #ifndef __OpenBSD__
45 #define pledge(p, e) 0
46 #endif
48 const char *addr; /* our addr */
49 const char *ssh_tflag;
50 const char *ssh_dest;
52 char ssh_host[256];
53 char ssh_port[16];
55 struct event sockev[MAXSOCK];
56 int socks[MAXSOCK];
57 int nsock;
59 struct event sighupev;
60 struct event sigintev;
61 struct event sigtermev;
62 struct event sigchldev;
63 struct event siginfoev;
65 struct timeval timeout = {120, 0};
66 struct event timeoutev;
68 pid_t ssh_pid = -1;
70 int conn;
72 struct conn {
73 int ntentative;
74 struct timeval retry;
75 struct event waitev;
76 int source;
77 struct bufferevent *sourcebev;
78 int to;
79 struct bufferevent *tobev;
80 } conns[MAXCONN];
82 static void
83 terminate(int fd, short event, void *data)
84 {
85 event_loopbreak();
86 }
88 static void
89 chld(int fd, short event, void *data)
90 {
91 int status;
93 if (waitpid(ssh_pid, &status, WNOHANG) == -1)
94 err(1, "waitpid");
96 ssh_pid = -1;
97 }
99 static void
100 info(int fd, short event, void *data)
102 warnx("connections: %d", conn);
105 static void
106 spawn_ssh(void)
108 warnx("spawning ssh...");
110 switch (ssh_pid = fork()) {
111 case -1:
112 err(1, "fork");
113 case 0:
114 execl(SSH_PATH, "ssh", "-L", ssh_tflag, "-NTq", ssh_dest,
115 NULL);
116 err(1, "exec");
117 default:
118 return;
122 static void
123 killing_time(int fd, short event, void *data)
125 if (ssh_pid == -1)
126 return;
128 warnx("killing time!");
129 kill(ssh_pid, SIGTERM);
130 ssh_pid = -1;
133 static void
134 nopcb(struct bufferevent *bev, void *d)
136 return;
139 static void
140 sreadcb(struct bufferevent *bev, void *d)
142 struct conn *c = d;
144 bufferevent_write_buffer(c->tobev, EVBUFFER_INPUT(bev));
147 static void
148 treadcb(struct bufferevent *bev, void *d)
150 struct conn *c = d;
152 bufferevent_write_buffer(c->sourcebev, EVBUFFER_INPUT(bev));
155 static void
156 errcb(struct bufferevent *bev, short event, void *d)
158 struct conn *c = d;
160 warnx("in errcb, closing connection");
162 bufferevent_free(c->sourcebev);
163 bufferevent_free(c->tobev);
165 close(c->source);
166 close(c->to);
168 c->source = -1;
169 c->to = -1;
171 if (--conn == 0) {
172 warnx("scheduling ssh termination (%llds)",
173 (long long)timeout.tv_sec);
174 if (timeout.tv_sec != 0) {
175 evtimer_set(&timeoutev, killing_time, NULL);
176 evtimer_add(&timeoutev, &timeout);
181 static int
182 connect_to_ssh(void)
184 struct addrinfo hints, *res, *res0;
185 int r, saved_errno, sock;
186 const char *cause;
188 memset(&hints, 0, sizeof(hints));
189 hints.ai_family = AF_UNSPEC;
190 hints.ai_socktype = SOCK_STREAM;
192 r = getaddrinfo(ssh_host, ssh_port, &hints, &res0);
193 if (r != 0)
194 errx(1, "getaddrinfo(\"%s\", \"%s\"): %s",
195 ssh_host, ssh_port, gai_strerror(r));
197 for (res = res0; res; res = res->ai_next) {
198 sock = socket(res->ai_family, res->ai_socktype,
199 res->ai_protocol);
200 if (sock == -1) {
201 cause = "socket";
202 continue;
205 if (connect(sock, res->ai_addr, res->ai_addrlen) == -1) {
206 cause = "connect";
207 saved_errno = errno;
208 close(sock);
209 errno = saved_errno;
210 sock = -1;
211 continue;
214 break;
217 if (sock == -1)
218 warn("%s", cause);
220 freeaddrinfo(res0);
221 return sock;
224 static void
225 try_to_connect(int fd, short event, void *d)
227 struct conn *c = d;
229 /* ssh may die in the meantime */
230 if (ssh_pid == -1) {
231 close(c->source);
232 c->source = -1;
233 return;
236 c->ntentative++;
237 warnx("trying to connect to %s:%s (%d/%d)", ssh_host, ssh_port,
238 c->ntentative, RETRIES);
240 if ((c->to = connect_to_ssh()) == -1) {
241 if (c->ntentative == RETRIES) {
242 warnx("giving up");
243 close(c->source);
244 c->source = -1;
245 return;
248 evtimer_set(&c->waitev, try_to_connect, c);
249 evtimer_add(&c->waitev, &c->retry);
250 return;
253 c->sourcebev = bufferevent_new(c->source, sreadcb, nopcb, errcb, c);
254 c->tobev = bufferevent_new(c->to, treadcb, nopcb, errcb, c);
255 if (c->sourcebev == NULL || c->tobev == NULL)
256 err(1, "bufferevent_new");
257 bufferevent_enable(c->sourcebev, EV_READ|EV_WRITE);
258 bufferevent_enable(c->tobev, EV_READ|EV_WRITE);
261 static void
262 do_accept(int fd, short event, void *data)
264 int s, i;
266 warnx("handling connection");
268 if (evtimer_pending(&timeoutev, NULL))
269 evtimer_del(&timeoutev);
271 if ((s = accept(fd, NULL, 0)) == -1)
272 err(1, "accept");
274 if (conn == MAXCONN) {
275 /* oops */
276 close(s);
277 return;
280 conn++;
282 if (ssh_pid == -1)
283 spawn_ssh();
285 for (i = 0; i < MAXCONN; ++i) {
286 if (conns[i].source != -1)
287 continue;
289 conns[i].source = s;
290 conns[i].ntentative = 0;
291 conns[i].retry.tv_sec = BACKOFF;
292 conns[i].retry.tv_usec = 0;
293 evtimer_set(&conns[i].waitev, try_to_connect, &conns[i]);
294 evtimer_add(&conns[i].waitev, &conns[i].retry);
295 break;
299 static const char *
300 copysec(const char *s, char *d, size_t len)
302 const char *c;
304 if ((c = strchr(s, ':')) == NULL)
305 return NULL;
306 if ((size_t)(c - s) >= len-1)
307 return NULL;
308 memset(d, 0, len);
309 memcpy(d, s, c - s);
310 return c;
313 static void
314 bind_socket(void)
316 struct addrinfo hints, *res, *res0;
317 int r, saved_errno;
318 char host[64];
319 const char *c, *h, *port, *cause;
321 if ((c = strchr(addr, ':')) == NULL) {
322 h = NULL;
323 port = addr;
324 } else {
325 if ((c = copysec(addr, host, sizeof(host))) == NULL)
326 errx(1, "ENAMETOOLONG");
328 h = host;
329 port = c+1;
332 memset(&hints, 0, sizeof(hints));
333 hints.ai_family = AF_UNSPEC;
334 hints.ai_socktype = SOCK_STREAM;
335 hints.ai_flags = AI_PASSIVE;
337 r = getaddrinfo(h, port, &hints, &res0);
338 if (r != 0)
339 errx(1, "getaddrinfo(%s): %s",
340 addr, gai_strerror(r));
342 for (res = res0; res && nsock < MAXSOCK; res = res->ai_next) {
343 socks[nsock] = socket(res->ai_family, res->ai_socktype,
344 res->ai_protocol);
345 if (socks[nsock] == -1) {
346 cause = "socket";
347 continue;
350 if (bind(socks[nsock], res->ai_addr, res->ai_addrlen) == -1) {
351 cause = "bind";
352 saved_errno = errno;
353 close(socks[nsock]);
354 errno = saved_errno;
355 continue;
358 listen(socks[nsock], 5);
360 nsock++;
362 if (nsock == 0)
363 err(1, "%s", cause);
365 freeaddrinfo(res0);
368 static void
369 parse_tflag(void)
371 const char *c;
373 if (isdigit(*ssh_tflag)) {
374 strlcpy(ssh_host, "localhost", sizeof(ssh_host));
375 if (copysec(ssh_tflag, ssh_port, sizeof(ssh_port)) == NULL)
376 goto err;
377 return;
380 if ((c = copysec(ssh_tflag, ssh_host, sizeof(ssh_host))) == NULL)
381 goto err;
382 if (copysec(c+1, ssh_port, sizeof(ssh_port)) == NULL)
383 goto err;
384 return;
386 err:
387 errx(1, "wrong value for -B");
390 static void __dead
391 usage(void)
393 fprintf(stderr, "usage: %s -B sshaddr -b addr [-t timeout]"
394 " destination\n", getprogname());
395 exit(1);
398 int
399 main(int argc, char **argv)
401 int ch, i;
402 const char *errstr;
404 while ((ch = getopt(argc, argv, "B:b:t:")) != -1) {
405 switch (ch) {
406 case 'B':
407 ssh_tflag = optarg;
408 parse_tflag();
409 break;
410 case 'b':
411 addr = optarg;
412 break;
413 case 't':
414 timeout.tv_sec = strtonum(optarg, 0, INT_MAX, &errstr);
415 if (errstr != NULL)
416 errx(1, "timeout is %s: %s", errstr, optarg);
417 break;
418 default:
419 usage();
422 argc -= optind;
423 argv += optind;
425 if (argc != 1 || addr == NULL || ssh_tflag == NULL)
426 usage();
428 ssh_dest = argv[0];
430 for (i = 0; i < MAXCONN; ++i) {
431 conns[i].source = -1;
432 conns[i].to = -1;
435 bind_socket();
437 signal(SIGPIPE, SIG_IGN);
439 event_init();
441 /* initialize the timer */
442 evtimer_set(&timeoutev, killing_time, NULL);
444 signal_set(&sighupev, SIGHUP, terminate, NULL);
445 signal_set(&sigintev, SIGINT, terminate, NULL);
446 signal_set(&sigtermev, SIGTERM, terminate, NULL);
447 signal_set(&sigchldev, SIGCHLD, chld, NULL);
448 signal_set(&siginfoev, SIGINFO, info, NULL);
450 signal_add(&sighupev, NULL);
451 signal_add(&sigintev, NULL);
452 signal_add(&sigtermev, NULL);
453 signal_add(&sigchldev, NULL);
454 signal_add(&siginfoev, NULL);
456 for (i = 0; i < nsock; ++i) {
457 event_set(&sockev[i], socks[i], EV_READ|EV_PERSIST,
458 do_accept, NULL);
459 event_add(&sockev[i], NULL);
462 /*
463 * dns, inet: bind the socket and connect to the childs.
464 * proc, exec: execute ssh on demand.
465 */
466 if (pledge("stdio dns inet proc exec", NULL) == -1)
467 err(1, "pledge");
469 warnx("lift off!");
470 event_dispatch();
472 if (ssh_pid != -1)
473 kill(ssh_pid, SIGINT);
475 return 0;