chiark / gitweb /
Build: Kill $(mkdir_p); use $(MKDIR_P).
[tripe] / pkstream / pkstream.c
... / ...
CommitLineData
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
13 * it under the terms of the GNU General Public License as published by
14 * the Free Software Foundation; either version 2 of the License, or
15 * (at your option) any later version.
16 *
17 * TrIPE is distributed in the hope that it will be useful,
18 * but WITHOUT ANY WARRANTY; without even the implied warranty of
19 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
20 * GNU General Public License for more details.
21 *
22 * You should have received a copy of the GNU General Public License
23 * along with TrIPE; if not, write to the Free Software Foundation,
24 * Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
25 */
26
27/*----- Header files ------------------------------------------------------*/
28
29#include "config.h"
30
31#include <ctype.h>
32#include <errno.h>
33#include <stdio.h>
34#include <stdlib.h>
35#include <string.h>
36
37#include <sys/time.h>
38#include <sys/types.h>
39#include <unistd.h>
40#include <fcntl.h>
41#include <sys/uio.h>
42#include <sys/socket.h>
43#include <netinet/in.h>
44#include <arpa/inet.h>
45#include <netdb.h>
46
47#include <mLib/alloc.h>
48#include <mLib/bits.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/*----- Data structures ---------------------------------------------------*/
58
59typedef struct pk {
60 struct pk *next; /* Next packet in the chain */
61 octet *p, *o; /* Buffer start and current posn */
62 size_t n; /* Size of packet remaining */
63} pk;
64
65typedef struct pkstream {
66 unsigned f; /* Flags... */
67#define PKF_FULL 1u /* Buffer is full: stop reading */
68 sel_file r, w; /* Read and write selectors */
69 pk *pks, **pk_tail; /* Packet queue */
70 size_t npk, szpk; /* Number and size of data */
71 selpk p; /* Packet parser */
72} pkstream;
73
74typedef struct connwait {
75 sel_file a; /* Selector */
76 struct sockaddr_in me; /* Who I'm meant to be */
77 struct in_addr peer; /* Who my peer is */
78} connwait;
79
80/*----- Static variables --------------------------------------------------*/
81
82static sel_state sel;
83static connwait cw;
84static int fd_udp;
85static size_t pk_nmax = 128, pk_szmax = 1024 * 1024;
86
87/*----- Main code ---------------------------------------------------------*/
88
89static int nonblockify(int fd)
90 { return (fdflags(fd, O_NONBLOCK, O_NONBLOCK, 0, 0)); }
91
92static int cloexec(int fd)
93 { return (fdflags(fd, 0, 0, FD_CLOEXEC, FD_CLOEXEC)); }
94
95static void dolisten(void);
96
97static void doclose(pkstream *p)
98{
99 pk *pk, *ppk;
100 close(p->w.fd);
101 close(p->p.reader.fd);
102 selpk_destroy(&p->p);
103 if (!(p->f & PKF_FULL))
104 sel_rmfile(&p->r);
105 if (p->npk)
106 sel_rmfile(&p->w);
107 for (pk = p->pks; pk; pk = ppk) {
108 ppk = pk->next;
109 xfree(pk->p);
110 xfree(pk);
111 }
112 xfree(p);
113 if (cw.me.sin_port != 0)
114 dolisten();
115 else
116 exit(0);
117}
118
119static void rdtcp(octet *b, size_t sz, pkbuf *pk, size_t *k, void *vp)
120{
121 pkstream *p = vp;
122 size_t pksz;
123
124 if (!sz) {
125 doclose(p);
126 return;
127 }
128 pksz = LOAD16(b);
129 if (pksz + 2 == sz) {
130 write(fd_udp, b + 2, pksz);
131 selpk_want(&p->p, 2);
132 } else {
133 selpk_want(&p->p, pksz + 2);
134 *k = sz;
135 }
136}
137
138static void wrtcp(int fd, unsigned mode, void *vp)
139{
140#define NPK 16
141 struct iovec iov[NPK];
142 pkstream *p = vp;
143 size_t i;
144 ssize_t n;
145 pk *pk, *ppk;
146
147 for (i = 0, pk = p->pks; i < NPK && pk; i++, pk = pk->next) {
148 iov[i].iov_base = pk->o;
149 iov[i].iov_len = pk->n;
150 }
151
152 if ((n = writev(fd, iov, i)) < 0) {
153 if (errno == EAGAIN || errno == EWOULDBLOCK || errno == EINTR)
154 return;
155 moan("couldn't write to TCP socket: %s", strerror(errno));
156 doclose(p);
157 return;
158 }
159
160 p->szpk -= n;
161 for (pk = p->pks; n && pk; pk = ppk) {
162 ppk = pk->next;
163 if (pk->n <= n) {
164 p->npk--;
165 n -= pk->n;
166 xfree(pk->p);
167 xfree(pk);
168 } else {
169 pk->n -= n;
170 pk->o += n;
171 break;
172 }
173 }
174 p->pks = pk;
175 if (!pk) {
176 p->pk_tail = &p->pks;
177 sel_rmfile(&p->w);
178 }
179 if ((p->f & PKF_FULL) && p->npk < pk_nmax && p->szpk < pk_szmax) {
180 p->f &= ~PKF_FULL;
181 sel_addfile(&p->r);
182 }
183}
184
185static void rdudp(int fd, unsigned mode, void *vp)
186{
187 octet buf[65536];
188 ssize_t n;
189 pkstream *p = vp;
190 pk *pk;
191
192 if ((n = read(fd, buf, sizeof(buf))) < 0) {
193 if (errno == EAGAIN || errno == EWOULDBLOCK || errno == EINTR)
194 return;
195 moan("couldn't read from UDP socket: %s", strerror(errno));
196 return;
197 }
198 pk = xmalloc(sizeof(*pk));
199 pk->next = 0;
200 pk->p = xmalloc(n + 2);
201 STORE16(pk->p, n);
202 memcpy(pk->p + 2, buf, n);
203 pk->o = pk->p;
204 pk->n = n + 2;
205 *p->pk_tail = pk;
206 p->pk_tail = &pk->next;
207 if (!p->npk)
208 sel_addfile(&p->w);
209 sel_force(&p->w);
210 p->npk++;
211 p->szpk += n + 2;
212 if (p->npk >= pk_nmax || p->szpk >= pk_szmax) {
213 sel_rmfile(&p->r);
214 p->f |= PKF_FULL;
215 }
216}
217
218static void dofwd(int fd_in, int fd_out)
219{
220 pkstream *p = xmalloc(sizeof(*p));
221 sel_initfile(&sel, &p->r, fd_udp, SEL_READ, rdudp, p);
222 sel_initfile(&sel, &p->w, fd_out, SEL_WRITE, wrtcp, p);
223 selpk_init(&p->p, &sel, fd_in, rdtcp, p);
224 selpk_want(&p->p, 2);
225 p->pks = 0;
226 p->pk_tail = &p->pks;
227 p->npk = p->szpk = 0;
228 p->f = 0;
229 sel_addfile(&p->r);
230}
231
232static void doaccept(int fd_s, unsigned mode, void *p)
233{
234 int fd;
235 struct sockaddr_in sin;
236 socklen_t sz = sizeof(sin);
237
238 if ((fd = accept(fd_s, (struct sockaddr *)&sin, &sz)) < 0) {
239 if (errno == EAGAIN || errno == EWOULDBLOCK || errno == EINTR)
240 return;
241 moan("couldn't accept incoming connection: %s", strerror(errno));
242 return;
243 }
244 if (cw.peer.s_addr != INADDR_ANY &&
245 cw.peer.s_addr != sin.sin_addr.s_addr) {
246 close(fd);
247 moan("rejecting connection from %s", inet_ntoa(sin.sin_addr));
248 return;
249 }
250 if (nonblockify(fd) || cloexec(fd)) {
251 close(fd);
252 moan("couldn't accept incoming connection: %s", strerror(errno));
253 return;
254 }
255 dofwd(fd, fd);
256 close(fd_s);
257 sel_rmfile(&cw.a);
258}
259
260static void dolisten(void)
261{
262 int fd;
263 int opt = 1;
264
265 if ((fd = socket(PF_INET, SOCK_STREAM, 0)) < 0 ||
266 setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt)) ||
267 bind(fd, (struct sockaddr *)&cw.me, sizeof(cw.me)) ||
268 listen(fd, 1) || nonblockify(fd) || cloexec(fd))
269 die(1, "couldn't set up listening socket: %s", strerror(errno));
270 sel_initfile(&sel, &cw.a, fd, SEL_READ, doaccept, 0);
271 sel_addfile(&cw.a);
272}
273
274static void parseaddr(const char *pp, struct in_addr *a, unsigned short *pt)
275{
276 char *p = xstrdup(pp);
277 char *q = 0;
278 if (a && pt) {
279 strtok(p, ":");
280 q = strtok(0, "");
281 if (!q)
282 die(1, "missing port number in address `%s'", p);
283 } else if (pt) {
284 q = p;
285 }
286
287 if (a) {
288 struct hostent *h;
289 if ((h = gethostbyname(p)) == 0)
290 die(1, "unknown host `%s'", p);
291 memcpy(a, h->h_addr, sizeof(*a));
292 }
293
294 if (pt) {
295 struct servent *s;
296 char *qq;
297 unsigned long n;
298 if ((s = getservbyname(q, "tcp")) != 0)
299 *pt = s->s_port;
300 else if ((n = strtoul(q, &qq, 0)) == 0 || *qq || n > 0xffff)
301 die(1, "bad port number `%s'", q);
302 else
303 *pt = htons(n);
304 }
305}
306
307static void usage(FILE *fp)
308{
309 pquis(fp,
310 "Usage: $ [-l PORT] [-b ADDR] [-p ADDR] [-c ADDR:PORT]\n\
311 ADDR:PORT ADDR:PORT\n");
312}
313
314static void version(FILE *fp)
315 { pquis(fp, "$, tripe version " VERSION "\n"); }
316
317static void help(FILE *fp)
318{
319 version(fp);
320 fputc('\n', fp);
321 usage(fp);
322 fputs("\n\
323Options:\n\
324\n\
325-h, --help Display this help text.\n\
326-v, --version Display version number.\n\
327-u, --usage Display pointless usage message.\n\
328\n\
329-l, --listen=PORT Listen for connections to TCP PORT.\n\
330-p, --peer=ADDR Only accept connections from IP ADDR.\n\
331-b, --bind=ADDR Bind to ADDR before connecting.\n\
332-c, --connect=ADDR:PORT Connect to IP ADDR, TCP PORT.\n\
333\n\
334Forwards UDP packets over a reliable stream. By default, uses stdin and\n\
335stdout; though it can use TCP sockets instead.\n\
336", fp);
337}
338
339int main(int argc, char *argv[])
340{
341 unsigned f = 0;
342 unsigned short pt;
343 struct sockaddr_in connaddr, bindaddr;
344 struct sockaddr_in udp_me, udp_peer;
345 int len = 65536;
346
347#define f_bogus 1u
348
349 ego(argv[0]);
350 bindaddr.sin_family = AF_INET;
351 bindaddr.sin_addr.s_addr = INADDR_ANY;
352 bindaddr.sin_port = 0;
353 connaddr.sin_family = AF_INET;
354 connaddr.sin_addr.s_addr = INADDR_ANY;
355 cw.me.sin_family = AF_INET;
356 cw.me.sin_addr.s_addr = INADDR_ANY;
357 cw.me.sin_port = 0;
358 cw.peer.s_addr = INADDR_ANY;
359 sel_init(&sel);
360 for (;;) {
361 static struct option opt[] = {
362 { "help", 0, 0, 'h' },
363 { "version", 0, 0, 'v' },
364 { "usage", 0, 0, 'u' },
365 { "listen", OPTF_ARGREQ, 0, 'l' },
366 { "peer", OPTF_ARGREQ, 0, 'p' },
367 { "bind", OPTF_ARGREQ, 0, 'b' },
368 { "connect", OPTF_ARGREQ, 0, 'c' },
369 { 0, 0, 0, 0 }
370 };
371 int i;
372
373 i = mdwopt(argc, argv, "hvul:p:b:c:", opt, 0, 0, 0);
374 if (i < 0)
375 break;
376 switch (i) {
377 case 'h':
378 help(stdout);
379 exit(0);
380 case 'v':
381 version(stdout);
382 exit(0);
383 case 'u':
384 usage(stdout);
385 exit(0);
386 case 'l':
387 parseaddr(optarg, 0, &pt);
388 cw.me.sin_port = pt;
389 break;
390 case 'p':
391 parseaddr(optarg, &cw.peer, 0);
392 break;
393 case 'b':
394 parseaddr(optarg, &bindaddr.sin_addr, 0);
395 break;
396 case 'c':
397 parseaddr(optarg, &connaddr.sin_addr, &pt);
398 connaddr.sin_port = pt;
399 break;
400 default:
401 f |= f_bogus;
402 break;
403 }
404 }
405 if (optind + 2 != argc || (f & f_bogus)) {
406 usage(stderr);
407 exit(1);
408 }
409
410 udp_me.sin_family = udp_peer.sin_family = AF_INET;
411 parseaddr(argv[optind], &udp_me.sin_addr, &pt);
412 udp_me.sin_port = pt;
413 parseaddr(argv[optind + 1], &udp_peer.sin_addr, &pt);
414 udp_peer.sin_port = pt;
415
416 if ((fd_udp = socket(PF_INET, SOCK_DGRAM, 0)) < 0 ||
417 bind(fd_udp, (struct sockaddr *)&udp_me, sizeof(udp_me)) ||
418 connect(fd_udp, (struct sockaddr *)&udp_peer, sizeof(udp_peer)) ||
419 setsockopt(fd_udp, SOL_SOCKET, SO_RCVBUF, &len, sizeof(len)) ||
420 setsockopt(fd_udp, SOL_SOCKET, SO_SNDBUF, &len, sizeof(len)) ||
421 nonblockify(fd_udp) || cloexec(fd_udp))
422 die(1, "couldn't set up UDP socket: %s", strerror(errno));
423
424 if (cw.me.sin_port != 0)
425 dolisten();
426 else if (connaddr.sin_addr.s_addr != INADDR_ANY) {
427 int fd;
428 if ((fd = socket(PF_INET, SOCK_STREAM, 0)) < 0 ||
429 bind(fd, (struct sockaddr *)&bindaddr, sizeof(bindaddr)) ||
430 connect(fd, (struct sockaddr *)&connaddr, sizeof(connaddr)) ||
431 nonblockify(fd) || cloexec(fd))
432 die(1, "couldn't connect to TCP server: %s", strerror(errno));
433 dofwd(fd, fd);
434 } else
435 dofwd(STDIN_FILENO, STDOUT_FILENO);
436
437 for (;;)
438 sel_select(&sel);
439 return (0);
440}
441
442/*----- That's all, folks -------------------------------------------------*/