3 * Forwarding UDP packets over a stream
5 * (c) 2003 Straylight/Edgeware
8 /*----- Licensing notice --------------------------------------------------*
10 * This file is part of Trivial IP Encryption (TrIPE).
12 * TrIPE is free software: you can redistribute it and/or modify it under
13 * the terms of the GNU General Public License as published by the Free
14 * Software Foundation; either version 3 of the License, or (at your
15 * option) any later version.
17 * TrIPE is distributed in the hope that it will be useful, but WITHOUT
18 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
19 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
22 * You should have received a copy of the GNU General Public License
23 * along with TrIPE. If not, see <https://www.gnu.org/licenses/>.
26 /*----- Header files ------------------------------------------------------*/
37 #include <sys/types.h>
41 #include <sys/socket.h>
42 #include <netinet/in.h>
43 #include <arpa/inet.h>
46 #include <mLib/alloc.h>
47 #include <mLib/bits.h>
48 #include <mLib/darray.h>
49 #include <mLib/dstr.h>
50 #include <mLib/fdflags.h>
51 #include <mLib/mdwopt.h>
52 #include <mLib/quis.h>
53 #include <mLib/report.h>
55 #include <mLib/selpk.h>
59 /*----- Data structures ---------------------------------------------------*/
63 struct sockaddr_in sin
;
64 struct sockaddr_in6 sin6
;
67 DA_DECL(addr_v
, addr
);
68 DA_DECL(str_v
, const char *);
71 struct pk
*next
; /* Next packet in the chain */
72 octet
*p
, *o
; /* Buffer start and current posn */
73 size_t n
; /* Size of packet remaining */
76 typedef struct pkstream
{
77 unsigned f
; /* Flags... */
78 #define PKF_FULL 1u /* Buffer is full: stop reading */
79 sel_file r
, w
; /* Read and write selectors */
80 pk
*pks
, **pk_tail
; /* Packet queue */
81 size_t npk
, szpk
; /* Number and size of data */
82 selpk p
; /* Packet parser */
85 typedef struct connwait
{
86 unsigned f
; /* Various flags */
87 #define cwf_port 1u /* Port is defined => listen */
88 sel_file
*sfv
; /* Selectors */
89 addr_v me
, peer
; /* Who I'm meant to be; who peer is */
92 /*----- Static variables --------------------------------------------------*/
97 static size_t pk_nmax
= 128, pk_szmax
= 1024*1024;
99 /*----- Main code ---------------------------------------------------------*/
101 static int nonblockify(int fd
)
102 { return (fdflags(fd
, O_NONBLOCK
, O_NONBLOCK
, 0, 0)); }
104 static int cloexec(int fd
)
105 { return (fdflags(fd
, 0, 0, FD_CLOEXEC
, FD_CLOEXEC
)); }
107 static socklen_t
addrsz(const addr
*a
)
109 switch (a
->sa
.sa_family
) {
110 case AF_INET
: return sizeof(a
->sin
);
111 case AF_INET6
: return sizeof(a
->sin6
);
116 static int knownafp(int af
)
119 case AF_INET
: case AF_INET6
: return (1);
124 static int initsock(int fd
, int af
)
131 if (setsockopt(fd
, IPPROTO_IPV6
, IPV6_V6ONLY
, &yes
, sizeof(yes
)))
139 static const char *addrstr(const addr
*a
)
141 static char buf
[128];
142 socklen_t n
= sizeof(buf
);
144 if (getnameinfo(&a
->sa
, addrsz(a
), buf
, n
, 0, 0, NI_NUMERICHOST
))
145 return ("<addrstr failed>");
149 static int addreq(const addr
*a
, const addr
*b
)
151 if (a
->sa
.sa_family
!= b
->sa
.sa_family
) return (0);
152 switch (a
->sa
.sa_family
) {
154 return (a
->sin
.sin_addr
.s_addr
== b
->sin
.sin_addr
.s_addr
);
156 return (!memcmp(a
->sin6
.sin6_addr
.s6_addr
,
157 b
->sin6
.sin6_addr
.s6_addr
,
159 a
->sin6
.sin6_scope_id
== b
->sin6
.sin6_scope_id
);
165 static void initaddr(addr
*a
, int af
)
167 a
->sa
.sa_family
= af
;
170 a
->sin
.sin_addr
.s_addr
= INADDR_ANY
;
174 memset(a
->sin6
.sin6_addr
.s6_addr
, 0, 16);
175 a
->sin6
.sin6_port
= 0;
176 a
->sin6
.sin6_flowinfo
= 0;
177 a
->sin6
.sin6_scope_id
= 0;
186 static void copyaddr(addr
*a
, const struct sockaddr
*sa
, unsigned f
)
188 const struct sockaddr_in
*sin
;
189 const struct sockaddr_in6
*sin6
;
191 a
->sa
.sa_family
= sa
->sa_family
;
192 switch (sa
->sa_family
) {
194 sin
= (const struct sockaddr_in
*)sa
;
195 if (f
&caf_addr
) a
->sin
.sin_addr
= sin
->sin_addr
;
196 if (f
&caf_port
) a
->sin
.sin_port
= sin
->sin_port
;
199 sin6
= (const struct sockaddr_in6
*)sa
;
201 a
->sin6
.sin6_addr
= sin6
->sin6_addr
;
202 a
->sin6
.sin6_scope_id
= sin6
->sin6_scope_id
;
204 if (f
&caf_port
) a
->sin6
.sin6_port
= sin6
->sin6_port
;
212 static void dolisten(void);
214 static void doclose(pkstream
*p
)
218 close(p
->p
.reader
.fd
);
219 selpk_destroy(&p
->p
);
220 if (!(p
->f
&PKF_FULL
)) sel_rmfile(&p
->r
);
221 if (p
->npk
) sel_rmfile(&p
->w
);
222 for (pk
= p
->pks
; pk
; pk
= ppk
) {
228 if (cw
.f
&cwf_port
) dolisten();
232 static void rdtcp(octet
*b
, size_t sz
, pkbuf
*pk
, size_t *k
, void *vp
)
237 if (!sz
) { doclose(p
); return; }
239 if (pksz
+ 2 == sz
) {
240 DISCARD(write(fd_udp
, b
+ 2, pksz
));
241 selpk_want(&p
->p
, 2);
243 selpk_want(&p
->p
, pksz
+ 2);
248 static void wrtcp(int fd
, unsigned mode
, void *vp
)
251 struct iovec iov
[NPK
];
257 for (i
= 0, pk
= p
->pks
; i
< NPK
&& pk
; i
++, pk
= pk
->next
) {
258 iov
[i
].iov_base
= pk
->o
;
259 iov
[i
].iov_len
= pk
->n
;
262 if ((n
= writev(fd
, iov
, i
)) < 0) {
263 if (errno
== EAGAIN
|| errno
== EWOULDBLOCK
|| errno
== EINTR
) return;
264 moan("couldn't write to TCP socket: %s", strerror(errno
));
270 for (pk
= p
->pks
; n
&& pk
; pk
= ppk
) {
284 if (!pk
) { p
->pk_tail
= &p
->pks
; sel_rmfile(&p
->w
); }
285 if ((p
->f
&PKF_FULL
) && p
->npk
< pk_nmax
&& p
->szpk
< pk_szmax
)
286 { p
->f
&= ~PKF_FULL
; sel_addfile(&p
->r
); }
289 static void rdudp(int fd
, unsigned mode
, void *vp
)
296 if ((n
= read(fd
, buf
, sizeof(buf
))) < 0) {
297 if (errno
== EAGAIN
|| errno
== EWOULDBLOCK
|| errno
== EINTR
)
299 moan("couldn't read from UDP socket: %s", strerror(errno
));
302 pk
= xmalloc(sizeof(*pk
));
304 pk
->p
= xmalloc(n
+ 2);
306 memcpy(pk
->p
+ 2, buf
, n
);
310 p
->pk_tail
= &pk
->next
;
311 if (!p
->npk
) sel_addfile(&p
->w
);
315 if (p
->npk
>= pk_nmax
|| p
->szpk
>= pk_szmax
)
316 { sel_rmfile(&p
->r
); p
->f
|= PKF_FULL
; }
319 static void dofwd(int fd_in
, int fd_out
)
321 pkstream
*p
= xmalloc(sizeof(*p
));
322 sel_initfile(&sel
, &p
->r
, fd_udp
, SEL_READ
, rdudp
, p
);
323 sel_initfile(&sel
, &p
->w
, fd_out
, SEL_WRITE
, wrtcp
, p
);
324 selpk_init(&p
->p
, &sel
, fd_in
, rdtcp
, p
);
325 selpk_want(&p
->p
, 2);
327 p
->pk_tail
= &p
->pks
;
328 p
->npk
= p
->szpk
= 0;
333 static void doaccept(int fd_s
, unsigned mode
, void *p
)
337 socklen_t sz
= sizeof(a
);
340 if ((fd
= accept(fd_s
, &a
.sa
, &sz
)) < 0) {
341 if (errno
== EAGAIN
|| errno
== EWOULDBLOCK
|| errno
== EINTR
) return;
342 moan("couldn't accept incoming connection: %s", strerror(errno
));
345 n
= DA_LEN(&cw
.peer
);
347 for (i
= 0; i
< n
; i
++) if (addreq(&a
, &DA(&cw
.peer
)[i
])) goto match
;
348 moan("rejecting connection from %s", addrstr(&a
));
351 if (nonblockify(fd
) || cloexec(fd
)) {
352 moan("couldn't accept incoming connection: %s", strerror(errno
));
357 for (i
= 0; i
< n
; i
++) { close(cw
.sfv
[i
].fd
); sel_rmfile(&cw
.sfv
[i
]); }
360 static void dolisten1(const addr
*a
, sel_file
*sf
)
365 if ((fd
= socket(a
->sa
.sa_family
, SOCK_STREAM
, IPPROTO_TCP
)) < 0 ||
366 setsockopt(fd
, SOL_SOCKET
, SO_REUSEADDR
, &opt
, sizeof(opt
)) ||
367 initsock(fd
, a
->sa
.sa_family
) ||
368 bind(fd
, &a
->sa
, addrsz(a
)) ||
369 listen(fd
, 1) || nonblockify(fd
) || cloexec(fd
))
370 die(1, "couldn't set up listening socket: %s", strerror(errno
));
371 sel_initfile(&sel
, sf
, fd
, SEL_READ
, doaccept
, 0);
375 static void dolisten(void)
380 for (i
= 0; i
< n
; i
++)
381 dolisten1(&DA(&cw
.me
)[i
], &cw
.sfv
[i
]);
384 static void pushaddrs(addr_v
*av
, const struct addrinfo
*ailist
)
386 const struct addrinfo
*ai
;
389 for (ai
= ailist
, n
= 0; ai
; ai
= ai
->ai_next
)
390 if (knownafp(ai
->ai_family
)) n
++;
392 for (i
= DA_LEN(av
), ai
= ailist
; ai
; ai
= ai
->ai_next
) {
393 if (!knownafp(ai
->ai_family
)) continue;
394 initaddr(&DA(av
)[i
], ai
->ai_family
);
395 copyaddr(&DA(av
)[i
++], ai
->ai_addr
, caf_addr
| caf_port
);
401 static void parseaddr(const struct addrinfo
*aihint
,
402 const char *host
, const char *svc
, unsigned f
,
403 struct addrinfo
**ai_out
)
405 char *alloc
= 0, *sep
;
409 alloc
= xstrdup(host
);
410 if (alloc
[0] != '[') {
411 if ((sep
= strchr(alloc
, ':')) == 0)
412 die(1, "missing port number in address `%s'", host
);
413 host
= alloc
; *sep
= 0; svc
= sep
+ 1;
415 if ((sep
= strchr(alloc
, ']')) == 0 || sep
[1] != ':')
416 die(1, "bad syntax in address `%s:'", host
);
417 host
= alloc
+ 1; *sep
= 0; svc
= sep
+ 2;
421 err
= getaddrinfo(host
, svc
, aihint
, ai_out
);
424 die(1, "failed to resolve hostname `%s', service `%s': %s",
425 host
, svc
, gai_strerror(err
));
427 die(1, "failed to resolve hostname `%s': %s", host
, gai_strerror(err
));
429 die(1, "failed to resolve service `%s': %s", svc
, gai_strerror(err
));
435 static void usage(FILE *fp
)
438 "Usage: $ [-46] [-l PORT] [-b ADDR] [-p ADDR] [-c ADDR:PORT]\n\
439 ADDR:PORT ADDR:PORT\n");
442 static void version(FILE *fp
)
443 { pquis(fp
, "$, tripe version " VERSION
"\n"); }
445 static void help(FILE *fp
)
453 -h, --help Display this help text.\n\
454 -v, --version Display version number.\n\
455 -u, --usage Display pointless usage message.\n\
457 -4, --ipv4 Restrict to IPv4 only.\n\
458 -6, --ipv6 Restrict to IPv6 only.\n\
459 -l, --listen=PORT Listen for connections to TCP PORT.\n\
460 -p, --peer=ADDR Only accept connections from IP ADDR.\n\
461 -b, --bind=ADDR Bind to ADDR before connecting.\n\
462 -c, --connect=ADDR:PORT Connect to IP ADDR, TCP PORT.\n\
464 Forwards UDP packets over a reliable stream. By default, uses stdin and\n\
465 stdout; though it can use TCP sockets instead.\n\
469 int main(int argc
, char *argv
[])
472 str_v bindhosts
= DA_INIT
, peerhosts
= DA_INIT
;
473 const char *bindsvc
= 0;
475 const char *connhost
= 0;
476 struct addrinfo aihint
= { 0 }, *ai
, *ailist
;
489 static struct option opt
[] = {
490 { "help", 0, 0, 'h' },
491 { "version", 0, 0, 'v' },
492 { "usage", 0, 0, 'u' },
493 { "ipv4", 0, 0, '4' },
494 { "ipv6", 0, 0, '6' },
495 { "listen", OPTF_ARGREQ
, 0, 'l' },
496 { "peer", OPTF_ARGREQ
, 0, 'p' },
497 { "bind", OPTF_ARGREQ
, 0, 'b' },
498 { "connect", OPTF_ARGREQ
, 0, 'c' },
503 i
= mdwopt(argc
, argv
, "hvu46l:p:b:c:", opt
, 0, 0, 0);
507 case 'h': help(stdout
); exit(0);
508 case 'v': version(stdout
); exit(0);
509 case 'u': usage(stdout
); exit(0);
510 case '4': af
= AF_INET
; break;
511 case '6': af
= AF_INET6
; break;
512 case 'l': bindsvc
= optarg
; break;
513 case 'p': DA_PUSH(&peerhosts
, optarg
); break;
514 case 'b': DA_PUSH(&bindhosts
, optarg
); break;
515 case 'c': connhost
= optarg
; break;
516 default: f
|= f_bogus
; break;
519 if (optind
+ 2 != argc
|| (f
&f_bogus
)) { usage(stderr
); exit(1); }
521 if (DA_LEN(&bindhosts
) && !bindsvc
&& !connhost
)
522 die(1, "bind addr only makes sense when listening or connecting");
523 if (DA_LEN(&peerhosts
) && !bindsvc
)
524 die(1, "peer addr only makes sense when listening");
525 if (bindsvc
&& connhost
)
526 die(1, "can't listen and connect");
528 aihint
.ai_family
= af
;
529 DA_CREATE(&cw
.me
); DA_CREATE(&cw
.peer
);
531 n
= DA_LEN(&bindhosts
);
533 aihint
.ai_socktype
= SOCK_STREAM
;
534 aihint
.ai_protocol
= IPPROTO_TCP
;
535 aihint
.ai_flags
= AI_ADDRCONFIG
| AI_PASSIVE
;
537 parseaddr(&aihint
, 0, bindsvc
, 0, &ailist
);
538 pushaddrs(&cw
.me
, ailist
);
539 freeaddrinfo(ailist
);
540 } else if (!bindsvc
) {
541 if (n
!= 1) die(1, "can only bind to one address as client");
542 parseaddr(&aihint
, DA(&bindhosts
)[0], 0, 0, &ailist
);
543 for (ai
= ailist
; ai
&& !knownafp(ai
->ai_family
); ai
= ai
->ai_next
);
545 die(1, "no usable addresses returned for `%s'", DA(&bindhosts
)[0]);
546 initaddr(&bindaddr
, ai
->ai_family
);
547 copyaddr(&bindaddr
, ai
->ai_addr
, caf_addr
);
548 aihint
.ai_family
= ai
->ai_family
;
549 freeaddrinfo(ailist
);
550 } else for (i
= 0; i
< n
; i
++) {
551 parseaddr(&aihint
, DA(&bindhosts
)[i
], bindsvc
, 0, &ailist
);
552 pushaddrs(&cw
.me
, ailist
);
553 freeaddrinfo(ailist
);
558 cw
.sfv
= xmalloc(n
*sizeof(*cw
.sfv
));
562 n
= DA_LEN(&peerhosts
);
564 aihint
.ai_socktype
= SOCK_STREAM
;
565 aihint
.ai_protocol
= IPPROTO_TCP
;
566 aihint
.ai_flags
= AI_ADDRCONFIG
;
567 for (i
= 0; i
< n
; i
++) {
568 parseaddr(&aihint
, DA(&peerhosts
)[i
], 0, 0, &ailist
);
569 pushaddrs(&cw
.peer
, ailist
);
570 freeaddrinfo(ailist
);
572 if (!DA_LEN(&cw
.peer
)) die(1, "no usable peer addresses");
576 aihint
.ai_socktype
= SOCK_STREAM
;
577 aihint
.ai_protocol
= IPPROTO_TCP
;
578 aihint
.ai_flags
= AI_ADDRCONFIG
;
579 parseaddr(&aihint
, connhost
, 0, paf_parse
, &ailist
);
581 for (ai
= ailist
; ai
; ai
= ai
->ai_next
) {
582 if ((fd
= socket(ai
->ai_family
, SOCK_STREAM
, IPPROTO_TCP
)) >= 0 &&
583 !initsock(fd
, ai
->ai_family
) &&
584 (!DA_LEN(&bindhosts
) ||
585 !bind(fd
, &bindaddr
.sa
, addrsz(&bindaddr
))) &&
586 !connect(fd
, ai
->ai_addr
, ai
->ai_addrlen
))
588 if (fd
>= 0) close(fd
);
590 die(1, "couldn't connect to TCP server: %s", strerror(errno
));
592 if (nonblockify(fd
) || cloexec(fd
))
593 die(1, "couldn't connect to TCP server: %s", strerror(errno
));
596 aihint
.ai_family
= af
;
597 aihint
.ai_socktype
= SOCK_DGRAM
;
598 aihint
.ai_protocol
= IPPROTO_UDP
;
599 aihint
.ai_flags
= AI_ADDRCONFIG
| AI_PASSIVE
;
600 parseaddr(&aihint
, argv
[optind
], 0, paf_parse
, &ailist
);
601 for (ai
= ailist
; ai
&& !knownafp(ai
->ai_family
); ai
= ai
->ai_next
);
602 if (!ai
) die(1, "no usable addresses returned for `%s'", argv
[optind
]);
603 if ((fd_udp
= socket(ai
->ai_family
, SOCK_DGRAM
, IPPROTO_UDP
)) < 0 ||
604 initsock(fd_udp
, ai
->ai_family
) ||
605 nonblockify(fd_udp
) || cloexec(fd_udp
) ||
606 setsockopt(fd_udp
, SOL_SOCKET
, SO_RCVBUF
, &len
, sizeof(len
)) ||
607 setsockopt(fd_udp
, SOL_SOCKET
, SO_SNDBUF
, &len
, sizeof(len
)) ||
608 bind(fd_udp
, ai
->ai_addr
, ai
->ai_addrlen
))
609 die(1, "couldn't set up UDP socket: %s", strerror(errno
));
610 freeaddrinfo(ailist
);
611 aihint
.ai_family
= ai
->ai_family
;
612 aihint
.ai_flags
= AI_ADDRCONFIG
;
613 parseaddr(&aihint
, argv
[optind
+ 1], 0, paf_parse
, &ailist
);
614 for (ai
= ailist
; ai
; ai
= ai
->ai_next
)
615 if (!connect(fd_udp
, ai
->ai_addr
, ai
->ai_addrlen
)) goto conn_udp
;
616 die(1, "couldn't set up UDP socket: %s", strerror(errno
));
619 if (bindsvc
) dolisten();
620 else if (connhost
) dofwd(fd
, fd
);
621 else dofwd(STDIN_FILENO
, STDOUT_FILENO
);
624 if (sel_select(&sel
) && errno
!= EINTR
)
625 die(1, "select failed: %s", strerror(errno
));
630 /*----- That's all, folks -------------------------------------------------*/