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