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