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