Don't ignore SIGCHLD, system() needs it.
[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 /* Some functions the less gifted operating systems might lack... */
44
45 #ifdef HAVE_MINGW
46 extern char *identname;
47 extern char *program_name;
48 extern char **g_argv;
49
50 static SC_HANDLE manager = NULL;
51 static SC_HANDLE service = NULL;
52 static SERVICE_STATUS status = {0};
53 static SERVICE_STATUS_HANDLE statushandle = 0;
54
55 bool install_service(void) {
56         char command[4096] = "\"";
57         char **argp;
58         bool space;
59         SERVICE_DESCRIPTION description = {"Virtual Private Network daemon"};
60
61         manager = OpenSCManager(NULL, NULL, SC_MANAGER_ALL_ACCESS);
62         if(!manager) {
63                 logger(LOG_ERR, "Could not open service manager: %s", winerror(GetLastError()));
64                 return false;
65         }
66
67         if(!strchr(program_name, '\\')) {
68                 GetCurrentDirectory(sizeof command - 1, command + 1);
69                 strncat(command, "\\", sizeof command - strlen(command));
70         }
71
72         strncat(command, program_name, sizeof command - strlen(command));
73
74         strncat(command, "\"", sizeof command - strlen(command));
75
76         for(argp = g_argv + 1; *argp; argp++) {
77                 space = strchr(*argp, ' ');
78                 strncat(command, " ", sizeof command - strlen(command));
79                 
80                 if(space)
81                         strncat(command, "\"", sizeof command - strlen(command));
82                 
83                 strncat(command, *argp, sizeof command - strlen(command));
84
85                 if(space)
86                         strncat(command, "\"", sizeof command - strlen(command));
87         }
88
89         service = CreateService(manager, identname, identname,
90                         SERVICE_ALL_ACCESS, SERVICE_WIN32_OWN_PROCESS, SERVICE_AUTO_START, SERVICE_ERROR_NORMAL,
91                         command, NULL, NULL, NULL, NULL, NULL);
92         
93         if(!service) {
94                 DWORD lasterror = GetLastError();
95                 logger(LOG_ERR, "Could not create %s service: %s", identname, winerror(lasterror));
96                 if(lasterror != ERROR_SERVICE_EXISTS)
97                         return false;
98         }
99
100         if(service) {
101                 ChangeServiceConfig2(service, SERVICE_CONFIG_DESCRIPTION, &description);
102                 logger(LOG_INFO, "%s service installed", identname);
103         } else {
104                 service = OpenService(manager, identname, SERVICE_ALL_ACCESS);
105         }
106
107         if(!StartService(service, 0, NULL))
108                 logger(LOG_WARNING, "Could not start %s service: %s", identname, winerror(GetLastError()));
109         else
110                 logger(LOG_INFO, "%s service started", identname);
111
112         return true;
113 }
114
115 bool remove_service(void) {
116         manager = OpenSCManager(NULL, NULL, SC_MANAGER_ALL_ACCESS);
117         if(!manager) {
118                 logger(LOG_ERR, "Could not open service manager: %s", winerror(GetLastError()));
119                 return false;
120         }
121
122         service = OpenService(manager, identname, SERVICE_ALL_ACCESS);
123
124         if(!service) {
125                 logger(LOG_ERR, "Could not open %s service: %s", identname, winerror(GetLastError()));
126                 return false;
127         }
128
129         if(!ControlService(service, SERVICE_CONTROL_STOP, &status))
130                 logger(LOG_ERR, "Could not stop %s service: %s", identname, winerror(GetLastError()));
131         else
132                 logger(LOG_INFO, "%s service stopped", identname);
133
134         if(!DeleteService(service)) {
135                 logger(LOG_ERR, "Could not remove %s service: %s", identname, winerror(GetLastError()));
136                 return false;
137         }
138
139         logger(LOG_INFO, "%s service removed", identname);
140
141         return true;
142 }
143
144 DWORD WINAPI controlhandler(DWORD request, DWORD type, LPVOID boe, LPVOID bah) {
145         switch(request) {
146                 case SERVICE_CONTROL_INTERROGATE:
147                         SetServiceStatus(statushandle, &status);
148                         return NO_ERROR;
149                 case SERVICE_CONTROL_STOP:
150                         logger(LOG_NOTICE, "Got %s request", "SERVICE_CONTROL_STOP");
151                         break;
152                 case SERVICE_CONTROL_SHUTDOWN:
153                         logger(LOG_NOTICE, "Got %s request", "SERVICE_CONTROL_SHUTDOWN");
154                         break;
155                 default:
156                         logger(LOG_WARNING, "Got unexpected request %d", request);
157                         return ERROR_CALL_NOT_IMPLEMENTED;
158         }
159
160         event_loopexit(NULL);
161         status.dwWaitHint = 30000; 
162         status.dwCurrentState = SERVICE_STOP_PENDING; 
163         SetServiceStatus(statushandle, &status);
164         return NO_ERROR;
165 }
166
167 VOID WINAPI run_service(DWORD argc, LPTSTR* argv) {
168         int err = 1;
169         extern int main2(int argc, char **argv);
170
171
172         status.dwServiceType = SERVICE_WIN32; 
173         status.dwControlsAccepted = SERVICE_ACCEPT_STOP | SERVICE_ACCEPT_SHUTDOWN;
174         status.dwWin32ExitCode = 0; 
175         status.dwServiceSpecificExitCode = 0; 
176         status.dwCheckPoint = 0; 
177
178         statushandle = RegisterServiceCtrlHandlerEx(identname, controlhandler, NULL); 
179
180         if (!statushandle) {
181                 logger(LOG_ERR, "System call `%s' failed: %s", "RegisterServiceCtrlHandlerEx", winerror(GetLastError()));
182                 err = 1;
183         } else {
184                 status.dwWaitHint = 30000; 
185                 status.dwCurrentState = SERVICE_START_PENDING; 
186                 SetServiceStatus(statushandle, &status);
187
188                 status.dwWaitHint = 0; 
189                 status.dwCurrentState = SERVICE_RUNNING;
190                 SetServiceStatus(statushandle, &status);
191
192                 err = main2(argc, argv);
193
194                 status.dwWaitHint = 0;
195                 status.dwCurrentState = SERVICE_STOPPED; 
196                 //status.dwWin32ExitCode = err; 
197                 SetServiceStatus(statushandle, &status);
198         }
199
200         return;
201 }
202
203 bool init_service(void) {
204         SERVICE_TABLE_ENTRY services[] = {
205                 {identname, run_service},
206                 {NULL, NULL}
207         };
208
209         if(!StartServiceCtrlDispatcher(services)) {
210                 if(GetLastError() == ERROR_FAILED_SERVICE_CONTROLLER_CONNECT) {
211                         return false;
212                 }
213                 else
214                         logger(LOG_ERR, "System call `%s' failed: %s", "StartServiceCtrlDispatcher", winerror(GetLastError()));
215         }
216
217         return true;
218 }
219 #endif
220
221 /*
222   Detach from current terminal
223 */
224 bool detach(void) {
225 #ifndef HAVE_MINGW
226         signal(SIGALRM, SIG_IGN);
227         signal(SIGPIPE, SIG_IGN);
228         signal(SIGUSR1, SIG_IGN);
229         signal(SIGUSR2, SIG_IGN);
230         signal(SIGWINCH, SIG_IGN);
231
232         closelogger();
233 #endif
234
235         if(do_detach) {
236 #ifndef HAVE_MINGW
237                 if(daemon(0, 0)) {
238                         fprintf(stderr, "Couldn't detach from terminal: %s",
239                                         strerror(errno));
240                         return false;
241                 }
242 #else
243                 if(!statushandle)
244                         exit(install_service());
245 #endif
246         }
247
248         openlogger(identname, use_logfile?LOGMODE_FILE:(do_detach?LOGMODE_SYSLOG:LOGMODE_STDERR));
249
250         logger(LOG_NOTICE, "tincd %s (%s %s) starting, debug level %d",
251                            VERSION, __DATE__, __TIME__, debug_level);
252
253         return true;
254 }
255
256 bool execute_script(const char *name, char **envp) {
257 #ifdef HAVE_SYSTEM
258         int status, len;
259         char *scriptname;
260         int i;
261
262 #ifndef HAVE_MINGW
263         len = xasprintf(&scriptname, "\"%s/%s\"", confbase, name);
264 #else
265         len = xasprintf(&scriptname, "\"%s/%s.bat\"", confbase, name);
266 #endif
267         if(len < 0)
268                 return false;
269
270         scriptname[len - 1] = '\0';
271
272 #ifndef HAVE_TUNEMU
273         /* First check if there is a script */
274
275         if(access(scriptname + 1, F_OK)) {
276                 free(scriptname);
277                 return true;
278         }
279 #endif
280
281         ifdebug(STATUS) logger(LOG_INFO, "Executing script %s", name);
282
283 #ifdef HAVE_PUTENV
284         /* Set environment */
285         
286         for(i = 0; envp[i]; i++)
287                 putenv(envp[i]);
288 #endif
289
290         scriptname[len - 1] = '\"';
291         status = system(scriptname);
292
293         free(scriptname);
294
295         /* Unset environment */
296
297         for(i = 0; envp[i]; i++) {
298                 char *e = strchr(envp[i], '=');
299                 if(e) {
300                         char p[e - envp[i] + 1];
301                         strncpy(p, envp[i], e - envp[i]);
302                         p[e - envp[i]] = '\0';
303                         putenv(p);
304                 }
305         }
306
307 #ifdef WEXITSTATUS
308         if(status != -1) {
309                 if(WIFEXITED(status)) { /* Child exited by itself */
310                         if(WEXITSTATUS(status)) {
311                                 logger(LOG_ERR, "Script %s exited with non-zero status %d",
312                                            name, WEXITSTATUS(status));
313                                 return false;
314                         }
315                 } else if(WIFSIGNALED(status)) {        /* Child was killed by a signal */
316                         logger(LOG_ERR, "Script %s was killed by signal %d (%s)",
317                                    name, WTERMSIG(status), strsignal(WTERMSIG(status)));
318                         return false;
319                 } else {                        /* Something strange happened */
320                         logger(LOG_ERR, "Script %s terminated abnormally", name);
321                         return false;
322                 }
323         } else {
324                 logger(LOG_ERR, "System call `%s' failed: %s", "system", strerror(errno));
325                 return false;
326         }
327 #endif
328 #endif
329         return true;
330 }