chiark / gitweb /
pkstream/pkstream.c: Introduce helper functions to fiddle with addresses.
[tripe] / pkstream / pkstream.c
CommitLineData
07212ba4 1/* -*-c-*-
07212ba4 2 *
3 * Forwarding UDP packets over a stream
4 *
5 * (c) 2003 Straylight/Edgeware
6 */
7
e04c2d50 8/*----- Licensing notice --------------------------------------------------*
07212ba4 9 *
10 * This file is part of Trivial IP Encryption (TrIPE).
11 *
11ad66c2
MW
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.
e04c2d50 16 *
11ad66c2
MW
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.
e04c2d50 21 *
07212ba4 22 * You should have received a copy of the GNU General Public License
11ad66c2 23 * along with TrIPE. If not, see <https://www.gnu.org/licenses/>.
07212ba4 24 */
25
07212ba4 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/dstr.h>
49#include <mLib/fdflags.h>
50#include <mLib/mdwopt.h>
51#include <mLib/quis.h>
52#include <mLib/report.h>
53#include <mLib/sel.h>
54#include <mLib/selpk.h>
55
23df0e5b
MW
56#include "util.h"
57
07212ba4 58/*----- Data structures ---------------------------------------------------*/
59
5db82aca
MW
60typedef union addr {
61 struct sockaddr sa;
62 struct sockaddr_in sin;
63} addr;
64
07212ba4 65typedef struct pk {
66 struct pk *next; /* Next packet in the chain */
67 octet *p, *o; /* Buffer start and current posn */
68 size_t n; /* Size of packet remaining */
69} pk;
70
71typedef struct pkstream {
72 unsigned f; /* Flags... */
73#define PKF_FULL 1u /* Buffer is full: stop reading */
74 sel_file r, w; /* Read and write selectors */
75 pk *pks, **pk_tail; /* Packet queue */
76 size_t npk, szpk; /* Number and size of data */
77 selpk p; /* Packet parser */
78} pkstream;
79
80typedef struct connwait {
8fc71d5a
MW
81 unsigned f; /* Various flags */
82#define cwf_port 1u /* Port is defined => listen */
07212ba4 83 sel_file a; /* Selector */
5db82aca 84 addr me, peer; /* Who I'm meant to be; who peer is */
07212ba4 85} connwait;
86
87/*----- Static variables --------------------------------------------------*/
88
89static sel_state sel;
90static connwait cw;
91static int fd_udp;
1afc65b6 92static size_t pk_nmax = 128, pk_szmax = 1024*1024;
07212ba4 93
94/*----- Main code ---------------------------------------------------------*/
95
96static int nonblockify(int fd)
f98df549 97 { return (fdflags(fd, O_NONBLOCK, O_NONBLOCK, 0, 0)); }
07212ba4 98
99static int cloexec(int fd)
f98df549 100 { return (fdflags(fd, 0, 0, FD_CLOEXEC, FD_CLOEXEC)); }
07212ba4 101
5426c57a
MW
102static socklen_t addrsz(const addr *a)
103{
104 switch (a->sa.sa_family) {
105 case AF_INET: return sizeof(a->sin);
106 default: abort();
107 }
108}
109
110static const char *addrstr(const addr *a)
111{
112 static char buf[128];
113 socklen_t n = sizeof(buf);
114
115 if (getnameinfo(&a->sa, addrsz(a), buf, n, 0, 0, NI_NUMERICHOST))
116 return ("<addrstr failed>");
117 return (buf);
118}
119
120static int addreq(const addr *a, const addr *b)
121{
122 if (a->sa.sa_family != b->sa.sa_family) return (0);
123 switch (a->sa.sa_family) {
124 case AF_INET:
125 return (a->sin.sin_addr.s_addr == b->sin.sin_addr.s_addr);
126 default:
127 abort();
128 }
129}
130
5db82aca 131static void initaddr(addr *a)
3912d793 132{
5db82aca
MW
133 a->sin.sin_family = AF_INET;
134 a->sin.sin_addr.s_addr = INADDR_ANY;
135 a->sin.sin_port = 0;
3912d793
MW
136}
137
07212ba4 138static void dolisten(void);
139
140static void doclose(pkstream *p)
141{
142 pk *pk, *ppk;
143 close(p->w.fd);
144 close(p->p.reader.fd);
145 selpk_destroy(&p->p);
1afc65b6
MW
146 if (!(p->f&PKF_FULL)) sel_rmfile(&p->r);
147 if (p->npk) sel_rmfile(&p->w);
07212ba4 148 for (pk = p->pks; pk; pk = ppk) {
149 ppk = pk->next;
150 xfree(pk->p);
151 xfree(pk);
152 }
153 xfree(p);
8fc71d5a 154 if (cw.f&cwf_port) dolisten();
1afc65b6 155 else exit(0);
07212ba4 156}
157
158static void rdtcp(octet *b, size_t sz, pkbuf *pk, size_t *k, void *vp)
159{
160 pkstream *p = vp;
161 size_t pksz;
162
1afc65b6 163 if (!sz) { doclose(p); return; }
07212ba4 164 pksz = LOAD16(b);
165 if (pksz + 2 == sz) {
99735357 166 DISCARD(write(fd_udp, b + 2, pksz));
07212ba4 167 selpk_want(&p->p, 2);
168 } else {
169 selpk_want(&p->p, pksz + 2);
170 *k = sz;
171 }
172}
173
174static void wrtcp(int fd, unsigned mode, void *vp)
175{
176#define NPK 16
177 struct iovec iov[NPK];
178 pkstream *p = vp;
179 size_t i;
180 ssize_t n;
181 pk *pk, *ppk;
182
183 for (i = 0, pk = p->pks; i < NPK && pk; i++, pk = pk->next) {
184 iov[i].iov_base = pk->o;
185 iov[i].iov_len = pk->n;
186 }
187
188 if ((n = writev(fd, iov, i)) < 0) {
1afc65b6 189 if (errno == EAGAIN || errno == EWOULDBLOCK || errno == EINTR) return;
07212ba4 190 moan("couldn't write to TCP socket: %s", strerror(errno));
191 doclose(p);
192 return;
193 }
194
195 p->szpk -= n;
196 for (pk = p->pks; n && pk; pk = ppk) {
197 ppk = pk->next;
198 if (pk->n <= n) {
199 p->npk--;
200 n -= pk->n;
201 xfree(pk->p);
202 xfree(pk);
203 } else {
204 pk->n -= n;
205 pk->o += n;
206 break;
207 }
208 }
209 p->pks = pk;
1afc65b6
MW
210 if (!pk) { p->pk_tail = &p->pks; sel_rmfile(&p->w); }
211 if ((p->f&PKF_FULL) && p->npk < pk_nmax && p->szpk < pk_szmax)
212 { p->f &= ~PKF_FULL; sel_addfile(&p->r); }
07212ba4 213}
214
215static void rdudp(int fd, unsigned mode, void *vp)
216{
217 octet buf[65536];
218 ssize_t n;
219 pkstream *p = vp;
220 pk *pk;
221
222 if ((n = read(fd, buf, sizeof(buf))) < 0) {
223 if (errno == EAGAIN || errno == EWOULDBLOCK || errno == EINTR)
224 return;
225 moan("couldn't read from UDP socket: %s", strerror(errno));
226 return;
227 }
228 pk = xmalloc(sizeof(*pk));
229 pk->next = 0;
230 pk->p = xmalloc(n + 2);
231 STORE16(pk->p, n);
232 memcpy(pk->p + 2, buf, n);
233 pk->o = pk->p;
234 pk->n = n + 2;
235 *p->pk_tail = pk;
236 p->pk_tail = &pk->next;
1afc65b6 237 if (!p->npk) sel_addfile(&p->w);
07212ba4 238 sel_force(&p->w);
239 p->npk++;
240 p->szpk += n + 2;
1afc65b6
MW
241 if (p->npk >= pk_nmax || p->szpk >= pk_szmax)
242 { sel_rmfile(&p->r); p->f |= PKF_FULL; }
07212ba4 243}
244
245static void dofwd(int fd_in, int fd_out)
246{
247 pkstream *p = xmalloc(sizeof(*p));
248 sel_initfile(&sel, &p->r, fd_udp, SEL_READ, rdudp, p);
249 sel_initfile(&sel, &p->w, fd_out, SEL_WRITE, wrtcp, p);
250 selpk_init(&p->p, &sel, fd_in, rdtcp, p);
251 selpk_want(&p->p, 2);
252 p->pks = 0;
253 p->pk_tail = &p->pks;
254 p->npk = p->szpk = 0;
255 p->f = 0;
256 sel_addfile(&p->r);
257}
258
259static void doaccept(int fd_s, unsigned mode, void *p)
260{
261 int fd;
5db82aca
MW
262 addr a;
263 socklen_t sz = sizeof(a);
07212ba4 264
5db82aca 265 if ((fd = accept(fd_s, &a.sa, &sz)) < 0) {
1afc65b6 266 if (errno == EAGAIN || errno == EWOULDBLOCK || errno == EINTR) return;
07212ba4 267 moan("couldn't accept incoming connection: %s", strerror(errno));
268 return;
269 }
5426c57a
MW
270 if (cw.peer.sin.sin_addr.s_addr != INADDR_ANY && !addreq(&a, &cw.peer)) {
271 moan("rejecting connection from %s", addrstr(&a));
1afc65b6 272 close(fd); return;
07212ba4 273 }
274 if (nonblockify(fd) || cloexec(fd)) {
07212ba4 275 moan("couldn't accept incoming connection: %s", strerror(errno));
1afc65b6 276 close(fd); return;
07212ba4 277 }
278 dofwd(fd, fd);
279 close(fd_s);
280 sel_rmfile(&cw.a);
281}
282
283static void dolisten(void)
284{
285 int fd;
286 int opt = 1;
287
288 if ((fd = socket(PF_INET, SOCK_STREAM, 0)) < 0 ||
07212ba4 289 setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt)) ||
5426c57a 290 bind(fd, &cw.me.sa, addrsz(&cw.me)) ||
07212ba4 291 listen(fd, 1) || nonblockify(fd) || cloexec(fd))
292 die(1, "couldn't set up listening socket: %s", strerror(errno));
293 sel_initfile(&sel, &cw.a, fd, SEL_READ, doaccept, 0);
294 sel_addfile(&cw.a);
295}
296
3912d793 297#define paf_parse 1u
5db82aca 298static void parseaddr(const char *host, const char *svc, unsigned f, addr *a)
07212ba4 299{
3912d793 300 char *alloc = 0, *sep;
1afc65b6
MW
301 struct hostent *h;
302 struct servent *s;
303 char *qq;
304 unsigned long n;
305
3912d793
MW
306 if (f&paf_parse) {
307 alloc = xstrdup(host);
308 if ((sep = strchr(alloc, ':')) == 0)
309 die(1, "missing port number in address `%s'", host);
310 host = alloc; *sep = 0; svc = sep + 1;
07212ba4 311 }
312
3912d793
MW
313 if (host) {
314 if ((h = gethostbyname(host)) == 0) die(1, "unknown host `%s'", host);
5db82aca 315 memcpy(&a->sin.sin_addr, h->h_addr, sizeof(a->sin.sin_addr));
07212ba4 316 }
317
3912d793
MW
318 if (svc) {
319 if ((n = strtoul(svc, &qq, 0)) > 0 && !*qq && n <= 0xffff)
5db82aca 320 a->sin.sin_port = htons(n);
3912d793 321 else if ((s = getservbyname(svc, "tcp")) != 0)
5db82aca 322 a->sin.sin_port = s->s_port;
3912d793
MW
323 else
324 die(1, "bad service name/number `%s'", svc);
07212ba4 325 }
3912d793
MW
326
327 xfree(alloc);
07212ba4 328}
329
330static void usage(FILE *fp)
331{
332 pquis(fp,
ef4a1ab7 333 "Usage: $ [-l PORT] [-b ADDR] [-p ADDR] [-c ADDR:PORT]\n\
334 ADDR:PORT ADDR:PORT\n");
07212ba4 335}
336
337static void version(FILE *fp)
f98df549 338 { pquis(fp, "$, tripe version " VERSION "\n"); }
07212ba4 339
340static void help(FILE *fp)
341{
342 version(fp);
343 fputc('\n', fp);
344 usage(fp);
345 fputs("\n\
346Options:\n\
347\n\
348-h, --help Display this help text.\n\
349-v, --version Display version number.\n\
350-u, --usage Display pointless usage message.\n\
351\n\
352-l, --listen=PORT Listen for connections to TCP PORT.\n\
ef4a1ab7 353-p, --peer=ADDR Only accept connections from IP ADDR.\n\
354-b, --bind=ADDR Bind to ADDR before connecting.\n\
07212ba4 355-c, --connect=ADDR:PORT Connect to IP ADDR, TCP PORT.\n\
356\n\
357Forwards UDP packets over a reliable stream. By default, uses stdin and\n\
358stdout; though it can use TCP sockets instead.\n\
359", fp);
360}
361
362int main(int argc, char *argv[])
363{
364 unsigned f = 0;
3912d793 365 const char *bindhost = 0, *bindsvc = 0, *peerhost = 0;
5db82aca 366 addr bindaddr;
3912d793 367 const char *connhost = 0;
5db82aca 368 addr tmpaddr;
3912d793 369 int fd = -1;
07212ba4 370 int len = 65536;
371
372#define f_bogus 1u
373
8fc71d5a
MW
374 cw.f = 0;
375
07212ba4 376 ego(argv[0]);
07212ba4 377 sel_init(&sel);
378 for (;;) {
379 static struct option opt[] = {
380 { "help", 0, 0, 'h' },
381 { "version", 0, 0, 'v' },
382 { "usage", 0, 0, 'u' },
383 { "listen", OPTF_ARGREQ, 0, 'l' },
384 { "peer", OPTF_ARGREQ, 0, 'p' },
ef4a1ab7 385 { "bind", OPTF_ARGREQ, 0, 'b' },
07212ba4 386 { "connect", OPTF_ARGREQ, 0, 'c' },
387 { 0, 0, 0, 0 }
388 };
389 int i;
390
ef4a1ab7 391 i = mdwopt(argc, argv, "hvul:p:b:c:", opt, 0, 0, 0);
07212ba4 392 if (i < 0)
393 break;
394 switch (i) {
1afc65b6
MW
395 case 'h': help(stdout); exit(0);
396 case 'v': version(stdout); exit(0);
397 case 'u': usage(stdout); exit(0);
3912d793
MW
398 case 'l': bindsvc = optarg; break;
399 case 'p': peerhost = optarg; break;
400 case 'b': bindhost = optarg; break;
401 case 'c': connhost = optarg; break;
1afc65b6 402 default: f |= f_bogus; break;
07212ba4 403 }
404 }
1afc65b6 405 if (optind + 2 != argc || (f&f_bogus)) { usage(stderr); exit(1); }
07212ba4 406
3912d793
MW
407 if (bindhost && !bindsvc && !connhost)
408 die(1, "bind addr only makes sense when listening or connecting");
409 if (peerhost && !bindsvc)
410 die(1, "peer addr only makes sense when listening");
411 if (bindsvc && connhost)
412 die(1, "can't listen and connect");
413
3912d793
MW
414 if (bindhost || bindsvc) {
415 initaddr(&bindaddr);
416 if (!bindsvc) parseaddr(bindhost, 0, 0, &bindaddr);
8fc71d5a
MW
417 else {
418 initaddr(&cw.me);
419 parseaddr(bindhost, bindsvc, 0, &cw.me);
420 cw.f |= cwf_port;
421 }
3912d793
MW
422 }
423
424 initaddr(&cw.peer);
425 if (peerhost) parseaddr(peerhost, 0, 0, &cw.peer);
07212ba4 426
3912d793
MW
427 if (connhost) {
428 initaddr(&tmpaddr);
429 parseaddr(connhost, 0, paf_parse, &tmpaddr);
430 if ((fd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP)) < 0 ||
431 (bindhost &&
5426c57a
MW
432 bind(fd, &bindaddr.sa, addrsz(&bindaddr))) ||
433 connect(fd, &tmpaddr.sa, addrsz(&tmpaddr)))
3912d793
MW
434 die(1, "couldn't connect to TCP server: %s", strerror(errno));
435 if (nonblockify(fd) || cloexec(fd))
436 die(1, "couldn't connect to TCP server: %s", strerror(errno));
437 }
438
439 initaddr(&tmpaddr);
440 parseaddr(argv[optind], 0, paf_parse, &tmpaddr);
441 if ((fd_udp = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP)) < 0 ||
442 nonblockify(fd_udp) || cloexec(fd_udp) ||
07212ba4 443 setsockopt(fd_udp, SOL_SOCKET, SO_RCVBUF, &len, sizeof(len)) ||
444 setsockopt(fd_udp, SOL_SOCKET, SO_SNDBUF, &len, sizeof(len)) ||
5426c57a 445 bind(fd_udp, &tmpaddr.sa, addrsz(&tmpaddr)))
3912d793
MW
446 die(1, "couldn't set up UDP socket: %s", strerror(errno));
447 initaddr(&tmpaddr);
448 parseaddr(argv[optind + 1], 0, paf_parse, &tmpaddr);
5426c57a 449 if (connect(fd_udp, &tmpaddr.sa, addrsz(&tmpaddr)))
07212ba4 450 die(1, "couldn't set up UDP socket: %s", strerror(errno));
451
3912d793
MW
452 if (bindsvc) dolisten();
453 else if (connhost) dofwd(fd, fd);
454 else dofwd(STDIN_FILENO, STDOUT_FILENO);
07212ba4 455
c14225f6
MW
456 for (;;) {
457 if (sel_select(&sel) && errno != EINTR)
458 die(1, "select failed: %s", strerror(errno));
459 }
07212ba4 460 return (0);
461}
462
463/*----- That's all, folks -------------------------------------------------*/