chiark / gitweb /
docs: Generate grammar and option summaries from manpage.
[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   ss->o = ssgo;
379   return (&ss->s);
380 }
381
382 /* --- @ss_accept@ --- *
383  *
384  * Arguments:   @int fd@ = file descriptor to accept from
385  *              @unsigned mode@ = what's ready with the descriptor
386  *              @void *p@ = pointer to the source definition
387  *
388  * Returns:     ---
389  *
390  * Use:         Accepts an incoming connection and attaches it to a target
391  *              endpoint.
392  */
393
394 static void ssource_destroy(source */*s*/);
395
396 static void ss_accept(int fd, unsigned mode, void *p)
397 {
398   ssource *ss = p;
399   ssept *e;
400   endpt *ee;
401   reffd *r;
402
403   /* --- Make the file descriptor --- */
404
405   {
406     int opt = 1;
407     if ((r = ss->a->ops->accept(fd, ss->ao, ss->s.desc)) == 0)
408       return;
409     setsockopt(r->fd, SOL_SOCKET, SO_OOBINLINE, &opt, sizeof(opt));
410     fdflags(r->fd, O_NONBLOCK, O_NONBLOCK, FD_CLOEXEC, FD_CLOEXEC);
411   }
412
413   /* --- Make an endpoint --- */
414
415   e = CREATE(ssept);
416   e->e.ops = &ssept_ops;
417   e->e.other = 0;
418   e->e.f = EPF_FILE;
419   e->e.t = 0;
420   e->e.in = e->e.out = r;
421   e->s = ss;
422   REFFD_INC(r);
423
424   /* --- Obtain the target endpoint and let rip --- */
425
426   if ((ee = ss->t->ops->create(ss->t, ss->s.desc)) == 0) {
427     REFFD_DEC(r);
428     REFFD_DEC(r);
429     DESTROY(e);
430     return;
431   }
432   fw_inc();
433
434   /* --- Remove the listening socket if necessary --- */
435
436   switch (ss->o.opt) {
437     case SOCKOPT_LIMIT:
438       ss->o.conn--;
439       if (!ss->o.conn) {
440         if (!(ss->ao->f & ADDRF_NOLOG))
441           fw_log(-1, "[%s] maximum connections reached", ss->s.desc);
442         sel_rmfile(&ss->r);
443         close(ss->r.fd);
444         if (ss->a->ops->unbind)
445           ss->a->ops->unbind(ss->a);
446       }
447       break;
448     case SOCKOPT_NOLIMIT:
449       break;
450     case SOCKOPT_ONESHOT:
451       sel_rmfile(&ss->r);
452       close(ss->r.fd);
453       if (ss->a->ops->unbind)
454         ss->a->ops->unbind(ss->a);
455       ssource_destroy(&ss->s);
456       break;
457   }
458
459   /* --- Let everything else happen --- */
460
461   endpt_join(&e->e, ee);
462 }
463
464 /* --- @ss_listen@ --- *
465  *
466  * Arguments:   @ssource *ss@ = source to listen on
467  *
468  * Returns:     ---
469  *
470  * Use:         Sets the socket to listen again, if it stopped for some
471  *              reason.  This is a copy of the code in the @read@ function,
472  *              because it has different (wildly different) error handling
473  *              behaviour.
474  */
475
476 static void ss_listen(ssource *ss)
477 {
478   int fd;
479   int opt = 1;
480
481   if (!(ss->ao->f & ADDRF_NOLOG))
482     fw_log(-1, "[%s] reattaching listener", ss->s.desc);
483
484   /* --- Make the socket --- */
485
486   if ((fd = ss->a->ops->bind(ss->a, ss->ao)) < 0) {
487     fw_log(-1, "[%s] couldn't create socket: %s",
488            ss->s.desc, strerror(errno));
489     goto fail_0;
490   }
491
492   /* --- Set it to listen for connections --- */
493
494   setsockopt(fd, SOL_SOCKET, SO_OOBINLINE, &opt, sizeof(opt));
495   fdflags(fd, O_NONBLOCK, O_NONBLOCK, FD_CLOEXEC, FD_CLOEXEC);
496   if (listen(fd, ss->o.listen)) {
497     fw_log(-1, "[%s] couldn't listen on socket: %s",
498            ss->s.desc, strerror(errno));
499     goto fail_1;
500   }
501
502   /* --- Set the listener up again --- */
503
504   ss->r.fd = fd;
505   sel_addfile(&ss->r);
506   return;
507
508   /* --- Tidy up if it failed --- *
509    *
510    * I'll just remove the entire source.
511    */
512
513 fail_1:
514   close(fd);
515 fail_0:
516   ss->o.conn = 0;
517   ssource_destroy(&ss->s);
518 }
519
520 /* --- @attach@ --- */
521
522 static void ssource_attach(source *s, scanner *sc, target *t)
523 {
524   ssource *ss = (ssource *)s;
525   int fd;
526   int opt = 1;
527
528   ss->t = t;
529
530   /* --- Initialize the description string --- */
531
532   {
533     dstr d = DSTR_INIT;
534     dstr_puts(&d, "socket.");
535     ss->a->ops->print(ss->a, ADDR_SRC, &d);
536     dstr_puts(&d, " -> ");
537     dstr_puts(&d, ss->t->desc);
538     ss->s.desc = xstrdup(d.buf);
539     dstr_destroy(&d);
540   }
541
542   /* --- Confirm the address --- */
543
544   if (ss->a->ops->confirm)
545     ss->a->ops->confirm(ss->a, ADDR_SRC, ss->ao);
546
547   /* --- Initialize the socket for listening --- */
548
549   if ((fd = ss->a->ops->bind(ss->a, ss->ao)) < 0)
550     error(sc, "couldn't bind socket `%s': %s", ss->s.desc, strerror(errno));
551
552   /* --- Set it to listen for connections --- */
553
554   setsockopt(fd, SOL_SOCKET, SO_OOBINLINE, &opt, sizeof(opt));
555   fdflags(fd, O_NONBLOCK, O_NONBLOCK, FD_CLOEXEC, FD_CLOEXEC);
556   if (listen(fd, ss->o.listen)) {
557     error(sc, "couldn't listen on socket `%s': %s",
558           ss->s.desc, strerror(errno));
559   }
560
561   /* --- We're ready to go now --- */
562
563   sel_initfile(sel, &ss->r, fd, SEL_READ, ss_accept, ss);
564   sel_addfile(&ss->r);
565   source_add(&ss->s);
566   fw_inc();
567 }
568
569 /* --- @destroy@ --- */
570
571 static void ssource_destroy(source *s)
572 {
573   ssource *ss = (ssource *)s;
574
575   if (ss->o.conn || ss->o.opt != SOCKOPT_LIMIT) {
576     sel_rmfile(&ss->r);
577     close(ss->r.fd);
578     if (ss->a->ops->unbind)
579       ss->a->ops->unbind(ss->a);
580   }
581   if (ss->a->ops->freesrcopts)
582     ss->a->ops->freesrcopts(ss->ao);
583   else
584     DESTROY(ss->ao);
585   xfree(ss->s.desc);
586   ss->a->ops->destroy(ss->a);
587   ss->t->ops->destroy(ss->t);
588   source_remove(&ss->s);
589   DESTROY(ss);
590   fw_dec();
591 }
592
593 /* --- Source definition block --- */
594
595 source_ops ssource_ops = {
596   "socket",
597   ssource_option, ssource_read, ssource_attach, ssource_destroy
598 };
599
600 /*----- Target definition -------------------------------------------------*/
601
602 /* --- @options@ --- */
603
604 static int starget_option(target *t, scanner *sc)
605 {
606   starget *st = (starget *)t;
607
608   CONF_BEGIN(sc, "starget", "socket target")
609
610   /* --- Pass the option around the various address types --- */
611
612   if (st) {
613     if (st->a->ops->option && st->a->ops->option(sc, st->ao, ADDR_DEST))
614       CONF_ACCEPT;
615   }
616   /* We'd have done it already if it was global */
617
618   /* --- Done --- */
619
620   CONF_END;
621 }
622
623 /* --- @read@ --- */
624
625 static target *starget_read(scanner *sc)
626 {
627   starget *st;
628   dstr d = DSTR_INIT;
629
630   (void)(conf_prefix(sc, "socket") || conf_prefix(sc, "sk"));
631   st = CREATE(starget);
632   st->t.ops = &starget_ops;
633   st->a = getaddr(sc, ADDR_DEST);
634   if (st->a->ops->inittargopts)
635     st->ao = st->a->ops->inittargopts();
636   else
637     st->ao = CREATE(addr_opts);
638   *st->ao = gtao;
639   dstr_puts(&d, "socket.");
640   st->a->ops->print(st->a, ADDR_DEST, &d);
641   st->t.desc = xstrdup(d.buf);
642   dstr_destroy(&d);
643   return (&st->t);
644 }
645
646 /* --- @confirm@ --- */
647
648 static void starget_confirm(target *t)
649 {
650   starget *st = (starget *)t;
651
652   if (st->a->ops->confirm)
653     st->a->ops->confirm(st->a, ADDR_DEST, st->ao);
654 }
655
656 /* --- @create@ --- */
657
658 static endpt *starget_create(target *t, const char *desc)
659 {
660   starget *st = (starget *)t;
661   stept *e = CREATE(stept);
662
663   e->e.ops = &stept_ops;
664   e->e.other = 0;
665   e->e.f = EPF_FILE | EPF_PENDING;
666   e->e.t = 0;
667   e->desc = xstrdup(desc);
668   if (st->a->ops->connect(st->a, st->ao, &e->c, &e->e)) {
669     fw_log(-1, "[%s] couldn't connect: %s", e->desc, strerror(errno));
670     DESTROY(e);
671     return (0);
672   }
673   fw_inc();
674   return (&e->e);
675 }
676
677 /* --- @destroy@ --- */
678
679 static void starget_destroy(target *t)
680 {
681   starget *st = (starget *)t;
682   if (st->a->ops->freetargopts)
683     st->a->ops->freetargopts(st->ao);
684   else
685     DESTROY(st->ao);
686   st->a->ops->destroy(st->a);
687   xfree(st->t.desc);
688   DESTROY(st);
689 }
690
691 /* --- Socket target definition block --- */
692
693 target_ops starget_ops = {
694   "socket",
695   starget_option, starget_read, starget_confirm,
696   starget_create, starget_destroy
697 };
698
699 /*----- That's all, folks -------------------------------------------------*/