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