3 * $Id: socket.c,v 1.6 2001/02/03 20:30:03 mdw Exp $
5 * Socket source and target definitions
7 * (c) 1999 Straylight/Edgeware
10 /*----- Licensing notice --------------------------------------------------*
12 * This file is part of the `fw' port forwarder.
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.
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.
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.
29 /*----- Revision history --------------------------------------------------*
32 * Revision 1.6 2001/02/03 20:30:03 mdw
33 * Support re-reading config files on SIGHUP.
35 * Revision 1.5 2000/03/23 23:20:42 mdw
36 * Remove listener even if connection option isn't SOCKOPT_LIMITED.
38 * Revision 1.4 1999/12/22 15:44:25 mdw
41 * Revision 1.3 1999/10/22 22:48:36 mdw
42 * New connection options: unlimited concurrent connections, and one-shot
45 * Revision 1.2 1999/07/27 18:30:53 mdw
46 * Various minor portability fixes.
48 * Revision 1.1 1999/07/26 23:33:32 mdw
49 * New sources and targets.
53 /*----- Header files ------------------------------------------------------*/
64 #include <sys/types.h>
67 #include <sys/socket.h>
68 #include <netinet/in.h>
69 #include <arpa/inet.h>
72 #include <mLib/alloc.h>
73 #include <mLib/conn.h>
74 #include <mLib/dstr.h>
75 #include <mLib/fdflags.h>
90 /*----- Data structures ---------------------------------------------------*/
92 /* --- Socket source options --- */
94 typedef struct ssource_opts {
99 static ssource_opts ssgo = { 256, 0 };
101 #define SOCKOPT_LIMIT 0u
102 #define SOCKOPT_NOLIMIT 1u
103 #define SOCKOPT_ONESHOT 2u
105 /* --- Socket source --- */
107 typedef struct ssource {
116 /* --- Socket target --- */
118 typedef struct starget {
124 /* --- Socket target endpoint --- */
126 typedef struct stept {
132 /* --- Socket source endpoint --- */
134 typedef struct ssept {
140 #define SKF_BROKEN 32u
142 /*----- Protocol table ----------------------------------------------------*/
144 static addr_ops *addrs[] = { &inet_ops, &un_ops, 0 };
146 /*----- Other persistent variables ----------------------------------------*/
148 static addr_opts gao = { 0 };
150 /*----- Parsing address types ---------------------------------------------*/
152 /* --- @getaddrtype@ --- *
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
158 * Returns: Pointer to address operations table or null.
160 * Use: Looks up a protocol name. Handy when parsing addresses and
161 * other bits of configuration. Returns null if no matching
165 static addr_ops *getaddrtype(scanner *sc, const char *p, int abbrev)
168 addr_ops *chosen = 0;
169 size_t sz = strlen(p);
171 for (ops = addrs; *ops; ops++) {
172 if (strncmp((*ops)->name, p, sz) == 0) {
173 if ((*ops)->name[sz] == 0)
175 else if (chosen && abbrev)
176 error(sc, "ambiguous socket address type `%s'", p);
185 /* --- @getaddr@ --- *
187 * Arguments: @scanner *sc@ = pointer to scanner to read from
188 * @unsigned type@ = address type (@ADDR_SRC@ or @ADDR_DEST@)
190 * Returns: Pointer to an address successfully read.
192 * Use: Reads an optionally qualified address.
195 static addr *getaddr(scanner *sc, unsigned type)
204 if (sc->t == CTOK_WORD)
205 ops = getaddrtype(sc, sc->d.buf, abbrev);
209 error(sc, "unknown socket address type `%s'", sc->d.buf);
215 return (ops->read(sc, type));
218 /*----- Socket endpoints --------------------------------------------------*/
220 /* --- @wclose@ --- */
222 static void sept_wclose(endpt *e)
224 shutdown(e->out->fd, 1);
227 /* --- @close@ (source) --- */
229 static void ss_listen(ssource */*ss*/);
231 static void ssept_close(endpt *e)
233 ssept *ee = (ssept *)e;
235 if (ee->s->o.opt == SOCKOPT_LIMIT) {
237 if (ee->s->o.conn == 1)
241 REFFD_DEC(ee->e.out);
246 /* --- @close@ (target) --- */
248 static void stept_close(endpt *e)
250 stept *ee = (stept *)e;
252 if (ee->e.f & EPF_PENDING) {
253 if (ee->e.f & SKF_CONN)
257 REFFD_DEC(ee->e.out);
265 /* --- @stept_go@ --- *
267 * Arguments: @int fd@ = file descriptor now ready for use
268 * @void *p@ = pointer to an endpoint structure
272 * Use: Handles successful connection of the target endpoint.
275 static void stept_go(int fd, void *p)
279 /* --- Complicated and subtle --- *
281 * This code interacts quite closely with @starget_create@, mainly through
282 * flags in the endpoint block.
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.
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.
297 fw_log(-1, "[%s] connection failed: %s", e->desc, strerror(errno));
299 if (e->e.f & EPF_PENDING)
302 e->e.f |= SKF_BROKEN;
304 reffd *r = reffd_init(fd);
306 e->e.in = e->e.out = r;
307 e->e.f &= ~(EPF_PENDING | SKF_CONN);
309 endpt_join(&e->e, e->e.other);
313 /* --- Socket endpoint definition --- */
315 static endpt_ops ssept_ops = {
316 0, 0, sept_wclose, ssept_close
319 static endpt_ops stept_ops = {
320 0, 0, sept_wclose, stept_close
323 /*----- Source definition -------------------------------------------------*/
325 /* --- @option@ --- */
327 static int ssource_option(source *s, scanner *sc)
329 ssource *ss = (ssource *)s;
330 ssource_opts *sso = ss ? &ss->o : &ssgo;
332 CONF_BEGIN(sc, "socket", "socket")
334 /* --- Make sure the next token is a word --- */
336 if (sc->t != CTOK_WORD)
337 error(sc, "parse error, option keyword expected");
339 /* --- Handle options at this level --- */
341 if (strcmp(sc->d.buf, "conn") == 0) {
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);
350 error(sc, "argument of `conn' must be positive");
351 sso->opt = SOCKOPT_LIMIT;
355 sso->opt = 1 + (1 & conf_enum(sc,
356 "unlimited,one-shot,infinite",
357 ENUM_ABBREV, "`conn' option"));
362 if (strcmp(sc->d.buf, "logging") == 0 ||
363 strcmp(sc->d.buf, "log") == 0) {
364 addr_opts *ao = ss ? ss->ao : &gao;
368 if (conf_enum(sc, "no,yes", ENUM_ABBREV, "logging status"))
369 ao->f &= ~ADDRF_NOLOG;
371 ao->f |= ADDRF_NOLOG;
375 /* --- Pass the option around the various address types --- */
378 if (ss->a->ops->option && ss->a->ops->option(sc, ss ? ss->ao : 0))
382 for (a = addrs; *a; a++) {
383 if ((*a)->option && (*a)->option(sc, 0))
388 /* --- Nobody understood the option --- */
395 static source *ssource_read(scanner *sc)
399 (void)(conf_prefix(sc, "socket") || conf_prefix(sc, "sk"));
400 ss = CREATE(ssource);
401 ss->s.ops = &ssource_ops;
404 ss->a = getaddr(sc, ADDR_SRC);
405 if (ss->a->ops->initopts)
406 ss->ao = ss->a->ops->initopts();
408 ss->ao = CREATE(addr_opts);
414 /* --- @ss_accept@ --- *
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
422 * Use: Accepts an incoming connection and attaches it to a target
426 static void ssource_destroy(source */*s*/);
428 static void ss_accept(int fd, unsigned mode, void *p)
435 /* --- Make the file descriptor --- */
439 if ((r = ss->a->ops->accept(fd, ss->ao, ss->s.desc)) == 0)
441 setsockopt(r->fd, SOL_SOCKET, SO_OOBINLINE, &opt, sizeof(opt));
442 fdflags(r->fd, O_NONBLOCK, O_NONBLOCK, FD_CLOEXEC, FD_CLOEXEC);
445 /* --- Make an endpoint --- */
448 e->e.ops = &ssept_ops;
452 e->e.in = e->e.out = r;
456 /* --- Obtain the target endpoint and let rip --- */
458 if ((ee = ss->t->ops->create(ss->t, ss->s.desc)) == 0) {
466 /* --- Remove the listening socket if necessary --- */
472 if (!(ss->ao->f & ADDRF_NOLOG))
473 fw_log(-1, "[%s] maximum connections reached", ss->s.desc);
476 if (ss->a->ops->unbind)
477 ss->a->ops->unbind(ss->a);
480 case SOCKOPT_NOLIMIT:
482 case SOCKOPT_ONESHOT:
485 if (ss->a->ops->unbind)
486 ss->a->ops->unbind(ss->a);
487 ssource_destroy(&ss->s);
491 /* --- Let everything else happen --- */
493 endpt_join(&e->e, ee);
496 /* --- @ss_listen@ --- *
498 * Arguments: @ssource *ss@ = source to listen on
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
508 static void ss_listen(ssource *ss)
510 gen_addr *ga = (gen_addr *)ss->a;
513 if (!(ss->ao->f & ADDRF_NOLOG))
514 fw_log(-1, "[%s] reattaching listener", ss->s.desc);
516 /* --- Make the socket --- */
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));
524 /* --- Set it to allow address reuse --- */
528 setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
529 fdflags(fd, O_NONBLOCK, O_NONBLOCK, FD_CLOEXEC, FD_CLOEXEC);
532 /* --- Bind it to the right port --- */
534 if (bind(fd, &ga->sa, ga->a.sz)) {
535 fw_log(-1, "[%s] couldn't bind socket: %s", ss->s.desc, strerror(errno));
538 if (ga->a.ops->bound)
539 ga->a.ops->bound(&ga->a, ss->ao);
541 /* --- Set it to listen for connections --- */
544 fw_log(-1, "[%s] couldn't listen on socket: %s",
545 ss->s.desc, strerror(errno));
549 /* --- Set the listener up again --- */
555 /* --- Tidy up if it failed --- *
557 * I'll just remove the entire source.
564 ssource_destroy(&ss->s);
567 /* --- @attach@ --- */
569 static void ssource_attach(source *s, scanner *sc, target *t)
571 ssource *ss = (ssource *)s;
576 /* --- Initialize the description string --- */
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);
588 /* --- Initialize the socket for listening --- */
591 gen_addr *ga = (gen_addr *)ss->a;
593 /* --- Make the socket --- */
595 if ((fd = socket(ga->a.ops->pf, SOCK_STREAM, 0)) < 0)
596 error(sc, "couldn't create socket: %s", strerror(errno));
598 /* --- Set it to allow address reuse --- */
602 setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
603 fdflags(fd, O_NONBLOCK, O_NONBLOCK, FD_CLOEXEC, FD_CLOEXEC);
606 /* --- Bind it to the right port --- */
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);
613 /* --- Set it to listen for connections --- */
616 error(sc, "couldn't listen on socket: %s", strerror(errno));
619 /* --- We're ready to go now --- */
621 sel_initfile(sel, &ss->r, fd, SEL_READ, ss_accept, ss);
627 /* --- @destroy@ --- */
629 static void ssource_destroy(source *s)
631 ssource *ss = (ssource *)s;
633 if (ss->o.conn || ss->o.opt != SOCKOPT_LIMIT) {
636 if (ss->a->ops->unbind)
637 ss->a->ops->unbind(ss->a);
639 if (ss->a->ops->freeopts)
640 ss->a->ops->freeopts(ss->ao);
644 ss->a->ops->destroy(ss->a);
645 ss->t->ops->destroy(ss->t);
646 source_remove(&ss->s);
651 /* --- Source definition block --- */
653 source_ops ssource_ops = {
655 ssource_option, ssource_read, ssource_attach, ssource_destroy
658 /*----- Target definition -------------------------------------------------*/
662 static target *starget_read(scanner *sc)
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);
678 /* --- @create@ --- *
680 * Arguments: @target *t@ = pointer to target
681 * @const char *desc@ = description of connection
683 * Returns: Pointer to a created endpoint.
685 * Use: Generates a target endpoint for communication.
688 static endpt *starget_create(target *t, const char *desc)
690 starget *st = (starget *)t;
691 stept *e = CREATE(stept);
693 gen_addr *ga = (gen_addr *)st->a;
696 if ((fd = socket(st->a->ops->pf, SOCK_STREAM, 0)) < 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;
702 e->e.f = EPF_FILE | SKF_CONN;
704 e->desc = xstrdup(desc);
706 /* --- Pay attention --- *
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.
719 conn_init(&e->c, sel, fd, &ga->sa, ga->a.sz, stept_go, e);
720 if (e->e.f & SKF_BROKEN) {
724 if (e->e.f & SKF_CONN)
725 e->e.f |= EPF_PENDING;
730 /* --- @destroy@ --- */
732 static void starget_destroy(target *t)
734 starget *st = (starget *)t;
735 st->a->ops->destroy(st->a);
740 /* --- Socket target definition block --- */
742 target_ops starget_ops = {
744 0, starget_read, starget_create, starget_destroy
747 /*----- That's all, folks -------------------------------------------------*/