pkstream/pkstream.c: Be more careful about handling address families.
[tripe] / pkstream / pkstream.c
1 /* -*-c-*-
2 *
3 * Forwarding UDP packets over a stream
4 *
5 * (c) 2003 Straylight/Edgeware
6 */
7
8 /*----- Licensing notice --------------------------------------------------*
9 *
10 * This file is part of Trivial IP Encryption (TrIPE).
11 *
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.
16 *
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
20 * for more details.
21 *
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/>.
24 */
25
26 /*----- Header files ------------------------------------------------------*/
27
28 #include "config.h"
29
30 #include <ctype.h>
31 #include <errno.h>
32 #include <stdio.h>
33 #include <stdlib.h>
34 #include <string.h>
35
36 #include <sys/time.h>
37 #include <sys/types.h>
38 #include <unistd.h>
39 #include <fcntl.h>
40 #include <sys/uio.h>
41 #include <sys/socket.h>
42 #include <netinet/in.h>
43 #include <arpa/inet.h>
44 #include <netdb.h>
45
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>
54 #include <mLib/sel.h>
55 #include <mLib/selpk.h>
56
57 #include "util.h"
58
59 /*----- Data structures ---------------------------------------------------*/
60
61 typedef union addr {
62 struct sockaddr sa;
63 struct sockaddr_in sin;
64 } addr;
65
66 DA_DECL(addr_v, addr);
67 DA_DECL(str_v, const char *);
68
69 typedef struct pk {
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 */
73 } pk;
74
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 */
82 } pkstream;
83
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 */
89 } connwait;
90
91 /*----- Static variables --------------------------------------------------*/
92
93 static sel_state sel;
94 static connwait cw;
95 static int fd_udp;
96 static size_t pk_nmax = 128, pk_szmax = 1024*1024;
97
98 /*----- Main code ---------------------------------------------------------*/
99
100 static int nonblockify(int fd)
101 { return (fdflags(fd, O_NONBLOCK, O_NONBLOCK, 0, 0)); }
102
103 static int cloexec(int fd)
104 { return (fdflags(fd, 0, 0, FD_CLOEXEC, FD_CLOEXEC)); }
105
106 static socklen_t addrsz(const addr *a)
107 {
108 switch (a->sa.sa_family) {
109 case AF_INET: return sizeof(a->sin);
110 default: abort();
111 }
112 }
113
114 static int knownafp(int af)
115 {
116 switch (af) {
117 case AF_INET: return (1);
118 default: return (0);
119 }
120 }
121
122 static int initsock(int fd, int af)
123 {
124 switch (af) {
125 case AF_INET: break;
126 default: abort();
127 }
128 return (0);
129 }
130
131 static const char *addrstr(const addr *a)
132 {
133 static char buf[128];
134 socklen_t n = sizeof(buf);
135
136 if (getnameinfo(&a->sa, addrsz(a), buf, n, 0, 0, NI_NUMERICHOST))
137 return ("<addrstr failed>");
138 return (buf);
139 }
140
141 static int addreq(const addr *a, const addr *b)
142 {
143 if (a->sa.sa_family != b->sa.sa_family) return (0);
144 switch (a->sa.sa_family) {
145 case AF_INET:
146 return (a->sin.sin_addr.s_addr == b->sin.sin_addr.s_addr);
147 default:
148 abort();
149 }
150 }
151
152 static void initaddr(addr *a, int af)
153 {
154 a->sa.sa_family = af;
155 switch (af) {
156 case AF_INET:
157 a->sin.sin_addr.s_addr = INADDR_ANY;
158 a->sin.sin_port = 0;
159 break;
160 default:
161 abort();
162 }
163 }
164
165 #define caf_addr 1u
166 #define caf_port 2u
167 static void copyaddr(addr *a, const struct sockaddr *sa, unsigned f)
168 {
169 const struct sockaddr_in *sin;
170
171 a->sa.sa_family = sa->sa_family;
172 switch (sa->sa_family) {
173 case AF_INET:
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;
177 break;
178 default:
179 abort();
180 }
181 }
182
183 static void dolisten(void);
184
185 static void doclose(pkstream *p)
186 {
187 pk *pk, *ppk;
188 close(p->w.fd);
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) {
194 ppk = pk->next;
195 xfree(pk->p);
196 xfree(pk);
197 }
198 xfree(p);
199 if (cw.f&cwf_port) dolisten();
200 else exit(0);
201 }
202
203 static void rdtcp(octet *b, size_t sz, pkbuf *pk, size_t *k, void *vp)
204 {
205 pkstream *p = vp;
206 size_t pksz;
207
208 if (!sz) { doclose(p); return; }
209 pksz = LOAD16(b);
210 if (pksz + 2 == sz) {
211 DISCARD(write(fd_udp, b + 2, pksz));
212 selpk_want(&p->p, 2);
213 } else {
214 selpk_want(&p->p, pksz + 2);
215 *k = sz;
216 }
217 }
218
219 static void wrtcp(int fd, unsigned mode, void *vp)
220 {
221 #define NPK 16
222 struct iovec iov[NPK];
223 pkstream *p = vp;
224 size_t i;
225 ssize_t n;
226 pk *pk, *ppk;
227
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;
231 }
232
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));
236 doclose(p);
237 return;
238 }
239
240 p->szpk -= n;
241 for (pk = p->pks; n && pk; pk = ppk) {
242 ppk = pk->next;
243 if (pk->n <= n) {
244 p->npk--;
245 n -= pk->n;
246 xfree(pk->p);
247 xfree(pk);
248 } else {
249 pk->n -= n;
250 pk->o += n;
251 break;
252 }
253 }
254 p->pks = pk;
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); }
258 }
259
260 static void rdudp(int fd, unsigned mode, void *vp)
261 {
262 octet buf[65536];
263 ssize_t n;
264 pkstream *p = vp;
265 pk *pk;
266
267 if ((n = read(fd, buf, sizeof(buf))) < 0) {
268 if (errno == EAGAIN || errno == EWOULDBLOCK || errno == EINTR)
269 return;
270 moan("couldn't read from UDP socket: %s", strerror(errno));
271 return;
272 }
273 pk = xmalloc(sizeof(*pk));
274 pk->next = 0;
275 pk->p = xmalloc(n + 2);
276 STORE16(pk->p, n);
277 memcpy(pk->p + 2, buf, n);
278 pk->o = pk->p;
279 pk->n = n + 2;
280 *p->pk_tail = pk;
281 p->pk_tail = &pk->next;
282 if (!p->npk) sel_addfile(&p->w);
283 sel_force(&p->w);
284 p->npk++;
285 p->szpk += n + 2;
286 if (p->npk >= pk_nmax || p->szpk >= pk_szmax)
287 { sel_rmfile(&p->r); p->f |= PKF_FULL; }
288 }
289
290 static void dofwd(int fd_in, int fd_out)
291 {
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);
297 p->pks = 0;
298 p->pk_tail = &p->pks;
299 p->npk = p->szpk = 0;
300 p->f = 0;
301 sel_addfile(&p->r);
302 }
303
304 static void doaccept(int fd_s, unsigned mode, void *p)
305 {
306 int fd;
307 addr a;
308 socklen_t sz = sizeof(a);
309 size_t i, n;
310
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));
314 return;
315 }
316 n = DA_LEN(&cw.peer);
317 if (!n) goto match;
318 for (i = 0; i < n; i++) if (addreq(&a, &DA(&cw.peer)[i])) goto match;
319 moan("rejecting connection from %s", addrstr(&a));
320 close(fd); return;
321 match:
322 if (nonblockify(fd) || cloexec(fd)) {
323 moan("couldn't accept incoming connection: %s", strerror(errno));
324 close(fd); return;
325 }
326 dofwd(fd, fd);
327 n = DA_LEN(&cw.me);
328 for (i = 0; i < n; i++) { close(cw.sfv[i].fd); sel_rmfile(&cw.sfv[i]); }
329 }
330
331 static void dolisten1(const addr *a, sel_file *sf)
332 {
333 int fd;
334 int opt = 1;
335
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);
343 sel_addfile(sf);
344 }
345
346 static void dolisten(void)
347 {
348 size_t i, n;
349
350 n = DA_LEN(&cw.me);
351 for (i = 0; i < n; i++)
352 dolisten1(&DA(&cw.me)[i], &cw.sfv[i]);
353 }
354
355 static void pushaddrs(addr_v *av, const struct addrinfo *ailist)
356 {
357 const struct addrinfo *ai;
358 size_t i, n;
359
360 for (ai = ailist, n = 0; ai; ai = ai->ai_next)
361 if (knownafp(ai->ai_family)) n++;
362 DA_ENSURE(av, 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);
367 }
368 DA_EXTEND(av, n);
369 }
370
371 #define paf_parse 1u
372 static void parseaddr(const struct addrinfo *aihint,
373 const char *host, const char *svc, unsigned f,
374 struct addrinfo **ai_out)
375 {
376 char *alloc = 0, *sep;
377 int err;
378
379 if (f&paf_parse) {
380 alloc = xstrdup(host);
381 if ((sep = strchr(alloc, ':')) == 0)
382 die(1, "missing port number in address `%s'", host);
383 host = alloc; *sep = 0; svc = sep + 1;
384 }
385
386 err = getaddrinfo(host, svc, aihint, ai_out);
387 if (err) {
388 if (host && svc) {
389 die(1, "failed to resolve hostname `%s', service `%s': %s",
390 host, svc, gai_strerror(err));
391 } else if (host)
392 die(1, "failed to resolve hostname `%s': %s", host, gai_strerror(err));
393 else
394 die(1, "failed to resolve service `%s': %s", svc, gai_strerror(err));
395 }
396
397 xfree(alloc);
398 }
399
400 static void usage(FILE *fp)
401 {
402 pquis(fp,
403 "Usage: $ [-l PORT] [-b ADDR] [-p ADDR] [-c ADDR:PORT]\n\
404 ADDR:PORT ADDR:PORT\n");
405 }
406
407 static void version(FILE *fp)
408 { pquis(fp, "$, tripe version " VERSION "\n"); }
409
410 static void help(FILE *fp)
411 {
412 version(fp);
413 fputc('\n', fp);
414 usage(fp);
415 fputs("\n\
416 Options:\n\
417 \n\
418 -h, --help Display this help text.\n\
419 -v, --version Display version number.\n\
420 -u, --usage Display pointless usage message.\n\
421 \n\
422 -l, --listen=PORT Listen for connections to TCP PORT.\n\
423 -p, --peer=ADDR Only accept connections from IP ADDR.\n\
424 -b, --bind=ADDR Bind to ADDR before connecting.\n\
425 -c, --connect=ADDR:PORT Connect to IP ADDR, TCP PORT.\n\
426 \n\
427 Forwards UDP packets over a reliable stream. By default, uses stdin and\n\
428 stdout; though it can use TCP sockets instead.\n\
429 ", fp);
430 }
431
432 int main(int argc, char *argv[])
433 {
434 unsigned f = 0;
435 str_v bindhosts = DA_INIT, peerhosts = DA_INIT;
436 const char *bindsvc = 0;
437 addr bindaddr;
438 const char *connhost = 0;
439 struct addrinfo aihint = { 0 }, *ai, *ailist;
440 int fd = -1;
441 int len = 65536;
442 size_t i, n;
443
444 #define f_bogus 1u
445
446 cw.f = 0;
447
448 ego(argv[0]);
449 sel_init(&sel);
450 for (;;) {
451 static struct option opt[] = {
452 { "help", 0, 0, 'h' },
453 { "version", 0, 0, 'v' },
454 { "usage", 0, 0, 'u' },
455 { "listen", OPTF_ARGREQ, 0, 'l' },
456 { "peer", OPTF_ARGREQ, 0, 'p' },
457 { "bind", OPTF_ARGREQ, 0, 'b' },
458 { "connect", OPTF_ARGREQ, 0, 'c' },
459 { 0, 0, 0, 0 }
460 };
461 int i;
462
463 i = mdwopt(argc, argv, "hvul:p:b:c:", opt, 0, 0, 0);
464 if (i < 0)
465 break;
466 switch (i) {
467 case 'h': help(stdout); exit(0);
468 case 'v': version(stdout); exit(0);
469 case 'u': usage(stdout); exit(0);
470 case 'l': bindsvc = optarg; break;
471 case 'p': DA_PUSH(&peerhosts, optarg); break;
472 case 'b': DA_PUSH(&bindhosts, optarg); break;
473 case 'c': connhost = optarg; break;
474 default: f |= f_bogus; break;
475 }
476 }
477 if (optind + 2 != argc || (f&f_bogus)) { usage(stderr); exit(1); }
478
479 if (DA_LEN(&bindhosts) && !bindsvc && !connhost)
480 die(1, "bind addr only makes sense when listening or connecting");
481 if (DA_LEN(&peerhosts) && !bindsvc)
482 die(1, "peer addr only makes sense when listening");
483 if (bindsvc && connhost)
484 die(1, "can't listen and connect");
485
486 aihint.ai_family = AF_INET;
487 DA_CREATE(&cw.me); DA_CREATE(&cw.peer);
488
489 n = DA_LEN(&bindhosts);
490 if (n || bindsvc) {
491 aihint.ai_socktype = SOCK_STREAM;
492 aihint.ai_protocol = IPPROTO_TCP;
493 aihint.ai_flags = AI_ADDRCONFIG | AI_PASSIVE;
494 if (!n) {
495 parseaddr(&aihint, 0, bindsvc, 0, &ailist);
496 pushaddrs(&cw.me, ailist);
497 freeaddrinfo(ailist);
498 } else if (!bindsvc) {
499 if (n != 1) die(1, "can only bind to one address as client");
500 parseaddr(&aihint, DA(&bindhosts)[0], 0, 0, &ailist);
501 for (ai = ailist; ai && !knownafp(ai->ai_family); ai = ai->ai_next);
502 if (!ai)
503 die(1, "no usable addresses returned for `%s'", DA(&bindhosts)[0]);
504 initaddr(&bindaddr, ai->ai_family);
505 copyaddr(&bindaddr, ai->ai_addr, caf_addr);
506 aihint.ai_family = ai->ai_family;
507 freeaddrinfo(ailist);
508 } else for (i = 0; i < n; i++) {
509 parseaddr(&aihint, DA(&bindhosts)[i], bindsvc, 0, &ailist);
510 pushaddrs(&cw.me, ailist);
511 freeaddrinfo(ailist);
512 }
513 if (bindsvc) {
514 cw.f |= cwf_port;
515 n = DA_LEN(&cw.me);
516 cw.sfv = xmalloc(n*sizeof(*cw.sfv));
517 }
518 }
519
520 n = DA_LEN(&peerhosts);
521 if (n) {
522 aihint.ai_socktype = SOCK_STREAM;
523 aihint.ai_protocol = IPPROTO_TCP;
524 aihint.ai_flags = AI_ADDRCONFIG;
525 for (i = 0; i < n; i++) {
526 parseaddr(&aihint, DA(&peerhosts)[i], 0, 0, &ailist);
527 pushaddrs(&cw.peer, ailist);
528 freeaddrinfo(ailist);
529 }
530 if (!DA_LEN(&cw.peer)) die(1, "no usable peer addresses");
531 }
532
533 if (connhost) {
534 aihint.ai_socktype = SOCK_STREAM;
535 aihint.ai_protocol = IPPROTO_TCP;
536 aihint.ai_flags = AI_ADDRCONFIG;
537 parseaddr(&aihint, connhost, 0, paf_parse, &ailist);
538
539 for (ai = ailist; ai; ai = ai->ai_next) {
540 if ((fd = socket(ai->ai_family, SOCK_STREAM, IPPROTO_TCP)) >= 0 &&
541 !initsock(fd, ai->ai_family) &&
542 (!DA_LEN(&bindhosts) ||
543 !bind(fd, &bindaddr.sa, addrsz(&bindaddr))) &&
544 !connect(fd, ai->ai_addr, ai->ai_addrlen))
545 goto conn_tcp;
546 if (fd >= 0) close(fd);
547 }
548 die(1, "couldn't connect to TCP server: %s", strerror(errno));
549 conn_tcp:
550 if (nonblockify(fd) || cloexec(fd))
551 die(1, "couldn't connect to TCP server: %s", strerror(errno));
552 }
553
554 aihint.ai_family = AF_INET;
555 aihint.ai_socktype = SOCK_DGRAM;
556 aihint.ai_protocol = IPPROTO_UDP;
557 aihint.ai_flags = AI_ADDRCONFIG | AI_PASSIVE;
558 parseaddr(&aihint, argv[optind], 0, paf_parse, &ailist);
559 for (ai = ailist; ai && !knownafp(ai->ai_family); ai = ai->ai_next);
560 if (!ai) die(1, "no usable addresses returned for `%s'", argv[optind]);
561 if ((fd_udp = socket(ai->ai_family, SOCK_DGRAM, IPPROTO_UDP)) < 0 ||
562 initsock(fd_udp, ai->ai_family) ||
563 nonblockify(fd_udp) || cloexec(fd_udp) ||
564 setsockopt(fd_udp, SOL_SOCKET, SO_RCVBUF, &len, sizeof(len)) ||
565 setsockopt(fd_udp, SOL_SOCKET, SO_SNDBUF, &len, sizeof(len)) ||
566 bind(fd_udp, ai->ai_addr, ai->ai_addrlen))
567 die(1, "couldn't set up UDP socket: %s", strerror(errno));
568 freeaddrinfo(ailist);
569 aihint.ai_family = ai->ai_family;
570 aihint.ai_flags = AI_ADDRCONFIG;
571 parseaddr(&aihint, argv[optind + 1], 0, paf_parse, &ailist);
572 for (ai = ailist; ai; ai = ai->ai_next)
573 if (!connect(fd_udp, ai->ai_addr, ai->ai_addrlen)) goto conn_udp;
574 die(1, "couldn't set up UDP socket: %s", strerror(errno));
575 conn_udp:
576
577 if (bindsvc) dolisten();
578 else if (connhost) dofwd(fd, fd);
579 else dofwd(STDIN_FILENO, STDOUT_FILENO);
580
581 for (;;) {
582 if (sel_select(&sel) && errno != EINTR)
583 die(1, "select failed: %s", strerror(errno));
584 }
585 return (0);
586 }
587
588 /*----- That's all, folks -------------------------------------------------*/