3 * $Id: socket.c,v 1.3 1999/10/22 22:48:36 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.3 1999/10/22 22:48:36 mdw
33 * New connection options: unlimited concurrent connections, and one-shot
36 * Revision 1.2 1999/07/27 18:30:53 mdw
37 * Various minor portability fixes.
39 * Revision 1.1 1999/07/26 23:33:32 mdw
40 * New sources and targets.
44 /*----- Header files ------------------------------------------------------*/
55 #include <sys/types.h>
58 #include <sys/socket.h>
59 #include <netinet/in.h>
60 #include <arpa/inet.h>
63 #include <mLib/alloc.h>
64 #include <mLib/conn.h>
65 #include <mLib/dstr.h>
66 #include <mLib/fdflags.h>
81 /*----- Data structures ---------------------------------------------------*/
83 /* --- Socket source options --- */
85 typedef struct ssource_opts
{
90 static ssource_opts ssgo
= { 256, 0 };
92 #define SOCKOPT_LIMIT 0u
93 #define SOCKOPT_NOLIMIT 1u
94 #define SOCKOPT_ONESHOT 2u
96 /* --- Socket source --- */
98 typedef struct ssource
{
107 /* --- Socket target --- */
109 typedef struct starget
{
115 /* --- Socket target endpoint --- */
117 typedef struct stept
{
123 /* --- Socket source endpoint --- */
125 typedef struct ssept
{
131 #define SKF_BROKEN 32u
133 /*----- Protocol table ----------------------------------------------------*/
135 static addr_ops
*addrs
[] = { &inet_ops
, &un_ops
, 0 };
137 /*----- Other persistent variables ----------------------------------------*/
139 static addr_opts gao
= { 0 };
141 /*----- Parsing address types ---------------------------------------------*/
143 /* --- @getaddrtype@ --- *
145 * Arguments: @scanner *sc@ = pointer to scanner (for error reporting)
146 * @const char *p@ = pointer to protocol name
147 * @int abbrev@ = nonzero to allow abbreviations
149 * Returns: Pointer to address operations table or null.
151 * Use: Looks up a protocol name. Handy when parsing addresses and
152 * other bits of configuration. Returns null if no matching
156 static addr_ops
*getaddrtype(scanner
*sc
, const char *p
, int abbrev
)
159 addr_ops
*chosen
= 0;
160 size_t sz
= strlen(p
);
162 for (ops
= addrs
; *ops
; ops
++) {
163 if (strncmp((*ops
)->name
, p
, sz
) == 0) {
164 if ((*ops
)->name
[sz
] == 0)
166 else if (chosen
&& abbrev
)
167 error(sc
, "ambiguous socket address type `%s'", p
);
176 /* --- @getaddr@ --- *
178 * Arguments: @scanner *sc@ = pointer to scanner to read from
179 * @unsigned type@ = address type (@ADDR_SRC@ or @ADDR_DEST@)
181 * Returns: Pointer to an address successfully read.
183 * Use: Reads an optionally qualified address.
186 static addr
*getaddr(scanner
*sc
, unsigned type
)
195 if (sc
->t
== CTOK_WORD
)
196 ops
= getaddrtype(sc
, sc
->d
.buf
, abbrev
);
200 error(sc
, "unknown socket address type `%s'", sc
->d
.buf
);
206 return (ops
->read(sc
, type
));
209 /*----- Socket endpoints --------------------------------------------------*/
211 /* --- @wclose@ --- */
213 static void sept_wclose(endpt
*e
)
215 shutdown(e
->out
->fd
, 1);
218 /* --- @close@ (source) --- */
220 static void ss_listen(ssource */
*ss*/
);
222 static void ssept_close(endpt
*e
)
224 ssept
*ee
= (ssept
*)e
;
226 if (ee
->s
->o
.opt
== SOCKOPT_LIMIT
) {
228 if (ee
->s
->o
.conn
== 1)
232 REFFD_DEC(ee
->e
.out
);
237 /* --- @close@ (target) --- */
239 static void stept_close(endpt
*e
)
241 stept
*ee
= (stept
*)e
;
243 if (ee
->e
.f
& EPF_PENDING
) {
244 if (ee
->e
.f
& SKF_CONN
)
248 REFFD_DEC(ee
->e
.out
);
255 /* --- @stept_go@ --- *
257 * Arguments: @int fd@ = file descriptor now ready for use
258 * @void *p@ = pointer to an endpoint structure
262 * Use: Handles successful connection of the target endpoint.
265 static void stept_go(int fd
, void *p
)
269 /* --- Complicated and subtle --- *
271 * This code interacts quite closely with @starget_create@, mainly through
272 * flags in the endpoint block.
274 * If the connection failed, I log a message (that's easy enough). The
275 * behaviour then depends on whether the endpoints have been joined yet.
276 * If not, I set @SKF_BROKEN@ and return, so that @starget_create@ can
277 * clean up the mess and return an immediate failure. If they have, I kill
278 * the connection and everything ought to work.
280 * If the connection worked, I clear @EPF_PENDING@ (as expected, because
281 * my endpoint is now ready), and @SKF_CONN@ (to let @starget_create@ know
282 * that the connection is already going). Then, only if this isn't the
283 * first attempt, I rejoin this endpoint to its partner.
287 fw_log(-1, "[%s] connection failed: %s", e
->desc
, strerror(errno
));
289 if (e
->e
.f
& EPF_PENDING
)
292 e
->e
.f
|= SKF_BROKEN
;
294 reffd
*r
= reffd_init(fd
);
296 e
->e
.in
= e
->e
.out
= r
;
297 e
->e
.f
&= ~(EPF_PENDING
| SKF_CONN
);
299 endpt_join(&e
->e
, e
->e
.other
);
303 /* --- Socket endpoint definition --- */
305 static endpt_ops ssept_ops
= {
306 0, 0, sept_wclose
, ssept_close
309 static endpt_ops stept_ops
= {
310 0, 0, sept_wclose
, stept_close
313 /*----- Source definition -------------------------------------------------*/
315 /* --- @option@ --- */
317 static int ssource_option(source
*s
, scanner
*sc
)
319 ssource
*ss
= (ssource
*)s
;
320 ssource_opts
*sso
= ss ?
&ss
->o
: &ssgo
;
322 CONF_BEGIN(sc
, "socket", "socket")
324 /* --- Make sure the next token is a word --- */
326 if (sc
->t
!= CTOK_WORD
)
327 error(sc
, "parse error, option keyword expected");
329 /* --- Handle options at this level --- */
331 if (strcmp(sc
->d
.buf
, "conn") == 0) {
335 if (sc
->t
!= CTOK_WORD
)
336 error(sc
, "parse error, expected `unlimited', `one-shot' or number");
337 if (isdigit((unsigned char)sc
->d
.buf
[0])) {
338 sso
->conn
= atoi(sc
->d
.buf
);
340 error(sc
, "argument of `conn' must be positive");
341 sso
->opt
= SOCKOPT_LIMIT
;
345 sso
->opt
= 1 + (1 & conf_enum(sc
,
346 "unlimited,one-shot,infinite",
347 ENUM_ABBREV
, "`conn' option"));
352 if (strcmp(sc
->d
.buf
, "logging") == 0 ||
353 strcmp(sc
->d
.buf
, "log") == 0) {
354 addr_opts
*ao
= ss ? ss
->ao
: &gao
;
358 if (conf_enum(sc
, "no,yes", ENUM_ABBREV
, "logging status"))
359 ao
->f
&= ~ADDRF_NOLOG
;
361 ao
->f
|= ADDRF_NOLOG
;
365 /* --- Pass the option around the various address types --- */
368 if (ss
->a
->ops
->option
&& ss
->a
->ops
->option(sc
, ss ? ss
->ao
: 0))
372 for (a
= addrs
; *a
; a
++) {
373 if ((*a
)->option
&& (*a
)->option(sc
, 0))
378 /* --- Nobody understood the option --- */
385 static source
*ssource_read(scanner
*sc
)
389 (void)(conf_prefix(sc
, "socket") || conf_prefix(sc
, "sk"));
390 ss
= CREATE(ssource
);
391 ss
->s
.ops
= &ssource_ops
;
394 ss
->a
= getaddr(sc
, ADDR_SRC
);
395 if (ss
->a
->ops
->initopts
)
396 ss
->ao
= ss
->a
->ops
->initopts();
398 ss
->ao
= CREATE(addr_opts
);
404 /* --- @ss_accept@ --- *
406 * Arguments: @int fd@ = file descriptor to accept from
407 * @unsigned mode@ = what's ready with the descriptor
408 * @void *p@ = pointer to the source definition
412 * Use: Accepts an incoming connection and attaches it to a target
416 static void ssource_destroy(source */
*s*/
);
418 static void ss_accept(int fd
, unsigned mode
, void *p
)
425 /* --- Make the file descriptor --- */
429 if ((r
= ss
->a
->ops
->accept(fd
, ss
->ao
, ss
->s
.desc
)) == 0)
431 setsockopt(r
->fd
, SOL_SOCKET
, SO_OOBINLINE
, &opt
, sizeof(opt
));
432 fdflags(r
->fd
, O_NONBLOCK
, O_NONBLOCK
, FD_CLOEXEC
, FD_CLOEXEC
);
435 /* --- Make an endpoint --- */
438 e
->e
.ops
= &ssept_ops
;
442 e
->e
.in
= e
->e
.out
= r
;
446 /* --- Obtain the target endpoint and let rip --- */
448 if ((ee
= ss
->t
->ops
->create(ss
->t
, ss
->s
.desc
)) == 0) {
456 /* --- Remove the listening socket if necessary --- */
462 if (!(ss
->ao
->f
& ADDRF_NOLOG
))
463 fw_log(-1, "[%s] maximum connections reached", ss
->s
.desc
);
466 if (ss
->a
->ops
->unbind
)
467 ss
->a
->ops
->unbind(ss
->a
);
470 case SOCKOPT_NOLIMIT
:
472 case SOCKOPT_ONESHOT
:
475 if (ss
->a
->ops
->unbind
)
476 ss
->a
->ops
->unbind(ss
->a
);
477 ssource_destroy(&ss
->s
);
481 /* --- Let everything else happen --- */
483 endpt_join(&e
->e
, ee
);
486 /* --- @ss_listen@ --- *
488 * Arguments: @ssource *ss@ = source to listen on
492 * Use: Sets the socket to listen again, if it stopped for some
493 * reason. This is a copy of the code in the @read@ function,
494 * because it has different (wildly different) error handling
498 static void ss_listen(ssource
*ss
)
500 gen_addr
*ga
= (gen_addr
*)ss
->a
;
503 if (!(ss
->ao
->f
& ADDRF_NOLOG
))
504 fw_log(-1, "[%s] reattaching listener", ss
->s
.desc
);
506 /* --- Make the socket --- */
508 if ((fd
= socket(ga
->a
.ops
->pf
, SOCK_STREAM
, 0)) < 0) {
509 fw_log(-1, "[%s] couldn't create socket: %s",
510 ss
->s
.desc
, strerror(errno
));
514 /* --- Set it to allow address reuse --- */
518 setsockopt(fd
, SOL_SOCKET
, SO_REUSEADDR
, &opt
, sizeof(opt
));
519 fdflags(fd
, O_NONBLOCK
, O_NONBLOCK
, FD_CLOEXEC
, FD_CLOEXEC
);
522 /* --- Bind it to the right port --- */
524 if (bind(fd
, &ga
->sa
, ga
->a
.sz
)) {
525 fw_log(-1, "[%s] couldn't bind to %s: %s", ss
->s
.desc
, strerror(errno
));
528 if (ga
->a
.ops
->bound
)
529 ga
->a
.ops
->bound(&ga
->a
, ss
->ao
);
531 /* --- Set it to listen for connections --- */
534 fw_log(-1, "[%s] couldn't listen on socket: %s",
535 ss
->s
.desc
, strerror(errno
));
539 /* --- Set the listener up again --- */
545 /* --- Tidy up if it failed --- *
547 * I'll just remove the entire source.
554 ssource_destroy(&ss
->s
);
557 /* --- @attach@ --- */
559 static void ssource_attach(source
*s
, scanner
*sc
, target
*t
)
561 ssource
*ss
= (ssource
*)s
;
566 /* --- Initialize the description string --- */
570 dstr_puts(&d
, "socket.");
571 ss
->a
->ops
->print(ss
->a
, ADDR_SRC
, &d
);
572 dstr_puts(&d
, " -> ");
573 dstr_puts(&d
, ss
->t
->desc
);
574 ss
->s
.desc
= xstrdup(d
.buf
);
578 /* --- Initialize the socket for listening --- */
581 gen_addr
*ga
= (gen_addr
*)ss
->a
;
583 /* --- Make the socket --- */
585 if ((fd
= socket(ga
->a
.ops
->pf
, SOCK_STREAM
, 0)) < 0)
586 error(sc
, "couldn't create socket: %s", strerror(errno
));
588 /* --- Set it to allow address reuse --- */
592 setsockopt(fd
, SOL_SOCKET
, SO_REUSEADDR
, &opt
, sizeof(opt
));
593 fdflags(fd
, O_NONBLOCK
, O_NONBLOCK
, FD_CLOEXEC
, FD_CLOEXEC
);
596 /* --- Bind it to the right port --- */
598 if (bind(fd
, &ga
->sa
, ga
->a
.sz
))
599 error(sc
, "couldn't bind to %s: %s", ss
->s
.desc
, strerror(errno
));
600 if (ga
->a
.ops
->bound
)
601 ga
->a
.ops
->bound(&ga
->a
, ss
->ao
);
603 /* --- Set it to listen for connections --- */
606 error(sc
, "couldn't listen on socket: %s", strerror(errno
));
609 /* --- We're ready to go now --- */
611 sel_initfile(sel
, &ss
->r
, fd
, SEL_READ
, ss_accept
, ss
);
617 /* --- @destroy@ --- */
619 static void ssource_destroy(source
*s
)
621 ssource
*ss
= (ssource
*)s
;
626 if (ss
->a
->ops
->unbind
)
627 ss
->a
->ops
->unbind(ss
->a
);
629 if (ss
->a
->ops
->freeopts
)
630 ss
->a
->ops
->freeopts(ss
->ao
);
633 /* free(ss->s.desc); */
634 ss
->a
->ops
->destroy(ss
->a
);
635 ss
->t
->ops
->destroy(ss
->t
);
636 source_remove(&ss
->s
);
641 /* --- Source definition block --- */
643 source_ops ssource_ops
= {
645 ssource_option
, ssource_read
, ssource_attach
, ssource_destroy
648 /*----- Target definition -------------------------------------------------*/
652 static target
*starget_read(scanner
*sc
)
657 (void)(conf_prefix(sc
, "socket") || conf_prefix(sc
, "sk"));
658 st
= CREATE(starget
);
659 st
->t
.ops
= &starget_ops
;
660 st
->a
= getaddr(sc
, ADDR_DEST
);
661 dstr_puts(&d
, "socket.");
662 st
->a
->ops
->print(st
->a
, ADDR_DEST
, &d
);
663 st
->t
.desc
= xstrdup(d
.buf
);
668 /* --- @create@ --- *
670 * Arguments: @target *t@ = pointer to target
671 * @const char *desc@ = description of connection
673 * Returns: Pointer to a created endpoint.
675 * Use: Generates a target endpoint for communication.
678 static endpt
*starget_create(target
*t
, const char *desc
)
680 starget
*st
= (starget
*)t
;
681 stept
*e
= CREATE(stept
);
683 gen_addr
*ga
= (gen_addr
*)st
->a
;
686 if ((fd
= socket(st
->a
->ops
->pf
, SOCK_STREAM
, 0)) < 0)
688 setsockopt(fd
, SOL_SOCKET
, SO_OOBINLINE
, &opt
, sizeof(opt
));
689 fdflags(fd
, O_NONBLOCK
, O_NONBLOCK
, FD_CLOEXEC
, FD_CLOEXEC
);
690 e
->e
.ops
= &stept_ops
;
692 e
->e
.f
= EPF_FILE
| SKF_CONN
;
696 /* --- Pay attention --- *
698 * This bit is quite subtle. The connect can succeed or fail later: that's
699 * fine. The problem comes if it makes its mind up right now. The flag
700 * @SKF_CONN@ signifies that I'm trying to connect. I set it up to begin
701 * with and @stept_go@ turns it off when it's done: @stept_close@ uses it
702 * to decide whether to kill the connection. The flag @EPF_PENDING@ is
703 * only set after @conn_init@ returns and @SKF_CONN@ is still set (meaning
704 * that the connection is still in progress). That's used to let
705 * @stept_go@ know whether to kill the other endpoint. The flag
706 * @SKF_BROKEN@ is used to signify an immediate failure.
709 conn_init(&e
->c
, sel
, fd
, &ga
->sa
, ga
->a
.sz
, stept_go
, e
);
710 if (e
->e
.f
& SKF_BROKEN
) {
714 if (e
->e
.f
& SKF_CONN
)
715 e
->e
.f
|= EPF_PENDING
;
720 /* --- @destroy@ --- */
722 static void starget_destroy(target
*t
)
724 starget
*st
= (starget
*)t
;
725 st
->a
->ops
->destroy(st
->a
);
726 /* free(st->t.desc); */
730 /* --- Socket target definition block --- */
732 target_ops starget_ops
= {
734 0, starget_read
, starget_create
, starget_destroy
737 /*----- That's all, folks -------------------------------------------------*/