chiark / gitweb /
server/tripe.c: Formalize the interval-timer arrangements.
[tripe] / server / tripe.c
1 /* -*-c-*-
2  *
3  * Main program
4  *
5  * (c) 2001 Straylight/Edgeware
6  */
7
8 /*----- Licensing notice --------------------------------------------------*
9  *
10  * This file is part of Trivial IP Encryption (TrIPE).
11  *
12  * TrIPE is free software: you can redistribute it and/or modify it under
13  * the terms of the GNU General Public License as published by the Free
14  * Software Foundation; either version 3 of the License, or (at your
15  * option) any later version.
16  *
17  * TrIPE is distributed in the hope that it will be useful, but WITHOUT
18  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
19  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
20  * for more details.
21  *
22  * You should have received a copy of the GNU General Public License
23  * along with TrIPE.  If not, see <https://www.gnu.org/licenses/>.
24  */
25
26 /*----- Header files ------------------------------------------------------*/
27
28 #include "tripe.h"
29
30 /*----- Global variables --------------------------------------------------*/
31
32 sel_state sel;
33
34 /*----- Static variables --------------------------------------------------*/
35
36 static sel_timer it;
37 #define T_INTERVAL MIN(1)
38
39 static unsigned iv_nreasons = 0;
40 static struct timeval iv_next = { 0, 0 };
41
42 /*----- The interval timer ------------------------------------------------*/
43
44 /* --- @interval@ --- *
45  *
46  * Arguments:   @struct timeval *tv@ = time when called
47  *              @void *v@ = boring pointer
48  *
49  * Returns:     ---
50  *
51  * Use:         Called periodically to do housekeeping tasks.
52  */
53
54 static void interval(struct timeval *tv, void *v)
55 {
56   T( trace(T_PEER, "peer: interval timer"); )
57   iv_next = *tv;
58   rand_seed(RAND_GLOBAL, MAXHASHSZ);
59   p_interval();
60   iv_next.tv_sec += T_INTERVAL;
61   sel_addtimer(&sel, &it, &iv_next, interval, v);
62 }
63
64 /* --- @iv_addreason@ --- *
65  *
66  * Arguments:   ---
67  *
68  * Returns:     ---
69  *
70  * Use:         Adds an `interval timer reason'; if there are no others, the
71  *              interval timer is engaged.
72  */
73
74 void iv_addreason(void)
75 {
76   struct timeval tv;
77
78   if (!iv_nreasons) {
79     gettimeofday(&tv, 0);
80     if (TV_CMP(&tv, >=, &iv_next)) interval(&tv, 0);
81     else sel_addtimer(&sel, &it, &iv_next, interval, 0);
82   }
83   iv_nreasons++;
84 }
85
86 /* --- @iv_rmreason@ --- *
87  *
88  * Arguments:   ---
89  *
90  * Returns:     ---
91  *
92  * Use:         Removes an interval timer reason; if there are none left, the
93  *              interval timer is disengaged.
94  */
95
96 void iv_rmreason(void)
97 {
98   assert(iv_nreasons); iv_nreasons--;
99   if (!iv_nreasons) sel_rmtimer(&it);
100 }
101
102 /*----- Main code ---------------------------------------------------------*/
103
104 /* --- @main@ --- *
105  *
106  * Arguments:   @int argc@ = number of command line arguments
107  *              @char *argv[]@ = vector of arguments
108  *
109  * Returns:     Zero if OK, nonzero on error.
110  *
111  * Use:         Main program.  Provides a simple VPN.
112  */
113
114 static void usage(FILE *fp)
115 {
116   pquis(fp, "Usage: $ [-DF] [-d DIR] [-b ADDR] [-p PORT] [-n TUNNEL]\n\
117         [-U USER] [-G GROUP] [-a SOCKET] [-m MODE] [-T TRACE-OPTS]\n\
118         [-k PRIV-KEYRING] [-K PUB-KEYRING] [-t KEY-TAG]\n");
119 }
120
121 static void version(FILE *fp) { pquis(fp, "$, version " VERSION "\n"); }
122
123 static void help(FILE *fp)
124 {
125   version(fp);
126   fputc('\n', fp);
127   usage(fp);
128   fputs("\n\
129 Options:\n\
130 \n\
131 -h, --help              Display this help text.\n\
132 -v, --version           Display version number.\n\
133 -u, --usage             Display pointless usage message.\n\
134     --tunnels           Display IP tunnel drivers and exit.\n\
135 \n\
136 -4, --ipv4              Transport over IPv4 only.\n\
137 -6, --ipv6              Transport over IPv6 only.\n\
138 -D, --daemon            Run in the background.\n\
139 -F, --foreground        Quit when stdin reports end-of-file.\n\
140 -d, --directory=DIR     Switch to directory DIR [default " CONFIGDIR "].\n\
141 -b, --bind-address=ADDR Bind UDP socket to this IP ADDR.\n\
142 -p, --port=PORT         Select UDP port to listen to "
143         "[default " STR(TRIPE_PORT) "].\n\
144 -n, --tunnel=TUNNEL     Seelect default tunnel driver.\n\
145 -U, --setuid=USER       Set uid to USER after initialization.\n\
146 -G, --setgid=GROUP      Set gid to GROUP after initialization.\n\
147 -k, --priv-keyring=FILE Get private key from FILE.\n\
148 -K, --pub-keyring=FILE  Get public keys from FILE.\n\
149 -t, --tag=KEYTAG        Use private key labelled TAG.\n\
150 -a, --admin-socket=FILE Use FILE as the adminstration socket.\n\
151 -m, --admin-perms=MODE  Permissions to set on admin socket [default 600].\n\
152 " T( "\
153 -T, --trace=OPTIONS     Turn on tracing options.\n\
154 " ) "\
155 ", fp);
156 }
157
158 int main(int argc, char *argv[])
159 {
160   const char *kr_priv = "keyring", *kr_pub = "keyring.pub";
161   const char *tag_priv = 0;
162   const char *csock = SOCKETDIR "/tripesock";
163   int csockmode = 0600;
164   const char *dir = CONFIGDIR;
165   const char *p;
166   const char *bindhost = 0, *bindsvc = STR(TRIPE_PORT);
167   struct addrinfo aihint = { 0 }, *ailist;
168   unsigned f = 0;
169   int i;
170   int err, selerr = 0;
171   unsigned af;
172   uid_t u = -1;
173   gid_t g = -1;
174
175 #define f_bogus 1u
176 #define f_daemon 2u
177 #define f_foreground 4u
178
179   ego(argv[0]);
180   T( trace_on(stderr, 0); )
181
182   if ((p = getenv("TRIPEDIR")) != 0)
183     dir = p;
184   if ((p = getenv("TRIPESOCK")) != 0)
185     csock = p;
186   tun_default = tunnels[0];
187   aihint.ai_family = AF_UNSPEC;
188
189   for (;;) {
190     static const struct option opts[] = {
191       { "help",         0,              0,      'h' },
192       { "version",      0,              0,      'v' },
193       { "usage",        0,              0,      'u' },
194       { "tunnels",      0,              0,      '0' },
195
196       { "ipv4",         0,              0,      '4' },
197       { "ipv6",         0,              0,      '6' },
198       { "daemon",       0,              0,      'D' },
199       { "foreground",   0,              0,      'F' },
200       { "uid",          OPTF_ARGREQ,    0,      'U' },
201       { "setuid",       OPTF_ARGREQ,    0,      'U' },
202       { "gid",          OPTF_ARGREQ,    0,      'G' },
203       { "setgid",       OPTF_ARGREQ,    0,      'G' },
204       { "bind-address", OPTF_ARGREQ,    0,      'b' },
205       { "tunnel",       OPTF_ARGREQ,    0,      'n' },
206       { "port",         OPTF_ARGREQ,    0,      'p' },
207       { "directory",    OPTF_ARGREQ,    0,      'd' },
208       { "priv-keyring", OPTF_ARGREQ,    0,      'k' },
209       { "pub-keyring",  OPTF_ARGREQ,    0,      'K' },
210       { "tag",          OPTF_ARGREQ,    0,      't' },
211       { "admin-socket", OPTF_ARGREQ,    0,      'a' },
212       { "admin-perms",  OPTF_ARGREQ,    0,      'm' },
213 #ifndef NTRACE
214       { "trace",        OPTF_ARGREQ,    0,      'T' },
215 #endif
216
217       { 0,              0,              0,      0 }
218     };
219
220     i = mdwopt(argc, argv, "hvu46DFU:G:b:n:p:d:k:K:t:a:m:" T("T:"),
221                opts, 0, 0, 0);
222     if (i < 0)
223       break;
224     switch (i) {
225       case 'h':
226         help(stdout);
227         exit(0);
228       case 'v':
229         version(stdout);
230         exit(0);
231       case 'u':
232         usage(stdout);
233         exit(0);
234
235       case '4':
236         aihint.ai_family = AF_INET;
237         break;
238       case '6':
239         aihint.ai_family = AF_INET6;
240         break;
241       case 'D':
242         f |= f_daemon;
243         break;
244       case 'U':
245         u = u_getuser(optarg, &g);
246         break;
247       case 'G':
248         g = u_getgroup(optarg);
249         break;
250       case 'F':
251         f |= f_foreground;
252         break;
253
254       case 'b':
255         bindhost = optarg;
256         break;
257       case 'p':
258         bindsvc = optarg;
259         break;
260       case 'n': {
261         int i;
262         for (i = 0;; i++) {
263           if (!tunnels[i])
264             die(EXIT_FAILURE, "unknown tunnel `%s'", optarg);
265           if (mystrieq(optarg, tunnels[i]->name))
266             break;
267         }
268         tun_default = tunnels[i];
269       } break;
270       case 'd':
271         dir = optarg;
272         break;
273       case 'k':
274         kr_priv = optarg;
275         break;
276       case 'K':
277         kr_pub = optarg;
278         break;
279       case 'a':
280         csock = optarg;
281         break;
282       case 'm': {
283         char *p;
284         csockmode = strtol(optarg, &p, 8);
285         if (*p) die(EXIT_FAILURE, "bad permissions: `%s'", optarg);
286       } break;
287       case 't':
288         tag_priv = optarg;
289         break;
290 #ifndef NTRACE
291       case 'T':
292         tr_flags = traceopt(tr_opts, optarg, tr_flags, 0);
293         trace_level(tr_flags);
294         break;
295 #endif
296       case '0': {
297         int i;
298         for (i = 0; tunnels[i]; i++)
299           puts(tunnels[i]->name);
300         exit(0);
301       } break;
302       default:
303         f |= f_bogus;
304         break;
305     }
306   }
307
308   if (optind < argc || (f & f_bogus)) {
309     usage(stderr);
310     exit(EXIT_FAILURE);
311   }
312   if (!(~f & (f_daemon | f_foreground)))
313     die(EXIT_FAILURE, "foreground operation for a daemon is silly");
314
315   aihint.ai_protocol = IPPROTO_UDP;
316   aihint.ai_socktype = SOCK_DGRAM;
317   aihint.ai_flags = AI_PASSIVE | AI_ADDRCONFIG;
318   if ((err = getaddrinfo(bindhost, bindsvc, &aihint, &ailist)) != 0) {
319     die(EXIT_FAILURE, "couldn't resolve hostname %c%s%c, port `%s': %s",
320         bindhost ? '`' : '<',
321         bindhost ? bindhost : "nil",
322         bindhost ? '\'' : '>',
323         bindsvc, gai_strerror(err));
324   }
325
326   if (chdir(dir)) {
327     die(EXIT_FAILURE, "can't set current directory to `%s': %s",
328         dir, strerror(errno));
329   }
330
331   sel_init(&sel);
332   sig_init(&sel);
333   rand_noisesrc(RAND_GLOBAL, &noise_source);
334   rand_seed(RAND_GLOBAL, MAXHASHSZ);
335   signal(SIGPIPE, SIG_IGN);
336
337   if (!(f & f_daemon)) {
338     af = AF_WARN;
339 #ifndef NTRACE
340     af |= AF_TRACE;
341 #endif
342     if (f & f_foreground)
343       af |= AF_FOREGROUND;
344     a_create(STDIN_FILENO, STDOUT_FILENO, af);
345     a_switcherr();
346   }
347
348   p_init();
349   for (i = 0; tunnels[i]; i++)
350     tunnels[i]->init();
351   p_bind(ailist); freeaddrinfo(ailist);
352
353   for (i = 0; tunnels[i]; i++) {
354     if (tunnels[i]->flags&TUNF_PRIVOPEN) {
355       ps_split(f & f_daemon);
356       break;
357     }
358   }
359
360   a_init();
361   a_signals();
362   a_listen(csock, u, g, csockmode);
363   u_setugid(u, g);
364   km_init(kr_priv, kr_pub, tag_priv);
365   kx_init();
366   if (f & f_daemon) {
367     if (daemonize()) {
368       a_warn("SERVER", "daemon-error", "?ERRNO", A_END);
369       exit(EXIT_FAILURE);
370     }
371     a_daemon();
372     a_switcherr();
373   }
374
375   gettimeofday(&iv_next, 0); iv_next.tv_sec += T_INTERVAL;
376   iv_addreason();
377
378   for (;;) {
379     a_preselect();
380     if (!sel_select(&sel))
381       selerr = 0;
382     else if (errno != EINTR && errno != EAGAIN) {
383       a_warn("SERVER", "select-error", "?ERRNO", A_END);
384       selerr++;
385       if (selerr > 8) {
386         a_warn("ABORT", "repeated-select-errors", A_END);
387         abort();
388       }
389     }
390   }
391
392   return (0);
393 }
394
395 /*----- That's all, folks -------------------------------------------------*/