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