pkstream/pkstream.c: Use `getaddrinfo' to resolve addresses and services.
[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 const char *addrstr(const addr *a)
115 {
116 static char buf[128];
117 socklen_t n = sizeof(buf);
118
119 if (getnameinfo(&a->sa, addrsz(a), buf, n, 0, 0, NI_NUMERICHOST))
120 return ("<addrstr failed>");
121 return (buf);
122 }
123
124 static int addreq(const addr *a, const addr *b)
125 {
126 if (a->sa.sa_family != b->sa.sa_family) return (0);
127 switch (a->sa.sa_family) {
128 case AF_INET:
129 return (a->sin.sin_addr.s_addr == b->sin.sin_addr.s_addr);
130 default:
131 abort();
132 }
133 }
134
135 static void initaddr(addr *a)
136 {
137 a->sin.sin_family = AF_INET;
138 a->sin.sin_addr.s_addr = INADDR_ANY;
139 a->sin.sin_port = 0;
140 }
141
142 #define caf_addr 1u
143 #define caf_port 2u
144 static void copyaddr(addr *a, const struct sockaddr *sa, unsigned f)
145 {
146 const struct sockaddr_in *sin;
147
148 a->sa.sa_family = sa->sa_family;
149 switch (sa->sa_family) {
150 case AF_INET:
151 sin = (const struct sockaddr_in *)sa;
152 if (f&caf_addr) a->sin.sin_addr = sin->sin_addr;
153 if (f&caf_port) a->sin.sin_port = sin->sin_port;
154 break;
155 default:
156 abort();
157 }
158 }
159
160 static void dolisten(void);
161
162 static void doclose(pkstream *p)
163 {
164 pk *pk, *ppk;
165 close(p->w.fd);
166 close(p->p.reader.fd);
167 selpk_destroy(&p->p);
168 if (!(p->f&PKF_FULL)) sel_rmfile(&p->r);
169 if (p->npk) sel_rmfile(&p->w);
170 for (pk = p->pks; pk; pk = ppk) {
171 ppk = pk->next;
172 xfree(pk->p);
173 xfree(pk);
174 }
175 xfree(p);
176 if (cw.f&cwf_port) dolisten();
177 else exit(0);
178 }
179
180 static void rdtcp(octet *b, size_t sz, pkbuf *pk, size_t *k, void *vp)
181 {
182 pkstream *p = vp;
183 size_t pksz;
184
185 if (!sz) { doclose(p); return; }
186 pksz = LOAD16(b);
187 if (pksz + 2 == sz) {
188 DISCARD(write(fd_udp, b + 2, pksz));
189 selpk_want(&p->p, 2);
190 } else {
191 selpk_want(&p->p, pksz + 2);
192 *k = sz;
193 }
194 }
195
196 static void wrtcp(int fd, unsigned mode, void *vp)
197 {
198 #define NPK 16
199 struct iovec iov[NPK];
200 pkstream *p = vp;
201 size_t i;
202 ssize_t n;
203 pk *pk, *ppk;
204
205 for (i = 0, pk = p->pks; i < NPK && pk; i++, pk = pk->next) {
206 iov[i].iov_base = pk->o;
207 iov[i].iov_len = pk->n;
208 }
209
210 if ((n = writev(fd, iov, i)) < 0) {
211 if (errno == EAGAIN || errno == EWOULDBLOCK || errno == EINTR) return;
212 moan("couldn't write to TCP socket: %s", strerror(errno));
213 doclose(p);
214 return;
215 }
216
217 p->szpk -= n;
218 for (pk = p->pks; n && pk; pk = ppk) {
219 ppk = pk->next;
220 if (pk->n <= n) {
221 p->npk--;
222 n -= pk->n;
223 xfree(pk->p);
224 xfree(pk);
225 } else {
226 pk->n -= n;
227 pk->o += n;
228 break;
229 }
230 }
231 p->pks = pk;
232 if (!pk) { p->pk_tail = &p->pks; sel_rmfile(&p->w); }
233 if ((p->f&PKF_FULL) && p->npk < pk_nmax && p->szpk < pk_szmax)
234 { p->f &= ~PKF_FULL; sel_addfile(&p->r); }
235 }
236
237 static void rdudp(int fd, unsigned mode, void *vp)
238 {
239 octet buf[65536];
240 ssize_t n;
241 pkstream *p = vp;
242 pk *pk;
243
244 if ((n = read(fd, buf, sizeof(buf))) < 0) {
245 if (errno == EAGAIN || errno == EWOULDBLOCK || errno == EINTR)
246 return;
247 moan("couldn't read from UDP socket: %s", strerror(errno));
248 return;
249 }
250 pk = xmalloc(sizeof(*pk));
251 pk->next = 0;
252 pk->p = xmalloc(n + 2);
253 STORE16(pk->p, n);
254 memcpy(pk->p + 2, buf, n);
255 pk->o = pk->p;
256 pk->n = n + 2;
257 *p->pk_tail = pk;
258 p->pk_tail = &pk->next;
259 if (!p->npk) sel_addfile(&p->w);
260 sel_force(&p->w);
261 p->npk++;
262 p->szpk += n + 2;
263 if (p->npk >= pk_nmax || p->szpk >= pk_szmax)
264 { sel_rmfile(&p->r); p->f |= PKF_FULL; }
265 }
266
267 static void dofwd(int fd_in, int fd_out)
268 {
269 pkstream *p = xmalloc(sizeof(*p));
270 sel_initfile(&sel, &p->r, fd_udp, SEL_READ, rdudp, p);
271 sel_initfile(&sel, &p->w, fd_out, SEL_WRITE, wrtcp, p);
272 selpk_init(&p->p, &sel, fd_in, rdtcp, p);
273 selpk_want(&p->p, 2);
274 p->pks = 0;
275 p->pk_tail = &p->pks;
276 p->npk = p->szpk = 0;
277 p->f = 0;
278 sel_addfile(&p->r);
279 }
280
281 static void doaccept(int fd_s, unsigned mode, void *p)
282 {
283 int fd;
284 addr a;
285 socklen_t sz = sizeof(a);
286 size_t i, n;
287
288 if ((fd = accept(fd_s, &a.sa, &sz)) < 0) {
289 if (errno == EAGAIN || errno == EWOULDBLOCK || errno == EINTR) return;
290 moan("couldn't accept incoming connection: %s", strerror(errno));
291 return;
292 }
293 n = DA_LEN(&cw.peer);
294 if (!n) goto match;
295 for (i = 0; i < n; i++) if (addreq(&a, &DA(&cw.peer)[i])) goto match;
296 moan("rejecting connection from %s", addrstr(&a));
297 close(fd); return;
298 match:
299 if (nonblockify(fd) || cloexec(fd)) {
300 moan("couldn't accept incoming connection: %s", strerror(errno));
301 close(fd); return;
302 }
303 dofwd(fd, fd);
304 n = DA_LEN(&cw.me);
305 for (i = 0; i < n; i++) { close(cw.sfv[i].fd); sel_rmfile(&cw.sfv[i]); }
306 }
307
308 static void dolisten1(const addr *a, sel_file *sf)
309 {
310 int fd;
311 int opt = 1;
312
313 if ((fd = socket(a->sa.sa_family, SOCK_STREAM, IPPROTO_TCP)) < 0 ||
314 setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt)) ||
315 bind(fd, &a->sa, addrsz(a)) ||
316 listen(fd, 1) || nonblockify(fd) || cloexec(fd))
317 die(1, "couldn't set up listening socket: %s", strerror(errno));
318 sel_initfile(&sel, sf, fd, SEL_READ, doaccept, 0);
319 sel_addfile(sf);
320 }
321
322 static void dolisten(void)
323 {
324 size_t i, n;
325
326 n = DA_LEN(&cw.me);
327 for (i = 0; i < n; i++)
328 dolisten1(&DA(&cw.me)[i], &cw.sfv[i]);
329 }
330
331 static void pushaddrs(addr_v *av, const struct addrinfo *ailist)
332 {
333 const struct addrinfo *ai;
334 size_t i, n;
335
336 for (ai = ailist, n = 0; ai; ai = ai->ai_next) n++;
337 DA_ENSURE(av, n);
338 for (i = DA_LEN(av), ai = ailist; ai; ai = ai->ai_next) {
339 initaddr(&DA(av)[i]);
340 copyaddr(&DA(av)[i++], ai->ai_addr, caf_addr | caf_port);
341 }
342 DA_EXTEND(av, n);
343 }
344
345 #define paf_parse 1u
346 static void parseaddr(const struct addrinfo *aihint,
347 const char *host, const char *svc, unsigned f,
348 struct addrinfo **ai_out)
349 {
350 char *alloc = 0, *sep;
351 int err;
352
353 if (f&paf_parse) {
354 alloc = xstrdup(host);
355 if ((sep = strchr(alloc, ':')) == 0)
356 die(1, "missing port number in address `%s'", host);
357 host = alloc; *sep = 0; svc = sep + 1;
358 }
359
360 err = getaddrinfo(host, svc, aihint, ai_out);
361 if (err) {
362 if (host && svc) {
363 die(1, "failed to resolve hostname `%s', service `%s': %s",
364 host, svc, gai_strerror(err));
365 } else if (host)
366 die(1, "failed to resolve hostname `%s': %s", host, gai_strerror(err));
367 else
368 die(1, "failed to resolve service `%s': %s", svc, gai_strerror(err));
369 }
370
371 xfree(alloc);
372 }
373
374 static void usage(FILE *fp)
375 {
376 pquis(fp,
377 "Usage: $ [-l PORT] [-b ADDR] [-p ADDR] [-c ADDR:PORT]\n\
378 ADDR:PORT ADDR:PORT\n");
379 }
380
381 static void version(FILE *fp)
382 { pquis(fp, "$, tripe version " VERSION "\n"); }
383
384 static void help(FILE *fp)
385 {
386 version(fp);
387 fputc('\n', fp);
388 usage(fp);
389 fputs("\n\
390 Options:\n\
391 \n\
392 -h, --help Display this help text.\n\
393 -v, --version Display version number.\n\
394 -u, --usage Display pointless usage message.\n\
395 \n\
396 -l, --listen=PORT Listen for connections to TCP PORT.\n\
397 -p, --peer=ADDR Only accept connections from IP ADDR.\n\
398 -b, --bind=ADDR Bind to ADDR before connecting.\n\
399 -c, --connect=ADDR:PORT Connect to IP ADDR, TCP PORT.\n\
400 \n\
401 Forwards UDP packets over a reliable stream. By default, uses stdin and\n\
402 stdout; though it can use TCP sockets instead.\n\
403 ", fp);
404 }
405
406 int main(int argc, char *argv[])
407 {
408 unsigned f = 0;
409 str_v bindhosts = DA_INIT, peerhosts = DA_INIT;
410 const char *bindsvc = 0;
411 addr bindaddr;
412 const char *connhost = 0;
413 struct addrinfo aihint = { 0 }, *ai, *ailist;
414 int fd = -1;
415 int len = 65536;
416 size_t i, n;
417
418 #define f_bogus 1u
419
420 cw.f = 0;
421
422 ego(argv[0]);
423 sel_init(&sel);
424 for (;;) {
425 static struct option opt[] = {
426 { "help", 0, 0, 'h' },
427 { "version", 0, 0, 'v' },
428 { "usage", 0, 0, 'u' },
429 { "listen", OPTF_ARGREQ, 0, 'l' },
430 { "peer", OPTF_ARGREQ, 0, 'p' },
431 { "bind", OPTF_ARGREQ, 0, 'b' },
432 { "connect", OPTF_ARGREQ, 0, 'c' },
433 { 0, 0, 0, 0 }
434 };
435 int i;
436
437 i = mdwopt(argc, argv, "hvul:p:b:c:", opt, 0, 0, 0);
438 if (i < 0)
439 break;
440 switch (i) {
441 case 'h': help(stdout); exit(0);
442 case 'v': version(stdout); exit(0);
443 case 'u': usage(stdout); exit(0);
444 case 'l': bindsvc = optarg; break;
445 case 'p': DA_PUSH(&peerhosts, optarg); break;
446 case 'b': DA_PUSH(&bindhosts, optarg); break;
447 case 'c': connhost = optarg; break;
448 default: f |= f_bogus; break;
449 }
450 }
451 if (optind + 2 != argc || (f&f_bogus)) { usage(stderr); exit(1); }
452
453 if (DA_LEN(&bindhosts) && !bindsvc && !connhost)
454 die(1, "bind addr only makes sense when listening or connecting");
455 if (DA_LEN(&peerhosts) && !bindsvc)
456 die(1, "peer addr only makes sense when listening");
457 if (bindsvc && connhost)
458 die(1, "can't listen and connect");
459
460 aihint.ai_family = AF_INET;
461 DA_CREATE(&cw.me); DA_CREATE(&cw.peer);
462
463 n = DA_LEN(&bindhosts);
464 if (n || bindsvc) {
465 aihint.ai_socktype = SOCK_STREAM;
466 aihint.ai_protocol = IPPROTO_TCP;
467 aihint.ai_flags = AI_ADDRCONFIG | AI_PASSIVE;
468 if (!n) {
469 parseaddr(&aihint, 0, bindsvc, 0, &ailist);
470 pushaddrs(&cw.me, ailist);
471 freeaddrinfo(ailist);
472 } else if (!bindsvc) {
473 if (n != 1) die(1, "can only bind to one address as client");
474 parseaddr(&aihint, DA(&bindhosts)[0], 0, 0, &ailist); ai = ailist;
475 initaddr(&bindaddr);
476 copyaddr(&bindaddr, ai->ai_addr, caf_addr);
477 freeaddrinfo(ailist);
478 } else for (i = 0; i < n; i++) {
479 parseaddr(&aihint, DA(&bindhosts)[i], bindsvc, 0, &ailist);
480 pushaddrs(&cw.me, ailist);
481 freeaddrinfo(ailist);
482 }
483 if (bindsvc) {
484 cw.f |= cwf_port;
485 n = DA_LEN(&cw.me);
486 cw.sfv = xmalloc(n*sizeof(*cw.sfv));
487 }
488 }
489
490 n = DA_LEN(&peerhosts);
491 if (n) {
492 aihint.ai_socktype = SOCK_STREAM;
493 aihint.ai_protocol = IPPROTO_TCP;
494 aihint.ai_flags = AI_ADDRCONFIG;
495 for (i = 0; i < n; i++) {
496 parseaddr(&aihint, DA(&peerhosts)[i], 0, 0, &ailist);
497 pushaddrs(&cw.peer, ailist);
498 freeaddrinfo(ailist);
499 }
500 }
501
502 if (connhost) {
503 aihint.ai_socktype = SOCK_STREAM;
504 aihint.ai_protocol = IPPROTO_TCP;
505 aihint.ai_flags = AI_ADDRCONFIG;
506 parseaddr(&aihint, connhost, 0, paf_parse, &ailist);
507
508 for (ai = ailist; ai; ai = ai->ai_next) {
509 if ((fd = socket(ai->ai_family, SOCK_STREAM, IPPROTO_TCP)) >= 0 &&
510 (!DA_LEN(&bindhosts) ||
511 !bind(fd, &bindaddr.sa, addrsz(&bindaddr))) &&
512 !connect(fd, ai->ai_addr, ai->ai_addrlen))
513 goto conn_tcp;
514 if (fd >= 0) close(fd);
515 }
516 die(1, "couldn't connect to TCP server: %s", strerror(errno));
517 conn_tcp:
518 if (nonblockify(fd) || cloexec(fd))
519 die(1, "couldn't connect to TCP server: %s", strerror(errno));
520 }
521
522 aihint.ai_socktype = SOCK_DGRAM;
523 aihint.ai_protocol = IPPROTO_UDP;
524 aihint.ai_flags = AI_ADDRCONFIG | AI_PASSIVE;
525 parseaddr(&aihint, argv[optind], 0, paf_parse, &ailist); ai = ailist;
526 if ((fd_udp = socket(ai->ai_family, SOCK_DGRAM, IPPROTO_UDP)) < 0 ||
527 nonblockify(fd_udp) || cloexec(fd_udp) ||
528 setsockopt(fd_udp, SOL_SOCKET, SO_RCVBUF, &len, sizeof(len)) ||
529 setsockopt(fd_udp, SOL_SOCKET, SO_SNDBUF, &len, sizeof(len)) ||
530 bind(fd_udp, ai->ai_addr, ai->ai_addrlen))
531 die(1, "couldn't set up UDP socket: %s", strerror(errno));
532 freeaddrinfo(ailist);
533 aihint.ai_flags = AI_ADDRCONFIG;
534 parseaddr(&aihint, argv[optind + 1], 0, paf_parse, &ailist);
535 for (ai = ailist; ai; ai = ai->ai_next)
536 if (!connect(fd_udp, ai->ai_addr, ai->ai_addrlen)) goto conn_udp;
537 die(1, "couldn't set up UDP socket: %s", strerror(errno));
538 conn_udp:
539
540 if (bindsvc) dolisten();
541 else if (connhost) dofwd(fd, fd);
542 else dofwd(STDIN_FILENO, STDOUT_FILENO);
543
544 for (;;) {
545 if (sel_select(&sel) && errno != EINTR)
546 die(1, "select failed: %s", strerror(errno));
547 }
548 return (0);
549 }
550
551 /*----- That's all, folks -------------------------------------------------*/