3 * $Id: socket.c,v 1.4 1999/12/22 15:44:25 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.4 1999/12/22 15:44:25 mdw
35 * Revision 1.3 1999/10/22 22:48:36 mdw
36 * New connection options: unlimited concurrent connections, and one-shot
39 * Revision 1.2 1999/07/27 18:30:53 mdw
40 * Various minor portability fixes.
42 * Revision 1.1 1999/07/26 23:33:32 mdw
43 * New sources and targets.
47 /*----- Header files ------------------------------------------------------*/
58 #include <sys/types.h>
61 #include <sys/socket.h>
62 #include <netinet/in.h>
63 #include <arpa/inet.h>
66 #include <mLib/alloc.h>
67 #include <mLib/conn.h>
68 #include <mLib/dstr.h>
69 #include <mLib/fdflags.h>
84 /*----- Data structures ---------------------------------------------------*/
86 /* --- Socket source options --- */
88 typedef struct ssource_opts {
93 static ssource_opts ssgo = { 256, 0 };
95 #define SOCKOPT_LIMIT 0u
96 #define SOCKOPT_NOLIMIT 1u
97 #define SOCKOPT_ONESHOT 2u
99 /* --- Socket source --- */
101 typedef struct ssource {
110 /* --- Socket target --- */
112 typedef struct starget {
118 /* --- Socket target endpoint --- */
120 typedef struct stept {
126 /* --- Socket source endpoint --- */
128 typedef struct ssept {
134 #define SKF_BROKEN 32u
136 /*----- Protocol table ----------------------------------------------------*/
138 static addr_ops *addrs[] = { &inet_ops, &un_ops, 0 };
140 /*----- Other persistent variables ----------------------------------------*/
142 static addr_opts gao = { 0 };
144 /*----- Parsing address types ---------------------------------------------*/
146 /* --- @getaddrtype@ --- *
148 * Arguments: @scanner *sc@ = pointer to scanner (for error reporting)
149 * @const char *p@ = pointer to protocol name
150 * @int abbrev@ = nonzero to allow abbreviations
152 * Returns: Pointer to address operations table or null.
154 * Use: Looks up a protocol name. Handy when parsing addresses and
155 * other bits of configuration. Returns null if no matching
159 static addr_ops *getaddrtype(scanner *sc, const char *p, int abbrev)
162 addr_ops *chosen = 0;
163 size_t sz = strlen(p);
165 for (ops = addrs; *ops; ops++) {
166 if (strncmp((*ops)->name, p, sz) == 0) {
167 if ((*ops)->name[sz] == 0)
169 else if (chosen && abbrev)
170 error(sc, "ambiguous socket address type `%s'", p);
179 /* --- @getaddr@ --- *
181 * Arguments: @scanner *sc@ = pointer to scanner to read from
182 * @unsigned type@ = address type (@ADDR_SRC@ or @ADDR_DEST@)
184 * Returns: Pointer to an address successfully read.
186 * Use: Reads an optionally qualified address.
189 static addr *getaddr(scanner *sc, unsigned type)
198 if (sc->t == CTOK_WORD)
199 ops = getaddrtype(sc, sc->d.buf, abbrev);
203 error(sc, "unknown socket address type `%s'", sc->d.buf);
209 return (ops->read(sc, type));
212 /*----- Socket endpoints --------------------------------------------------*/
214 /* --- @wclose@ --- */
216 static void sept_wclose(endpt *e)
218 shutdown(e->out->fd, 1);
221 /* --- @close@ (source) --- */
223 static void ss_listen(ssource */*ss*/);
225 static void ssept_close(endpt *e)
227 ssept *ee = (ssept *)e;
229 if (ee->s->o.opt == SOCKOPT_LIMIT) {
231 if (ee->s->o.conn == 1)
235 REFFD_DEC(ee->e.out);
240 /* --- @close@ (target) --- */
242 static void stept_close(endpt *e)
244 stept *ee = (stept *)e;
246 if (ee->e.f & EPF_PENDING) {
247 if (ee->e.f & SKF_CONN)
251 REFFD_DEC(ee->e.out);
258 /* --- @stept_go@ --- *
260 * Arguments: @int fd@ = file descriptor now ready for use
261 * @void *p@ = pointer to an endpoint structure
265 * Use: Handles successful connection of the target endpoint.
268 static void stept_go(int fd, void *p)
272 /* --- Complicated and subtle --- *
274 * This code interacts quite closely with @starget_create@, mainly through
275 * flags in the endpoint block.
277 * If the connection failed, I log a message (that's easy enough). The
278 * behaviour then depends on whether the endpoints have been joined yet.
279 * If not, I set @SKF_BROKEN@ and return, so that @starget_create@ can
280 * clean up the mess and return an immediate failure. If they have, I kill
281 * the connection and everything ought to work.
283 * If the connection worked, I clear @EPF_PENDING@ (as expected, because
284 * my endpoint is now ready), and @SKF_CONN@ (to let @starget_create@ know
285 * that the connection is already going). Then, only if this isn't the
286 * first attempt, I rejoin this endpoint to its partner.
290 fw_log(-1, "[%s] connection failed: %s", e->desc, strerror(errno));
292 if (e->e.f & EPF_PENDING)
295 e->e.f |= SKF_BROKEN;
297 reffd *r = reffd_init(fd);
299 e->e.in = e->e.out = r;
300 e->e.f &= ~(EPF_PENDING | SKF_CONN);
302 endpt_join(&e->e, e->e.other);
306 /* --- Socket endpoint definition --- */
308 static endpt_ops ssept_ops = {
309 0, 0, sept_wclose, ssept_close
312 static endpt_ops stept_ops = {
313 0, 0, sept_wclose, stept_close
316 /*----- Source definition -------------------------------------------------*/
318 /* --- @option@ --- */
320 static int ssource_option(source *s, scanner *sc)
322 ssource *ss = (ssource *)s;
323 ssource_opts *sso = ss ? &ss->o : &ssgo;
325 CONF_BEGIN(sc, "socket", "socket")
327 /* --- Make sure the next token is a word --- */
329 if (sc->t != CTOK_WORD)
330 error(sc, "parse error, option keyword expected");
332 /* --- Handle options at this level --- */
334 if (strcmp(sc->d.buf, "conn") == 0) {
338 if (sc->t != CTOK_WORD)
339 error(sc, "parse error, expected `unlimited', `one-shot' or number");
340 if (isdigit((unsigned char)sc->d.buf[0])) {
341 sso->conn = atoi(sc->d.buf);
343 error(sc, "argument of `conn' must be positive");
344 sso->opt = SOCKOPT_LIMIT;
348 sso->opt = 1 + (1 & conf_enum(sc,
349 "unlimited,one-shot,infinite",
350 ENUM_ABBREV, "`conn' option"));
355 if (strcmp(sc->d.buf, "logging") == 0 ||
356 strcmp(sc->d.buf, "log") == 0) {
357 addr_opts *ao = ss ? ss->ao : &gao;
361 if (conf_enum(sc, "no,yes", ENUM_ABBREV, "logging status"))
362 ao->f &= ~ADDRF_NOLOG;
364 ao->f |= ADDRF_NOLOG;
368 /* --- Pass the option around the various address types --- */
371 if (ss->a->ops->option && ss->a->ops->option(sc, ss ? ss->ao : 0))
375 for (a = addrs; *a; a++) {
376 if ((*a)->option && (*a)->option(sc, 0))
381 /* --- Nobody understood the option --- */
388 static source *ssource_read(scanner *sc)
392 (void)(conf_prefix(sc, "socket") || conf_prefix(sc, "sk"));
393 ss = CREATE(ssource);
394 ss->s.ops = &ssource_ops;
397 ss->a = getaddr(sc, ADDR_SRC);
398 if (ss->a->ops->initopts)
399 ss->ao = ss->a->ops->initopts();
401 ss->ao = CREATE(addr_opts);
407 /* --- @ss_accept@ --- *
409 * Arguments: @int fd@ = file descriptor to accept from
410 * @unsigned mode@ = what's ready with the descriptor
411 * @void *p@ = pointer to the source definition
415 * Use: Accepts an incoming connection and attaches it to a target
419 static void ssource_destroy(source */*s*/);
421 static void ss_accept(int fd, unsigned mode, void *p)
428 /* --- Make the file descriptor --- */
432 if ((r = ss->a->ops->accept(fd, ss->ao, ss->s.desc)) == 0)
434 setsockopt(r->fd, SOL_SOCKET, SO_OOBINLINE, &opt, sizeof(opt));
435 fdflags(r->fd, O_NONBLOCK, O_NONBLOCK, FD_CLOEXEC, FD_CLOEXEC);
438 /* --- Make an endpoint --- */
441 e->e.ops = &ssept_ops;
445 e->e.in = e->e.out = r;
449 /* --- Obtain the target endpoint and let rip --- */
451 if ((ee = ss->t->ops->create(ss->t, ss->s.desc)) == 0) {
459 /* --- Remove the listening socket if necessary --- */
465 if (!(ss->ao->f & ADDRF_NOLOG))
466 fw_log(-1, "[%s] maximum connections reached", ss->s.desc);
469 if (ss->a->ops->unbind)
470 ss->a->ops->unbind(ss->a);
473 case SOCKOPT_NOLIMIT:
475 case SOCKOPT_ONESHOT:
478 if (ss->a->ops->unbind)
479 ss->a->ops->unbind(ss->a);
480 ssource_destroy(&ss->s);
484 /* --- Let everything else happen --- */
486 endpt_join(&e->e, ee);
489 /* --- @ss_listen@ --- *
491 * Arguments: @ssource *ss@ = source to listen on
495 * Use: Sets the socket to listen again, if it stopped for some
496 * reason. This is a copy of the code in the @read@ function,
497 * because it has different (wildly different) error handling
501 static void ss_listen(ssource *ss)
503 gen_addr *ga = (gen_addr *)ss->a;
506 if (!(ss->ao->f & ADDRF_NOLOG))
507 fw_log(-1, "[%s] reattaching listener", ss->s.desc);
509 /* --- Make the socket --- */
511 if ((fd = socket(ga->a.ops->pf, SOCK_STREAM, 0)) < 0) {
512 fw_log(-1, "[%s] couldn't create socket: %s",
513 ss->s.desc, strerror(errno));
517 /* --- Set it to allow address reuse --- */
521 setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
522 fdflags(fd, O_NONBLOCK, O_NONBLOCK, FD_CLOEXEC, FD_CLOEXEC);
525 /* --- Bind it to the right port --- */
527 if (bind(fd, &ga->sa, ga->a.sz)) {
528 fw_log(-1, "[%s] couldn't bind socket: %s", ss->s.desc, strerror(errno));
531 if (ga->a.ops->bound)
532 ga->a.ops->bound(&ga->a, ss->ao);
534 /* --- Set it to listen for connections --- */
537 fw_log(-1, "[%s] couldn't listen on socket: %s",
538 ss->s.desc, strerror(errno));
542 /* --- Set the listener up again --- */
548 /* --- Tidy up if it failed --- *
550 * I'll just remove the entire source.
557 ssource_destroy(&ss->s);
560 /* --- @attach@ --- */
562 static void ssource_attach(source *s, scanner *sc, target *t)
564 ssource *ss = (ssource *)s;
569 /* --- Initialize the description string --- */
573 dstr_puts(&d, "socket.");
574 ss->a->ops->print(ss->a, ADDR_SRC, &d);
575 dstr_puts(&d, " -> ");
576 dstr_puts(&d, ss->t->desc);
577 ss->s.desc = xstrdup(d.buf);
581 /* --- Initialize the socket for listening --- */
584 gen_addr *ga = (gen_addr *)ss->a;
586 /* --- Make the socket --- */
588 if ((fd = socket(ga->a.ops->pf, SOCK_STREAM, 0)) < 0)
589 error(sc, "couldn't create socket: %s", strerror(errno));
591 /* --- Set it to allow address reuse --- */
595 setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
596 fdflags(fd, O_NONBLOCK, O_NONBLOCK, FD_CLOEXEC, FD_CLOEXEC);
599 /* --- Bind it to the right port --- */
601 if (bind(fd, &ga->sa, ga->a.sz))
602 error(sc, "couldn't bind to %s: %s", ss->s.desc, strerror(errno));
603 if (ga->a.ops->bound)
604 ga->a.ops->bound(&ga->a, ss->ao);
606 /* --- Set it to listen for connections --- */
609 error(sc, "couldn't listen on socket: %s", strerror(errno));
612 /* --- We're ready to go now --- */
614 sel_initfile(sel, &ss->r, fd, SEL_READ, ss_accept, ss);
620 /* --- @destroy@ --- */
622 static void ssource_destroy(source *s)
624 ssource *ss = (ssource *)s;
629 if (ss->a->ops->unbind)
630 ss->a->ops->unbind(ss->a);
632 if (ss->a->ops->freeopts)
633 ss->a->ops->freeopts(ss->ao);
636 /* free(ss->s.desc); */
637 ss->a->ops->destroy(ss->a);
638 ss->t->ops->destroy(ss->t);
639 source_remove(&ss->s);
644 /* --- Source definition block --- */
646 source_ops ssource_ops = {
648 ssource_option, ssource_read, ssource_attach, ssource_destroy
651 /*----- Target definition -------------------------------------------------*/
655 static target *starget_read(scanner *sc)
660 (void)(conf_prefix(sc, "socket") || conf_prefix(sc, "sk"));
661 st = CREATE(starget);
662 st->t.ops = &starget_ops;
663 st->a = getaddr(sc, ADDR_DEST);
664 dstr_puts(&d, "socket.");
665 st->a->ops->print(st->a, ADDR_DEST, &d);
666 st->t.desc = xstrdup(d.buf);
671 /* --- @create@ --- *
673 * Arguments: @target *t@ = pointer to target
674 * @const char *desc@ = description of connection
676 * Returns: Pointer to a created endpoint.
678 * Use: Generates a target endpoint for communication.
681 static endpt *starget_create(target *t, const char *desc)
683 starget *st = (starget *)t;
684 stept *e = CREATE(stept);
686 gen_addr *ga = (gen_addr *)st->a;
689 if ((fd = socket(st->a->ops->pf, SOCK_STREAM, 0)) < 0)
691 setsockopt(fd, SOL_SOCKET, SO_OOBINLINE, &opt, sizeof(opt));
692 fdflags(fd, O_NONBLOCK, O_NONBLOCK, FD_CLOEXEC, FD_CLOEXEC);
693 e->e.ops = &stept_ops;
695 e->e.f = EPF_FILE | SKF_CONN;
699 /* --- Pay attention --- *
701 * This bit is quite subtle. The connect can succeed or fail later: that's
702 * fine. The problem comes if it makes its mind up right now. The flag
703 * @SKF_CONN@ signifies that I'm trying to connect. I set it up to begin
704 * with and @stept_go@ turns it off when it's done: @stept_close@ uses it
705 * to decide whether to kill the connection. The flag @EPF_PENDING@ is
706 * only set after @conn_init@ returns and @SKF_CONN@ is still set (meaning
707 * that the connection is still in progress). That's used to let
708 * @stept_go@ know whether to kill the other endpoint. The flag
709 * @SKF_BROKEN@ is used to signify an immediate failure.
712 conn_init(&e->c, sel, fd, &ga->sa, ga->a.sz, stept_go, e);
713 if (e->e.f & SKF_BROKEN) {
717 if (e->e.f & SKF_CONN)
718 e->e.f |= EPF_PENDING;
723 /* --- @destroy@ --- */
725 static void starget_destroy(target *t)
727 starget *st = (starget *)t;
728 st->a->ops->destroy(st->a);
729 /* free(st->t.desc); */
733 /* --- Socket target definition block --- */
735 target_ops starget_ops = {
737 0, starget_read, starget_create, starget_destroy
740 /*----- That's all, folks -------------------------------------------------*/