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