Configure minimum reconnect timeouts.
[tinc] / src / process.c
1 /*
2     process.c -- process management functions
3     Copyright (C) 1999-2005 Ivo Timmermans,
4                   2000-2013 Guus Sliepen <guus@tinc-vpn.org>
5
6     This program is free software; you can redistribute it and/or modify
7     it under the terms of the GNU General Public License as published by
8     the Free Software Foundation; either version 2 of the License, or
9     (at your option) any later version.
10
11     This program is distributed in the hope that it will be useful,
12     but WITHOUT ANY WARRANTY; without even the implied warranty of
13     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14     GNU General Public License for more details.
15
16     You should have received a copy of the GNU General Public License along
17     with this program; if not, write to the Free Software Foundation, Inc.,
18     51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
19 */
20
21 #include "system.h"
22
23 #include "conf.h"
24 #include "connection.h"
25 #include "device.h"
26 #include "edge.h"
27 #include "logger.h"
28 #include "net.h"
29 #include "node.h"
30 #include "pidfile.h"
31 #include "process.h"
32 #include "subnet.h"
33 #include "utils.h"
34 #include "xalloc.h"
35
36 /* If zero, don't detach from the terminal. */
37 bool do_detach = true;
38 bool sighup = false;
39 bool sigalrm = false;
40
41 extern char *identname;
42 extern char *pidfilename;
43 extern char **g_argv;
44 extern bool use_logfile;
45
46 #ifndef HAVE_MINGW
47 static sigset_t emptysigset;
48 #endif
49
50 static void memory_full(int size) {
51         logger(LOG_ERR, "Memory exhausted (couldn't allocate %d bytes), exitting.", size);
52         exit(1);
53 }
54
55 /* Some functions the less gifted operating systems might lack... */
56
57 #ifdef HAVE_MINGW
58 extern char *identname;
59 extern char *program_name;
60 extern char **g_argv;
61
62 static SC_HANDLE manager = NULL;
63 static SC_HANDLE service = NULL;
64 static SERVICE_STATUS status = {0};
65 static SERVICE_STATUS_HANDLE statushandle = 0;
66
67 bool install_service(void) {
68         char command[4096] = "\"";
69         char **argp;
70         bool space;
71         SERVICE_DESCRIPTION description = {"Virtual Private Network daemon"};
72
73         manager = OpenSCManager(NULL, NULL, SC_MANAGER_ALL_ACCESS);
74         if(!manager) {
75                 logger(LOG_ERR, "Could not open service manager: %s", winerror(GetLastError()));
76                 return false;
77         }
78
79         if(!strchr(program_name, '\\')) {
80                 GetCurrentDirectory(sizeof command - 1, command + 1);
81                 strncat(command, "\\", sizeof command - strlen(command));
82         }
83
84         strncat(command, program_name, sizeof command - strlen(command));
85
86         strncat(command, "\"", sizeof command - strlen(command));
87
88         for(argp = g_argv + 1; *argp; argp++) {
89                 space = strchr(*argp, ' ');
90                 strncat(command, " ", sizeof command - strlen(command));
91                 
92                 if(space)
93                         strncat(command, "\"", sizeof command - strlen(command));
94                 
95                 strncat(command, *argp, sizeof command - strlen(command));
96
97                 if(space)
98                         strncat(command, "\"", sizeof command - strlen(command));
99         }
100
101         service = CreateService(manager, identname, identname,
102                         SERVICE_ALL_ACCESS, SERVICE_WIN32_OWN_PROCESS, SERVICE_AUTO_START, SERVICE_ERROR_NORMAL,
103                         command, NULL, NULL, NULL, NULL, NULL);
104         
105         if(!service) {
106                 DWORD lasterror = GetLastError();
107                 logger(LOG_ERR, "Could not create %s service: %s", identname, winerror(lasterror));
108                 if(lasterror != ERROR_SERVICE_EXISTS)
109                         return false;
110         }
111
112         if(service) {
113                 ChangeServiceConfig2(service, SERVICE_CONFIG_DESCRIPTION, &description);
114                 logger(LOG_INFO, "%s service installed", identname);
115         } else {
116                 service = OpenService(manager, identname, SERVICE_ALL_ACCESS);
117         }
118
119         if(!StartService(service, 0, NULL))
120                 logger(LOG_WARNING, "Could not start %s service: %s", identname, winerror(GetLastError()));
121         else
122                 logger(LOG_INFO, "%s service started", identname);
123
124         return true;
125 }
126
127 bool remove_service(void) {
128         manager = OpenSCManager(NULL, NULL, SC_MANAGER_ALL_ACCESS);
129         if(!manager) {
130                 logger(LOG_ERR, "Could not open service manager: %s", winerror(GetLastError()));
131                 return false;
132         }
133
134         service = OpenService(manager, identname, SERVICE_ALL_ACCESS);
135
136         if(!service) {
137                 logger(LOG_ERR, "Could not open %s service: %s", identname, winerror(GetLastError()));
138                 return false;
139         }
140
141         if(!ControlService(service, SERVICE_CONTROL_STOP, &status))
142                 logger(LOG_ERR, "Could not stop %s service: %s", identname, winerror(GetLastError()));
143         else
144                 logger(LOG_INFO, "%s service stopped", identname);
145
146         if(!DeleteService(service)) {
147                 logger(LOG_ERR, "Could not remove %s service: %s", identname, winerror(GetLastError()));
148                 return false;
149         }
150
151         logger(LOG_INFO, "%s service removed", identname);
152
153         return true;
154 }
155
156 DWORD WINAPI controlhandler(DWORD request, DWORD type, LPVOID boe, LPVOID bah) {
157         switch(request) {
158                 case SERVICE_CONTROL_INTERROGATE:
159                         SetServiceStatus(statushandle, &status);
160                         return NO_ERROR;
161                 case SERVICE_CONTROL_STOP:
162                         logger(LOG_NOTICE, "Got %s request", "SERVICE_CONTROL_STOP");
163                         break;
164                 case SERVICE_CONTROL_SHUTDOWN:
165                         logger(LOG_NOTICE, "Got %s request", "SERVICE_CONTROL_SHUTDOWN");
166                         break;
167                 default:
168                         logger(LOG_WARNING, "Got unexpected request %d", (int)request);
169                         return ERROR_CALL_NOT_IMPLEMENTED;
170         }
171
172         if(running) {
173                 running = false;
174                 status.dwWaitHint = 30000; 
175                 status.dwCurrentState = SERVICE_STOP_PENDING; 
176                 SetServiceStatus(statushandle, &status);
177                 return NO_ERROR;
178         } else {
179                 status.dwWaitHint = 0; 
180                 status.dwCurrentState = SERVICE_STOPPED; 
181                 SetServiceStatus(statushandle, &status);
182                 exit(1);
183         }
184
185 }
186
187 VOID WINAPI run_service(DWORD argc, LPTSTR* argv) {
188         extern int main2(int argc, char **argv);
189
190         status.dwServiceType = SERVICE_WIN32; 
191         status.dwControlsAccepted = SERVICE_ACCEPT_STOP | SERVICE_ACCEPT_SHUTDOWN;
192         status.dwWin32ExitCode = 0; 
193         status.dwServiceSpecificExitCode = 0; 
194         status.dwCheckPoint = 0; 
195
196         statushandle = RegisterServiceCtrlHandlerEx(identname, controlhandler, NULL); 
197
198         if (!statushandle) {
199                 logger(LOG_ERR, "System call `%s' failed: %s", "RegisterServiceCtrlHandlerEx", winerror(GetLastError()));
200         } else {
201                 status.dwWaitHint = 30000; 
202                 status.dwCurrentState = SERVICE_START_PENDING; 
203                 SetServiceStatus(statushandle, &status);
204
205                 status.dwWaitHint = 0; 
206                 status.dwCurrentState = SERVICE_RUNNING;
207                 SetServiceStatus(statushandle, &status);
208
209                 main2(argc, argv);
210
211                 status.dwWaitHint = 0;
212                 status.dwCurrentState = SERVICE_STOPPED; 
213                 SetServiceStatus(statushandle, &status);
214         }
215
216         return;
217 }
218
219 bool init_service(void) {
220         SERVICE_TABLE_ENTRY services[] = {
221                 {identname, run_service},
222                 {NULL, NULL}
223         };
224
225         if(!StartServiceCtrlDispatcher(services)) {
226                 if(GetLastError() == ERROR_FAILED_SERVICE_CONTROLLER_CONNECT) {
227                         return false;
228                 }
229                 else
230                         logger(LOG_ERR, "System call `%s' failed: %s", "StartServiceCtrlDispatcher", winerror(GetLastError()));
231         }
232
233         return true;
234 }
235 #endif
236
237 #ifndef HAVE_MINGW
238 /*
239   check for an existing tinc for this net, and write pid to pidfile
240 */
241 static bool write_pidfile(void) {
242         pid_t pid;
243
244         pid = check_pid(pidfilename);
245
246         if(pid) {
247                 if(netname)
248                         fprintf(stderr, "A tincd is already running for net `%s' with pid %ld.\n",
249                                         netname, (long)pid);
250                 else
251                         fprintf(stderr, "A tincd is already running with pid %ld.\n", (long)pid);
252                 return false;
253         }
254
255         /* if it's locked, write-protected, or whatever */
256         if(!write_pid(pidfilename)) {
257                 fprintf(stderr, "Couldn't write pid file %s: %s\n", pidfilename, strerror(errno));
258                 return false;
259         }
260
261         return true;
262 }
263 #endif
264
265 /*
266   kill older tincd for this net
267 */
268 bool kill_other(int signal) {
269 #ifndef HAVE_MINGW
270         pid_t pid;
271
272         pid = read_pid(pidfilename);
273
274         if(!pid) {
275                 if(netname)
276                         fprintf(stderr, "No other tincd is running for net `%s'.\n",
277                                         netname);
278                 else
279                         fprintf(stderr, "No other tincd is running.\n");
280                 return false;
281         }
282
283         errno = 0;                                      /* No error, sometimes errno is only changed on error */
284
285         /* ESRCH is returned when no process with that pid is found */
286         if(kill(pid, signal) && errno == ESRCH) {
287                 if(netname)
288                         fprintf(stderr, "The tincd for net `%s' is no longer running. ",
289                                         netname);
290                 else
291                         fprintf(stderr, "The tincd is no longer running. ");
292
293                 fprintf(stderr, "Removing stale lock file.\n");
294                 remove_pid(pidfilename);
295         }
296
297         return true;
298 #else
299         return remove_service();
300 #endif
301 }
302
303 /*
304   Detach from current terminal, write pidfile, kill parent
305 */
306 bool detach(void) {
307         setup_signals();
308
309         /* First check if we can open a fresh new pidfile */
310
311 #ifndef HAVE_MINGW
312         if(!write_pidfile())
313                 return false;
314
315         /* If we succeeded in doing that, detach */
316
317         closelogger();
318 #endif
319
320         if(do_detach) {
321 #ifndef HAVE_MINGW
322                 if(daemon(0, 0)) {
323                         fprintf(stderr, "Couldn't detach from terminal: %s",
324                                         strerror(errno));
325                         return false;
326                 }
327
328                 /* Now UPDATE the pid in the pidfile, because we changed it... */
329
330                 if(!write_pid(pidfilename)) {
331                         fprintf(stderr, "Could not write pid file %s: %s\n", pidfilename, strerror(errno));
332                         return false;
333                 }
334 #else
335                 if(!statushandle)
336                         exit(install_service());
337 #endif
338         }
339
340         openlogger(identname, use_logfile?LOGMODE_FILE:(do_detach?LOGMODE_SYSLOG:LOGMODE_STDERR));
341
342         logger(LOG_NOTICE, "tincd %s (%s %s) starting, debug level %d",
343                            VERSION, __DATE__, __TIME__, debug_level);
344
345         xalloc_fail_func = memory_full;
346
347         return true;
348 }
349
350 bool execute_script(const char *name, char **envp) {
351 #ifdef HAVE_SYSTEM
352         char *scriptname;
353         char *interpreter = NULL;
354         config_t *cfg_interpreter;
355         int status, len, i;
356
357         cfg_interpreter = lookup_config(config_tree, "ScriptsInterpreter");
358 #ifndef HAVE_MINGW
359         len = xasprintf(&scriptname, "\"%s/%s\"", confbase, name);
360 #else
361         if(cfg_interpreter)
362                 len = xasprintf(&scriptname, "\"%s/%s\"", confbase, name);
363         else
364                 len = xasprintf(&scriptname, "\"%s/%s.bat\"", confbase, name);
365 #endif
366         if(len < 0)
367                 return false;
368
369         scriptname[len - 1] = '\0';
370
371         /* First check if there is a script */
372         if(access(scriptname + 1, F_OK)) {
373                 free(scriptname);
374                 return true;
375         }
376
377         // Custom scripts interpreter
378         if(get_config_string(cfg_interpreter, &interpreter)) {
379                 // Force custom scripts interpreter allowing execution of scripts on android without execution flag (such as on /sdcard)
380                 free(scriptname);
381                 len = xasprintf(&scriptname, "%s \"%s/%s\"", interpreter, confbase, name);
382                 free(interpreter);
383                 if(len < 0)
384                         return false;
385         }
386
387         ifdebug(STATUS) logger(LOG_INFO, "Executing script %s", name);
388
389 #ifdef HAVE_PUTENV
390         /* Set environment */
391         
392         for(i = 0; envp[i]; i++)
393                 putenv(envp[i]);
394 #endif
395
396         scriptname[len - 1] = '\"';
397         status = system(scriptname);
398
399         free(scriptname);
400
401         /* Unset environment */
402
403         for(i = 0; envp[i]; i++) {
404                 char *e = strchr(envp[i], '=');
405                 if(e) {
406                         char p[e - envp[i] + 1];
407                         strncpy(p, envp[i], e - envp[i]);
408                         p[e - envp[i]] = '\0';
409                         putenv(p);
410                 }
411         }
412
413         if(status != -1) {
414 #ifdef WEXITSTATUS
415                 if(WIFEXITED(status)) { /* Child exited by itself */
416                         if(WEXITSTATUS(status)) {
417                                 logger(LOG_ERR, "Script %s exited with non-zero status %d",
418                                            name, WEXITSTATUS(status));
419                                 return false;
420                         }
421                 } else if(WIFSIGNALED(status)) {        /* Child was killed by a signal */
422                         logger(LOG_ERR, "Script %s was killed by signal %d (%s)",
423                                    name, WTERMSIG(status), strsignal(WTERMSIG(status)));
424                         return false;
425                 } else {                        /* Something strange happened */
426                         logger(LOG_ERR, "Script %s terminated abnormally", name);
427                         return false;
428                 }
429 #endif
430         } else {
431                 logger(LOG_ERR, "System call `%s' failed: %s", "system", strerror(errno));
432                 return false;
433         }
434 #endif
435         return true;
436 }
437
438
439 /*
440   Signal handlers.
441 */
442
443 #ifndef HAVE_MINGW
444 static RETSIGTYPE sigterm_handler(int a) {
445         logger(LOG_NOTICE, "Got %s signal", "TERM");
446         if(running)
447                 running = false;
448         else
449                 exit(1);
450 }
451
452 static RETSIGTYPE sigquit_handler(int a) {
453         logger(LOG_NOTICE, "Got %s signal", "QUIT");
454         if(running)
455                 running = false;
456         else
457                 exit(1);
458 }
459
460 static RETSIGTYPE fatal_signal_square(int a) {
461         logger(LOG_ERR, "Got another fatal signal %d (%s): not restarting.", a,
462                    strsignal(a));
463         exit(1);
464 }
465
466 static RETSIGTYPE fatal_signal_handler(int a) {
467         struct sigaction act;
468         logger(LOG_ERR, "Got fatal signal %d (%s)", a, strsignal(a));
469
470         if(do_detach) {
471                 logger(LOG_NOTICE, "Trying to re-execute in 5 seconds...");
472
473                 act.sa_handler = fatal_signal_square;
474                 act.sa_mask = emptysigset;
475                 act.sa_flags = 0;
476                 sigaction(SIGSEGV, &act, NULL);
477
478                 close_network_connections();
479                 sleep(5);
480                 remove_pid(pidfilename);
481                 execvp(g_argv[0], g_argv);
482         } else {
483                 logger(LOG_NOTICE, "Not restarting.");
484                 exit(1);
485         }
486 }
487
488 static RETSIGTYPE sighup_handler(int a) {
489         logger(LOG_NOTICE, "Got %s signal", "HUP");
490         sighup = true;
491 }
492
493 static RETSIGTYPE sigint_handler(int a) {
494         static int saved_debug_level = -1;
495
496         logger(LOG_NOTICE, "Got %s signal", "INT");
497
498         if(saved_debug_level != -1) {
499                 logger(LOG_NOTICE, "Reverting to old debug level (%d)",
500                         saved_debug_level);
501                 debug_level = saved_debug_level;
502                 saved_debug_level = -1;
503         } else {
504                 logger(LOG_NOTICE,
505                         "Temporarily setting debug level to 5.  Kill me with SIGINT again to go back to level %d.",
506                         debug_level);
507                 saved_debug_level = debug_level;
508                 debug_level = 5;
509         }
510 }
511
512 static RETSIGTYPE sigalrm_handler(int a) {
513         logger(LOG_NOTICE, "Got %s signal", "ALRM");
514         sigalrm = true;
515 }
516
517 static RETSIGTYPE sigusr1_handler(int a) {
518         dump_connections();
519 }
520
521 static RETSIGTYPE sigusr2_handler(int a) {
522         devops.dump_stats();
523         dump_nodes();
524         dump_edges();
525         dump_subnets();
526 }
527
528 static RETSIGTYPE sigwinch_handler(int a) {
529         do_purge = true;
530 }
531
532 static RETSIGTYPE unexpected_signal_handler(int a) {
533         logger(LOG_WARNING, "Got unexpected signal %d (%s)", a, strsignal(a));
534 }
535
536 static RETSIGTYPE ignore_signal_handler(int a) {
537         ifdebug(SCARY_THINGS) logger(LOG_DEBUG, "Ignored signal %d (%s)", a, strsignal(a));
538 }
539
540 static struct {
541         int signal;
542         void (*handler)(int);
543 } sighandlers[] = {
544         {SIGHUP, sighup_handler},
545         {SIGTERM, sigterm_handler},
546         {SIGQUIT, sigquit_handler},
547         {SIGSEGV, fatal_signal_handler},
548         {SIGBUS, fatal_signal_handler},
549         {SIGILL, fatal_signal_handler},
550         {SIGPIPE, ignore_signal_handler},
551         {SIGINT, sigint_handler},
552         {SIGUSR1, sigusr1_handler},
553         {SIGUSR2, sigusr2_handler},
554         {SIGCHLD, ignore_signal_handler},
555         {SIGALRM, sigalrm_handler},
556         {SIGWINCH, sigwinch_handler},
557         {SIGABRT, SIG_DFL},
558         {0, NULL}
559 };
560 #endif
561
562 void setup_signals(void) {
563 #ifndef HAVE_MINGW
564         int i;
565         struct sigaction act;
566
567         sigemptyset(&emptysigset);
568         act.sa_handler = NULL;
569         act.sa_mask = emptysigset;
570         act.sa_flags = 0;
571
572         /* Set a default signal handler for every signal, errors will be
573            ignored. */
574         for(i = 1; i < NSIG; i++) {
575                 if(!do_detach)
576                         act.sa_handler = SIG_DFL;
577                 else
578                         act.sa_handler = unexpected_signal_handler;
579                 sigaction(i, &act, NULL);
580         }
581
582         /* If we didn't detach, allow coredumps */
583         if(!do_detach)
584                 sighandlers[3].handler = SIG_DFL;
585
586         /* Then, for each known signal that we want to catch, assign a
587            handler to the signal, with error checking this time. */
588         for(i = 0; sighandlers[i].signal; i++) {
589                 act.sa_handler = sighandlers[i].handler;
590                 if(sigaction(sighandlers[i].signal, &act, NULL) < 0)
591                         fprintf(stderr, "Installing signal handler for signal %d (%s) failed: %s\n",
592                                         sighandlers[i].signal, strsignal(sighandlers[i].signal),
593                                         strerror(errno));
594         }
595 #endif
596 }