chiark / gitweb /
c85c2d4f0cf8923a8dc3a277b14b2b7c13c0c6b6
[fwd] / socket.c
1 /* -*-c-*-
2  *
3  * $Id: socket.c,v 1.12 2004/04/08 01:36:25 mdw Exp $
4  *
5  * Socket source and target definitions
6  *
7  * (c) 1999 Straylight/Edgeware
8  */
9
10 /*----- Licensing notice --------------------------------------------------* 
11  *
12  * This file is part of the `fw' port forwarder.
13  *
14  * `fw' is free software; you can redistribute it and/or modify
15  * it under the terms of the GNU General Public License as published by
16  * the Free Software Foundation; either version 2 of the License, or
17  * (at your option) any later version.
18  * 
19  * `fw' is distributed in the hope that it will be useful,
20  * but WITHOUT ANY WARRANTY; without even the implied warranty of
21  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
22  * GNU General Public License for more details.
23  * 
24  * You should have received a copy of the GNU General Public License
25  * along with `fw'; if not, write to the Free Software Foundation,
26  * Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
27  */
28
29 /*----- Header files ------------------------------------------------------*/
30
31 #include "config.h"
32
33 #include <ctype.h>
34 #include <errno.h>
35 #include <limits.h>
36 #include <stdio.h>
37 #include <stdlib.h>
38 #include <string.h>
39
40 #include <sys/types.h>
41 #include <unistd.h>
42
43 #include <sys/socket.h>
44 #include <netinet/in.h>
45 #include <arpa/inet.h>
46 #include <netdb.h>
47
48 #include <mLib/alloc.h>
49 #include <mLib/conn.h>
50 #include <mLib/dstr.h>
51 #include <mLib/fdflags.h>
52 #include <mLib/sel.h>
53 #include <mLib/sub.h>
54
55 #include "addr.h"
56 #include "conf.h"
57 #include "endpt.h"
58 #include "fw.h"
59 #include "scan.h"
60 #include "socket.h"
61 #include "target.h"
62
63 #include "inet.h"
64 #include "un.h"
65
66 /*----- Data structures ---------------------------------------------------*/
67
68 /* --- Socket source options --- */
69
70 typedef struct ssource_opts {
71   unsigned opt;
72   unsigned conn;
73   unsigned listen;
74 } ssource_opts;
75
76 static ssource_opts ssgo = { 256, 0, 5 };
77
78 #define SOCKOPT_LIMIT 0u
79 #define SOCKOPT_NOLIMIT 1u
80 #define SOCKOPT_ONESHOT 2u
81
82 /* --- Socket source --- */
83
84 typedef struct ssource {
85   source s;
86   addr *a;
87   target *t;
88   addr_opts *ao;
89   ssource_opts o;
90   sel_file r;
91 } ssource;
92
93 /* --- Socket target --- */
94
95 typedef struct starget {
96   target t;
97   addr *a;
98   addr_opts *ao;
99 } starget;
100
101 /* --- Socket target endpoint --- */
102
103 typedef struct stept {
104   endpt e;
105   conn c;
106   char *desc;
107 } stept;
108
109 /* --- Socket source endpoint --- */
110
111 typedef struct ssept {
112   endpt e;
113   ssource *s;
114 } ssept;
115
116 /*----- Protocol table ----------------------------------------------------*/
117
118 static addr_ops *addrs[] = { &inet_ops, &un_ops, 0 };
119
120 /*----- Other persistent variables ----------------------------------------*/
121
122 static addr_opts gsao = { 0 }, gtao = { 0 };
123
124 /*----- Parsing address types ---------------------------------------------*/
125
126 /* --- @getaddrtype@ --- *
127  *
128  * Arguments:   @scanner *sc@ = pointer to scanner (for error reporting)
129  *              @const char *p@ = pointer to protocol name
130  *              @int abbrev@ = nonzero to allow abbreviations
131  *
132  * Returns:     Pointer to address operations table or null.
133  *
134  * Use:         Looks up a protocol name.  Handy when parsing addresses and
135  *              other bits of configuration.  Returns null if no matching
136  *              address was found.
137  */
138
139 static addr_ops *getaddrtype(scanner *sc, const char *p, int abbrev)
140 {
141   addr_ops **ops;
142   addr_ops *chosen = 0;
143   size_t sz = strlen(p);
144
145   for (ops = addrs; *ops; ops++) {
146     if (strncmp((*ops)->name, p, sz) == 0) {
147       if ((*ops)->name[sz] == 0)
148         return (*ops);
149       else if (chosen && abbrev)
150         error(sc, "ambiguous socket address type `%s'", p);
151       chosen = *ops;
152     }
153   }
154   if (!abbrev)
155     return (0);
156   return (chosen);
157 }
158
159 /* --- @getaddr@ --- *
160  *
161  * Arguments:   @scanner *sc@ = pointer to scanner to read from
162  *              @unsigned type@ = address type (@ADDR_SRC@ or @ADDR_DEST@)
163  *
164  * Returns:     Pointer to an address successfully read.
165  *
166  * Use:         Reads an optionally qualified address.
167  */
168
169 static addr *getaddr(scanner *sc, unsigned type)
170 {
171   addr_ops *ops = 0;
172   int abbrev = 0;
173
174   if (sc->t == ':') {
175     token(sc);
176     abbrev = 1;
177   }
178   if (sc->t == CTOK_WORD)
179     ops = getaddrtype(sc, sc->d.buf, abbrev);
180   if (ops)
181     token(sc);
182   else if (abbrev)
183     error(sc, "unknown socket address type `%s'", sc->d.buf);
184   else
185     ops = &inet_ops;
186   if (sc->t == ':')
187     token(sc);
188
189   return (ops->read(sc, type));
190 }
191
192 /*----- Socket endpoints --------------------------------------------------*/
193
194 /* --- @wclose@ --- */
195
196 static void sept_wclose(endpt *e)
197 {
198   shutdown(e->out->fd, 1);
199 }
200
201 /* --- @close@ (source) --- */
202
203 static void ss_listen(ssource */*ss*/);
204
205 static void ssept_close(endpt *e)
206 {
207   ssept *ee = (ssept *)e;
208
209   if (ee->s->o.opt == SOCKOPT_LIMIT) {
210     ee->s->o.conn++;
211     if (ee->s->o.conn == 1)
212       ss_listen(ee->s);
213   }
214   REFFD_DEC(ee->e.in);
215   REFFD_DEC(ee->e.out);
216   fw_dec();
217   DESTROY(ee);
218 }
219
220 /* --- @close@ (target) --- */
221
222 static void stept_close(endpt *e)
223 {
224   stept *ee = (stept *)e;
225
226   if (ee->e.f & EPF_PENDING)
227     conn_kill(&ee->c);
228   else {
229     REFFD_DEC(ee->e.in);
230     REFFD_DEC(ee->e.out);
231   }
232
233   xfree(ee->desc);
234   fw_dec();
235   DESTROY(ee);
236 }
237
238 /* --- @starget_connected@ --- *
239  *
240  * Arguments:   @int fd@ = file descriptor now ready for use
241  *              @void *p@ = pointer to an endpoint structure
242  *
243  * Returns:     ---
244  *
245  * Use:         Handles successful connection of the target endpoint.
246  */
247
248 void starget_connected(int fd, void *p)
249 {
250   stept *e = p;
251
252   if (fd == -1) {
253     fw_log(-1, "[%s] connection failed: %s", e->desc, strerror(errno));
254     endpt_kill(&e->e);
255   } else {
256     reffd *r = reffd_init(fd);
257     int opt = 1;
258     REFFD_INC(r);
259     fdflags(fd, O_NONBLOCK, O_NONBLOCK, FD_CLOEXEC, FD_CLOEXEC);
260     setsockopt(fd, SOL_SOCKET, SO_OOBINLINE, &opt, sizeof(opt));
261     e->e.in = e->e.out = r;
262     e->e.f &= ~EPF_PENDING;
263     if (e->e.other)
264       endpt_join(&e->e, e->e.other);
265   }
266 }
267
268 /* --- Socket endpoint definition --- */
269
270 static endpt_ops ssept_ops = {
271   0, 0, sept_wclose, ssept_close
272 };
273
274 static endpt_ops stept_ops = {
275   0, 0, sept_wclose, stept_close
276 };
277
278 /*----- Source definition -------------------------------------------------*/
279
280 /* --- @option@ --- */
281
282 static int ssource_option(source *s, scanner *sc)
283 {
284   ssource *ss = (ssource *)s;
285   ssource_opts *sso = ss ? &ss->o : &ssgo;
286
287   CONF_BEGIN(sc, "socket", "socket source")
288
289   /* --- Make sure the next token is a word --- */
290
291   if (sc->t != CTOK_WORD)
292     error(sc, "parse error, option keyword expected");
293
294   /* --- Handle options at this level --- */
295
296   if (strcmp(sc->d.buf, "conn") == 0) {
297     token(sc);
298     if (sc->t == '=')
299       token(sc);
300     if (sc->t != CTOK_WORD)
301       error(sc, "parse error, expected `unlimited', `one-shot' or number");
302     if (isdigit((unsigned char)sc->d.buf[0])) {
303       sso->conn = atoi(sc->d.buf);
304       if (sso->conn == 0)
305         error(sc, "argument of `conn' must be positive");
306       sso->opt = SOCKOPT_LIMIT;
307       token(sc);
308     } else {
309       sso->conn = 0;
310       sso->opt = 1 + (1 & conf_enum(sc,
311                                     "unlimited,one-shot,infinite",
312                                     ENUM_ABBREV, "`conn' option"));
313     }
314     CONF_ACCEPT;
315   }
316
317   if (strcmp(sc->d.buf, "listen") == 0) {
318     token(sc);
319     if (sc->t == '=')
320       token(sc);
321     if (sc->t != CTOK_WORD || !isdigit((unsigned char)sc->d.buf[0]))
322       error(sc, "parse error, expected number");
323     sso->listen = atoi(sc->d.buf);
324     if (sso->listen == 0)
325       error(sc, "argument of `listen' must be positive");
326     token(sc);
327     CONF_ACCEPT;
328   }
329
330   if (strcmp(sc->d.buf, "logging") == 0 ||
331       strcmp(sc->d.buf, "log") == 0) {
332     addr_opts *ao = ss ? ss->ao : &gsao;
333     token(sc);
334     if (sc->t == '=')
335       token(sc);
336     if (conf_enum(sc, "no,yes", ENUM_ABBREV, "logging status"))
337       ao->f &= ~ADDRF_NOLOG;
338     else
339       ao->f |= ADDRF_NOLOG;
340     CONF_ACCEPT;
341   }
342
343   /* --- Pass the option around the various address types --- */
344
345   if (ss) {
346     if (ss->a->ops->option && ss->a->ops->option(sc, ss->ao, ADDR_SRC))
347       CONF_ACCEPT;
348   } else {
349     addr_ops **a;
350     for (a = addrs; *a; a++) {
351       if ((*a)->option && (*a)->option(sc, 0, ADDR_GLOBAL))
352         CONF_ACCEPT;
353     }
354   }
355
356   /* --- Nobody understood the option --- */
357
358   CONF_END;
359 }
360
361 /* --- @read@ --- */
362
363 static source *ssource_read(scanner *sc)
364 {
365   ssource *ss;
366
367   (void)(conf_prefix(sc, "socket") || conf_prefix(sc, "sk"));
368   ss = CREATE(ssource);
369   ss->s.ops = &ssource_ops;
370   ss->s.desc = 0;
371   ss->t = 0;
372   ss->a = getaddr(sc, ADDR_SRC);
373   if (ss->a->ops->initsrcopts)
374     ss->ao = ss->a->ops->initsrcopts();
375   else {
376     ss->ao = CREATE(addr_opts);
377     *ss->ao = gsao;
378   }
379   ss->o = ssgo;
380   return (&ss->s);
381 }
382
383 /* --- @ss_accept@ --- *
384  *
385  * Arguments:   @int fd@ = file descriptor to accept from
386  *              @unsigned mode@ = what's ready with the descriptor
387  *              @void *p@ = pointer to the source definition
388  *
389  * Returns:     ---
390  *
391  * Use:         Accepts an incoming connection and attaches it to a target
392  *              endpoint.
393  */
394
395 static void ssource_destroy(source */*s*/);
396
397 static void ss_accept(int fd, unsigned mode, void *p)
398 {
399   ssource *ss = p;
400   ssept *e;
401   endpt *ee;
402   reffd *r;
403
404   /* --- Make the file descriptor --- */
405
406   {
407     int opt = 1;
408     if ((r = ss->a->ops->accept(fd, ss->ao, ss->s.desc)) == 0)
409       return;
410     setsockopt(r->fd, SOL_SOCKET, SO_OOBINLINE, &opt, sizeof(opt));
411     fdflags(r->fd, O_NONBLOCK, O_NONBLOCK, FD_CLOEXEC, FD_CLOEXEC);
412   }
413
414   /* --- Make an endpoint --- */
415
416   e = CREATE(ssept);
417   e->e.ops = &ssept_ops;
418   e->e.other = 0;
419   e->e.f = EPF_FILE;
420   e->e.t = 0;
421   e->e.in = e->e.out = r;
422   e->s = ss;
423   REFFD_INC(r);
424
425   /* --- Obtain the target endpoint and let rip --- */
426
427   if ((ee = ss->t->ops->create(ss->t, ss->s.desc)) == 0) {
428     REFFD_DEC(r);
429     REFFD_DEC(r);
430     DESTROY(e);
431     return;
432   }
433   fw_inc();
434
435   /* --- Remove the listening socket if necessary --- */
436
437   switch (ss->o.opt) {
438     case SOCKOPT_LIMIT:
439       ss->o.conn--;
440       if (!ss->o.conn) {
441         if (!(ss->ao->f & ADDRF_NOLOG))
442           fw_log(-1, "[%s] maximum connections reached", ss->s.desc);
443         sel_rmfile(&ss->r);
444         close(ss->r.fd);
445         if (ss->a->ops->unbind)
446           ss->a->ops->unbind(ss->a);
447       }
448       break;
449     case SOCKOPT_NOLIMIT:
450       break;
451     case SOCKOPT_ONESHOT:
452       sel_rmfile(&ss->r);
453       close(ss->r.fd);
454       if (ss->a->ops->unbind)
455         ss->a->ops->unbind(ss->a);
456       ssource_destroy(&ss->s);
457       break;
458   }
459
460   /* --- Let everything else happen --- */
461
462   endpt_join(&e->e, ee);
463 }
464
465 /* --- @ss_listen@ --- *
466  *
467  * Arguments:   @ssource *ss@ = source to listen on
468  *
469  * Returns:     ---
470  *
471  * Use:         Sets the socket to listen again, if it stopped for some
472  *              reason.  This is a copy of the code in the @read@ function,
473  *              because it has different (wildly different) error handling
474  *              behaviour.
475  */
476
477 static void ss_listen(ssource *ss)
478 {
479   int fd;
480   int opt = 1;
481
482   if (!(ss->ao->f & ADDRF_NOLOG))
483     fw_log(-1, "[%s] reattaching listener", ss->s.desc);
484
485   /* --- Make the socket --- */
486
487   if ((fd = ss->a->ops->bind(ss->a, ss->ao)) < 0) {
488     fw_log(-1, "[%s] couldn't create socket: %s",
489            ss->s.desc, strerror(errno));
490     goto fail_0;
491   }
492
493   /* --- Set it to listen for connections --- */
494
495   setsockopt(fd, SOL_SOCKET, SO_OOBINLINE, &opt, sizeof(opt));
496   fdflags(fd, O_NONBLOCK, O_NONBLOCK, FD_CLOEXEC, FD_CLOEXEC);
497   if (listen(fd, ss->o.listen)) {
498     fw_log(-1, "[%s] couldn't listen on socket: %s",
499            ss->s.desc, strerror(errno));
500     goto fail_1;
501   }
502
503   /* --- Set the listener up again --- */
504
505   ss->r.fd = fd;
506   sel_addfile(&ss->r);
507   return;
508
509   /* --- Tidy up if it failed --- *
510    *
511    * I'll just remove the entire source.
512    */
513
514 fail_1:
515   close(fd);
516 fail_0:
517   ss->o.conn = 0;
518   ssource_destroy(&ss->s);
519 }
520
521 /* --- @attach@ --- */
522
523 static void ssource_attach(source *s, scanner *sc, target *t)
524 {
525   ssource *ss = (ssource *)s;
526   int fd;
527   int opt = 1;
528
529   ss->t = t;
530
531   /* --- Initialize the description string --- */
532
533   {
534     dstr d = DSTR_INIT;
535     dstr_puts(&d, "socket.");
536     ss->a->ops->print(ss->a, ADDR_SRC, &d);
537     dstr_puts(&d, " -> ");
538     dstr_puts(&d, ss->t->desc);
539     ss->s.desc = xstrdup(d.buf);
540     dstr_destroy(&d);
541   }
542
543   /* --- Confirm the address --- */
544
545   if (ss->a->ops->confirm)
546     ss->a->ops->confirm(ss->a, ADDR_SRC, ss->ao);
547
548   /* --- Initialize the socket for listening --- */
549
550   if ((fd = ss->a->ops->bind(ss->a, ss->ao)) < 0)
551     error(sc, "couldn't bind socket `%s': %s", ss->s.desc, strerror(errno));
552
553   /* --- Set it to listen for connections --- */
554
555   setsockopt(fd, SOL_SOCKET, SO_OOBINLINE, &opt, sizeof(opt));
556   fdflags(fd, O_NONBLOCK, O_NONBLOCK, FD_CLOEXEC, FD_CLOEXEC);
557   if (listen(fd, ss->o.listen)) {
558     error(sc, "couldn't listen on socket `%s': %s",
559           ss->s.desc, strerror(errno));
560   }
561
562   /* --- We're ready to go now --- */
563
564   sel_initfile(sel, &ss->r, fd, SEL_READ, ss_accept, ss);
565   sel_addfile(&ss->r);
566   source_add(&ss->s);
567   fw_inc();
568 }
569
570 /* --- @destroy@ --- */
571
572 static void ssource_destroy(source *s)
573 {
574   ssource *ss = (ssource *)s;
575
576   if (ss->o.conn || ss->o.opt != SOCKOPT_LIMIT) {
577     sel_rmfile(&ss->r);
578     close(ss->r.fd);
579     if (ss->a->ops->unbind)
580       ss->a->ops->unbind(ss->a);
581   }
582   if (ss->a->ops->freesrcopts)
583     ss->a->ops->freesrcopts(ss->ao);
584   else
585     DESTROY(ss->ao);
586   xfree(ss->s.desc);
587   ss->a->ops->destroy(ss->a);
588   ss->t->ops->destroy(ss->t);
589   source_remove(&ss->s);
590   DESTROY(ss);
591   fw_dec();
592 }
593
594 /* --- Source definition block --- */
595
596 source_ops ssource_ops = {
597   "socket",
598   ssource_option, ssource_read, ssource_attach, ssource_destroy
599 };
600
601 /*----- Target definition -------------------------------------------------*/
602
603 /* --- @options@ --- */
604
605 static int starget_option(target *t, scanner *sc)
606 {
607   starget *st = (starget *)t;
608
609   CONF_BEGIN(sc, "starget", "socket target")
610
611   /* --- Pass the option around the various address types --- */
612
613   if (st) {
614     if (st->a->ops->option && st->a->ops->option(sc, st->ao, ADDR_DEST))
615       CONF_ACCEPT;
616   }
617   /* We'd have done it already if it was global */
618
619   /* --- Done --- */
620
621   CONF_END;
622 }
623
624 /* --- @read@ --- */
625
626 static target *starget_read(scanner *sc)
627 {
628   starget *st;
629   dstr d = DSTR_INIT;
630
631   (void)(conf_prefix(sc, "socket") || conf_prefix(sc, "sk"));
632   st = CREATE(starget);
633   st->t.ops = &starget_ops;
634   st->a = getaddr(sc, ADDR_DEST);
635   if (st->a->ops->inittargopts)
636     st->ao = st->a->ops->inittargopts();
637   else {
638     st->ao = CREATE(addr_opts);
639     *st->ao = gtao;
640   }
641   dstr_puts(&d, "socket.");
642   st->a->ops->print(st->a, ADDR_DEST, &d);
643   st->t.desc = xstrdup(d.buf);
644   dstr_destroy(&d);
645   return (&st->t);
646 }
647
648 /* --- @confirm@ --- */
649
650 static void starget_confirm(target *t)
651 {
652   starget *st = (starget *)t;
653
654   if (st->a->ops->confirm)
655     st->a->ops->confirm(st->a, ADDR_DEST, st->ao);
656 }
657
658 /* --- @create@ --- */
659
660 static endpt *starget_create(target *t, const char *desc)
661 {
662   starget *st = (starget *)t;
663   stept *e = CREATE(stept);
664
665   e->e.ops = &stept_ops;
666   e->e.other = 0;
667   e->e.f = EPF_FILE | EPF_PENDING;
668   e->e.t = 0;
669   e->desc = xstrdup(desc);
670   if (st->a->ops->connect(st->a, st->ao, &e->c, &e->e)) {
671     fw_log(-1, "[%s] couldn't connect: %s", e->desc, strerror(errno));
672     DESTROY(e);
673     return (0);
674   }
675   fw_inc();
676   return (&e->e);
677 }
678
679 /* --- @destroy@ --- */
680
681 static void starget_destroy(target *t)
682 {
683   starget *st = (starget *)t;
684   if (st->a->ops->freetargopts)
685     st->a->ops->freetargopts(st->ao);
686   else
687     DESTROY(st->ao);
688   st->a->ops->destroy(st->a);
689   xfree(st->t.desc);
690   DESTROY(st);
691 }
692
693 /* --- Socket target definition block --- */
694
695 target_ops starget_ops = {
696   "socket",
697   starget_option, starget_read, starget_confirm,
698   starget_create, starget_destroy
699 };
700
701 /*----- That's all, folks -------------------------------------------------*/