020dfa0db65f59561c58ca81c260c7b1e834d329
[oweals/tinc.git] / 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, "Could 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         int status, len;
353         char *scriptname;
354         int i;
355         char *interpreter = NULL;
356
357 #ifndef HAVE_MINGW
358         len = xasprintf(&scriptname, "\"%s/%s\"", confbase, name);
359 #else
360         len = xasprintf(&scriptname, "\"%s/%s.bat\"", confbase, name);
361 #endif
362         if(len < 0)
363                 return false;
364
365         scriptname[len - 1] = '\0';
366
367         /* First check if there is a script */
368
369         if(access(scriptname + 1, F_OK)) {
370                 free(scriptname);
371                 return true;
372         }
373
374         // Custom scripts interpreter
375         if(get_config_string(lookup_config(config_tree, "ScriptsInterpreter"), &interpreter)) {
376                 // Force custom scripts interpreter allowing execution of scripts on android without execution flag (such as on /sdcard)
377                 free(scriptname);
378                 len = xasprintf(&scriptname, "%s \"%s/%s\"", interpreter, confbase, name);
379                 free(interpreter);
380                 if(len < 0)
381                         return false;
382         }
383
384         ifdebug(STATUS) logger(LOG_INFO, "Executing script %s", name);
385
386 #ifdef HAVE_PUTENV
387         /* Set environment */
388         
389         for(i = 0; envp[i]; i++)
390                 putenv(envp[i]);
391 #endif
392
393         scriptname[len - 1] = '\"';
394         status = system(scriptname);
395
396         free(scriptname);
397
398         /* Unset environment */
399
400         for(i = 0; envp[i]; i++) {
401                 char *e = strchr(envp[i], '=');
402                 if(e) {
403                         char p[e - envp[i] + 1];
404                         strncpy(p, envp[i], e - envp[i]);
405                         p[e - envp[i]] = '\0';
406                         putenv(p);
407                 }
408         }
409
410         if(status != -1) {
411 #ifdef WEXITSTATUS
412                 if(WIFEXITED(status)) { /* Child exited by itself */
413                         if(WEXITSTATUS(status)) {
414                                 logger(LOG_ERR, "Script %s exited with non-zero status %d",
415                                            name, WEXITSTATUS(status));
416                                 return false;
417                         }
418                 } else if(WIFSIGNALED(status)) {        /* Child was killed by a signal */
419                         logger(LOG_ERR, "Script %s was killed by signal %d (%s)",
420                                    name, WTERMSIG(status), strsignal(WTERMSIG(status)));
421                         return false;
422                 } else {                        /* Something strange happened */
423                         logger(LOG_ERR, "Script %s terminated abnormally", name);
424                         return false;
425                 }
426 #endif
427         } else {
428                 logger(LOG_ERR, "System call `%s' failed: %s", "system", strerror(errno));
429                 return false;
430         }
431 #endif
432         return true;
433 }
434
435
436 /*
437   Signal handlers.
438 */
439
440 #ifndef HAVE_MINGW
441 static RETSIGTYPE sigterm_handler(int a) {
442         logger(LOG_NOTICE, "Got %s signal", "TERM");
443         if(running)
444                 running = false;
445         else
446                 exit(1);
447 }
448
449 static RETSIGTYPE sigquit_handler(int a) {
450         logger(LOG_NOTICE, "Got %s signal", "QUIT");
451         if(running)
452                 running = false;
453         else
454                 exit(1);
455 }
456
457 static RETSIGTYPE fatal_signal_square(int a) {
458         logger(LOG_ERR, "Got another fatal signal %d (%s): not restarting.", a,
459                    strsignal(a));
460         exit(1);
461 }
462
463 static RETSIGTYPE fatal_signal_handler(int a) {
464         struct sigaction act;
465         logger(LOG_ERR, "Got fatal signal %d (%s)", a, strsignal(a));
466
467         if(do_detach) {
468                 logger(LOG_NOTICE, "Trying to re-execute in 5 seconds...");
469
470                 act.sa_handler = fatal_signal_square;
471                 act.sa_mask = emptysigset;
472                 act.sa_flags = 0;
473                 sigaction(SIGSEGV, &act, NULL);
474
475                 close_network_connections();
476                 sleep(5);
477                 remove_pid(pidfilename);
478                 execvp(g_argv[0], g_argv);
479         } else {
480                 logger(LOG_NOTICE, "Not restarting.");
481                 exit(1);
482         }
483 }
484
485 static RETSIGTYPE sighup_handler(int a) {
486         logger(LOG_NOTICE, "Got %s signal", "HUP");
487         sighup = true;
488 }
489
490 static RETSIGTYPE sigint_handler(int a) {
491         static int saved_debug_level = -1;
492
493         logger(LOG_NOTICE, "Got %s signal", "INT");
494
495         if(saved_debug_level != -1) {
496                 logger(LOG_NOTICE, "Reverting to old debug level (%d)",
497                         saved_debug_level);
498                 debug_level = saved_debug_level;
499                 saved_debug_level = -1;
500         } else {
501                 logger(LOG_NOTICE,
502                         "Temporarily setting debug level to 5.  Kill me with SIGINT again to go back to level %d.",
503                         debug_level);
504                 saved_debug_level = debug_level;
505                 debug_level = 5;
506         }
507 }
508
509 static RETSIGTYPE sigalrm_handler(int a) {
510         logger(LOG_NOTICE, "Got %s signal", "ALRM");
511         sigalrm = true;
512 }
513
514 static RETSIGTYPE sigusr1_handler(int a) {
515         dump_connections();
516 }
517
518 static RETSIGTYPE sigusr2_handler(int a) {
519         devops.dump_stats();
520         dump_nodes();
521         dump_edges();
522         dump_subnets();
523 }
524
525 static RETSIGTYPE sigwinch_handler(int a) {
526         do_purge = true;
527 }
528
529 static RETSIGTYPE unexpected_signal_handler(int a) {
530         logger(LOG_WARNING, "Got unexpected signal %d (%s)", a, strsignal(a));
531 }
532
533 static RETSIGTYPE ignore_signal_handler(int a) {
534         ifdebug(SCARY_THINGS) logger(LOG_DEBUG, "Ignored signal %d (%s)", a, strsignal(a));
535 }
536
537 static struct {
538         int signal;
539         void (*handler)(int);
540 } sighandlers[] = {
541         {SIGHUP, sighup_handler},
542         {SIGTERM, sigterm_handler},
543         {SIGQUIT, sigquit_handler},
544         {SIGSEGV, fatal_signal_handler},
545         {SIGBUS, fatal_signal_handler},
546         {SIGILL, fatal_signal_handler},
547         {SIGPIPE, ignore_signal_handler},
548         {SIGINT, sigint_handler},
549         {SIGUSR1, sigusr1_handler},
550         {SIGUSR2, sigusr2_handler},
551         {SIGCHLD, ignore_signal_handler},
552         {SIGALRM, sigalrm_handler},
553         {SIGWINCH, sigwinch_handler},
554         {SIGABRT, SIG_DFL},
555         {0, NULL}
556 };
557 #endif
558
559 void setup_signals(void) {
560 #ifndef HAVE_MINGW
561         int i;
562         struct sigaction act;
563
564         sigemptyset(&emptysigset);
565         act.sa_handler = NULL;
566         act.sa_mask = emptysigset;
567         act.sa_flags = 0;
568
569         /* Set a default signal handler for every signal, errors will be
570            ignored. */
571         for(i = 1; i < NSIG; i++) {
572                 if(!do_detach)
573                         act.sa_handler = SIG_DFL;
574                 else
575                         act.sa_handler = unexpected_signal_handler;
576                 sigaction(i, &act, NULL);
577         }
578
579         /* If we didn't detach, allow coredumps */
580         if(!do_detach)
581                 sighandlers[3].handler = SIG_DFL;
582
583         /* Then, for each known signal that we want to catch, assign a
584            handler to the signal, with error checking this time. */
585         for(i = 0; sighandlers[i].signal; i++) {
586                 act.sa_handler = sighandlers[i].handler;
587                 if(sigaction(sighandlers[i].signal, &act, NULL) < 0)
588                         fprintf(stderr, "Installing signal handler for signal %d (%s) failed: %s\n",
589                                         sighandlers[i].signal, strsignal(sighandlers[i].signal),
590                                         strerror(errno));
591         }
592 #endif
593 }