chiark / gitweb /
server/: Make initialization errors be non-fatal and restartable.
[tripe] / server / standalone.c
1 /* -*-c-*-
2  *
3  * Initialization for the standalone server
4  *
5  * (c) 2018 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 /*----- Tunnel table ------------------------------------------------------*/
31
32 static const tunnel_ops *tunnels[] = {
33 #ifdef TUN_LINUX
34   &tun_linux,
35 #endif
36 #ifdef TUN_BSD
37   &tun_bsd,
38 #endif
39 #ifdef TUN_UNET
40   &tun_unet,
41 #endif
42   &tun_slip,
43 };
44
45 /*----- Main code ---------------------------------------------------------*/
46
47 /* --- @main@ --- *
48  *
49  * Arguments:   @int argc@ = number of command line arguments
50  *              @char *argv[]@ = vector of arguments
51  *
52  * Returns:     Zero if OK, nonzero on error.
53  *
54  * Use:         Main program.  Provides a simple VPN.
55  */
56
57 static void usage(FILE *fp)
58 {
59   pquis(fp, "Usage: $ [-DF] [-d DIR] [-b ADDR] [-p PORT] [-n TUNNEL]\n\
60         [-U USER] [-G GROUP] [-a SOCKET] [-m MODE] [-T TRACE-OPTS]\n\
61         [-k PRIV-KEYRING] [-K PUB-KEYRING] [-t KEY-TAG]\n");
62 }
63
64 static void version(FILE *fp) { pquis(fp, "$, version " VERSION "\n"); }
65
66 static void help(FILE *fp)
67 {
68   version(fp);
69   fputc('\n', fp);
70   usage(fp);
71   fputs("\n\
72 Options:\n\
73 \n\
74 -h, --help              Display this help text.\n\
75 -v, --version           Display version number.\n\
76 -u, --usage             Display pointless usage message.\n\
77     --tunnels           Display IP tunnel drivers and exit.\n\
78 \n\
79 -4, --ipv4              Transport over IPv4 only.\n\
80 -6, --ipv6              Transport over IPv6 only.\n\
81 -D, --daemon            Run in the background.\n\
82 -F, --foreground        Quit when stdin reports end-of-file.\n\
83 -d, --directory=DIR     Switch to directory DIR [default " CONFIGDIR "].\n\
84 -b, --bind-address=ADDR Bind UDP socket to this IP ADDR.\n\
85 -p, --port=PORT         Select UDP port to listen to "
86         "[default " STR(TRIPE_PORT) "].\n\
87 -n, --tunnel=TUNNEL     Seelect default tunnel driver.\n\
88 -U, --setuid=USER       Set uid to USER after initialization.\n\
89 -G, --setgid=GROUP      Set gid to GROUP after initialization.\n\
90 -k, --priv-keyring=FILE Get private key from FILE.\n\
91 -K, --pub-keyring=FILE  Get public keys from FILE.\n\
92 -t, --tag=KEYTAG        Use private key labelled TAG.\n\
93 -a, --admin-socket=FILE Use FILE as the adminstration socket.\n\
94 -m, --admin-perms=MODE  Permissions to set on admin socket [default 600].\n\
95 " T( "\
96 -T, --trace=OPTIONS     Turn on tracing options.\n\
97 " ) "\
98 ", fp);
99 }
100
101 int main(int argc, char *argv[])
102 {
103   const char *kr_priv = "keyring", *kr_pub = "keyring.pub";
104   const char *tag_priv = 0;
105   const char *csock = SOCKETDIR "/tripesock";
106   int csockmode = 0600;
107   const char *dir = CONFIGDIR;
108   const char *p;
109   const char *bindhost = 0, *bindsvc = STR(TRIPE_PORT);
110   struct addrinfo aihint = { 0 }, *ailist;
111   const tunnel_ops *dflt = 0;
112   unsigned f = 0;
113   int i;
114   int err;
115   unsigned af;
116   uid_t u = -1;
117   gid_t g = -1;
118
119 #define f_bogus 1u
120 #define f_daemon 2u
121 #define f_foreground 4u
122
123   ego(argv[0]);
124   T( trace_on(stderr, 0); )
125
126   if ((p = getenv("TRIPEDIR")) != 0)
127     dir = p;
128   if ((p = getenv("TRIPESOCK")) != 0)
129     csock = p;
130   aihint.ai_family = AF_UNSPEC;
131
132   for (;;) {
133     static const struct option opts[] = {
134       { "help",         0,              0,      'h' },
135       { "version",      0,              0,      'v' },
136       { "usage",        0,              0,      'u' },
137       { "tunnels",      0,              0,      '0' },
138
139       { "ipv4",         0,              0,      '4' },
140       { "ipv6",         0,              0,      '6' },
141       { "daemon",       0,              0,      'D' },
142       { "foreground",   0,              0,      'F' },
143       { "uid",          OPTF_ARGREQ,    0,      'U' },
144       { "setuid",       OPTF_ARGREQ,    0,      'U' },
145       { "gid",          OPTF_ARGREQ,    0,      'G' },
146       { "setgid",       OPTF_ARGREQ,    0,      'G' },
147       { "bind-address", OPTF_ARGREQ,    0,      'b' },
148       { "tunnel",       OPTF_ARGREQ,    0,      'n' },
149       { "port",         OPTF_ARGREQ,    0,      'p' },
150       { "directory",    OPTF_ARGREQ,    0,      'd' },
151       { "priv-keyring", OPTF_ARGREQ,    0,      'k' },
152       { "pub-keyring",  OPTF_ARGREQ,    0,      'K' },
153       { "tag",          OPTF_ARGREQ,    0,      't' },
154       { "admin-socket", OPTF_ARGREQ,    0,      'a' },
155       { "admin-perms",  OPTF_ARGREQ,    0,      'm' },
156 #ifndef NTRACE
157       { "trace",        OPTF_ARGREQ,    0,      'T' },
158 #endif
159
160       { 0,              0,              0,      0 }
161     };
162
163     i = mdwopt(argc, argv, "hvu46DFU:G:b:n:p:d:k:K:t:a:m:" T("T:"),
164                opts, 0, 0, 0);
165     if (i < 0)
166       break;
167     switch (i) {
168       case 'h':
169         help(stdout);
170         exit(0);
171       case 'v':
172         version(stdout);
173         exit(0);
174       case 'u':
175         usage(stdout);
176         exit(0);
177
178       case '4':
179         aihint.ai_family = AF_INET;
180         break;
181       case '6':
182         aihint.ai_family = AF_INET6;
183         break;
184       case 'D':
185         f |= f_daemon;
186         break;
187       case 'U':
188         u = u_getuser(optarg, &g);
189         break;
190       case 'G':
191         g = u_getgroup(optarg);
192         break;
193       case 'F':
194         f |= f_foreground;
195         break;
196
197       case 'b':
198         bindhost = optarg;
199         break;
200       case 'p':
201         bindsvc = optarg;
202         break;
203       case 'n': {
204         int i;
205         for (i = 0; i < N(tunnels); i++)
206           if (mystrieq(optarg, tunnels[i]->name))
207             { dflt = tunnels[i]; goto found_tun; }
208         die(EXIT_FAILURE, "unknown tunnel `%s'", optarg);
209       found_tun:;
210       } break;
211       case 'd':
212         dir = optarg;
213         break;
214       case 'k':
215         kr_priv = optarg;
216         break;
217       case 'K':
218         kr_pub = optarg;
219         break;
220       case 'a':
221         csock = optarg;
222         break;
223       case 'm': {
224         char *p;
225         csockmode = strtol(optarg, &p, 8);
226         if (*p) die(EXIT_FAILURE, "bad permissions: `%s'", optarg);
227       } break;
228       case 't':
229         tag_priv = optarg;
230         break;
231 #ifndef NTRACE
232       case 'T':
233         tr_flags = traceopt(tr_opts, optarg, tr_flags, 0);
234         trace_level(tr_flags);
235         break;
236 #endif
237       case '0': {
238         int i;
239         for (i = 0; i < N(tunnels); i++)
240           puts(tunnels[i]->name);
241         exit(0);
242       } break;
243       default:
244         f |= f_bogus;
245         break;
246     }
247   }
248
249   if (optind < argc || (f & f_bogus)) {
250     usage(stderr);
251     exit(EXIT_FAILURE);
252   }
253   if (!(~f & (f_daemon | f_foreground)))
254     die(EXIT_FAILURE, "foreground operation for a daemon is silly");
255
256   aihint.ai_protocol = IPPROTO_UDP;
257   aihint.ai_socktype = SOCK_DGRAM;
258   aihint.ai_flags = AI_PASSIVE | AI_ADDRCONFIG;
259   if ((err = getaddrinfo(bindhost, bindsvc, &aihint, &ailist)) != 0) {
260     die(EXIT_FAILURE, "couldn't resolve hostname %c%s%c, port `%s': %s",
261         bindhost ? '`' : '<',
262         bindhost ? bindhost : "nil",
263         bindhost ? '\'' : '>',
264         bindsvc, gai_strerror(err));
265   }
266
267   if (chdir(dir)) {
268     die(EXIT_FAILURE, "can't set current directory to `%s': %s",
269         dir, strerror(errno));
270   }
271
272   rand_noisesrc(RAND_GLOBAL, &noise_source);
273   rand_seed(RAND_GLOBAL, MAXHASHSZ);
274
275   lp_init();
276
277   if (!(f & f_daemon)) {
278     af = AF_WARN;
279 #ifndef NTRACE
280     af |= AF_TRACE;
281 #endif
282     if (f & f_foreground)
283       af |= AF_FOREGROUND;
284     a_create(STDIN_FILENO, STDOUT_FILENO, af);
285     a_switcherr();
286   }
287
288   p_init();
289   for (i = 0; i < N(tunnels); i++)
290     if (p_addtun(tunnels[i])) exit(EXIT_FAILURE);
291   if (dflt) p_setdflttun(dflt);
292   if (p_bind(ailist)) exit(EXIT_FAILURE);
293   freeaddrinfo(ailist);
294
295   for (i = 0; tunnels[i]; i++) {
296     if (tunnels[i]->flags&TUNF_PRIVOPEN) {
297       if (ps_split(f & f_daemon)) exit(EXIT_FAILURE);
298       break;
299     }
300   }
301
302   if (a_init()) exit(EXIT_FAILURE);
303   a_signals();
304   if (a_listen(csock, u, g, csockmode)) exit(EXIT_FAILURE);
305   u_setugid(u, g);
306   if (km_init(kr_priv, kr_pub, tag_priv)) exit(EXIT_FAILURE);
307   kx_init();
308   if (f & f_daemon) {
309     if (daemonize()) {
310       a_warn("SERVER", "daemon-error", "?ERRNO", A_END);
311       exit(EXIT_FAILURE);
312     }
313     a_daemon();
314     a_switcherr();
315   }
316
317   lp_run();
318
319   p_destroyall();
320   p_unbind();
321   a_unlisten();
322   km_clear();
323   ps_quit();
324   return (0);
325 }
326
327 /*----- That's all, folks -------------------------------------------------*/