3 * $Id: socket.c,v 1.1 1999/07/26 23:33:32 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.1 1999/07/26 23:33:32 mdw
33 * New sources and targets.
37 /*----- Header files ------------------------------------------------------*/
47 #include <sys/socket.h>
48 #include <netinet/in.h>
49 #include <arpa/inet.h>
52 #include <mLib/alloc.h>
53 #include <mLib/conn.h>
54 #include <mLib/dstr.h>
55 #include <mLib/fdflags.h>
70 /*----- Data structures ---------------------------------------------------*/
72 /* --- Socket source options --- */
74 typedef struct ssource_opts {
78 static ssource_opts ssgo = { 256 };
80 /* --- Socket source --- */
82 typedef struct ssource {
91 /* --- Socket target --- */
93 typedef struct starget {
99 /* --- Socket target endpoint --- */
101 typedef struct stept {
107 /* --- Socket source endpoint --- */
109 typedef struct ssept {
115 #define SKF_BROKEN 32u
117 /*----- Protocol table ----------------------------------------------------*/
119 static addr_ops *addrs[] = { &inet_ops, &un_ops, 0 };
121 /*----- Other persistent variables ----------------------------------------*/
123 static addr_opts gao = { 0 };
125 /*----- Parsing address types ---------------------------------------------*/
127 /* --- @getaddrtype@ --- *
129 * Arguments: @scanner *sc@ = pointer to scanner (for error reporting)
130 * @const char *p@ = pointer to protocol name
131 * @int abbrev@ = nonzero to allow abbreviations
133 * Returns: Pointer to address operations table or null.
135 * Use: Looks up a protocol name. Handy when parsing addresses and
136 * other bits of configuration. Returns null if no matching
140 static addr_ops *getaddrtype(scanner *sc, const char *p, int abbrev)
143 addr_ops *chosen = 0;
144 size_t sz = strlen(p);
146 for (ops = addrs; *ops; ops++) {
147 if (strncmp((*ops)->name, p, sz) == 0) {
148 if ((*ops)->name[sz] == 0)
150 else if (chosen && abbrev)
151 error(sc, "ambiguous socket address type `%s'", p);
160 /* --- @getaddr@ --- *
162 * Arguments: @scanner *sc@ = pointer to scanner to read from
163 * @unsigned type@ = address type (@ADDR_SRC@ or @ADDR_DEST@)
165 * Returns: Pointer to an address successfully read.
167 * Use: Reads an optionally qualified address.
170 static addr *getaddr(scanner *sc, unsigned type)
179 if (sc->t == CTOK_WORD)
180 ops = getaddrtype(sc, sc->d.buf, abbrev);
184 error(sc, "unknown socket address type `%s'", sc->d.buf);
190 return (ops->read(sc, type));
193 /*----- Socket endpoints --------------------------------------------------*/
195 /* --- @wclose@ --- */
197 static void sept_wclose(endpt *e)
199 shutdown(e->out->fd, 1);
202 /* --- @close@ (source) --- */
204 static void ss_listen(ssource */*ss*/);
206 static void ssept_close(endpt *e)
208 ssept *ee = (ssept *)e;
210 if (!ee->s->o.conn) {
216 REFFD_DEC(ee->e.out);
221 /* --- @close@ (target) --- */
223 static void stept_close(endpt *e)
225 stept *ee = (stept *)e;
227 if (ee->e.f & EPF_PENDING) {
228 if (ee->e.f & SKF_CONN)
232 REFFD_DEC(ee->e.out);
239 /* --- @stept_go@ --- *
241 * Arguments: @int fd@ = file descriptor now ready for use
242 * @void *p@ = pointer to an endpoint structure
246 * Use: Handles successful connection of the target endpoint.
249 static void stept_go(int fd, void *p)
253 /* --- Complicated and subtle --- *
255 * This code interacts quite closely with @starget_create@, mainly through
256 * flags in the endpoint block.
258 * If the connection failed, I log a message (that's easy enough). The
259 * behaviour then depends on whether the endpoints have been joined yet.
260 * If not, I set @SKF_BROKEN@ and return, so that @starget_create@ can
261 * clean up the mess and return an immediate failure. If they have, I kill
262 * the connection and everything ought to work.
264 * If the connection worked, I clear @EPF_PENDING@ (as expected, because
265 * my endpoint is now ready), and @SKF_CONN@ (to let @starget_create@ know
266 * that the connection is already going). Then, only if this isn't the
267 * first attempt, I rejoin this endpoint to its partner.
271 fw_log(-1, "[%s] connection failed: %s", e->desc, strerror(errno));
273 if (e->e.f & EPF_PENDING)
276 e->e.f |= SKF_BROKEN;
278 reffd *r = reffd_init(fd);
280 e->e.in = e->e.out = r;
281 e->e.f &= ~(EPF_PENDING | SKF_CONN);
283 endpt_join(&e->e, e->e.other);
287 /* --- Socket endpoint definition --- */
289 static endpt_ops ssept_ops = {
290 0, sept_wclose, ssept_close
293 static endpt_ops stept_ops = {
294 0, sept_wclose, stept_close
297 /*----- Source definition -------------------------------------------------*/
299 /* --- @option@ --- */
301 static int ssource_option(source *s, scanner *sc)
303 ssource *ss = (ssource *)s;
304 ssource_opts *sso = ss ? &ss->o : &ssgo;
306 CONF_BEGIN(sc, "socket", "socket")
308 /* --- Make sure the next token is a word --- */
310 if (sc->t != CTOK_WORD)
311 error(sc, "parse error, option keyword expected");
313 /* --- Handle options at this level --- */
315 if (strcmp(sc->d.buf, "conn") == 0) {
319 if (sc->t != CTOK_WORD || !isdigit((unsigned char)sc->d.buf[0]))
320 error(sc, "parse error, argument of `conn' must be a number");
321 sso->conn = atoi(sc->d.buf);
323 error(sc, "argument of `conn' must be positive");
328 if (strcmp(sc->d.buf, "logging") == 0 ||
329 strcmp(sc->d.buf, "log") == 0) {
330 addr_opts *ao = ss ? ss->ao : &gao;
334 if (conf_enum(sc, "no,yes", ENUM_ABBREV, "logging status"))
335 ao->f &= ~ADDRF_NOLOG;
337 ao->f |= ADDRF_NOLOG;
341 /* --- Pass the option around the various address types --- */
344 if (ss->a->ops->option && ss->a->ops->option(sc, ss ? ss->ao : 0))
348 for (a = addrs; *a; a++) {
349 if ((*a)->option && (*a)->option(sc, 0))
354 /* --- Nobody understood the option --- */
361 static source *ssource_read(scanner *sc)
365 (void)(conf_prefix(sc, "socket") || conf_prefix(sc, "sk"));
366 ss = CREATE(ssource);
367 ss->s.ops = &ssource_ops;
370 ss->a = getaddr(sc, ADDR_SRC);
371 if (ss->a->ops->initopts)
372 ss->ao = ss->a->ops->initopts();
374 ss->ao = CREATE(addr_opts);
380 /* --- @ss_accept@ --- *
382 * Arguments: @int fd@ = file descriptor to accept from
383 * @unsigned mode@ = what's ready with the descriptor
384 * @void *p@ = pointer to the source definition
388 * Use: Accepts an incoming connection and attaches it to a target
392 static void ss_accept(int fd, unsigned mode, void *p)
399 /* --- Make the file descriptor --- */
403 if ((r = ss->a->ops->accept(fd, ss->ao, ss->s.desc)) == 0)
405 setsockopt(r->fd, SOL_SOCKET, SO_OOBINLINE, &opt, sizeof(opt));
406 fdflags(r->fd, O_NONBLOCK, O_NONBLOCK, FD_CLOEXEC, FD_CLOEXEC);
409 /* --- Make an endpoint --- */
412 e->e.ops = &ssept_ops;
416 e->e.in = e->e.out = r;
420 /* --- Obtain the target endpoint and let rip --- */
422 if ((ee = ss->t->ops->create(ss->t, ss->s.desc)) == 0) {
429 /* --- Remove the listening socket if necessary --- */
433 fw_log(-1, "[%s] maximum connections reached", ss->s.desc);
436 if (ss->a->ops->unbind)
437 ss->a->ops->unbind(ss->a);
440 /* --- Let everything else happen --- */
443 endpt_join(&e->e, ee);
446 /* --- @ss_listen@ --- *
448 * Arguments: @ssource *ss@ = source to listen on
452 * Use: Sets the socket to listen again, if it stopped for some
453 * reason. This is a copy of the code in the @read@ function,
454 * because it has different (wildly different) error handling
458 static void ssource_destroy(source */*s*/);
460 static void ss_listen(ssource *ss)
462 gen_addr *ga = (gen_addr *)ss->a;
465 fw_log(-1, "[%s] reattaching listener", ss->s.desc);
467 /* --- Make the socket --- */
469 if ((fd = socket(ga->a.ops->pf, SOCK_STREAM, 0)) < 0) {
470 fw_log(-1, "[%s] couldn't create socket: %s",
471 ss->s.desc, strerror(errno));
475 /* --- Set it to allow address reuse --- */
479 setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
480 fdflags(fd, O_NONBLOCK, O_NONBLOCK, FD_CLOEXEC, FD_CLOEXEC);
483 /* --- Bind it to the right port --- */
485 if (bind(fd, &ga->sa, ga->a.sz)) {
486 fw_log(-1, "[%s] couldn't bind to %s: %s", ss->s.desc, strerror(errno));
489 if (ga->a.ops->bound)
490 ga->a.ops->bound(&ga->a, ss->ao);
492 /* --- Set it to listen for connections --- */
495 fw_log(-1, "[%s] couldn't listen on socket: %s",
496 ss->s.desc, strerror(errno));
500 /* --- Set the listener up again --- */
506 /* --- Tidy up if it failed --- *
508 * I'll just remove the entire source.
515 ssource_destroy(&ss->s);
518 /* --- @attach@ --- */
520 static void ssource_attach(source *s, scanner *sc, target *t)
522 ssource *ss = (ssource *)s;
527 /* --- Initialize the description string --- */
531 dstr_puts(&d, "socket.");
532 ss->a->ops->print(ss->a, ADDR_SRC, &d);
533 dstr_puts(&d, " -> ");
534 dstr_puts(&d, ss->t->desc);
535 ss->s.desc = xstrdup(d.buf);
539 /* --- Initialize the socket for listening --- */
542 gen_addr *ga = (gen_addr *)ss->a;
544 /* --- Make the socket --- */
546 if ((fd = socket(ga->a.ops->pf, SOCK_STREAM, 0)) < 0)
547 error(sc, "couldn't create socket: %s", strerror(errno));
549 /* --- Set it to allow address reuse --- */
553 setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
554 fdflags(fd, O_NONBLOCK, O_NONBLOCK, FD_CLOEXEC, FD_CLOEXEC);
557 /* --- Bind it to the right port --- */
559 if (bind(fd, &ga->sa, ga->a.sz))
560 error(sc, "couldn't bind to %s: %s", ss->s.desc, strerror(errno));
561 if (ga->a.ops->bound)
562 ga->a.ops->bound(&ga->a, ss->ao);
564 /* --- Set it to listen for connections --- */
567 error(sc, "couldn't listen on socket: %s", strerror(errno));
570 /* --- We're ready to go now --- */
572 sel_initfile(sel, &ss->r, fd, SEL_READ, ss_accept, ss);
578 /* --- @destroy@ --- */
580 static void ssource_destroy(source *s)
582 ssource *ss = (ssource *)s;
587 if (ss->a->ops->unbind)
588 ss->a->ops->unbind(ss->a);
590 if (ss->a->ops->freeopts)
591 ss->a->ops->freeopts(ss->ao);
594 /* free(ss->s.desc); */
595 ss->a->ops->destroy(ss->a);
596 ss->t->ops->destroy(ss->t);
597 source_remove(&ss->s);
602 /* --- Source definition block --- */
604 source_ops ssource_ops = {
606 ssource_option, ssource_read, ssource_attach, ssource_destroy
609 /*----- Target definition -------------------------------------------------*/
613 static target *starget_read(scanner *sc)
618 (void)(conf_prefix(sc, "socket") || conf_prefix(sc, "sk"));
619 st = CREATE(starget);
620 st->t.ops = &starget_ops;
621 st->a = getaddr(sc, ADDR_DEST);
622 dstr_puts(&d, "socket.");
623 st->a->ops->print(st->a, ADDR_DEST, &d);
624 st->t.desc = xstrdup(d.buf);
629 /* --- @create@ --- *
631 * Arguments: @target *t@ = pointer to target
632 * @const char *desc@ = description of connection
634 * Returns: Pointer to a created endpoint.
636 * Use: Generates a target endpoint for communication.
639 static endpt *starget_create(target *t, const char *desc)
641 starget *st = (starget *)t;
642 stept *e = CREATE(stept);
644 gen_addr *ga = (gen_addr *)st->a;
647 if ((fd = socket(st->a->ops->pf, SOCK_STREAM, 0)) < 0)
649 setsockopt(fd, SOL_SOCKET, SO_OOBINLINE, &opt, sizeof(opt));
650 fdflags(fd, O_NONBLOCK, O_NONBLOCK, FD_CLOEXEC, FD_CLOEXEC);
651 e->e.ops = &stept_ops;
653 e->e.f = EPF_FILE | SKF_CONN;
657 /* --- Pay attention --- *
659 * This bit is quite subtle. The connect can succeed or fail later: that's
660 * fine. The problem comes if it makes its mind up right now. The flag
661 * @SKF_CONN@ signifies that I'm trying to connect. I set it up to begin
662 * with and @stept_go@ turns it off when it's done: @stept_close@ uses it
663 * to decide whether to kill the connection. The flag @EPF_PENDING@ is
664 * only set after @conn_init@ returns and @SKF_CONN@ is still set (meaning
665 * that the connection is still in progress). That's used to let
666 * @stept_go@ know whether to kill the other endpoint. The flag
667 * @SKF_BROKEN@ is used to signify an immediate failure.
670 conn_init(&e->c, sel, fd, &ga->sa, ga->a.sz, stept_go, e);
671 if (e->e.f & SKF_BROKEN) {
675 if (e->e.f & SKF_CONN)
676 e->e.f |= EPF_PENDING;
681 /* --- @destroy@ --- */
683 static void starget_destroy(target *t)
685 starget *st = (starget *)t;
686 st->a->ops->destroy(st->a);
687 /* free(st->t.desc); */
691 /* --- Socket target definition block --- */
693 target_ops starget_ops = {
695 0, starget_read, starget_create, starget_destroy
698 /*----- That's all, folks -------------------------------------------------*/