d08f70ffd0a029ae525873ff74f996d90cd5ab6a
[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.71 2003/08/10 13:35:05 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         if(!strchr(program_name, '\\')) {
97                 GetCurrentDirectory(sizeof(command), command);
98                 strncat(command, "\\", sizeof(command));
99         }
100
101         strncat(command, program_name, sizeof(command));
102         for(argp = g_argv + 1; *argp; argp++) {
103                 space = strchr(*argp, ' ');
104                 strncat(command, " ", sizeof(command));
105                 
106                 if(space)
107                         strncat(command, "\"", sizeof(command));
108                 
109                 strncat(command, *argp, sizeof(command));
110
111                 if(space)
112                         strncat(command, "\"", sizeof(command));
113         }
114
115         service = CreateService(manager, identname, identname,
116                         SERVICE_ALL_ACCESS, SERVICE_WIN32_OWN_PROCESS, SERVICE_AUTO_START, SERVICE_ERROR_NORMAL,
117                         command, "NDIS", NULL, NULL, NULL, NULL);
118         
119         if(!service) {
120                 logger(LOG_ERR, _("Could not create %s service: %s"), identname, winerror(GetLastError()));
121                 return false;
122         }
123
124         ChangeServiceConfig2(service, SERVICE_CONFIG_DESCRIPTION, &description);
125
126         logger(LOG_INFO, _("%s service installed"), identname);
127
128         if(!StartService(service, 0, NULL))
129                 logger(LOG_WARNING, _("Could not start %s service: %s"), identname, winerror(GetLastError()));
130         else
131                 logger(LOG_INFO, _("%s service started"), identname);
132
133         return true;
134 }
135
136 bool remove_service(void) {
137         manager = OpenSCManager(NULL, NULL, SC_MANAGER_ALL_ACCESS);
138         if(!manager) {
139                 logger(LOG_ERR, _("Could not open service manager: %s"), winerror(GetLastError()));
140                 return false;
141         }
142
143         service = OpenService(manager, identname, SERVICE_ALL_ACCESS);
144
145         if(!service) {
146                 logger(LOG_ERR, _("Could not open %s service: %s"), identname, winerror(GetLastError()));
147                 return false;
148         }
149
150         if(!ControlService(service, SERVICE_CONTROL_STOP, &status))
151                 logger(LOG_ERR, _("Could not stop %s service: %s"), identname, winerror(GetLastError()));
152         else
153                 logger(LOG_INFO, _("%s service stopped"), identname);
154
155         if(!DeleteService(service)) {
156                 logger(LOG_ERR, _("Could not remove %s service: %s"), identname, winerror(GetLastError()));
157                 return false;
158         }
159
160         logger(LOG_INFO, _("%s service removed"), identname);
161
162         return true;
163 }
164
165 DWORD WINAPI controlhandler(DWORD request, DWORD type, LPVOID boe, LPVOID bah) {
166         switch(request) {
167                 case SERVICE_CONTROL_STOP:
168                         logger(LOG_NOTICE, _("Got %s request"), "SERVICE_CONTROL_STOP");
169                         running = false;
170                         break;
171                 case SERVICE_CONTROL_SHUTDOWN:
172                         logger(LOG_NOTICE, _("Got %s request"), "SERVICE_CONTROL_SHUTDOWN");
173                         running = false;
174                         break;
175                 default:
176                         logger(LOG_WARNING, _("Got unexpected request %d"), request);
177                         return ERROR_CALL_NOT_IMPLEMENTED;
178         }
179
180         if(!running) {
181                 status.dwWaitHint = 30000; 
182                 status.dwCurrentState = SERVICE_STOP_PENDING; 
183                 SetServiceStatus(statushandle, &status);
184         }
185
186         return NO_ERROR;
187 }
188
189 VOID WINAPI run_service(DWORD argc, LPTSTR* argv)
190 {
191         int err = 1;
192         extern int main2(int argc, char **argv);
193
194
195         status.dwServiceType = SERVICE_WIN32; 
196         status.dwControlsAccepted = SERVICE_ACCEPT_STOP | SERVICE_ACCEPT_SHUTDOWN;
197         status.dwWin32ExitCode = 0; 
198         status.dwServiceSpecificExitCode = 0; 
199         status.dwCheckPoint = 0; 
200
201         statushandle = RegisterServiceCtrlHandlerEx(identname, controlhandler, NULL); 
202
203         if (!statushandle) {
204                 logger(LOG_ERR, _("System call `%s' failed: %s"), "RegisterServiceCtrlHandlerEx", winerror(GetLastError()));
205                 err = 1;
206         } else {
207                 status.dwWaitHint = 30000; 
208                 status.dwCurrentState = SERVICE_START_PENDING; 
209                 SetServiceStatus(statushandle, &status);
210
211                 status.dwWaitHint = 0; 
212                 status.dwCurrentState = SERVICE_RUNNING;
213                 SetServiceStatus(statushandle, &status);
214
215                 err = main2(argc, argv);
216
217                 status.dwWaitHint = 0;
218                 status.dwCurrentState = SERVICE_STOPPED; 
219                 //status.dwWin32ExitCode = err; 
220                 SetServiceStatus(statushandle, &status);
221         }
222
223         return;
224 }
225
226 bool init_service(void) {
227         SERVICE_TABLE_ENTRY services[] = {
228                 {identname, run_service},
229                 {NULL, NULL}
230         };
231
232         if(!StartServiceCtrlDispatcher(services)) {
233                 if(GetLastError() == ERROR_FAILED_SERVICE_CONTROLLER_CONNECT) {
234                         return false;
235                 }
236                 else
237                         logger(LOG_ERR, _("System call `%s' failed: %s"), "StartServiceCtrlDispatcher", winerror(GetLastError()));
238         }
239
240         return true;
241 }
242 #endif
243
244 #ifndef HAVE_MINGW
245 /*
246   check for an existing tinc for this net, and write pid to pidfile
247 */
248 static bool write_pidfile(void)
249 {
250         int pid;
251
252         cp();
253
254         pid = check_pid(pidfilename);
255
256         if(pid) {
257                 if(netname)
258                         fprintf(stderr, _("A tincd is already running for net `%s' with pid %d.\n"),
259                                         netname, pid);
260                 else
261                         fprintf(stderr, _("A tincd is already running with pid %d.\n"), pid);
262                 return false;
263         }
264
265         /* if it's locked, write-protected, or whatever */
266         if(!write_pid(pidfilename))
267                 return false;
268
269         return true;
270 }
271 #endif
272
273 /*
274   kill older tincd for this net
275 */
276 bool kill_other(int signal)
277 {
278 #ifndef HAVE_MINGW
279         int pid;
280
281         cp();
282
283         pid = read_pid(pidfilename);
284
285         if(!pid) {
286                 if(netname)
287                         fprintf(stderr, _("No other tincd is running for net `%s'.\n"),
288                                         netname);
289                 else
290                         fprintf(stderr, _("No other tincd is running.\n"));
291                 return false;
292         }
293
294         errno = 0;                                      /* No error, sometimes errno is only changed on error */
295
296         /* ESRCH is returned when no process with that pid is found */
297         if(kill(pid, signal) && errno == ESRCH) {
298                 if(netname)
299                         fprintf(stderr, _("The tincd for net `%s' is no longer running. "),
300                                         netname);
301                 else
302                         fprintf(stderr, _("The tincd is no longer running. "));
303
304                 fprintf(stderr, _("Removing stale lock file.\n"));
305                 remove_pid(pidfilename);
306         }
307
308         return true;
309 #else
310         return remove_service();
311 #endif
312 }
313
314 /*
315   Detach from current terminal, write pidfile, kill parent
316 */
317 bool detach(void)
318 {
319         cp();
320
321         setup_signals();
322
323         /* First check if we can open a fresh new pidfile */
324
325 #ifndef HAVE_MINGW
326         if(!write_pidfile())
327                 return false;
328
329         /* If we succeeded in doing that, detach */
330
331         closelogger();
332 #endif
333
334         if(do_detach) {
335 #ifndef HAVE_MINGW
336                 if(daemon(0, 0)) {
337                         fprintf(stderr, _("Couldn't detach from terminal: %s"),
338                                         strerror(errno));
339                         return false;
340                 }
341
342                 /* Now UPDATE the pid in the pidfile, because we changed it... */
343
344                 if(!write_pid(pidfilename))
345                         return false;
346 #else
347                 if(!statushandle)
348                         exit(install_service());
349 #endif
350         }
351
352         openlogger(identname, use_logfile?LOGMODE_FILE:(do_detach?LOGMODE_SYSLOG:LOGMODE_STDERR));
353
354         logger(LOG_NOTICE, _("tincd %s (%s %s) starting, debug level %d"),
355                            VERSION, __DATE__, __TIME__, debug_level);
356
357         xalloc_fail_func = memory_full;
358
359         return true;
360 }
361
362 bool execute_script(const char *name, char **envp)
363 {
364 #ifdef HAVE_SYSTEM
365         int status;
366         struct stat s;
367         char *scriptname;
368
369         cp();
370
371 #ifndef HAVE_MINGW
372         asprintf(&scriptname, "%s/%s", confbase, name);
373
374         /* First check if there is a script */
375
376         if(stat(scriptname, &s))
377                 return true;
378
379         ifdebug(STATUS) logger(LOG_INFO, _("Executing script %s"), name);
380
381         free(scriptname);
382 #endif
383
384 #ifdef HAVE_PUTENV
385         /* Set environment */
386         
387         while(*envp)
388                 putenv(*envp++);
389 #endif
390
391         asprintf(&scriptname, "\"%s/%s\"", confbase, name);
392         status = system(scriptname);
393
394         free(scriptname);
395
396         /* Unset environment? */
397
398 #ifdef WEXITSTATUS
399         if(status != -1) {
400                 if(WIFEXITED(status)) { /* Child exited by itself */
401                         if(WEXITSTATUS(status)) {
402                                 logger(LOG_ERR, _("Script %s exited with non-zero status %d"),
403                                            name, WEXITSTATUS(status));
404                                 return false;
405                         }
406                 } else if(WIFSIGNALED(status)) {        /* Child was killed by a signal */
407                         logger(LOG_ERR, _("Script %s was killed by signal %d (%s)"),
408                                    name, WTERMSIG(status), strsignal(WTERMSIG(status)));
409                         return false;
410                 } else {                        /* Something strange happened */
411                         logger(LOG_ERR, _("Script %s terminated abnormally"), name);
412                         return false;
413                 }
414         } else {
415                 logger(LOG_ERR, _("System call `%s' failed: %s"), "system", strerror(errno));
416                 return false;
417         }
418 #endif
419 #endif
420         return true;
421 }
422
423
424 /*
425   Signal handlers.
426 */
427
428 #ifndef HAVE_MINGW
429 static RETSIGTYPE sigterm_handler(int a)
430 {
431         logger(LOG_NOTICE, _("Got %s signal"), "TERM");
432         running = false;
433 }
434
435 static RETSIGTYPE sigquit_handler(int a)
436 {
437         logger(LOG_NOTICE, _("Got %s signal"), "QUIT");
438         running = false;
439 }
440
441 static RETSIGTYPE fatal_signal_square(int a)
442 {
443         logger(LOG_ERR, _("Got another fatal signal %d (%s): not restarting."), a,
444                    strsignal(a));
445         cp_trace();
446         exit(1);
447 }
448
449 static RETSIGTYPE fatal_signal_handler(int a)
450 {
451         struct sigaction act;
452         logger(LOG_ERR, _("Got fatal signal %d (%s)"), a, strsignal(a));
453         cp_trace();
454
455         if(do_detach) {
456                 logger(LOG_NOTICE, _("Trying to re-execute in 5 seconds..."));
457
458                 act.sa_handler = fatal_signal_square;
459                 act.sa_mask = emptysigset;
460                 act.sa_flags = 0;
461                 sigaction(SIGSEGV, &act, NULL);
462
463                 close_network_connections();
464                 sleep(5);
465                 remove_pid(pidfilename);
466                 execvp(g_argv[0], g_argv);
467         } else {
468                 logger(LOG_NOTICE, _("Not restarting."));
469                 exit(1);
470         }
471 }
472
473 static RETSIGTYPE sighup_handler(int a)
474 {
475         logger(LOG_NOTICE, _("Got %s signal"), "HUP");
476         sighup = true;
477 }
478
479 static RETSIGTYPE sigint_handler(int a)
480 {
481         logger(LOG_NOTICE, _("Got %s signal"), "INT");
482
483         if(saved_debug_level != -1) {
484                 logger(LOG_NOTICE, _("Reverting to old debug level (%d)"),
485                         saved_debug_level);
486                 debug_level = saved_debug_level;
487                 saved_debug_level = -1;
488         } else {
489                 logger(LOG_NOTICE,
490                         _("Temporarily setting debug level to 5.  Kill me with SIGINT again to go back to level %d."),
491                         debug_level);
492                 saved_debug_level = debug_level;
493                 debug_level = 5;
494         }
495 }
496
497 static RETSIGTYPE sigalrm_handler(int a)
498 {
499         logger(LOG_NOTICE, _("Got %s signal"), "ALRM");
500         sigalrm = true;
501 }
502
503 static RETSIGTYPE sigusr1_handler(int a)
504 {
505         dump_connections();
506 }
507
508 static RETSIGTYPE sigusr2_handler(int a)
509 {
510         dump_device_stats();
511         dump_nodes();
512         dump_edges();
513         dump_subnets();
514 }
515
516 static RETSIGTYPE sigwinch_handler(int a)
517 {
518         do_purge = true;
519 }
520
521 static RETSIGTYPE unexpected_signal_handler(int a)
522 {
523         logger(LOG_WARNING, _("Got unexpected signal %d (%s)"), a, strsignal(a));
524         cp_trace();
525 }
526
527 static RETSIGTYPE ignore_signal_handler(int a)
528 {
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         {0, NULL}
550 };
551 #endif
552
553 void setup_signals(void)
554 {
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 = 0; 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 }