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