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