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