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