chiark / gitweb /
0a80b48f32b5829e04ba8367958a259344184549
[fwd] / socket.c
1 /* -*-c-*-
2  *
3  * $Id: socket.c,v 1.6 2001/02/03 20:30:03 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.6  2001/02/03 20:30:03  mdw
33  * Support re-reading config files on SIGHUP.
34  *
35  * Revision 1.5  2000/03/23 23:20:42  mdw
36  * Remove listener even if connection option isn't SOCKOPT_LIMITED.
37  *
38  * Revision 1.4  1999/12/22 15:44:25  mdw
39  * Fix log message.
40  *
41  * Revision 1.3  1999/10/22 22:48:36  mdw
42  * New connection options: unlimited concurrent connections, and one-shot
43  * listening sockets.
44  *
45  * Revision 1.2  1999/07/27 18:30:53  mdw
46  * Various minor portability fixes.
47  *
48  * Revision 1.1  1999/07/26 23:33:32  mdw
49  * New sources and targets.
50  *
51  */
52
53 /*----- Header files ------------------------------------------------------*/
54
55 #include "config.h"
56
57 #include <ctype.h>
58 #include <errno.h>
59 #include <limits.h>
60 #include <stdio.h>
61 #include <stdlib.h>
62 #include <string.h>
63
64 #include <sys/types.h>
65 #include <unistd.h>
66
67 #include <sys/socket.h>
68 #include <netinet/in.h>
69 #include <arpa/inet.h>
70 #include <netdb.h>
71
72 #include <mLib/alloc.h>
73 #include <mLib/conn.h>
74 #include <mLib/dstr.h>
75 #include <mLib/fdflags.h>
76 #include <mLib/sel.h>
77 #include <mLib/sub.h>
78
79 #include "addr.h"
80 #include "conf.h"
81 #include "endpt.h"
82 #include "fw.h"
83 #include "scan.h"
84 #include "socket.h"
85 #include "target.h"
86
87 #include "inet.h"
88 #include "un.h"
89
90 /*----- Data structures ---------------------------------------------------*/
91
92 /* --- Socket source options --- */
93
94 typedef struct ssource_opts {
95   unsigned opt;
96   unsigned conn;
97 } ssource_opts;
98
99 static ssource_opts ssgo = { 256, 0 };
100
101 #define SOCKOPT_LIMIT 0u
102 #define SOCKOPT_NOLIMIT 1u
103 #define SOCKOPT_ONESHOT 2u
104
105 /* --- Socket source --- */
106
107 typedef struct ssource {
108   source s;
109   addr *a;
110   target *t;
111   addr_opts *ao;
112   ssource_opts o;
113   sel_file r;
114 } ssource;
115
116 /* --- Socket target --- */
117
118 typedef struct starget {
119   target t;
120   addr *a;
121   addr_opts *ao;
122 } starget;
123
124 /* --- Socket target endpoint --- */
125
126 typedef struct stept {
127   endpt e;
128   conn c;
129   char *desc;
130 } stept;
131
132 /* --- Socket source endpoint --- */
133
134 typedef struct ssept {
135   endpt e;
136   ssource *s;
137 } ssept;
138
139 #define SKF_CONN 16u
140 #define SKF_BROKEN 32u
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     if (ee->e.f & SKF_CONN)
254       conn_kill(&ee->c);
255   } else {
256     REFFD_DEC(ee->e.in);
257     REFFD_DEC(ee->e.out);
258   }
259
260   free(ee->desc);
261   fw_dec();
262   DESTROY(ee);
263 }
264
265 /* --- @stept_go@ --- *
266  *
267  * Arguments:   @int fd@ = file descriptor now ready for use
268  *              @void *p@ = pointer to an endpoint structure
269  *
270  * Returns:     ---
271  *
272  * Use:         Handles successful connection of the target endpoint.
273  */
274
275 static void stept_go(int fd, void *p)
276 {
277   stept *e = p;
278
279   /* --- Complicated and subtle --- *
280    *
281    * This code interacts quite closely with @starget_create@, mainly through
282    * flags in the endpoint block.
283    *
284    * If the connection failed, I log a message (that's easy enough).  The
285    * behaviour then depends on whether the endpoints have been joined yet.
286    * If not, I set @SKF_BROKEN@ and return, so that @starget_create@ can
287    * clean up the mess and return an immediate failure.  If they have, I kill
288    * the connection and everything ought to work.
289    *
290    * If the connection worked, I clear @EPF_PENDING@ (as expected, because
291    * my endpoint is now ready), and @SKF_CONN@ (to let @starget_create@ know
292    * that the connection is already going).  Then, only if this isn't the
293    * first attempt, I rejoin this endpoint to its partner.
294    */
295
296   if (fd == -1) {
297     fw_log(-1, "[%s] connection failed: %s", e->desc, strerror(errno));
298     e->e.f &= ~SKF_CONN;
299     if (e->e.f & EPF_PENDING)
300       endpt_kill(&e->e);
301     else
302       e->e.f |= SKF_BROKEN;
303   } else {
304     reffd *r = reffd_init(fd);
305     REFFD_INC(r);
306     e->e.in = e->e.out = r;
307     e->e.f &= ~(EPF_PENDING | SKF_CONN);
308     if (e->e.other)
309       endpt_join(&e->e, e->e.other);
310   }
311 }
312
313 /* --- Socket endpoint definition --- */
314
315 static endpt_ops ssept_ops = {
316   0, 0, sept_wclose, ssept_close
317 };
318
319 static endpt_ops stept_ops = {
320   0, 0, sept_wclose, stept_close
321 };
322
323 /*----- Source definition -------------------------------------------------*/
324
325 /* --- @option@ --- */
326
327 static int ssource_option(source *s, scanner *sc)
328 {
329   ssource *ss = (ssource *)s;
330   ssource_opts *sso = ss ? &ss->o : &ssgo;
331
332   CONF_BEGIN(sc, "socket", "socket")
333
334   /* --- Make sure the next token is a word --- */
335
336   if (sc->t != CTOK_WORD)
337     error(sc, "parse error, option keyword expected");
338
339   /* --- Handle options at this level --- */
340
341   if (strcmp(sc->d.buf, "conn") == 0) {
342     token(sc);
343     if (sc->t == '=')
344       token(sc);
345     if (sc->t != CTOK_WORD)
346       error(sc, "parse error, expected `unlimited', `one-shot' or number");
347     if (isdigit((unsigned char)sc->d.buf[0])) {
348       sso->conn = atoi(sc->d.buf);
349       if (sso->conn == 0)
350         error(sc, "argument of `conn' must be positive");
351       sso->opt = SOCKOPT_LIMIT;
352       token(sc);
353     } else {
354       sso->conn = 0;
355       sso->opt = 1 + (1 & conf_enum(sc,
356                                     "unlimited,one-shot,infinite",
357                                     ENUM_ABBREV, "`conn' option"));
358     }
359     CONF_ACCEPT;
360   }
361
362   if (strcmp(sc->d.buf, "logging") == 0 ||
363       strcmp(sc->d.buf, "log") == 0) {
364     addr_opts *ao = ss ? ss->ao : &gao;
365     token(sc);
366     if (sc->t == '=')
367       token(sc);
368     if (conf_enum(sc, "no,yes", ENUM_ABBREV, "logging status"))
369       ao->f &= ~ADDRF_NOLOG;
370     else
371       ao->f |= ADDRF_NOLOG;
372     CONF_ACCEPT;
373   }
374
375   /* --- Pass the option around the various address types --- */
376
377   if (ss) {
378     if (ss->a->ops->option && ss->a->ops->option(sc, ss ? ss->ao : 0))
379       CONF_ACCEPT;
380   } else {
381     addr_ops **a;
382     for (a = addrs; *a; a++) {
383       if ((*a)->option && (*a)->option(sc, 0))
384         CONF_ACCEPT;
385     }
386   }
387
388   /* --- Nobody understood the option --- */
389
390   CONF_END;
391 }
392
393 /* --- @read@ --- */
394
395 static source *ssource_read(scanner *sc)
396 {
397   ssource *ss;
398
399   (void)(conf_prefix(sc, "socket") || conf_prefix(sc, "sk"));
400   ss = CREATE(ssource);
401   ss->s.ops = &ssource_ops;
402   ss->s.desc = 0;
403   ss->t = 0;
404   ss->a = getaddr(sc, ADDR_SRC);
405   if (ss->a->ops->initopts)
406     ss->ao = ss->a->ops->initopts();
407   else
408     ss->ao = CREATE(addr_opts);
409   *ss->ao = gao;
410   ss->o = ssgo;
411   return (&ss->s);
412 }
413
414 /* --- @ss_accept@ --- *
415  *
416  * Arguments:   @int fd@ = file descriptor to accept from
417  *              @unsigned mode@ = what's ready with the descriptor
418  *              @void *p@ = pointer to the source definition
419  *
420  * Returns:     ---
421  *
422  * Use:         Accepts an incoming connection and attaches it to a target
423  *              endpoint.
424  */
425
426 static void ssource_destroy(source */*s*/);
427
428 static void ss_accept(int fd, unsigned mode, void *p)
429 {
430   ssource *ss = p;
431   ssept *e;
432   endpt *ee;
433   reffd *r;
434
435   /* --- Make the file descriptor --- */
436
437   {
438     int opt = 1;
439     if ((r = ss->a->ops->accept(fd, ss->ao, ss->s.desc)) == 0)
440       return;
441     setsockopt(r->fd, SOL_SOCKET, SO_OOBINLINE, &opt, sizeof(opt));
442     fdflags(r->fd, O_NONBLOCK, O_NONBLOCK, FD_CLOEXEC, FD_CLOEXEC);
443   }
444
445   /* --- Make an endpoint --- */
446
447   e = CREATE(ssept);
448   e->e.ops = &ssept_ops;
449   e->e.other = 0;
450   e->e.f = EPF_FILE;
451   e->e.t = 0;
452   e->e.in = e->e.out = r;
453   e->s = ss;
454   REFFD_INC(r);
455
456   /* --- Obtain the target endpoint and let rip --- */
457
458   if ((ee = ss->t->ops->create(ss->t, ss->s.desc)) == 0) {
459     REFFD_DEC(r);
460     REFFD_DEC(r);
461     DESTROY(e);
462     return;
463   }
464   fw_inc();
465
466   /* --- Remove the listening socket if necessary --- */
467
468   switch (ss->o.opt) {
469     case SOCKOPT_LIMIT:
470       ss->o.conn--;
471       if (!ss->o.conn) {
472         if (!(ss->ao->f & ADDRF_NOLOG))
473           fw_log(-1, "[%s] maximum connections reached", ss->s.desc);
474         sel_rmfile(&ss->r);
475         close(ss->r.fd);
476         if (ss->a->ops->unbind)
477           ss->a->ops->unbind(ss->a);
478       }
479       break;
480     case SOCKOPT_NOLIMIT:
481       break;
482     case SOCKOPT_ONESHOT:
483       sel_rmfile(&ss->r);
484       close(ss->r.fd);
485       if (ss->a->ops->unbind)
486         ss->a->ops->unbind(ss->a);
487       ssource_destroy(&ss->s);
488       break;
489   }
490
491   /* --- Let everything else happen --- */
492
493   endpt_join(&e->e, ee);
494 }
495
496 /* --- @ss_listen@ --- *
497  *
498  * Arguments:   @ssource *ss@ = source to listen on
499  *
500  * Returns:     ---
501  *
502  * Use:         Sets the socket to listen again, if it stopped for some
503  *              reason.  This is a copy of the code in the @read@ function,
504  *              because it has different (wildly different) error handling
505  *              behaviour.
506  */
507
508 static void ss_listen(ssource *ss)
509 {
510   gen_addr *ga = (gen_addr *)ss->a;
511   int fd;
512
513   if (!(ss->ao->f & ADDRF_NOLOG))
514     fw_log(-1, "[%s] reattaching listener", ss->s.desc);
515
516   /* --- Make the socket --- */
517
518   if ((fd = socket(ga->a.ops->pf, SOCK_STREAM, 0)) < 0) {
519     fw_log(-1, "[%s] couldn't create socket: %s",
520            ss->s.desc, strerror(errno));
521     goto fail_0;
522   }
523
524   /* --- Set it to allow address reuse --- */
525
526   {
527     int opt = 1;
528     setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
529     fdflags(fd, O_NONBLOCK, O_NONBLOCK, FD_CLOEXEC, FD_CLOEXEC);
530   }
531
532   /* --- Bind it to the right port --- */
533
534   if (bind(fd, &ga->sa, ga->a.sz)) {
535     fw_log(-1, "[%s] couldn't bind socket: %s", ss->s.desc, strerror(errno));
536     goto fail_1;
537   }
538   if (ga->a.ops->bound)
539     ga->a.ops->bound(&ga->a, ss->ao);
540
541   /* --- Set it to listen for connections --- */
542
543   if (listen(fd, 5)) {
544     fw_log(-1, "[%s] couldn't listen on socket: %s",
545            ss->s.desc, strerror(errno));
546     goto fail_1;
547   }
548
549   /* --- Set the listener up again --- */
550
551   ss->r.fd = fd;
552   sel_addfile(&ss->r);
553   return;
554
555   /* --- Tidy up if it failed --- *
556    *
557    * I'll just remove the entire source.
558    */
559
560 fail_1:
561   close(fd);
562 fail_0:
563   ss->o.conn = 0;
564   ssource_destroy(&ss->s);
565 }
566
567 /* --- @attach@ --- */
568
569 static void ssource_attach(source *s, scanner *sc, target *t)
570 {
571   ssource *ss = (ssource *)s;
572   int fd;
573
574   ss->t = t;
575
576   /* --- Initialize the description string --- */
577
578   {
579     dstr d = DSTR_INIT;
580     dstr_puts(&d, "socket.");
581     ss->a->ops->print(ss->a, ADDR_SRC, &d);
582     dstr_puts(&d, " -> ");
583     dstr_puts(&d, ss->t->desc);
584     ss->s.desc = xstrdup(d.buf);
585     dstr_destroy(&d);
586   }
587
588   /* --- Initialize the socket for listening --- */
589
590   {
591     gen_addr *ga = (gen_addr *)ss->a;
592
593     /* --- Make the socket --- */
594
595     if ((fd = socket(ga->a.ops->pf, SOCK_STREAM, 0)) < 0)
596       error(sc, "couldn't create socket: %s", strerror(errno));
597
598     /* --- Set it to allow address reuse --- */
599
600     {
601       int opt = 1;
602       setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
603       fdflags(fd, O_NONBLOCK, O_NONBLOCK, FD_CLOEXEC, FD_CLOEXEC);
604     }
605
606     /* --- Bind it to the right port --- */
607
608     if (bind(fd, &ga->sa, ga->a.sz))
609       error(sc, "couldn't bind to %s: %s", ss->s.desc, strerror(errno));
610     if (ga->a.ops->bound)
611       ga->a.ops->bound(&ga->a, ss->ao);
612
613     /* --- Set it to listen for connections --- */
614
615     if (listen(fd, 5))
616       error(sc, "couldn't listen on socket: %s", strerror(errno));
617   }
618
619   /* --- We're ready to go now --- */
620
621   sel_initfile(sel, &ss->r, fd, SEL_READ, ss_accept, ss);
622   sel_addfile(&ss->r);
623   source_add(&ss->s);
624   fw_inc();
625 }
626
627 /* --- @destroy@ --- */
628
629 static void ssource_destroy(source *s)
630 {
631   ssource *ss = (ssource *)s;
632
633   if (ss->o.conn || ss->o.opt != SOCKOPT_LIMIT) {
634     sel_rmfile(&ss->r);
635     close(ss->r.fd);
636     if (ss->a->ops->unbind)
637       ss->a->ops->unbind(ss->a);
638   }
639   if (ss->a->ops->freeopts)
640     ss->a->ops->freeopts(ss->ao);
641   else
642     DESTROY(ss->ao);
643   free(ss->s.desc);
644   ss->a->ops->destroy(ss->a);
645   ss->t->ops->destroy(ss->t);
646   source_remove(&ss->s);
647   DESTROY(ss);
648   fw_dec();
649 }
650
651 /* --- Source definition block --- */
652
653 source_ops ssource_ops = {
654   "socket",
655   ssource_option, ssource_read, ssource_attach, ssource_destroy
656 };
657
658 /*----- Target definition -------------------------------------------------*/
659
660 /* --- @read@ --- */
661
662 static target *starget_read(scanner *sc)
663 {
664   starget *st;
665   dstr d = DSTR_INIT;
666
667   (void)(conf_prefix(sc, "socket") || conf_prefix(sc, "sk"));
668   st = CREATE(starget);
669   st->t.ops = &starget_ops;
670   st->a = getaddr(sc, ADDR_DEST);
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   int fd;
693   gen_addr *ga = (gen_addr *)st->a;
694   int opt;
695
696   if ((fd = socket(st->a->ops->pf, SOCK_STREAM, 0)) < 0)
697     return (0);
698   setsockopt(fd, SOL_SOCKET, SO_OOBINLINE, &opt, sizeof(opt));
699   fdflags(fd, O_NONBLOCK, O_NONBLOCK, FD_CLOEXEC, FD_CLOEXEC);
700   e->e.ops = &stept_ops;
701   e->e.other = 0;
702   e->e.f = EPF_FILE | SKF_CONN;
703   e->e.t = 0;
704   e->desc = xstrdup(desc);
705
706   /* --- Pay attention --- *
707    *
708    * This bit is quite subtle.  The connect can succeed or fail later: that's
709    * fine.  The problem comes if it makes its mind up right now.  The flag
710    * @SKF_CONN@ signifies that I'm trying to connect.  I set it up to begin
711    * with and @stept_go@ turns it off when it's done: @stept_close@ uses it
712    * to decide whether to kill the connection.  The flag @EPF_PENDING@ is
713    * only set after @conn_init@ returns and @SKF_CONN@ is still set (meaning
714    * that the connection is still in progress).  That's used to let
715    * @stept_go@ know whether to kill the other endpoint.  The flag
716    * @SKF_BROKEN@ is used to signify an immediate failure.
717    */
718
719   conn_init(&e->c, sel, fd, &ga->sa, ga->a.sz, stept_go, e);
720   if (e->e.f & SKF_BROKEN) {
721     DESTROY(e);
722     return (0);
723   }
724   if (e->e.f & SKF_CONN)
725     e->e.f |= EPF_PENDING;
726   fw_inc();
727   return (&e->e);
728 }
729
730 /* --- @destroy@ --- */
731
732 static void starget_destroy(target *t)
733 {
734   starget *st = (starget *)t;
735   st->a->ops->destroy(st->a);
736   free(st->t.desc);
737   DESTROY(st);
738 }
739
740 /* --- Socket target definition block --- */
741
742 target_ops starget_ops = {
743   "socket",
744   0, starget_read, starget_create, starget_destroy
745 };
746
747 /*----- That's all, folks -------------------------------------------------*/