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