Remove last references to the global variable "running".
[tinc] / src / process.c
1 /*
2     process.c -- process management functions
3     Copyright (C) 1999-2005 Ivo Timmermans,
4                   2000-2006 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     $Id$
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 sigalrm = false;
40
41 extern char *identname;
42 extern char *pidfilename;
43 extern char **g_argv;
44 extern bool use_logfile;
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_STOP:
156                         logger(LOG_NOTICE, _("Got %s request"), "SERVICE_CONTROL_STOP");
157                         break;
158                 case SERVICE_CONTROL_SHUTDOWN:
159                         logger(LOG_NOTICE, _("Got %s request"), "SERVICE_CONTROL_SHUTDOWN");
160                         break;
161                 default:
162                         logger(LOG_WARNING, _("Got unexpected request %d"), request);
163                         return ERROR_CALL_NOT_IMPLEMENTED;
164         }
165
166         event_loopexit(NULL);
167         status.dwWaitHint = 30000; 
168         status.dwCurrentState = SERVICE_STOP_PENDING; 
169         SetServiceStatus(statushandle, &status);
170         return NO_ERROR;
171 }
172
173 VOID WINAPI run_service(DWORD argc, LPTSTR* argv)
174 {
175         int err = 1;
176         extern int main2(int argc, char **argv);
177
178
179         status.dwServiceType = SERVICE_WIN32; 
180         status.dwControlsAccepted = SERVICE_ACCEPT_STOP | SERVICE_ACCEPT_SHUTDOWN;
181         status.dwWin32ExitCode = 0; 
182         status.dwServiceSpecificExitCode = 0; 
183         status.dwCheckPoint = 0; 
184
185         statushandle = RegisterServiceCtrlHandlerEx(identname, controlhandler, NULL); 
186
187         if (!statushandle) {
188                 logger(LOG_ERR, _("System call `%s' failed: %s"), "RegisterServiceCtrlHandlerEx", winerror(GetLastError()));
189                 err = 1;
190         } else {
191                 status.dwWaitHint = 30000; 
192                 status.dwCurrentState = SERVICE_START_PENDING; 
193                 SetServiceStatus(statushandle, &status);
194
195                 status.dwWaitHint = 0; 
196                 status.dwCurrentState = SERVICE_RUNNING;
197                 SetServiceStatus(statushandle, &status);
198
199                 err = main2(argc, argv);
200
201                 status.dwWaitHint = 0;
202                 status.dwCurrentState = SERVICE_STOPPED; 
203                 //status.dwWin32ExitCode = err; 
204                 SetServiceStatus(statushandle, &status);
205         }
206
207         return;
208 }
209
210 bool init_service(void) {
211         SERVICE_TABLE_ENTRY services[] = {
212                 {identname, run_service},
213                 {NULL, NULL}
214         };
215
216         if(!StartServiceCtrlDispatcher(services)) {
217                 if(GetLastError() == ERROR_FAILED_SERVICE_CONTROLLER_CONNECT) {
218                         return false;
219                 }
220                 else
221                         logger(LOG_ERR, _("System call `%s' failed: %s"), "StartServiceCtrlDispatcher", winerror(GetLastError()));
222         }
223
224         return true;
225 }
226 #endif
227
228 #ifndef HAVE_MINGW
229 /*
230   check for an existing tinc for this net, and write pid to pidfile
231 */
232 static bool write_pidfile(void)
233 {
234         pid_t pid;
235
236         cp();
237
238         pid = check_pid(pidfilename);
239
240         if(pid) {
241                 if(netname)
242                         fprintf(stderr, _("A tincd is already running for net `%s' with pid %ld.\n"),
243                                         netname, (long)pid);
244                 else
245                         fprintf(stderr, _("A tincd is already running with pid %ld.\n"), (long)pid);
246                 return false;
247         }
248
249         /* if it's locked, write-protected, or whatever */
250         if(!write_pid(pidfilename)) {
251                 fprintf(stderr, _("Could write pid file %s: %s\n"), pidfilename, strerror(errno));
252                 return false;
253         }
254
255         return true;
256 }
257 #endif
258
259 /*
260   kill older tincd for this net
261 */
262 bool kill_other(int signal)
263 {
264 #ifndef HAVE_MINGW
265         pid_t pid;
266
267         cp();
268
269         pid = read_pid(pidfilename);
270
271         if(!pid) {
272                 if(netname)
273                         fprintf(stderr, _("No other tincd is running for net `%s'.\n"),
274                                         netname);
275                 else
276                         fprintf(stderr, _("No other tincd is running.\n"));
277                 return false;
278         }
279
280         errno = 0;                                      /* No error, sometimes errno is only changed on error */
281
282         /* ESRCH is returned when no process with that pid is found */
283         if(kill(pid, signal) && errno == ESRCH) {
284                 if(netname)
285                         fprintf(stderr, _("The tincd for net `%s' is no longer running. "),
286                                         netname);
287                 else
288                         fprintf(stderr, _("The tincd is no longer running. "));
289
290                 fprintf(stderr, _("Removing stale lock file.\n"));
291                 remove_pid(pidfilename);
292         }
293
294         return true;
295 #else
296         return remove_service();
297 #endif
298 }
299
300 /*
301   Detach from current terminal, write pidfile, kill parent
302 */
303 bool detach(void)
304 {
305         cp();
306
307         setup_signals();
308
309         /* First check if we can open a fresh new pidfile */
310
311 #ifndef HAVE_MINGW
312         if(!write_pidfile())
313                 return false;
314
315         /* If we succeeded in doing that, detach */
316
317         closelogger();
318 #endif
319
320         if(do_detach) {
321 #ifndef HAVE_MINGW
322                 if(daemon(0, 0)) {
323                         fprintf(stderr, _("Couldn't detach from terminal: %s"),
324                                         strerror(errno));
325                         return false;
326                 }
327
328                 /* Now UPDATE the pid in the pidfile, because we changed it... */
329
330                 if(!write_pid(pidfilename)) {
331                         fprintf(stderr, _("Could not write pid file %s: %s\n"), pidfilename, strerror(errno));
332                         return false;
333                 }
334 #else
335                 if(!statushandle)
336                         exit(install_service());
337 #endif
338         }
339
340         openlogger(identname, use_logfile?LOGMODE_FILE:(do_detach?LOGMODE_SYSLOG:LOGMODE_STDERR));
341
342         logger(LOG_NOTICE, _("tincd %s (%s %s) starting, debug level %d"),
343                            VERSION, __DATE__, __TIME__, debug_level);
344
345         xalloc_fail_func = memory_full;
346
347         return true;
348 }
349
350 bool execute_script(const char *name, char **envp)
351 {
352 #ifdef HAVE_SYSTEM
353         int status, len;
354         struct stat s;
355         char *scriptname, *p;
356         int i;
357
358         cp();
359
360 #ifndef HAVE_MINGW
361         len = asprintf(&scriptname, "\"%s/%s\"", confbase, name);
362 #else
363         len = asprintf(&scriptname, "\"%s/%s.bat\"", confbase, name);
364 #endif
365         if(len < 0)
366                 return false;
367
368         scriptname[len - 1] = '\0';
369
370         /* First check if there is a script */
371
372         if(stat(scriptname + 1, &s)) {
373                 free(scriptname);
374                 return true;
375         }
376
377         ifdebug(STATUS) logger(LOG_INFO, _("Executing script %s"), name);
378
379 #ifdef HAVE_PUTENV
380         /* Set environment */
381         
382         for(i = 0; envp[i]; i++)
383                 putenv(envp[i]);
384 #endif
385
386         scriptname[len - 1] = '\"';
387         status = system(scriptname);
388
389         free(scriptname);
390
391         /* Unset environment */
392
393         for(i = 0; envp[i]; i++) {
394                 char *e = strchr(envp[i], '=');
395                 if(e) {
396                         p = alloca(e - envp[i] + 1);
397                         strncpy(p, envp[i], e - envp[i]);
398                         p[e - envp[i]] = '\0';
399                         putenv(p);
400                 }
401         }
402
403 #ifdef WEXITSTATUS
404         if(status != -1) {
405                 if(WIFEXITED(status)) { /* Child exited by itself */
406                         if(WEXITSTATUS(status)) {
407                                 logger(LOG_ERR, _("Script %s exited with non-zero status %d"),
408                                            name, WEXITSTATUS(status));
409                                 return false;
410                         }
411                 } else if(WIFSIGNALED(status)) {        /* Child was killed by a signal */
412                         logger(LOG_ERR, _("Script %s was killed by signal %d (%s)"),
413                                    name, WTERMSIG(status), strsignal(WTERMSIG(status)));
414                         return false;
415                 } else {                        /* Something strange happened */
416                         logger(LOG_ERR, _("Script %s terminated abnormally"), name);
417                         return false;
418                 }
419         } else {
420                 logger(LOG_ERR, _("System call `%s' failed: %s"), "system", strerror(errno));
421                 return false;
422         }
423 #endif
424 #endif
425         return true;
426 }
427
428
429 /*
430   Signal handlers.
431 */
432
433 #ifndef HAVE_MINGW
434 static RETSIGTYPE fatal_signal_square(int a)
435 {
436         logger(LOG_ERR, _("Got another fatal signal %d (%s): not restarting."), a,
437                    strsignal(a));
438         cp_trace();
439         exit(1);
440 }
441
442 static RETSIGTYPE fatal_signal_handler(int a)
443 {
444         struct sigaction act;
445         logger(LOG_ERR, _("Got fatal signal %d (%s)"), a, strsignal(a));
446         cp_trace();
447
448         if(do_detach) {
449                 logger(LOG_NOTICE, _("Trying to re-execute in 5 seconds..."));
450
451                 act.sa_handler = fatal_signal_square;
452                 act.sa_mask = emptysigset;
453                 act.sa_flags = 0;
454                 sigaction(SIGSEGV, &act, NULL);
455
456                 close_network_connections();
457                 sleep(5);
458                 remove_pid(pidfilename);
459                 execvp(g_argv[0], g_argv);
460         } else {
461                 logger(LOG_NOTICE, _("Not restarting."));
462                 exit(1);
463         }
464 }
465
466 static RETSIGTYPE unexpected_signal_handler(int a)
467 {
468         logger(LOG_WARNING, _("Got unexpected signal %d (%s)"), a, strsignal(a));
469         cp_trace();
470 }
471
472 static RETSIGTYPE ignore_signal_handler(int a)
473 {
474         ifdebug(SCARY_THINGS) logger(LOG_DEBUG, _("Ignored signal %d (%s)"), a, strsignal(a));
475 }
476
477 static struct {
478         int signal;
479         void (*handler)(int);
480 } sighandlers[] = {
481         {SIGSEGV, fatal_signal_handler},
482         {SIGBUS, fatal_signal_handler},
483         {SIGILL, fatal_signal_handler},
484         {SIGPIPE, ignore_signal_handler},
485         {SIGCHLD, ignore_signal_handler},
486         {0, NULL}
487 };
488 #endif
489
490 void setup_signals(void)
491 {
492 #ifndef HAVE_MINGW
493         int i;
494         struct sigaction act;
495
496         sigemptyset(&emptysigset);
497         act.sa_handler = NULL;
498         act.sa_mask = emptysigset;
499         act.sa_flags = 0;
500
501         /* Set a default signal handler for every signal, errors will be
502            ignored. */
503         for(i = 0; i < NSIG; i++) {
504                 if(!do_detach)
505                         act.sa_handler = SIG_DFL;
506                 else
507                         act.sa_handler = unexpected_signal_handler;
508                 sigaction(i, &act, NULL);
509         }
510
511         /* If we didn't detach, allow coredumps */
512         if(!do_detach)
513                 sighandlers[0].handler = SIG_DFL;
514
515         /* Then, for each known signal that we want to catch, assign a
516            handler to the signal, with error checking this time. */
517         for(i = 0; sighandlers[i].signal; i++) {
518                 act.sa_handler = sighandlers[i].handler;
519                 if(sigaction(sighandlers[i].signal, &act, NULL) < 0)
520                         fprintf(stderr, _("Installing signal handler for signal %d (%s) failed: %s\n"),
521                                         sighandlers[i].signal, strsignal(sighandlers[i].signal),
522                                         strerror(errno));
523         }
524 #endif
525 }