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