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