3 * $Id: socket.c,v 1.8 2002/02/22 23:44:44 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.8 2002/02/22 23:44:44 mdw
33 * Call @xfree@ rather than @free@. Add option to change the listen(2)
36 * Revision 1.7 2001/06/22 19:37:00 mdw
37 * New @conn_init@ interface.
39 * Revision 1.6 2001/02/03 20:30:03 mdw
40 * Support re-reading config files on SIGHUP.
42 * Revision 1.5 2000/03/23 23:20:42 mdw
43 * Remove listener even if connection option isn't SOCKOPT_LIMITED.
45 * Revision 1.4 1999/12/22 15:44:25 mdw
48 * Revision 1.3 1999/10/22 22:48:36 mdw
49 * New connection options: unlimited concurrent connections, and one-shot
52 * Revision 1.2 1999/07/27 18:30:53 mdw
53 * Various minor portability fixes.
55 * Revision 1.1 1999/07/26 23:33:32 mdw
56 * New sources and targets.
60 /*----- Header files ------------------------------------------------------*/
71 #include <sys/types.h>
74 #include <sys/socket.h>
75 #include <netinet/in.h>
76 #include <arpa/inet.h>
79 #include <mLib/alloc.h>
80 #include <mLib/conn.h>
81 #include <mLib/dstr.h>
82 #include <mLib/fdflags.h>
97 /*----- Data structures ---------------------------------------------------*/
99 /* --- Socket source options --- */
101 typedef struct ssource_opts {
107 static ssource_opts ssgo = { 256, 0, 5 };
109 #define SOCKOPT_LIMIT 0u
110 #define SOCKOPT_NOLIMIT 1u
111 #define SOCKOPT_ONESHOT 2u
113 /* --- Socket source --- */
115 typedef struct ssource {
124 /* --- Socket target --- */
126 typedef struct starget {
132 /* --- Socket target endpoint --- */
134 typedef struct stept {
140 /* --- Socket source endpoint --- */
142 typedef struct ssept {
147 /*----- Protocol table ----------------------------------------------------*/
149 static addr_ops *addrs[] = { &inet_ops, &un_ops, 0 };
151 /*----- Other persistent variables ----------------------------------------*/
153 static addr_opts gao = { 0 };
155 /*----- Parsing address types ---------------------------------------------*/
157 /* --- @getaddrtype@ --- *
159 * Arguments: @scanner *sc@ = pointer to scanner (for error reporting)
160 * @const char *p@ = pointer to protocol name
161 * @int abbrev@ = nonzero to allow abbreviations
163 * Returns: Pointer to address operations table or null.
165 * Use: Looks up a protocol name. Handy when parsing addresses and
166 * other bits of configuration. Returns null if no matching
170 static addr_ops *getaddrtype(scanner *sc, const char *p, int abbrev)
173 addr_ops *chosen = 0;
174 size_t sz = strlen(p);
176 for (ops = addrs; *ops; ops++) {
177 if (strncmp((*ops)->name, p, sz) == 0) {
178 if ((*ops)->name[sz] == 0)
180 else if (chosen && abbrev)
181 error(sc, "ambiguous socket address type `%s'", p);
190 /* --- @getaddr@ --- *
192 * Arguments: @scanner *sc@ = pointer to scanner to read from
193 * @unsigned type@ = address type (@ADDR_SRC@ or @ADDR_DEST@)
195 * Returns: Pointer to an address successfully read.
197 * Use: Reads an optionally qualified address.
200 static addr *getaddr(scanner *sc, unsigned type)
209 if (sc->t == CTOK_WORD)
210 ops = getaddrtype(sc, sc->d.buf, abbrev);
214 error(sc, "unknown socket address type `%s'", sc->d.buf);
220 return (ops->read(sc, type));
223 /*----- Socket endpoints --------------------------------------------------*/
225 /* --- @wclose@ --- */
227 static void sept_wclose(endpt *e)
229 shutdown(e->out->fd, 1);
232 /* --- @close@ (source) --- */
234 static void ss_listen(ssource */*ss*/);
236 static void ssept_close(endpt *e)
238 ssept *ee = (ssept *)e;
240 if (ee->s->o.opt == SOCKOPT_LIMIT) {
242 if (ee->s->o.conn == 1)
246 REFFD_DEC(ee->e.out);
251 /* --- @close@ (target) --- */
253 static void stept_close(endpt *e)
255 stept *ee = (stept *)e;
257 if (ee->e.f & EPF_PENDING)
261 REFFD_DEC(ee->e.out);
269 /* --- @stept_go@ --- *
271 * Arguments: @int fd@ = file descriptor now ready for use
272 * @void *p@ = pointer to an endpoint structure
276 * Use: Handles successful connection of the target endpoint.
279 static void stept_go(int fd, void *p)
284 fw_log(-1, "[%s] connection failed: %s", e->desc, strerror(errno));
287 reffd *r = reffd_init(fd);
289 e->e.in = e->e.out = r;
290 e->e.f &= ~EPF_PENDING;
292 endpt_join(&e->e, e->e.other);
296 /* --- Socket endpoint definition --- */
298 static endpt_ops ssept_ops = {
299 0, 0, sept_wclose, ssept_close
302 static endpt_ops stept_ops = {
303 0, 0, sept_wclose, stept_close
306 /*----- Source definition -------------------------------------------------*/
308 /* --- @option@ --- */
310 static int ssource_option(source *s, scanner *sc)
312 ssource *ss = (ssource *)s;
313 ssource_opts *sso = ss ? &ss->o : &ssgo;
315 CONF_BEGIN(sc, "socket", "socket")
317 /* --- Make sure the next token is a word --- */
319 if (sc->t != CTOK_WORD)
320 error(sc, "parse error, option keyword expected");
322 /* --- Handle options at this level --- */
324 if (strcmp(sc->d.buf, "conn") == 0) {
328 if (sc->t != CTOK_WORD)
329 error(sc, "parse error, expected `unlimited', `one-shot' or number");
330 if (isdigit((unsigned char)sc->d.buf[0])) {
331 sso->conn = atoi(sc->d.buf);
333 error(sc, "argument of `conn' must be positive");
334 sso->opt = SOCKOPT_LIMIT;
338 sso->opt = 1 + (1 & conf_enum(sc,
339 "unlimited,one-shot,infinite",
340 ENUM_ABBREV, "`conn' option"));
345 if (strcmp(sc->d.buf, "listen") == 0) {
349 if (sc->t != CTOK_WORD || !isdigit((unsigned char)sc->d.buf[0]))
350 error(sc, "parse error, expected number");
351 sso->listen = atoi(sc->d.buf);
352 if (sso->listen == 0)
353 error(sc, "argument of `listen' must be positive");
357 if (strcmp(sc->d.buf, "logging") == 0 ||
358 strcmp(sc->d.buf, "log") == 0) {
359 addr_opts *ao = ss ? ss->ao : &gao;
363 if (conf_enum(sc, "no,yes", ENUM_ABBREV, "logging status"))
364 ao->f &= ~ADDRF_NOLOG;
366 ao->f |= ADDRF_NOLOG;
370 /* --- Pass the option around the various address types --- */
373 if (ss->a->ops->option && ss->a->ops->option(sc, ss ? ss->ao : 0))
377 for (a = addrs; *a; a++) {
378 if ((*a)->option && (*a)->option(sc, 0))
383 /* --- Nobody understood the option --- */
390 static source *ssource_read(scanner *sc)
394 (void)(conf_prefix(sc, "socket") || conf_prefix(sc, "sk"));
395 ss = CREATE(ssource);
396 ss->s.ops = &ssource_ops;
399 ss->a = getaddr(sc, ADDR_SRC);
400 if (ss->a->ops->initopts)
401 ss->ao = ss->a->ops->initopts();
403 ss->ao = CREATE(addr_opts);
409 /* --- @ss_accept@ --- *
411 * Arguments: @int fd@ = file descriptor to accept from
412 * @unsigned mode@ = what's ready with the descriptor
413 * @void *p@ = pointer to the source definition
417 * Use: Accepts an incoming connection and attaches it to a target
421 static void ssource_destroy(source */*s*/);
423 static void ss_accept(int fd, unsigned mode, void *p)
430 /* --- Make the file descriptor --- */
434 if ((r = ss->a->ops->accept(fd, ss->ao, ss->s.desc)) == 0)
436 setsockopt(r->fd, SOL_SOCKET, SO_OOBINLINE, &opt, sizeof(opt));
437 fdflags(r->fd, O_NONBLOCK, O_NONBLOCK, FD_CLOEXEC, FD_CLOEXEC);
440 /* --- Make an endpoint --- */
443 e->e.ops = &ssept_ops;
447 e->e.in = e->e.out = r;
451 /* --- Obtain the target endpoint and let rip --- */
453 if ((ee = ss->t->ops->create(ss->t, ss->s.desc)) == 0) {
461 /* --- Remove the listening socket if necessary --- */
467 if (!(ss->ao->f & ADDRF_NOLOG))
468 fw_log(-1, "[%s] maximum connections reached", ss->s.desc);
471 if (ss->a->ops->unbind)
472 ss->a->ops->unbind(ss->a);
475 case SOCKOPT_NOLIMIT:
477 case SOCKOPT_ONESHOT:
480 if (ss->a->ops->unbind)
481 ss->a->ops->unbind(ss->a);
482 ssource_destroy(&ss->s);
486 /* --- Let everything else happen --- */
488 endpt_join(&e->e, ee);
491 /* --- @ss_listen@ --- *
493 * Arguments: @ssource *ss@ = source to listen on
497 * Use: Sets the socket to listen again, if it stopped for some
498 * reason. This is a copy of the code in the @read@ function,
499 * because it has different (wildly different) error handling
503 static void ss_listen(ssource *ss)
505 gen_addr *ga = (gen_addr *)ss->a;
508 if (!(ss->ao->f & ADDRF_NOLOG))
509 fw_log(-1, "[%s] reattaching listener", ss->s.desc);
511 /* --- Make the socket --- */
513 if ((fd = socket(ga->a.ops->pf, SOCK_STREAM, 0)) < 0) {
514 fw_log(-1, "[%s] couldn't create socket: %s",
515 ss->s.desc, strerror(errno));
519 /* --- Set it to allow address reuse --- */
523 setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
524 fdflags(fd, O_NONBLOCK, O_NONBLOCK, FD_CLOEXEC, FD_CLOEXEC);
527 /* --- Bind it to the right port --- */
529 if (bind(fd, &ga->sa, ga->a.sz)) {
530 fw_log(-1, "[%s] couldn't bind socket: %s", ss->s.desc, strerror(errno));
533 if (ga->a.ops->bound)
534 ga->a.ops->bound(&ga->a, ss->ao);
536 /* --- Set it to listen for connections --- */
538 if (listen(fd, ss->o.listen)) {
539 fw_log(-1, "[%s] couldn't listen on socket: %s",
540 ss->s.desc, strerror(errno));
544 /* --- Set the listener up again --- */
550 /* --- Tidy up if it failed --- *
552 * I'll just remove the entire source.
559 ssource_destroy(&ss->s);
562 /* --- @attach@ --- */
564 static void ssource_attach(source *s, scanner *sc, target *t)
566 ssource *ss = (ssource *)s;
571 /* --- Initialize the description string --- */
575 dstr_puts(&d, "socket.");
576 ss->a->ops->print(ss->a, ADDR_SRC, &d);
577 dstr_puts(&d, " -> ");
578 dstr_puts(&d, ss->t->desc);
579 ss->s.desc = xstrdup(d.buf);
583 /* --- Initialize the socket for listening --- */
586 gen_addr *ga = (gen_addr *)ss->a;
588 /* --- Make the socket --- */
590 if ((fd = socket(ga->a.ops->pf, SOCK_STREAM, 0)) < 0)
591 error(sc, "couldn't create socket: %s", strerror(errno));
593 /* --- Set it to allow address reuse --- */
597 setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
598 fdflags(fd, O_NONBLOCK, O_NONBLOCK, FD_CLOEXEC, FD_CLOEXEC);
601 /* --- Bind it to the right port --- */
603 if (bind(fd, &ga->sa, ga->a.sz))
604 error(sc, "couldn't bind to %s: %s", ss->s.desc, strerror(errno));
605 if (ga->a.ops->bound)
606 ga->a.ops->bound(&ga->a, ss->ao);
608 /* --- Set it to listen for connections --- */
611 error(sc, "couldn't listen on socket: %s", strerror(errno));
614 /* --- We're ready to go now --- */
616 sel_initfile(sel, &ss->r, fd, SEL_READ, ss_accept, ss);
622 /* --- @destroy@ --- */
624 static void ssource_destroy(source *s)
626 ssource *ss = (ssource *)s;
628 if (ss->o.conn || ss->o.opt != SOCKOPT_LIMIT) {
631 if (ss->a->ops->unbind)
632 ss->a->ops->unbind(ss->a);
634 if (ss->a->ops->freeopts)
635 ss->a->ops->freeopts(ss->ao);
639 ss->a->ops->destroy(ss->a);
640 ss->t->ops->destroy(ss->t);
641 source_remove(&ss->s);
646 /* --- Source definition block --- */
648 source_ops ssource_ops = {
650 ssource_option, ssource_read, ssource_attach, ssource_destroy
653 /*----- Target definition -------------------------------------------------*/
657 static target *starget_read(scanner *sc)
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 dstr_puts(&d, "socket.");
667 st->a->ops->print(st->a, ADDR_DEST, &d);
668 st->t.desc = xstrdup(d.buf);
673 /* --- @create@ --- *
675 * Arguments: @target *t@ = pointer to target
676 * @const char *desc@ = description of connection
678 * Returns: Pointer to a created endpoint.
680 * Use: Generates a target endpoint for communication.
683 static endpt *starget_create(target *t, const char *desc)
685 starget *st = (starget *)t;
686 stept *e = CREATE(stept);
688 gen_addr *ga = (gen_addr *)st->a;
691 if ((fd = socket(st->a->ops->pf, SOCK_STREAM, 0)) < 0)
693 setsockopt(fd, SOL_SOCKET, SO_OOBINLINE, &opt, sizeof(opt));
694 fdflags(fd, O_NONBLOCK, O_NONBLOCK, FD_CLOEXEC, FD_CLOEXEC);
695 e->e.ops = &stept_ops;
697 e->e.f = EPF_FILE | EPF_PENDING;
699 e->desc = xstrdup(desc);
701 if (conn_init(&e->c, sel, fd, &ga->sa, ga->a.sz, stept_go, e)) {
702 fw_log(-1, "[%s] connection failed: %s", e->desc, strerror(errno));
710 /* --- @destroy@ --- */
712 static void starget_destroy(target *t)
714 starget *st = (starget *)t;
715 st->a->ops->destroy(st->a);
720 /* --- Socket target definition block --- */
722 target_ops starget_ops = {
724 0, starget_read, starget_create, starget_destroy
727 /*----- That's all, folks -------------------------------------------------*/