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