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