3 * $Id: socket.c,v 1.2 1999/07/27 18:30:53 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.2 1999/07/27 18:30:53 mdw
33 * Various minor portability fixes.
35 * Revision 1.1 1999/07/26 23:33:32 mdw
36 * New sources and targets.
40 /*----- Header files ------------------------------------------------------*/
50 #include <sys/types.h>
53 #include <sys/socket.h>
54 #include <netinet/in.h>
55 #include <arpa/inet.h>
58 #include <mLib/alloc.h>
59 #include <mLib/conn.h>
60 #include <mLib/dstr.h>
61 #include <mLib/fdflags.h>
76 /*----- Data structures ---------------------------------------------------*/
78 /* --- Socket source options --- */
80 typedef struct ssource_opts {
84 static ssource_opts ssgo = { 256 };
86 /* --- Socket source --- */
88 typedef struct ssource {
97 /* --- Socket target --- */
99 typedef struct starget {
105 /* --- Socket target endpoint --- */
107 typedef struct stept {
113 /* --- Socket source endpoint --- */
115 typedef struct ssept {
121 #define SKF_BROKEN 32u
123 /*----- Protocol table ----------------------------------------------------*/
125 static addr_ops *addrs[] = { &inet_ops, &un_ops, 0 };
127 /*----- Other persistent variables ----------------------------------------*/
129 static addr_opts gao = { 0 };
131 /*----- Parsing address types ---------------------------------------------*/
133 /* --- @getaddrtype@ --- *
135 * Arguments: @scanner *sc@ = pointer to scanner (for error reporting)
136 * @const char *p@ = pointer to protocol name
137 * @int abbrev@ = nonzero to allow abbreviations
139 * Returns: Pointer to address operations table or null.
141 * Use: Looks up a protocol name. Handy when parsing addresses and
142 * other bits of configuration. Returns null if no matching
146 static addr_ops *getaddrtype(scanner *sc, const char *p, int abbrev)
149 addr_ops *chosen = 0;
150 size_t sz = strlen(p);
152 for (ops = addrs; *ops; ops++) {
153 if (strncmp((*ops)->name, p, sz) == 0) {
154 if ((*ops)->name[sz] == 0)
156 else if (chosen && abbrev)
157 error(sc, "ambiguous socket address type `%s'", p);
166 /* --- @getaddr@ --- *
168 * Arguments: @scanner *sc@ = pointer to scanner to read from
169 * @unsigned type@ = address type (@ADDR_SRC@ or @ADDR_DEST@)
171 * Returns: Pointer to an address successfully read.
173 * Use: Reads an optionally qualified address.
176 static addr *getaddr(scanner *sc, unsigned type)
185 if (sc->t == CTOK_WORD)
186 ops = getaddrtype(sc, sc->d.buf, abbrev);
190 error(sc, "unknown socket address type `%s'", sc->d.buf);
196 return (ops->read(sc, type));
199 /*----- Socket endpoints --------------------------------------------------*/
201 /* --- @wclose@ --- */
203 static void sept_wclose(endpt *e)
205 shutdown(e->out->fd, 1);
208 /* --- @close@ (source) --- */
210 static void ss_listen(ssource */*ss*/);
212 static void ssept_close(endpt *e)
214 ssept *ee = (ssept *)e;
216 if (!ee->s->o.conn) {
222 REFFD_DEC(ee->e.out);
227 /* --- @close@ (target) --- */
229 static void stept_close(endpt *e)
231 stept *ee = (stept *)e;
233 if (ee->e.f & EPF_PENDING) {
234 if (ee->e.f & SKF_CONN)
238 REFFD_DEC(ee->e.out);
245 /* --- @stept_go@ --- *
247 * Arguments: @int fd@ = file descriptor now ready for use
248 * @void *p@ = pointer to an endpoint structure
252 * Use: Handles successful connection of the target endpoint.
255 static void stept_go(int fd, void *p)
259 /* --- Complicated and subtle --- *
261 * This code interacts quite closely with @starget_create@, mainly through
262 * flags in the endpoint block.
264 * If the connection failed, I log a message (that's easy enough). The
265 * behaviour then depends on whether the endpoints have been joined yet.
266 * If not, I set @SKF_BROKEN@ and return, so that @starget_create@ can
267 * clean up the mess and return an immediate failure. If they have, I kill
268 * the connection and everything ought to work.
270 * If the connection worked, I clear @EPF_PENDING@ (as expected, because
271 * my endpoint is now ready), and @SKF_CONN@ (to let @starget_create@ know
272 * that the connection is already going). Then, only if this isn't the
273 * first attempt, I rejoin this endpoint to its partner.
277 fw_log(-1, "[%s] connection failed: %s", e->desc, strerror(errno));
279 if (e->e.f & EPF_PENDING)
282 e->e.f |= SKF_BROKEN;
284 reffd *r = reffd_init(fd);
286 e->e.in = e->e.out = r;
287 e->e.f &= ~(EPF_PENDING | SKF_CONN);
289 endpt_join(&e->e, e->e.other);
293 /* --- Socket endpoint definition --- */
295 static endpt_ops ssept_ops = {
296 0, sept_wclose, ssept_close
299 static endpt_ops stept_ops = {
300 0, sept_wclose, stept_close
303 /*----- Source definition -------------------------------------------------*/
305 /* --- @option@ --- */
307 static int ssource_option(source *s, scanner *sc)
309 ssource *ss = (ssource *)s;
310 ssource_opts *sso = ss ? &ss->o : &ssgo;
312 CONF_BEGIN(sc, "socket", "socket")
314 /* --- Make sure the next token is a word --- */
316 if (sc->t != CTOK_WORD)
317 error(sc, "parse error, option keyword expected");
319 /* --- Handle options at this level --- */
321 if (strcmp(sc->d.buf, "conn") == 0) {
325 if (sc->t != CTOK_WORD || !isdigit((unsigned char)sc->d.buf[0]))
326 error(sc, "parse error, argument of `conn' must be a number");
327 sso->conn = atoi(sc->d.buf);
329 error(sc, "argument of `conn' must be positive");
334 if (strcmp(sc->d.buf, "logging") == 0 ||
335 strcmp(sc->d.buf, "log") == 0) {
336 addr_opts *ao = ss ? ss->ao : &gao;
340 if (conf_enum(sc, "no,yes", ENUM_ABBREV, "logging status"))
341 ao->f &= ~ADDRF_NOLOG;
343 ao->f |= ADDRF_NOLOG;
347 /* --- Pass the option around the various address types --- */
350 if (ss->a->ops->option && ss->a->ops->option(sc, ss ? ss->ao : 0))
354 for (a = addrs; *a; a++) {
355 if ((*a)->option && (*a)->option(sc, 0))
360 /* --- Nobody understood the option --- */
367 static source *ssource_read(scanner *sc)
371 (void)(conf_prefix(sc, "socket") || conf_prefix(sc, "sk"));
372 ss = CREATE(ssource);
373 ss->s.ops = &ssource_ops;
376 ss->a = getaddr(sc, ADDR_SRC);
377 if (ss->a->ops->initopts)
378 ss->ao = ss->a->ops->initopts();
380 ss->ao = CREATE(addr_opts);
386 /* --- @ss_accept@ --- *
388 * Arguments: @int fd@ = file descriptor to accept from
389 * @unsigned mode@ = what's ready with the descriptor
390 * @void *p@ = pointer to the source definition
394 * Use: Accepts an incoming connection and attaches it to a target
398 static void ss_accept(int fd, unsigned mode, void *p)
405 /* --- Make the file descriptor --- */
409 if ((r = ss->a->ops->accept(fd, ss->ao, ss->s.desc)) == 0)
411 setsockopt(r->fd, SOL_SOCKET, SO_OOBINLINE, &opt, sizeof(opt));
412 fdflags(r->fd, O_NONBLOCK, O_NONBLOCK, FD_CLOEXEC, FD_CLOEXEC);
415 /* --- Make an endpoint --- */
418 e->e.ops = &ssept_ops;
422 e->e.in = e->e.out = r;
426 /* --- Obtain the target endpoint and let rip --- */
428 if ((ee = ss->t->ops->create(ss->t, ss->s.desc)) == 0) {
435 /* --- Remove the listening socket if necessary --- */
439 fw_log(-1, "[%s] maximum connections reached", ss->s.desc);
442 if (ss->a->ops->unbind)
443 ss->a->ops->unbind(ss->a);
446 /* --- Let everything else happen --- */
449 endpt_join(&e->e, ee);
452 /* --- @ss_listen@ --- *
454 * Arguments: @ssource *ss@ = source to listen on
458 * Use: Sets the socket to listen again, if it stopped for some
459 * reason. This is a copy of the code in the @read@ function,
460 * because it has different (wildly different) error handling
464 static void ssource_destroy(source */*s*/);
466 static void ss_listen(ssource *ss)
468 gen_addr *ga = (gen_addr *)ss->a;
471 fw_log(-1, "[%s] reattaching listener", ss->s.desc);
473 /* --- Make the socket --- */
475 if ((fd = socket(ga->a.ops->pf, SOCK_STREAM, 0)) < 0) {
476 fw_log(-1, "[%s] couldn't create socket: %s",
477 ss->s.desc, strerror(errno));
481 /* --- Set it to allow address reuse --- */
485 setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
486 fdflags(fd, O_NONBLOCK, O_NONBLOCK, FD_CLOEXEC, FD_CLOEXEC);
489 /* --- Bind it to the right port --- */
491 if (bind(fd, &ga->sa, ga->a.sz)) {
492 fw_log(-1, "[%s] couldn't bind to %s: %s", ss->s.desc, strerror(errno));
495 if (ga->a.ops->bound)
496 ga->a.ops->bound(&ga->a, ss->ao);
498 /* --- Set it to listen for connections --- */
501 fw_log(-1, "[%s] couldn't listen on socket: %s",
502 ss->s.desc, strerror(errno));
506 /* --- Set the listener up again --- */
512 /* --- Tidy up if it failed --- *
514 * I'll just remove the entire source.
521 ssource_destroy(&ss->s);
524 /* --- @attach@ --- */
526 static void ssource_attach(source *s, scanner *sc, target *t)
528 ssource *ss = (ssource *)s;
533 /* --- Initialize the description string --- */
537 dstr_puts(&d, "socket.");
538 ss->a->ops->print(ss->a, ADDR_SRC, &d);
539 dstr_puts(&d, " -> ");
540 dstr_puts(&d, ss->t->desc);
541 ss->s.desc = xstrdup(d.buf);
545 /* --- Initialize the socket for listening --- */
548 gen_addr *ga = (gen_addr *)ss->a;
550 /* --- Make the socket --- */
552 if ((fd = socket(ga->a.ops->pf, SOCK_STREAM, 0)) < 0)
553 error(sc, "couldn't create socket: %s", strerror(errno));
555 /* --- Set it to allow address reuse --- */
559 setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
560 fdflags(fd, O_NONBLOCK, O_NONBLOCK, FD_CLOEXEC, FD_CLOEXEC);
563 /* --- Bind it to the right port --- */
565 if (bind(fd, &ga->sa, ga->a.sz))
566 error(sc, "couldn't bind to %s: %s", ss->s.desc, strerror(errno));
567 if (ga->a.ops->bound)
568 ga->a.ops->bound(&ga->a, ss->ao);
570 /* --- Set it to listen for connections --- */
573 error(sc, "couldn't listen on socket: %s", strerror(errno));
576 /* --- We're ready to go now --- */
578 sel_initfile(sel, &ss->r, fd, SEL_READ, ss_accept, ss);
584 /* --- @destroy@ --- */
586 static void ssource_destroy(source *s)
588 ssource *ss = (ssource *)s;
593 if (ss->a->ops->unbind)
594 ss->a->ops->unbind(ss->a);
596 if (ss->a->ops->freeopts)
597 ss->a->ops->freeopts(ss->ao);
600 /* free(ss->s.desc); */
601 ss->a->ops->destroy(ss->a);
602 ss->t->ops->destroy(ss->t);
603 source_remove(&ss->s);
608 /* --- Source definition block --- */
610 source_ops ssource_ops = {
612 ssource_option, ssource_read, ssource_attach, ssource_destroy
615 /*----- Target definition -------------------------------------------------*/
619 static target *starget_read(scanner *sc)
624 (void)(conf_prefix(sc, "socket") || conf_prefix(sc, "sk"));
625 st = CREATE(starget);
626 st->t.ops = &starget_ops;
627 st->a = getaddr(sc, ADDR_DEST);
628 dstr_puts(&d, "socket.");
629 st->a->ops->print(st->a, ADDR_DEST, &d);
630 st->t.desc = xstrdup(d.buf);
635 /* --- @create@ --- *
637 * Arguments: @target *t@ = pointer to target
638 * @const char *desc@ = description of connection
640 * Returns: Pointer to a created endpoint.
642 * Use: Generates a target endpoint for communication.
645 static endpt *starget_create(target *t, const char *desc)
647 starget *st = (starget *)t;
648 stept *e = CREATE(stept);
650 gen_addr *ga = (gen_addr *)st->a;
653 if ((fd = socket(st->a->ops->pf, SOCK_STREAM, 0)) < 0)
655 setsockopt(fd, SOL_SOCKET, SO_OOBINLINE, &opt, sizeof(opt));
656 fdflags(fd, O_NONBLOCK, O_NONBLOCK, FD_CLOEXEC, FD_CLOEXEC);
657 e->e.ops = &stept_ops;
659 e->e.f = EPF_FILE | SKF_CONN;
663 /* --- Pay attention --- *
665 * This bit is quite subtle. The connect can succeed or fail later: that's
666 * fine. The problem comes if it makes its mind up right now. The flag
667 * @SKF_CONN@ signifies that I'm trying to connect. I set it up to begin
668 * with and @stept_go@ turns it off when it's done: @stept_close@ uses it
669 * to decide whether to kill the connection. The flag @EPF_PENDING@ is
670 * only set after @conn_init@ returns and @SKF_CONN@ is still set (meaning
671 * that the connection is still in progress). That's used to let
672 * @stept_go@ know whether to kill the other endpoint. The flag
673 * @SKF_BROKEN@ is used to signify an immediate failure.
676 conn_init(&e->c, sel, fd, &ga->sa, ga->a.sz, stept_go, e);
677 if (e->e.f & SKF_BROKEN) {
681 if (e->e.f & SKF_CONN)
682 e->e.f |= EPF_PENDING;
687 /* --- @destroy@ --- */
689 static void starget_destroy(target *t)
691 starget *st = (starget *)t;
692 st->a->ops->destroy(st->a);
693 /* free(st->t.desc); */
697 /* --- Socket target definition block --- */
699 target_ops starget_ops = {
701 0, starget_read, starget_create, starget_destroy
704 /*----- That's all, folks -------------------------------------------------*/