Even simpler 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 /* 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(SIGCHLD, SIG_IGN);
228
229         closelogger();
230 #endif
231
232         if(do_detach) {
233 #ifndef HAVE_MINGW
234                 if(daemon(0, 0)) {
235                         fprintf(stderr, "Couldn't detach from terminal: %s",
236                                         strerror(errno));
237                         return false;
238                 }
239 #else
240                 if(!statushandle)
241                         exit(install_service());
242 #endif
243         }
244
245         openlogger(identname, use_logfile?LOGMODE_FILE:(do_detach?LOGMODE_SYSLOG:LOGMODE_STDERR));
246
247         logger(LOG_NOTICE, "tincd %s (%s %s) starting, debug level %d",
248                            VERSION, __DATE__, __TIME__, debug_level);
249
250         return true;
251 }
252
253 bool execute_script(const char *name, char **envp) {
254 #ifdef HAVE_SYSTEM
255         int status, len;
256         char *scriptname;
257         int i;
258
259 #ifndef HAVE_MINGW
260         len = xasprintf(&scriptname, "\"%s/%s\"", confbase, name);
261 #else
262         len = xasprintf(&scriptname, "\"%s/%s.bat\"", confbase, name);
263 #endif
264         if(len < 0)
265                 return false;
266
267         scriptname[len - 1] = '\0';
268
269 #ifndef HAVE_TUNEMU
270         /* First check if there is a script */
271
272         if(access(scriptname + 1, F_OK)) {
273                 free(scriptname);
274                 return true;
275         }
276 #endif
277
278         ifdebug(STATUS) logger(LOG_INFO, "Executing script %s", name);
279
280 #ifdef HAVE_PUTENV
281         /* Set environment */
282         
283         for(i = 0; envp[i]; i++)
284                 putenv(envp[i]);
285 #endif
286
287         scriptname[len - 1] = '\"';
288         status = system(scriptname);
289
290         free(scriptname);
291
292         /* Unset environment */
293
294         for(i = 0; envp[i]; i++) {
295                 char *e = strchr(envp[i], '=');
296                 if(e) {
297                         char p[e - envp[i] + 1];
298                         strncpy(p, envp[i], e - envp[i]);
299                         p[e - envp[i]] = '\0';
300                         putenv(p);
301                 }
302         }
303
304 #ifdef WEXITSTATUS
305         if(status != -1) {
306                 if(WIFEXITED(status)) { /* Child exited by itself */
307                         if(WEXITSTATUS(status)) {
308                                 logger(LOG_ERR, "Script %s exited with non-zero status %d",
309                                            name, WEXITSTATUS(status));
310                                 return false;
311                         }
312                 } else if(WIFSIGNALED(status)) {        /* Child was killed by a signal */
313                         logger(LOG_ERR, "Script %s was killed by signal %d (%s)",
314                                    name, WTERMSIG(status), strsignal(WTERMSIG(status)));
315                         return false;
316                 } else {                        /* Something strange happened */
317                         logger(LOG_ERR, "Script %s terminated abnormally", name);
318                         return false;
319                 }
320         } else {
321                 logger(LOG_ERR, "System call `%s' failed: %s", "system", strerror(errno));
322                 return false;
323         }
324 #endif
325 #endif
326         return true;
327 }