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