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