3 * $Id: socket.c,v 1.5 2000/03/23 23:20:42 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.5 2000/03/23 23:20:42 mdw
33 * Remove listener even if connection option isn't SOCKOPT_LIMITED.
35 * Revision 1.4 1999/12/22 15:44:25 mdw
38 * Revision 1.3 1999/10/22 22:48:36 mdw
39 * New connection options: unlimited concurrent connections, and one-shot
42 * Revision 1.2 1999/07/27 18:30:53 mdw
43 * Various minor portability fixes.
45 * Revision 1.1 1999/07/26 23:33:32 mdw
46 * New sources and targets.
50 /*----- Header files ------------------------------------------------------*/
61 #include <sys/types.h>
64 #include <sys/socket.h>
65 #include <netinet/in.h>
66 #include <arpa/inet.h>
69 #include <mLib/alloc.h>
70 #include <mLib/conn.h>
71 #include <mLib/dstr.h>
72 #include <mLib/fdflags.h>
87 /*----- Data structures ---------------------------------------------------*/
89 /* --- Socket source options --- */
91 typedef struct ssource_opts
{
96 static ssource_opts ssgo
= { 256, 0 };
98 #define SOCKOPT_LIMIT 0u
99 #define SOCKOPT_NOLIMIT 1u
100 #define SOCKOPT_ONESHOT 2u
102 /* --- Socket source --- */
104 typedef struct ssource
{
113 /* --- Socket target --- */
115 typedef struct starget
{
121 /* --- Socket target endpoint --- */
123 typedef struct stept
{
129 /* --- Socket source endpoint --- */
131 typedef struct ssept
{
137 #define SKF_BROKEN 32u
139 /*----- Protocol table ----------------------------------------------------*/
141 static addr_ops
*addrs
[] = { &inet_ops
, &un_ops
, 0 };
143 /*----- Other persistent variables ----------------------------------------*/
145 static addr_opts gao
= { 0 };
147 /*----- Parsing address types ---------------------------------------------*/
149 /* --- @getaddrtype@ --- *
151 * Arguments: @scanner *sc@ = pointer to scanner (for error reporting)
152 * @const char *p@ = pointer to protocol name
153 * @int abbrev@ = nonzero to allow abbreviations
155 * Returns: Pointer to address operations table or null.
157 * Use: Looks up a protocol name. Handy when parsing addresses and
158 * other bits of configuration. Returns null if no matching
162 static addr_ops
*getaddrtype(scanner
*sc
, const char *p
, int abbrev
)
165 addr_ops
*chosen
= 0;
166 size_t sz
= strlen(p
);
168 for (ops
= addrs
; *ops
; ops
++) {
169 if (strncmp((*ops
)->name
, p
, sz
) == 0) {
170 if ((*ops
)->name
[sz
] == 0)
172 else if (chosen
&& abbrev
)
173 error(sc
, "ambiguous socket address type `%s'", p
);
182 /* --- @getaddr@ --- *
184 * Arguments: @scanner *sc@ = pointer to scanner to read from
185 * @unsigned type@ = address type (@ADDR_SRC@ or @ADDR_DEST@)
187 * Returns: Pointer to an address successfully read.
189 * Use: Reads an optionally qualified address.
192 static addr
*getaddr(scanner
*sc
, unsigned type
)
201 if (sc
->t
== CTOK_WORD
)
202 ops
= getaddrtype(sc
, sc
->d
.buf
, abbrev
);
206 error(sc
, "unknown socket address type `%s'", sc
->d
.buf
);
212 return (ops
->read(sc
, type
));
215 /*----- Socket endpoints --------------------------------------------------*/
217 /* --- @wclose@ --- */
219 static void sept_wclose(endpt
*e
)
221 shutdown(e
->out
->fd
, 1);
224 /* --- @close@ (source) --- */
226 static void ss_listen(ssource */
*ss*/
);
228 static void ssept_close(endpt
*e
)
230 ssept
*ee
= (ssept
*)e
;
232 if (ee
->s
->o
.opt
== SOCKOPT_LIMIT
) {
234 if (ee
->s
->o
.conn
== 1)
238 REFFD_DEC(ee
->e
.out
);
243 /* --- @close@ (target) --- */
245 static void stept_close(endpt
*e
)
247 stept
*ee
= (stept
*)e
;
249 if (ee
->e
.f
& EPF_PENDING
) {
250 if (ee
->e
.f
& SKF_CONN
)
254 REFFD_DEC(ee
->e
.out
);
261 /* --- @stept_go@ --- *
263 * Arguments: @int fd@ = file descriptor now ready for use
264 * @void *p@ = pointer to an endpoint structure
268 * Use: Handles successful connection of the target endpoint.
271 static void stept_go(int fd
, void *p
)
275 /* --- Complicated and subtle --- *
277 * This code interacts quite closely with @starget_create@, mainly through
278 * flags in the endpoint block.
280 * If the connection failed, I log a message (that's easy enough). The
281 * behaviour then depends on whether the endpoints have been joined yet.
282 * If not, I set @SKF_BROKEN@ and return, so that @starget_create@ can
283 * clean up the mess and return an immediate failure. If they have, I kill
284 * the connection and everything ought to work.
286 * If the connection worked, I clear @EPF_PENDING@ (as expected, because
287 * my endpoint is now ready), and @SKF_CONN@ (to let @starget_create@ know
288 * that the connection is already going). Then, only if this isn't the
289 * first attempt, I rejoin this endpoint to its partner.
293 fw_log(-1, "[%s] connection failed: %s", e
->desc
, strerror(errno
));
295 if (e
->e
.f
& EPF_PENDING
)
298 e
->e
.f
|= SKF_BROKEN
;
300 reffd
*r
= reffd_init(fd
);
302 e
->e
.in
= e
->e
.out
= r
;
303 e
->e
.f
&= ~(EPF_PENDING
| SKF_CONN
);
305 endpt_join(&e
->e
, e
->e
.other
);
309 /* --- Socket endpoint definition --- */
311 static endpt_ops ssept_ops
= {
312 0, 0, sept_wclose
, ssept_close
315 static endpt_ops stept_ops
= {
316 0, 0, sept_wclose
, stept_close
319 /*----- Source definition -------------------------------------------------*/
321 /* --- @option@ --- */
323 static int ssource_option(source
*s
, scanner
*sc
)
325 ssource
*ss
= (ssource
*)s
;
326 ssource_opts
*sso
= ss ?
&ss
->o
: &ssgo
;
328 CONF_BEGIN(sc
, "socket", "socket")
330 /* --- Make sure the next token is a word --- */
332 if (sc
->t
!= CTOK_WORD
)
333 error(sc
, "parse error, option keyword expected");
335 /* --- Handle options at this level --- */
337 if (strcmp(sc
->d
.buf
, "conn") == 0) {
341 if (sc
->t
!= CTOK_WORD
)
342 error(sc
, "parse error, expected `unlimited', `one-shot' or number");
343 if (isdigit((unsigned char)sc
->d
.buf
[0])) {
344 sso
->conn
= atoi(sc
->d
.buf
);
346 error(sc
, "argument of `conn' must be positive");
347 sso
->opt
= SOCKOPT_LIMIT
;
351 sso
->opt
= 1 + (1 & conf_enum(sc
,
352 "unlimited,one-shot,infinite",
353 ENUM_ABBREV
, "`conn' option"));
358 if (strcmp(sc
->d
.buf
, "logging") == 0 ||
359 strcmp(sc
->d
.buf
, "log") == 0) {
360 addr_opts
*ao
= ss ? ss
->ao
: &gao
;
364 if (conf_enum(sc
, "no,yes", ENUM_ABBREV
, "logging status"))
365 ao
->f
&= ~ADDRF_NOLOG
;
367 ao
->f
|= ADDRF_NOLOG
;
371 /* --- Pass the option around the various address types --- */
374 if (ss
->a
->ops
->option
&& ss
->a
->ops
->option(sc
, ss ? ss
->ao
: 0))
378 for (a
= addrs
; *a
; a
++) {
379 if ((*a
)->option
&& (*a
)->option(sc
, 0))
384 /* --- Nobody understood the option --- */
391 static source
*ssource_read(scanner
*sc
)
395 (void)(conf_prefix(sc
, "socket") || conf_prefix(sc
, "sk"));
396 ss
= CREATE(ssource
);
397 ss
->s
.ops
= &ssource_ops
;
400 ss
->a
= getaddr(sc
, ADDR_SRC
);
401 if (ss
->a
->ops
->initopts
)
402 ss
->ao
= ss
->a
->ops
->initopts();
404 ss
->ao
= CREATE(addr_opts
);
410 /* --- @ss_accept@ --- *
412 * Arguments: @int fd@ = file descriptor to accept from
413 * @unsigned mode@ = what's ready with the descriptor
414 * @void *p@ = pointer to the source definition
418 * Use: Accepts an incoming connection and attaches it to a target
422 static void ssource_destroy(source */
*s*/
);
424 static void ss_accept(int fd
, unsigned mode
, void *p
)
431 /* --- Make the file descriptor --- */
435 if ((r
= ss
->a
->ops
->accept(fd
, ss
->ao
, ss
->s
.desc
)) == 0)
437 setsockopt(r
->fd
, SOL_SOCKET
, SO_OOBINLINE
, &opt
, sizeof(opt
));
438 fdflags(r
->fd
, O_NONBLOCK
, O_NONBLOCK
, FD_CLOEXEC
, FD_CLOEXEC
);
441 /* --- Make an endpoint --- */
444 e
->e
.ops
= &ssept_ops
;
448 e
->e
.in
= e
->e
.out
= r
;
452 /* --- Obtain the target endpoint and let rip --- */
454 if ((ee
= ss
->t
->ops
->create(ss
->t
, ss
->s
.desc
)) == 0) {
462 /* --- Remove the listening socket if necessary --- */
468 if (!(ss
->ao
->f
& ADDRF_NOLOG
))
469 fw_log(-1, "[%s] maximum connections reached", ss
->s
.desc
);
472 if (ss
->a
->ops
->unbind
)
473 ss
->a
->ops
->unbind(ss
->a
);
476 case SOCKOPT_NOLIMIT
:
478 case SOCKOPT_ONESHOT
:
481 if (ss
->a
->ops
->unbind
)
482 ss
->a
->ops
->unbind(ss
->a
);
483 ssource_destroy(&ss
->s
);
487 /* --- Let everything else happen --- */
489 endpt_join(&e
->e
, ee
);
492 /* --- @ss_listen@ --- *
494 * Arguments: @ssource *ss@ = source to listen on
498 * Use: Sets the socket to listen again, if it stopped for some
499 * reason. This is a copy of the code in the @read@ function,
500 * because it has different (wildly different) error handling
504 static void ss_listen(ssource
*ss
)
506 gen_addr
*ga
= (gen_addr
*)ss
->a
;
509 if (!(ss
->ao
->f
& ADDRF_NOLOG
))
510 fw_log(-1, "[%s] reattaching listener", ss
->s
.desc
);
512 /* --- Make the socket --- */
514 if ((fd
= socket(ga
->a
.ops
->pf
, SOCK_STREAM
, 0)) < 0) {
515 fw_log(-1, "[%s] couldn't create socket: %s",
516 ss
->s
.desc
, strerror(errno
));
520 /* --- Set it to allow address reuse --- */
524 setsockopt(fd
, SOL_SOCKET
, SO_REUSEADDR
, &opt
, sizeof(opt
));
525 fdflags(fd
, O_NONBLOCK
, O_NONBLOCK
, FD_CLOEXEC
, FD_CLOEXEC
);
528 /* --- Bind it to the right port --- */
530 if (bind(fd
, &ga
->sa
, ga
->a
.sz
)) {
531 fw_log(-1, "[%s] couldn't bind socket: %s", ss
->s
.desc
, strerror(errno
));
534 if (ga
->a
.ops
->bound
)
535 ga
->a
.ops
->bound(&ga
->a
, ss
->ao
);
537 /* --- Set it to listen for connections --- */
540 fw_log(-1, "[%s] couldn't listen on socket: %s",
541 ss
->s
.desc
, strerror(errno
));
545 /* --- Set the listener up again --- */
551 /* --- Tidy up if it failed --- *
553 * I'll just remove the entire source.
560 ssource_destroy(&ss
->s
);
563 /* --- @attach@ --- */
565 static void ssource_attach(source
*s
, scanner
*sc
, target
*t
)
567 ssource
*ss
= (ssource
*)s
;
572 /* --- Initialize the description string --- */
576 dstr_puts(&d
, "socket.");
577 ss
->a
->ops
->print(ss
->a
, ADDR_SRC
, &d
);
578 dstr_puts(&d
, " -> ");
579 dstr_puts(&d
, ss
->t
->desc
);
580 ss
->s
.desc
= xstrdup(d
.buf
);
584 /* --- Initialize the socket for listening --- */
587 gen_addr
*ga
= (gen_addr
*)ss
->a
;
589 /* --- Make the socket --- */
591 if ((fd
= socket(ga
->a
.ops
->pf
, SOCK_STREAM
, 0)) < 0)
592 error(sc
, "couldn't create socket: %s", strerror(errno
));
594 /* --- Set it to allow address reuse --- */
598 setsockopt(fd
, SOL_SOCKET
, SO_REUSEADDR
, &opt
, sizeof(opt
));
599 fdflags(fd
, O_NONBLOCK
, O_NONBLOCK
, FD_CLOEXEC
, FD_CLOEXEC
);
602 /* --- Bind it to the right port --- */
604 if (bind(fd
, &ga
->sa
, ga
->a
.sz
))
605 error(sc
, "couldn't bind to %s: %s", ss
->s
.desc
, strerror(errno
));
606 if (ga
->a
.ops
->bound
)
607 ga
->a
.ops
->bound(&ga
->a
, ss
->ao
);
609 /* --- Set it to listen for connections --- */
612 error(sc
, "couldn't listen on socket: %s", strerror(errno
));
615 /* --- We're ready to go now --- */
617 sel_initfile(sel
, &ss
->r
, fd
, SEL_READ
, ss_accept
, ss
);
623 /* --- @destroy@ --- */
625 static void ssource_destroy(source
*s
)
627 ssource
*ss
= (ssource
*)s
;
629 if (ss
->o
.conn
|| ss
->o
.opt
!= SOCKOPT_LIMIT
) {
632 if (ss
->a
->ops
->unbind
)
633 ss
->a
->ops
->unbind(ss
->a
);
635 if (ss
->a
->ops
->freeopts
)
636 ss
->a
->ops
->freeopts(ss
->ao
);
639 /* free(ss->s.desc); */
640 ss
->a
->ops
->destroy(ss
->a
);
641 ss
->t
->ops
->destroy(ss
->t
);
642 source_remove(&ss
->s
);
647 /* --- Source definition block --- */
649 source_ops ssource_ops
= {
651 ssource_option
, ssource_read
, ssource_attach
, ssource_destroy
654 /*----- Target definition -------------------------------------------------*/
658 static target
*starget_read(scanner
*sc
)
663 (void)(conf_prefix(sc
, "socket") || conf_prefix(sc
, "sk"));
664 st
= CREATE(starget
);
665 st
->t
.ops
= &starget_ops
;
666 st
->a
= getaddr(sc
, ADDR_DEST
);
667 dstr_puts(&d
, "socket.");
668 st
->a
->ops
->print(st
->a
, ADDR_DEST
, &d
);
669 st
->t
.desc
= xstrdup(d
.buf
);
674 /* --- @create@ --- *
676 * Arguments: @target *t@ = pointer to target
677 * @const char *desc@ = description of connection
679 * Returns: Pointer to a created endpoint.
681 * Use: Generates a target endpoint for communication.
684 static endpt
*starget_create(target
*t
, const char *desc
)
686 starget
*st
= (starget
*)t
;
687 stept
*e
= CREATE(stept
);
689 gen_addr
*ga
= (gen_addr
*)st
->a
;
692 if ((fd
= socket(st
->a
->ops
->pf
, SOCK_STREAM
, 0)) < 0)
694 setsockopt(fd
, SOL_SOCKET
, SO_OOBINLINE
, &opt
, sizeof(opt
));
695 fdflags(fd
, O_NONBLOCK
, O_NONBLOCK
, FD_CLOEXEC
, FD_CLOEXEC
);
696 e
->e
.ops
= &stept_ops
;
698 e
->e
.f
= EPF_FILE
| SKF_CONN
;
702 /* --- Pay attention --- *
704 * This bit is quite subtle. The connect can succeed or fail later: that's
705 * fine. The problem comes if it makes its mind up right now. The flag
706 * @SKF_CONN@ signifies that I'm trying to connect. I set it up to begin
707 * with and @stept_go@ turns it off when it's done: @stept_close@ uses it
708 * to decide whether to kill the connection. The flag @EPF_PENDING@ is
709 * only set after @conn_init@ returns and @SKF_CONN@ is still set (meaning
710 * that the connection is still in progress). That's used to let
711 * @stept_go@ know whether to kill the other endpoint. The flag
712 * @SKF_BROKEN@ is used to signify an immediate failure.
715 conn_init(&e
->c
, sel
, fd
, &ga
->sa
, ga
->a
.sz
, stept_go
, e
);
716 if (e
->e
.f
& SKF_BROKEN
) {
720 if (e
->e
.f
& SKF_CONN
)
721 e
->e
.f
|= EPF_PENDING
;
726 /* --- @destroy@ --- */
728 static void starget_destroy(target
*t
)
730 starget
*st
= (starget
*)t
;
731 st
->a
->ops
->destroy(st
->a
);
732 /* free(st->t.desc); */
736 /* --- Socket target definition block --- */
738 target_ops starget_ops
= {
740 0, starget_read
, starget_create
, starget_destroy
743 /*----- That's all, folks -------------------------------------------------*/