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