Simplify signal handling.
[tinc] / src / process.c
1 /*
2     process.c -- process management functions
3     Copyright (C) 1999-2005 Ivo Timmermans,
4                   2000-2011 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 "control.h"
26 #include "device.h"
27 #include "edge.h"
28 #include "logger.h"
29 #include "node.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 sigalrm = false;
38
39 extern char *identname;
40 extern char **g_argv;
41 extern bool use_logfile;
42
43 static void memory_full(int size) {
44         logger(LOG_ERR, "Memory exhausted (couldn't allocate %d bytes), exitting.", size);
45         exit(1);
46 }
47
48 /* Some functions the less gifted operating systems might lack... */
49
50 #ifdef HAVE_MINGW
51 extern char *identname;
52 extern char *program_name;
53 extern char **g_argv;
54
55 static SC_HANDLE manager = NULL;
56 static SC_HANDLE service = NULL;
57 static SERVICE_STATUS status = {0};
58 static SERVICE_STATUS_HANDLE statushandle = 0;
59
60 bool install_service(void) {
61         char command[4096] = "\"";
62         char **argp;
63         bool space;
64         SERVICE_DESCRIPTION description = {"Virtual Private Network daemon"};
65
66         manager = OpenSCManager(NULL, NULL, SC_MANAGER_ALL_ACCESS);
67         if(!manager) {
68                 logger(LOG_ERR, "Could not open service manager: %s", winerror(GetLastError()));
69                 return false;
70         }
71
72         if(!strchr(program_name, '\\')) {
73                 GetCurrentDirectory(sizeof command - 1, command + 1);
74                 strncat(command, "\\", sizeof command - strlen(command));
75         }
76
77         strncat(command, program_name, sizeof command - strlen(command));
78
79         strncat(command, "\"", sizeof command - strlen(command));
80
81         for(argp = g_argv + 1; *argp; argp++) {
82                 space = strchr(*argp, ' ');
83                 strncat(command, " ", sizeof command - strlen(command));
84                 
85                 if(space)
86                         strncat(command, "\"", sizeof command - strlen(command));
87                 
88                 strncat(command, *argp, sizeof command - strlen(command));
89
90                 if(space)
91                         strncat(command, "\"", sizeof command - strlen(command));
92         }
93
94         service = CreateService(manager, identname, identname,
95                         SERVICE_ALL_ACCESS, SERVICE_WIN32_OWN_PROCESS, SERVICE_AUTO_START, SERVICE_ERROR_NORMAL,
96                         command, NULL, NULL, NULL, NULL, NULL);
97         
98         if(!service) {
99                 DWORD lasterror = GetLastError();
100                 logger(LOG_ERR, "Could not create %s service: %s", identname, winerror(lasterror));
101                 if(lasterror != ERROR_SERVICE_EXISTS)
102                         return false;
103         }
104
105         if(service) {
106                 ChangeServiceConfig2(service, SERVICE_CONFIG_DESCRIPTION, &description);
107                 logger(LOG_INFO, "%s service installed", identname);
108         } else {
109                 service = OpenService(manager, identname, SERVICE_ALL_ACCESS);
110         }
111
112         if(!StartService(service, 0, NULL))
113                 logger(LOG_WARNING, "Could not start %s service: %s", identname, winerror(GetLastError()));
114         else
115                 logger(LOG_INFO, "%s service started", identname);
116
117         return true;
118 }
119
120 bool remove_service(void) {
121         manager = OpenSCManager(NULL, NULL, SC_MANAGER_ALL_ACCESS);
122         if(!manager) {
123                 logger(LOG_ERR, "Could not open service manager: %s", winerror(GetLastError()));
124                 return false;
125         }
126
127         service = OpenService(manager, identname, SERVICE_ALL_ACCESS);
128
129         if(!service) {
130                 logger(LOG_ERR, "Could not open %s service: %s", identname, winerror(GetLastError()));
131                 return false;
132         }
133
134         if(!ControlService(service, SERVICE_CONTROL_STOP, &status))
135                 logger(LOG_ERR, "Could not stop %s service: %s", identname, winerror(GetLastError()));
136         else
137                 logger(LOG_INFO, "%s service stopped", identname);
138
139         if(!DeleteService(service)) {
140                 logger(LOG_ERR, "Could not remove %s service: %s", identname, winerror(GetLastError()));
141                 return false;
142         }
143
144         logger(LOG_INFO, "%s service removed", identname);
145
146         return true;
147 }
148
149 DWORD WINAPI controlhandler(DWORD request, DWORD type, LPVOID boe, LPVOID bah) {
150         switch(request) {
151                 case SERVICE_CONTROL_INTERROGATE:
152                         SetServiceStatus(statushandle, &status);
153                         return NO_ERROR;
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 /*
227   Detach from current terminal
228 */
229 bool detach(void) {
230         setup_signals();
231
232 #ifndef HAVE_MINGW
233         closelogger();
234 #endif
235
236         if(do_detach) {
237 #ifndef HAVE_MINGW
238                 if(daemon(0, 0)) {
239                         fprintf(stderr, "Couldn't detach from terminal: %s",
240                                         strerror(errno));
241                         return false;
242                 }
243 #else
244                 if(!statushandle)
245                         exit(install_service());
246 #endif
247         }
248
249         openlogger(identname, use_logfile?LOGMODE_FILE:(do_detach?LOGMODE_SYSLOG:LOGMODE_STDERR));
250
251         logger(LOG_NOTICE, "tincd %s (%s %s) starting, debug level %d",
252                            VERSION, __DATE__, __TIME__, debug_level);
253
254         xalloc_fail_func = memory_full;
255
256         return true;
257 }
258
259 bool execute_script(const char *name, char **envp) {
260 #ifdef HAVE_SYSTEM
261         int status, len;
262         char *scriptname;
263         int i;
264
265 #ifndef HAVE_MINGW
266         len = xasprintf(&scriptname, "\"%s/%s\"", confbase, name);
267 #else
268         len = xasprintf(&scriptname, "\"%s/%s.bat\"", confbase, name);
269 #endif
270         if(len < 0)
271                 return false;
272
273         scriptname[len - 1] = '\0';
274
275 #ifndef HAVE_TUNEMU
276         /* First check if there is a script */
277
278         if(access(scriptname + 1, F_OK)) {
279                 free(scriptname);
280                 return true;
281         }
282 #endif
283
284         ifdebug(STATUS) logger(LOG_INFO, "Executing script %s", name);
285
286 #ifdef HAVE_PUTENV
287         /* Set environment */
288         
289         for(i = 0; envp[i]; i++)
290                 putenv(envp[i]);
291 #endif
292
293         scriptname[len - 1] = '\"';
294         status = system(scriptname);
295
296         free(scriptname);
297
298         /* Unset environment */
299
300         for(i = 0; envp[i]; i++) {
301                 char *e = strchr(envp[i], '=');
302                 if(e) {
303                         char p[e - envp[i] + 1];
304                         strncpy(p, envp[i], e - envp[i]);
305                         p[e - envp[i]] = '\0';
306                         putenv(p);
307                 }
308         }
309
310 #ifdef WEXITSTATUS
311         if(status != -1) {
312                 if(WIFEXITED(status)) { /* Child exited by itself */
313                         if(WEXITSTATUS(status)) {
314                                 logger(LOG_ERR, "Script %s exited with non-zero status %d",
315                                            name, WEXITSTATUS(status));
316                                 return false;
317                         }
318                 } else if(WIFSIGNALED(status)) {        /* Child was killed by a signal */
319                         logger(LOG_ERR, "Script %s was killed by signal %d (%s)",
320                                    name, WTERMSIG(status), strsignal(WTERMSIG(status)));
321                         return false;
322                 } else {                        /* Something strange happened */
323                         logger(LOG_ERR, "Script %s terminated abnormally", name);
324                         return false;
325                 }
326         } else {
327                 logger(LOG_ERR, "System call `%s' failed: %s", "system", strerror(errno));
328                 return false;
329         }
330 #endif
331 #endif
332         return true;
333 }
334
335
336 /*
337   Signal handlers.
338 */
339
340 #ifndef HAVE_MINGW
341 static RETSIGTYPE ignore_signal_handler(int a) {
342         ifdebug(SCARY_THINGS) logger(LOG_DEBUG, "Ignored signal %d (%s)", a, strsignal(a));
343 }
344
345 static struct {
346         int signal;
347         void (*handler)(int);
348 } sighandlers[] = {
349         {SIGPIPE, ignore_signal_handler},
350         {SIGCHLD, ignore_signal_handler},
351         {0, NULL}
352 };
353 #endif
354
355 void setup_signals(void) {
356 #ifndef HAVE_MINGW
357         int i;
358         struct sigaction act = {NULL};
359
360         sigemptyset(&act.sa_mask);
361
362         for(i = 0; sighandlers[i].signal; i++) {
363                 act.sa_handler = sighandlers[i].handler;
364                 if(sigaction(sighandlers[i].signal, &act, NULL) < 0)
365                         fprintf(stderr, "Installing signal handler for signal %d (%s) failed: %s\n",
366                                         sighandlers[i].signal, strsignal(sighandlers[i].signal),
367                                         strerror(errno));
368         }
369 #endif
370 }