Remove listener even if connection option isn't SOCKOPT_LIMITED.
[fwd] / socket.c
CommitLineData
48bb1f76 1/* -*-c-*-
2 *
14865057 3 * $Id: socket.c,v 1.5 2000/03/23 23:20:42 mdw Exp $
48bb1f76 4 *
5 * Socket source and target definitions
6 *
7 * (c) 1999 Straylight/Edgeware
8 */
9
10/*----- Licensing notice --------------------------------------------------*
11 *
12 * This file is part of the `fw' port forwarder.
13 *
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.
18 *
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.
23 *
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.
27 */
28
29/*----- Revision history --------------------------------------------------*
30 *
31 * $Log: socket.c,v $
14865057 32 * Revision 1.5 2000/03/23 23:20:42 mdw
33 * Remove listener even if connection option isn't SOCKOPT_LIMITED.
34 *
20922c31 35 * Revision 1.4 1999/12/22 15:44:25 mdw
36 * Fix log message.
37 *
0fe44b09 38 * Revision 1.3 1999/10/22 22:48:36 mdw
39 * New connection options: unlimited concurrent connections, and one-shot
40 * listening sockets.
41 *
e0ce9d38 42 * Revision 1.2 1999/07/27 18:30:53 mdw
43 * Various minor portability fixes.
44 *
48bb1f76 45 * Revision 1.1 1999/07/26 23:33:32 mdw
46 * New sources and targets.
47 *
48 */
49
50/*----- Header files ------------------------------------------------------*/
51
52#include "config.h"
53
54#include <ctype.h>
55#include <errno.h>
0fe44b09 56#include <limits.h>
48bb1f76 57#include <stdio.h>
58#include <stdlib.h>
59#include <string.h>
60
e0ce9d38 61#include <sys/types.h>
62#include <unistd.h>
63
48bb1f76 64#include <sys/socket.h>
65#include <netinet/in.h>
66#include <arpa/inet.h>
67#include <netdb.h>
68
69#include <mLib/alloc.h>
70#include <mLib/conn.h>
71#include <mLib/dstr.h>
72#include <mLib/fdflags.h>
73#include <mLib/sel.h>
74#include <mLib/sub.h>
75
76#include "addr.h"
77#include "conf.h"
78#include "endpt.h"
79#include "fw.h"
80#include "scan.h"
81#include "socket.h"
82#include "target.h"
83
84#include "inet.h"
85#include "un.h"
86
87/*----- Data structures ---------------------------------------------------*/
88
89/* --- Socket source options --- */
90
91typedef struct ssource_opts {
0fe44b09 92 unsigned opt;
48bb1f76 93 unsigned conn;
94} ssource_opts;
95
0fe44b09 96static ssource_opts ssgo = { 256, 0 };
97
98#define SOCKOPT_LIMIT 0u
99#define SOCKOPT_NOLIMIT 1u
100#define SOCKOPT_ONESHOT 2u
48bb1f76 101
102/* --- Socket source --- */
103
104typedef struct ssource {
105 source s;
106 addr *a;
107 target *t;
108 addr_opts *ao;
109 ssource_opts o;
110 sel_file r;
111} ssource;
112
113/* --- Socket target --- */
114
115typedef struct starget {
116 target t;
117 addr *a;
118 addr_opts *ao;
119} starget;
120
121/* --- Socket target endpoint --- */
122
123typedef struct stept {
124 endpt e;
125 conn c;
126 const char *desc;
127} stept;
128
129/* --- Socket source endpoint --- */
130
131typedef struct ssept {
132 endpt e;
133 ssource *s;
134} ssept;
135
136#define SKF_CONN 16u
137#define SKF_BROKEN 32u
138
139/*----- Protocol table ----------------------------------------------------*/
140
141static addr_ops *addrs[] = { &inet_ops, &un_ops, 0 };
142
143/*----- Other persistent variables ----------------------------------------*/
144
145static addr_opts gao = { 0 };
146
147/*----- Parsing address types ---------------------------------------------*/
148
149/* --- @getaddrtype@ --- *
150 *
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
154 *
155 * Returns: Pointer to address operations table or null.
156 *
157 * Use: Looks up a protocol name. Handy when parsing addresses and
158 * other bits of configuration. Returns null if no matching
159 * address was found.
160 */
161
162static addr_ops *getaddrtype(scanner *sc, const char *p, int abbrev)
163{
164 addr_ops **ops;
165 addr_ops *chosen = 0;
166 size_t sz = strlen(p);
167
168 for (ops = addrs; *ops; ops++) {
169 if (strncmp((*ops)->name, p, sz) == 0) {
170 if ((*ops)->name[sz] == 0)
171 return (*ops);
172 else if (chosen && abbrev)
173 error(sc, "ambiguous socket address type `%s'", p);
174 chosen = *ops;
175 }
176 }
177 if (!abbrev)
178 return (0);
179 return (chosen);
180}
181
182/* --- @getaddr@ --- *
183 *
184 * Arguments: @scanner *sc@ = pointer to scanner to read from
185 * @unsigned type@ = address type (@ADDR_SRC@ or @ADDR_DEST@)
186 *
187 * Returns: Pointer to an address successfully read.
188 *
189 * Use: Reads an optionally qualified address.
190 */
191
192static addr *getaddr(scanner *sc, unsigned type)
193{
194 addr_ops *ops = 0;
195 int abbrev = 0;
196
197 if (sc->t == ':') {
198 token(sc);
199 abbrev = 1;
200 }
201 if (sc->t == CTOK_WORD)
202 ops = getaddrtype(sc, sc->d.buf, abbrev);
203 if (ops)
204 token(sc);
205 else if (abbrev)
206 error(sc, "unknown socket address type `%s'", sc->d.buf);
207 else
208 ops = &inet_ops;
209 if (sc->t == ':')
210 token(sc);
211
212 return (ops->read(sc, type));
213}
214
215/*----- Socket endpoints --------------------------------------------------*/
216
217/* --- @wclose@ --- */
218
219static void sept_wclose(endpt *e)
220{
221 shutdown(e->out->fd, 1);
222}
223
224/* --- @close@ (source) --- */
225
226static void ss_listen(ssource */*ss*/);
227
228static void ssept_close(endpt *e)
229{
230 ssept *ee = (ssept *)e;
231
0fe44b09 232 if (ee->s->o.opt == SOCKOPT_LIMIT) {
48bb1f76 233 ee->s->o.conn++;
0fe44b09 234 if (ee->s->o.conn == 1)
235 ss_listen(ee->s);
236 }
48bb1f76 237 REFFD_DEC(ee->e.in);
238 REFFD_DEC(ee->e.out);
239 fw_dec();
240 DESTROY(ee);
241}
242
243/* --- @close@ (target) --- */
244
245static void stept_close(endpt *e)
246{
247 stept *ee = (stept *)e;
248
249 if (ee->e.f & EPF_PENDING) {
250 if (ee->e.f & SKF_CONN)
251 conn_kill(&ee->c);
252 } else {
253 REFFD_DEC(ee->e.in);
254 REFFD_DEC(ee->e.out);
255 }
256
257 fw_dec();
258 DESTROY(ee);
259}
260
261/* --- @stept_go@ --- *
262 *
263 * Arguments: @int fd@ = file descriptor now ready for use
264 * @void *p@ = pointer to an endpoint structure
265 *
266 * Returns: ---
267 *
268 * Use: Handles successful connection of the target endpoint.
269 */
270
271static void stept_go(int fd, void *p)
272{
273 stept *e = p;
274
275 /* --- Complicated and subtle --- *
276 *
277 * This code interacts quite closely with @starget_create@, mainly through
278 * flags in the endpoint block.
279 *
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.
285 *
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.
290 */
291
292 if (fd == -1) {
293 fw_log(-1, "[%s] connection failed: %s", e->desc, strerror(errno));
294 e->e.f &= ~SKF_CONN;
295 if (e->e.f & EPF_PENDING)
296 endpt_kill(&e->e);
297 else
298 e->e.f |= SKF_BROKEN;
299 } else {
300 reffd *r = reffd_init(fd);
301 REFFD_INC(r);
302 e->e.in = e->e.out = r;
303 e->e.f &= ~(EPF_PENDING | SKF_CONN);
304 if (e->e.other)
305 endpt_join(&e->e, e->e.other);
306 }
307}
308
309/* --- Socket endpoint definition --- */
310
311static endpt_ops ssept_ops = {
0fe44b09 312 0, 0, sept_wclose, ssept_close
48bb1f76 313};
314
315static endpt_ops stept_ops = {
0fe44b09 316 0, 0, sept_wclose, stept_close
48bb1f76 317};
318
319/*----- Source definition -------------------------------------------------*/
320
321/* --- @option@ --- */
322
323static int ssource_option(source *s, scanner *sc)
324{
325 ssource *ss = (ssource *)s;
326 ssource_opts *sso = ss ? &ss->o : &ssgo;
327
328 CONF_BEGIN(sc, "socket", "socket")
329
330 /* --- Make sure the next token is a word --- */
331
332 if (sc->t != CTOK_WORD)
333 error(sc, "parse error, option keyword expected");
334
335 /* --- Handle options at this level --- */
336
337 if (strcmp(sc->d.buf, "conn") == 0) {
338 token(sc);
339 if (sc->t == '=')
340 token(sc);
0fe44b09 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);
345 if (sso->conn == 0)
346 error(sc, "argument of `conn' must be positive");
347 sso->opt = SOCKOPT_LIMIT;
348 token(sc);
349 } else {
350 sso->conn = 0;
351 sso->opt = 1 + (1 & conf_enum(sc,
352 "unlimited,one-shot,infinite",
353 ENUM_ABBREV, "`conn' option"));
354 }
48bb1f76 355 CONF_ACCEPT;
356 }
357
358 if (strcmp(sc->d.buf, "logging") == 0 ||
359 strcmp(sc->d.buf, "log") == 0) {
360 addr_opts *ao = ss ? ss->ao : &gao;
361 token(sc);
362 if (sc->t == '=')
363 token(sc);
364 if (conf_enum(sc, "no,yes", ENUM_ABBREV, "logging status"))
365 ao->f &= ~ADDRF_NOLOG;
366 else
367 ao->f |= ADDRF_NOLOG;
368 CONF_ACCEPT;
369 }
370
371 /* --- Pass the option around the various address types --- */
372
373 if (ss) {
374 if (ss->a->ops->option && ss->a->ops->option(sc, ss ? ss->ao : 0))
375 CONF_ACCEPT;
376 } else {
377 addr_ops **a;
378 for (a = addrs; *a; a++) {
379 if ((*a)->option && (*a)->option(sc, 0))
380 CONF_ACCEPT;
381 }
382 }
383
384 /* --- Nobody understood the option --- */
385
386 CONF_END;
387}
388
389/* --- @read@ --- */
390
391static source *ssource_read(scanner *sc)
392{
393 ssource *ss;
394
395 (void)(conf_prefix(sc, "socket") || conf_prefix(sc, "sk"));
396 ss = CREATE(ssource);
397 ss->s.ops = &ssource_ops;
398 ss->s.desc = 0;
399 ss->t = 0;
400 ss->a = getaddr(sc, ADDR_SRC);
401 if (ss->a->ops->initopts)
402 ss->ao = ss->a->ops->initopts();
403 else
404 ss->ao = CREATE(addr_opts);
405 *ss->ao = gao;
406 ss->o = ssgo;
407 return (&ss->s);
408}
409
410/* --- @ss_accept@ --- *
411 *
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
415 *
416 * Returns: ---
417 *
418 * Use: Accepts an incoming connection and attaches it to a target
419 * endpoint.
420 */
421
0fe44b09 422static void ssource_destroy(source */*s*/);
423
48bb1f76 424static void ss_accept(int fd, unsigned mode, void *p)
425{
426 ssource *ss = p;
427 ssept *e;
428 endpt *ee;
429 reffd *r;
430
431 /* --- Make the file descriptor --- */
432
433 {
434 int opt = 1;
435 if ((r = ss->a->ops->accept(fd, ss->ao, ss->s.desc)) == 0)
436 return;
437 setsockopt(r->fd, SOL_SOCKET, SO_OOBINLINE, &opt, sizeof(opt));
438 fdflags(r->fd, O_NONBLOCK, O_NONBLOCK, FD_CLOEXEC, FD_CLOEXEC);
439 }
440
441 /* --- Make an endpoint --- */
442
443 e = CREATE(ssept);
444 e->e.ops = &ssept_ops;
445 e->e.other = 0;
446 e->e.f = EPF_FILE;
447 e->e.t = 0;
448 e->e.in = e->e.out = r;
449 e->s = ss;
450 REFFD_INC(r);
451
452 /* --- Obtain the target endpoint and let rip --- */
453
454 if ((ee = ss->t->ops->create(ss->t, ss->s.desc)) == 0) {
455 REFFD_DEC(r);
456 REFFD_DEC(r);
457 DESTROY(e);
458 return;
459 }
0fe44b09 460 fw_inc();
48bb1f76 461
462 /* --- Remove the listening socket if necessary --- */
463
0fe44b09 464 switch (ss->o.opt) {
465 case SOCKOPT_LIMIT:
466 ss->o.conn--;
467 if (!ss->o.conn) {
468 if (!(ss->ao->f & ADDRF_NOLOG))
469 fw_log(-1, "[%s] maximum connections reached", ss->s.desc);
470 sel_rmfile(&ss->r);
471 close(ss->r.fd);
472 if (ss->a->ops->unbind)
473 ss->a->ops->unbind(ss->a);
474 }
475 break;
476 case SOCKOPT_NOLIMIT:
477 break;
478 case SOCKOPT_ONESHOT:
479 sel_rmfile(&ss->r);
480 close(ss->r.fd);
481 if (ss->a->ops->unbind)
482 ss->a->ops->unbind(ss->a);
483 ssource_destroy(&ss->s);
484 break;
48bb1f76 485 }
486
487 /* --- Let everything else happen --- */
488
48bb1f76 489 endpt_join(&e->e, ee);
490}
491
492/* --- @ss_listen@ --- *
493 *
494 * Arguments: @ssource *ss@ = source to listen on
495 *
496 * Returns: ---
497 *
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
501 * behaviour.
502 */
503
48bb1f76 504static void ss_listen(ssource *ss)
505{
506 gen_addr *ga = (gen_addr *)ss->a;
507 int fd;
508
0fe44b09 509 if (!(ss->ao->f & ADDRF_NOLOG))
510 fw_log(-1, "[%s] reattaching listener", ss->s.desc);
48bb1f76 511
512 /* --- Make the socket --- */
513
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));
517 goto fail_0;
518 }
519
520 /* --- Set it to allow address reuse --- */
521
522 {
523 int opt = 1;
524 setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
525 fdflags(fd, O_NONBLOCK, O_NONBLOCK, FD_CLOEXEC, FD_CLOEXEC);
526 }
527
528 /* --- Bind it to the right port --- */
529
530 if (bind(fd, &ga->sa, ga->a.sz)) {
20922c31 531 fw_log(-1, "[%s] couldn't bind socket: %s", ss->s.desc, strerror(errno));
48bb1f76 532 goto fail_1;
533 }
534 if (ga->a.ops->bound)
535 ga->a.ops->bound(&ga->a, ss->ao);
536
537 /* --- Set it to listen for connections --- */
538
539 if (listen(fd, 5)) {
540 fw_log(-1, "[%s] couldn't listen on socket: %s",
541 ss->s.desc, strerror(errno));
542 goto fail_1;
543 }
544
545 /* --- Set the listener up again --- */
546
547 ss->r.fd = fd;
548 sel_addfile(&ss->r);
549 return;
550
551 /* --- Tidy up if it failed --- *
552 *
553 * I'll just remove the entire source.
554 */
555
556fail_1:
557 close(fd);
558fail_0:
559 ss->o.conn = 0;
560 ssource_destroy(&ss->s);
561}
562
563/* --- @attach@ --- */
564
565static void ssource_attach(source *s, scanner *sc, target *t)
566{
567 ssource *ss = (ssource *)s;
568 int fd;
569
570 ss->t = t;
571
572 /* --- Initialize the description string --- */
573
574 {
575 dstr d = DSTR_INIT;
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);
581 dstr_destroy(&d);
582 }
583
584 /* --- Initialize the socket for listening --- */
585
586 {
587 gen_addr *ga = (gen_addr *)ss->a;
588
589 /* --- Make the socket --- */
590
591 if ((fd = socket(ga->a.ops->pf, SOCK_STREAM, 0)) < 0)
592 error(sc, "couldn't create socket: %s", strerror(errno));
593
594 /* --- Set it to allow address reuse --- */
595
596 {
597 int opt = 1;
598 setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
599 fdflags(fd, O_NONBLOCK, O_NONBLOCK, FD_CLOEXEC, FD_CLOEXEC);
600 }
601
602 /* --- Bind it to the right port --- */
603
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);
608
609 /* --- Set it to listen for connections --- */
610
611 if (listen(fd, 5))
612 error(sc, "couldn't listen on socket: %s", strerror(errno));
613 }
614
615 /* --- We're ready to go now --- */
616
617 sel_initfile(sel, &ss->r, fd, SEL_READ, ss_accept, ss);
618 sel_addfile(&ss->r);
619 source_add(&ss->s);
620 fw_inc();
621}
622
623/* --- @destroy@ --- */
624
625static void ssource_destroy(source *s)
626{
627 ssource *ss = (ssource *)s;
628
14865057 629 if (ss->o.conn || ss->o.opt != SOCKOPT_LIMIT) {
48bb1f76 630 sel_rmfile(&ss->r);
631 close(ss->r.fd);
632 if (ss->a->ops->unbind)
633 ss->a->ops->unbind(ss->a);
634 }
635 if (ss->a->ops->freeopts)
636 ss->a->ops->freeopts(ss->ao);
637 else
638 DESTROY(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);
643 DESTROY(ss);
644 fw_dec();
645}
646
647/* --- Source definition block --- */
648
649source_ops ssource_ops = {
650 "socket",
651 ssource_option, ssource_read, ssource_attach, ssource_destroy
652};
653
654/*----- Target definition -------------------------------------------------*/
655
656/* --- @read@ --- */
657
658static target *starget_read(scanner *sc)
659{
660 starget *st;
661 dstr d = DSTR_INIT;
662
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);
670 dstr_destroy(&d);
671 return (&st->t);
672}
673
674/* --- @create@ --- *
675 *
676 * Arguments: @target *t@ = pointer to target
677 * @const char *desc@ = description of connection
678 *
679 * Returns: Pointer to a created endpoint.
680 *
681 * Use: Generates a target endpoint for communication.
682 */
683
684static endpt *starget_create(target *t, const char *desc)
685{
686 starget *st = (starget *)t;
687 stept *e = CREATE(stept);
688 int fd;
689 gen_addr *ga = (gen_addr *)st->a;
690 int opt;
691
692 if ((fd = socket(st->a->ops->pf, SOCK_STREAM, 0)) < 0)
693 return (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;
697 e->e.other = 0;
698 e->e.f = EPF_FILE | SKF_CONN;
699 e->e.t = 0;
700 e->desc = desc;
701
702 /* --- Pay attention --- *
703 *
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.
713 */
714
715 conn_init(&e->c, sel, fd, &ga->sa, ga->a.sz, stept_go, e);
716 if (e->e.f & SKF_BROKEN) {
717 DESTROY(e);
718 return (0);
719 }
720 if (e->e.f & SKF_CONN)
721 e->e.f |= EPF_PENDING;
722 fw_inc();
723 return (&e->e);
724}
725
726/* --- @destroy@ --- */
727
728static void starget_destroy(target *t)
729{
730 starget *st = (starget *)t;
731 st->a->ops->destroy(st->a);
732 /* free(st->t.desc); */
733 DESTROY(st);
734}
735
736/* --- Socket target definition block --- */
737
738target_ops starget_ops = {
739 "socket",
740 0, starget_read, starget_create, starget_destroy
741};
742
743/*----- That's all, folks -------------------------------------------------*/