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