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
;
66 DA_DECL(addr_v
, addr
);
67 DA_DECL(str_v
, const char *);
70 struct pk
*next
; /* Next packet in the chain */
71 octet
*p
, *o
; /* Buffer start and current posn */
72 size_t n
; /* Size of packet remaining */
75 typedef struct pkstream
{
76 unsigned f
; /* Flags... */
77 #define PKF_FULL 1u /* Buffer is full: stop reading */
78 sel_file r
, w
; /* Read and write selectors */
79 pk
*pks
, **pk_tail
; /* Packet queue */
80 size_t npk
, szpk
; /* Number and size of data */
81 selpk p
; /* Packet parser */
84 typedef struct connwait
{
85 unsigned f
; /* Various flags */
86 #define cwf_port 1u /* Port is defined => listen */
87 sel_file
*sfv
; /* Selectors */
88 addr_v me
, peer
; /* Who I'm meant to be; who peer is */
91 /*----- Static variables --------------------------------------------------*/
96 static size_t pk_nmax
= 128, pk_szmax
= 1024*1024;
98 /*----- Main code ---------------------------------------------------------*/
100 static int nonblockify(int fd
)
101 { return (fdflags(fd
, O_NONBLOCK
, O_NONBLOCK
, 0, 0)); }
103 static int cloexec(int fd
)
104 { return (fdflags(fd
, 0, 0, FD_CLOEXEC
, FD_CLOEXEC
)); }
106 static socklen_t
addrsz(const addr
*a
)
108 switch (a
->sa
.sa_family
) {
109 case AF_INET
: return sizeof(a
->sin
);
114 static int knownafp(int af
)
117 case AF_INET
: return (1);
122 static int initsock(int fd
, int af
)
131 static const char *addrstr(const addr
*a
)
133 static char buf
[128];
134 socklen_t n
= sizeof(buf
);
136 if (getnameinfo(&a
->sa
, addrsz(a
), buf
, n
, 0, 0, NI_NUMERICHOST
))
137 return ("<addrstr failed>");
141 static int addreq(const addr
*a
, const addr
*b
)
143 if (a
->sa
.sa_family
!= b
->sa
.sa_family
) return (0);
144 switch (a
->sa
.sa_family
) {
146 return (a
->sin
.sin_addr
.s_addr
== b
->sin
.sin_addr
.s_addr
);
152 static void initaddr(addr
*a
, int af
)
154 a
->sa
.sa_family
= af
;
157 a
->sin
.sin_addr
.s_addr
= INADDR_ANY
;
167 static void copyaddr(addr
*a
, const struct sockaddr
*sa
, unsigned f
)
169 const struct sockaddr_in
*sin
;
171 a
->sa
.sa_family
= sa
->sa_family
;
172 switch (sa
->sa_family
) {
174 sin
= (const struct sockaddr_in
*)sa
;
175 if (f
&caf_addr
) a
->sin
.sin_addr
= sin
->sin_addr
;
176 if (f
&caf_port
) a
->sin
.sin_port
= sin
->sin_port
;
183 static void dolisten(void);
185 static void doclose(pkstream
*p
)
189 close(p
->p
.reader
.fd
);
190 selpk_destroy(&p
->p
);
191 if (!(p
->f
&PKF_FULL
)) sel_rmfile(&p
->r
);
192 if (p
->npk
) sel_rmfile(&p
->w
);
193 for (pk
= p
->pks
; pk
; pk
= ppk
) {
199 if (cw
.f
&cwf_port
) dolisten();
203 static void rdtcp(octet
*b
, size_t sz
, pkbuf
*pk
, size_t *k
, void *vp
)
208 if (!sz
) { doclose(p
); return; }
210 if (pksz
+ 2 == sz
) {
211 DISCARD(write(fd_udp
, b
+ 2, pksz
));
212 selpk_want(&p
->p
, 2);
214 selpk_want(&p
->p
, pksz
+ 2);
219 static void wrtcp(int fd
, unsigned mode
, void *vp
)
222 struct iovec iov
[NPK
];
228 for (i
= 0, pk
= p
->pks
; i
< NPK
&& pk
; i
++, pk
= pk
->next
) {
229 iov
[i
].iov_base
= pk
->o
;
230 iov
[i
].iov_len
= pk
->n
;
233 if ((n
= writev(fd
, iov
, i
)) < 0) {
234 if (errno
== EAGAIN
|| errno
== EWOULDBLOCK
|| errno
== EINTR
) return;
235 moan("couldn't write to TCP socket: %s", strerror(errno
));
241 for (pk
= p
->pks
; n
&& pk
; pk
= ppk
) {
255 if (!pk
) { p
->pk_tail
= &p
->pks
; sel_rmfile(&p
->w
); }
256 if ((p
->f
&PKF_FULL
) && p
->npk
< pk_nmax
&& p
->szpk
< pk_szmax
)
257 { p
->f
&= ~PKF_FULL
; sel_addfile(&p
->r
); }
260 static void rdudp(int fd
, unsigned mode
, void *vp
)
267 if ((n
= read(fd
, buf
, sizeof(buf
))) < 0) {
268 if (errno
== EAGAIN
|| errno
== EWOULDBLOCK
|| errno
== EINTR
)
270 moan("couldn't read from UDP socket: %s", strerror(errno
));
273 pk
= xmalloc(sizeof(*pk
));
275 pk
->p
= xmalloc(n
+ 2);
277 memcpy(pk
->p
+ 2, buf
, n
);
281 p
->pk_tail
= &pk
->next
;
282 if (!p
->npk
) sel_addfile(&p
->w
);
286 if (p
->npk
>= pk_nmax
|| p
->szpk
>= pk_szmax
)
287 { sel_rmfile(&p
->r
); p
->f
|= PKF_FULL
; }
290 static void dofwd(int fd_in
, int fd_out
)
292 pkstream
*p
= xmalloc(sizeof(*p
));
293 sel_initfile(&sel
, &p
->r
, fd_udp
, SEL_READ
, rdudp
, p
);
294 sel_initfile(&sel
, &p
->w
, fd_out
, SEL_WRITE
, wrtcp
, p
);
295 selpk_init(&p
->p
, &sel
, fd_in
, rdtcp
, p
);
296 selpk_want(&p
->p
, 2);
298 p
->pk_tail
= &p
->pks
;
299 p
->npk
= p
->szpk
= 0;
304 static void doaccept(int fd_s
, unsigned mode
, void *p
)
308 socklen_t sz
= sizeof(a
);
311 if ((fd
= accept(fd_s
, &a
.sa
, &sz
)) < 0) {
312 if (errno
== EAGAIN
|| errno
== EWOULDBLOCK
|| errno
== EINTR
) return;
313 moan("couldn't accept incoming connection: %s", strerror(errno
));
316 n
= DA_LEN(&cw
.peer
);
318 for (i
= 0; i
< n
; i
++) if (addreq(&a
, &DA(&cw
.peer
)[i
])) goto match
;
319 moan("rejecting connection from %s", addrstr(&a
));
322 if (nonblockify(fd
) || cloexec(fd
)) {
323 moan("couldn't accept incoming connection: %s", strerror(errno
));
328 for (i
= 0; i
< n
; i
++) { close(cw
.sfv
[i
].fd
); sel_rmfile(&cw
.sfv
[i
]); }
331 static void dolisten1(const addr
*a
, sel_file
*sf
)
336 if ((fd
= socket(a
->sa
.sa_family
, SOCK_STREAM
, IPPROTO_TCP
)) < 0 ||
337 setsockopt(fd
, SOL_SOCKET
, SO_REUSEADDR
, &opt
, sizeof(opt
)) ||
338 initsock(fd
, a
->sa
.sa_family
) ||
339 bind(fd
, &a
->sa
, addrsz(a
)) ||
340 listen(fd
, 1) || nonblockify(fd
) || cloexec(fd
))
341 die(1, "couldn't set up listening socket: %s", strerror(errno
));
342 sel_initfile(&sel
, sf
, fd
, SEL_READ
, doaccept
, 0);
346 static void dolisten(void)
351 for (i
= 0; i
< n
; i
++)
352 dolisten1(&DA(&cw
.me
)[i
], &cw
.sfv
[i
]);
355 static void pushaddrs(addr_v
*av
, const struct addrinfo
*ailist
)
357 const struct addrinfo
*ai
;
360 for (ai
= ailist
, n
= 0; ai
; ai
= ai
->ai_next
)
361 if (knownafp(ai
->ai_family
)) n
++;
363 for (i
= DA_LEN(av
), ai
= ailist
; ai
; ai
= ai
->ai_next
) {
364 if (!knownafp(ai
->ai_family
)) continue;
365 initaddr(&DA(av
)[i
], ai
->ai_family
);
366 copyaddr(&DA(av
)[i
++], ai
->ai_addr
, caf_addr
| caf_port
);
372 static void parseaddr(const struct addrinfo
*aihint
,
373 const char *host
, const char *svc
, unsigned f
,
374 struct addrinfo
**ai_out
)
376 char *alloc
= 0, *sep
;
380 alloc
= xstrdup(host
);
381 if (alloc
[0] != '[') {
382 if ((sep
= strchr(alloc
, ':')) == 0)
383 die(1, "missing port number in address `%s'", host
);
384 host
= alloc
; *sep
= 0; svc
= sep
+ 1;
386 if ((sep
= strchr(alloc
, ']')) == 0 || sep
[1] != ':')
387 die(1, "bad syntax in address `%s:'", host
);
388 host
= alloc
+ 1; *sep
= 0; svc
= sep
+ 2;
392 err
= getaddrinfo(host
, svc
, aihint
, ai_out
);
395 die(1, "failed to resolve hostname `%s', service `%s': %s",
396 host
, svc
, gai_strerror(err
));
398 die(1, "failed to resolve hostname `%s': %s", host
, gai_strerror(err
));
400 die(1, "failed to resolve service `%s': %s", svc
, gai_strerror(err
));
406 static void usage(FILE *fp
)
409 "Usage: $ [-l PORT] [-b ADDR] [-p ADDR] [-c ADDR:PORT]\n\
410 ADDR:PORT ADDR:PORT\n");
413 static void version(FILE *fp
)
414 { pquis(fp
, "$, tripe version " VERSION
"\n"); }
416 static void help(FILE *fp
)
424 -h, --help Display this help text.\n\
425 -v, --version Display version number.\n\
426 -u, --usage Display pointless usage message.\n\
428 -l, --listen=PORT Listen for connections to TCP PORT.\n\
429 -p, --peer=ADDR Only accept connections from IP ADDR.\n\
430 -b, --bind=ADDR Bind to ADDR before connecting.\n\
431 -c, --connect=ADDR:PORT Connect to IP ADDR, TCP PORT.\n\
433 Forwards UDP packets over a reliable stream. By default, uses stdin and\n\
434 stdout; though it can use TCP sockets instead.\n\
438 int main(int argc
, char *argv
[])
441 str_v bindhosts
= DA_INIT
, peerhosts
= DA_INIT
;
442 const char *bindsvc
= 0;
444 const char *connhost
= 0;
445 struct addrinfo aihint
= { 0 }, *ai
, *ailist
;
457 static struct option opt
[] = {
458 { "help", 0, 0, 'h' },
459 { "version", 0, 0, 'v' },
460 { "usage", 0, 0, 'u' },
461 { "listen", OPTF_ARGREQ
, 0, 'l' },
462 { "peer", OPTF_ARGREQ
, 0, 'p' },
463 { "bind", OPTF_ARGREQ
, 0, 'b' },
464 { "connect", OPTF_ARGREQ
, 0, 'c' },
469 i
= mdwopt(argc
, argv
, "hvul:p:b:c:", opt
, 0, 0, 0);
473 case 'h': help(stdout
); exit(0);
474 case 'v': version(stdout
); exit(0);
475 case 'u': usage(stdout
); exit(0);
476 case 'l': bindsvc
= optarg
; break;
477 case 'p': DA_PUSH(&peerhosts
, optarg
); break;
478 case 'b': DA_PUSH(&bindhosts
, optarg
); break;
479 case 'c': connhost
= optarg
; break;
480 default: f
|= f_bogus
; break;
483 if (optind
+ 2 != argc
|| (f
&f_bogus
)) { usage(stderr
); exit(1); }
485 if (DA_LEN(&bindhosts
) && !bindsvc
&& !connhost
)
486 die(1, "bind addr only makes sense when listening or connecting");
487 if (DA_LEN(&peerhosts
) && !bindsvc
)
488 die(1, "peer addr only makes sense when listening");
489 if (bindsvc
&& connhost
)
490 die(1, "can't listen and connect");
492 aihint
.ai_family
= AF_INET
;
493 DA_CREATE(&cw
.me
); DA_CREATE(&cw
.peer
);
495 n
= DA_LEN(&bindhosts
);
497 aihint
.ai_socktype
= SOCK_STREAM
;
498 aihint
.ai_protocol
= IPPROTO_TCP
;
499 aihint
.ai_flags
= AI_ADDRCONFIG
| AI_PASSIVE
;
501 parseaddr(&aihint
, 0, bindsvc
, 0, &ailist
);
502 pushaddrs(&cw
.me
, ailist
);
503 freeaddrinfo(ailist
);
504 } else if (!bindsvc
) {
505 if (n
!= 1) die(1, "can only bind to one address as client");
506 parseaddr(&aihint
, DA(&bindhosts
)[0], 0, 0, &ailist
);
507 for (ai
= ailist
; ai
&& !knownafp(ai
->ai_family
); ai
= ai
->ai_next
);
509 die(1, "no usable addresses returned for `%s'", DA(&bindhosts
)[0]);
510 initaddr(&bindaddr
, ai
->ai_family
);
511 copyaddr(&bindaddr
, ai
->ai_addr
, caf_addr
);
512 aihint
.ai_family
= ai
->ai_family
;
513 freeaddrinfo(ailist
);
514 } else for (i
= 0; i
< n
; i
++) {
515 parseaddr(&aihint
, DA(&bindhosts
)[i
], bindsvc
, 0, &ailist
);
516 pushaddrs(&cw
.me
, ailist
);
517 freeaddrinfo(ailist
);
522 cw
.sfv
= xmalloc(n
*sizeof(*cw
.sfv
));
526 n
= DA_LEN(&peerhosts
);
528 aihint
.ai_socktype
= SOCK_STREAM
;
529 aihint
.ai_protocol
= IPPROTO_TCP
;
530 aihint
.ai_flags
= AI_ADDRCONFIG
;
531 for (i
= 0; i
< n
; i
++) {
532 parseaddr(&aihint
, DA(&peerhosts
)[i
], 0, 0, &ailist
);
533 pushaddrs(&cw
.peer
, ailist
);
534 freeaddrinfo(ailist
);
536 if (!DA_LEN(&cw
.peer
)) die(1, "no usable peer addresses");
540 aihint
.ai_socktype
= SOCK_STREAM
;
541 aihint
.ai_protocol
= IPPROTO_TCP
;
542 aihint
.ai_flags
= AI_ADDRCONFIG
;
543 parseaddr(&aihint
, connhost
, 0, paf_parse
, &ailist
);
545 for (ai
= ailist
; ai
; ai
= ai
->ai_next
) {
546 if ((fd
= socket(ai
->ai_family
, SOCK_STREAM
, IPPROTO_TCP
)) >= 0 &&
547 !initsock(fd
, ai
->ai_family
) &&
548 (!DA_LEN(&bindhosts
) ||
549 !bind(fd
, &bindaddr
.sa
, addrsz(&bindaddr
))) &&
550 !connect(fd
, ai
->ai_addr
, ai
->ai_addrlen
))
552 if (fd
>= 0) close(fd
);
554 die(1, "couldn't connect to TCP server: %s", strerror(errno
));
556 if (nonblockify(fd
) || cloexec(fd
))
557 die(1, "couldn't connect to TCP server: %s", strerror(errno
));
560 aihint
.ai_family
= AF_INET
;
561 aihint
.ai_socktype
= SOCK_DGRAM
;
562 aihint
.ai_protocol
= IPPROTO_UDP
;
563 aihint
.ai_flags
= AI_ADDRCONFIG
| AI_PASSIVE
;
564 parseaddr(&aihint
, argv
[optind
], 0, paf_parse
, &ailist
);
565 for (ai
= ailist
; ai
&& !knownafp(ai
->ai_family
); ai
= ai
->ai_next
);
566 if (!ai
) die(1, "no usable addresses returned for `%s'", argv
[optind
]);
567 if ((fd_udp
= socket(ai
->ai_family
, SOCK_DGRAM
, IPPROTO_UDP
)) < 0 ||
568 initsock(fd_udp
, ai
->ai_family
) ||
569 nonblockify(fd_udp
) || cloexec(fd_udp
) ||
570 setsockopt(fd_udp
, SOL_SOCKET
, SO_RCVBUF
, &len
, sizeof(len
)) ||
571 setsockopt(fd_udp
, SOL_SOCKET
, SO_SNDBUF
, &len
, sizeof(len
)) ||
572 bind(fd_udp
, ai
->ai_addr
, ai
->ai_addrlen
))
573 die(1, "couldn't set up UDP socket: %s", strerror(errno
));
574 freeaddrinfo(ailist
);
575 aihint
.ai_family
= ai
->ai_family
;
576 aihint
.ai_flags
= AI_ADDRCONFIG
;
577 parseaddr(&aihint
, argv
[optind
+ 1], 0, paf_parse
, &ailist
);
578 for (ai
= ailist
; ai
; ai
= ai
->ai_next
)
579 if (!connect(fd_udp
, ai
->ai_addr
, ai
->ai_addrlen
)) goto conn_udp
;
580 die(1, "couldn't set up UDP socket: %s", strerror(errno
));
583 if (bindsvc
) dolisten();
584 else if (connhost
) dofwd(fd
, fd
);
585 else dofwd(STDIN_FILENO
, STDOUT_FILENO
);
588 if (sel_select(&sel
) && errno
!= EINTR
)
589 die(1, "select failed: %s", strerror(errno
));
594 /*----- That's all, folks -------------------------------------------------*/