Re-add support for SIGALRM.
[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 "net.h"
30 #include "node.h"
31 #include "process.h"
32 #include "subnet.h"
33 #include "utils.h"
34 #include "xalloc.h"
35
36 /* If zero, don't detach from the terminal. */
37 bool do_detach = true;
38 bool sigalrm = false;
39
40 extern char *identname;
41 extern char **g_argv;
42 extern bool use_logfile;
43
44 /* Some functions the less gifted operating systems might lack... */
45
46 #ifdef HAVE_MINGW
47 extern char *identname;
48 extern char *program_name;
49 extern char **g_argv;
50
51 static SC_HANDLE manager = NULL;
52 static SC_HANDLE service = NULL;
53 static SERVICE_STATUS status = {0};
54 static SERVICE_STATUS_HANDLE statushandle = 0;
55
56 bool install_service(void) {
57         char command[4096] = "\"";
58         char **argp;
59         bool space;
60         SERVICE_DESCRIPTION description = {"Virtual Private Network daemon"};
61
62         manager = OpenSCManager(NULL, NULL, SC_MANAGER_ALL_ACCESS);
63         if(!manager) {
64                 logger(LOG_ERR, "Could not open service manager: %s", winerror(GetLastError()));
65                 return false;
66         }
67
68         if(!strchr(program_name, '\\')) {
69                 GetCurrentDirectory(sizeof command - 1, command + 1);
70                 strncat(command, "\\", sizeof command - strlen(command));
71         }
72
73         strncat(command, program_name, sizeof command - strlen(command));
74
75         strncat(command, "\"", sizeof command - strlen(command));
76
77         for(argp = g_argv + 1; *argp; argp++) {
78                 space = strchr(*argp, ' ');
79                 strncat(command, " ", sizeof command - strlen(command));
80                 
81                 if(space)
82                         strncat(command, "\"", sizeof command - strlen(command));
83                 
84                 strncat(command, *argp, sizeof command - strlen(command));
85
86                 if(space)
87                         strncat(command, "\"", sizeof command - strlen(command));
88         }
89
90         service = CreateService(manager, identname, identname,
91                         SERVICE_ALL_ACCESS, SERVICE_WIN32_OWN_PROCESS, SERVICE_AUTO_START, SERVICE_ERROR_NORMAL,
92                         command, NULL, NULL, NULL, NULL, NULL);
93         
94         if(!service) {
95                 DWORD lasterror = GetLastError();
96                 logger(LOG_ERR, "Could not create %s service: %s", identname, winerror(lasterror));
97                 if(lasterror != ERROR_SERVICE_EXISTS)
98                         return false;
99         }
100
101         if(service) {
102                 ChangeServiceConfig2(service, SERVICE_CONFIG_DESCRIPTION, &description);
103                 logger(LOG_INFO, "%s service installed", identname);
104         } else {
105                 service = OpenService(manager, identname, SERVICE_ALL_ACCESS);
106         }
107
108         if(!StartService(service, 0, NULL))
109                 logger(LOG_WARNING, "Could not start %s service: %s", identname, winerror(GetLastError()));
110         else
111                 logger(LOG_INFO, "%s service started", identname);
112
113         return true;
114 }
115
116 bool remove_service(void) {
117         manager = OpenSCManager(NULL, NULL, SC_MANAGER_ALL_ACCESS);
118         if(!manager) {
119                 logger(LOG_ERR, "Could not open service manager: %s", winerror(GetLastError()));
120                 return false;
121         }
122
123         service = OpenService(manager, identname, SERVICE_ALL_ACCESS);
124
125         if(!service) {
126                 logger(LOG_ERR, "Could not open %s service: %s", identname, winerror(GetLastError()));
127                 return false;
128         }
129
130         if(!ControlService(service, SERVICE_CONTROL_STOP, &status))
131                 logger(LOG_ERR, "Could not stop %s service: %s", identname, winerror(GetLastError()));
132         else
133                 logger(LOG_INFO, "%s service stopped", identname);
134
135         if(!DeleteService(service)) {
136                 logger(LOG_ERR, "Could not remove %s service: %s", identname, winerror(GetLastError()));
137                 return false;
138         }
139
140         logger(LOG_INFO, "%s service removed", identname);
141
142         return true;
143 }
144
145 DWORD WINAPI controlhandler(DWORD request, DWORD type, LPVOID boe, LPVOID bah) {
146         switch(request) {
147                 case SERVICE_CONTROL_INTERROGATE:
148                         SetServiceStatus(statushandle, &status);
149                         return NO_ERROR;
150                 case SERVICE_CONTROL_STOP:
151                         logger(LOG_NOTICE, "Got %s request", "SERVICE_CONTROL_STOP");
152                         break;
153                 case SERVICE_CONTROL_SHUTDOWN:
154                         logger(LOG_NOTICE, "Got %s request", "SERVICE_CONTROL_SHUTDOWN");
155                         break;
156                 default:
157                         logger(LOG_WARNING, "Got unexpected request %d", request);
158                         return ERROR_CALL_NOT_IMPLEMENTED;
159         }
160
161         event_loopexit(NULL);
162         status.dwWaitHint = 30000; 
163         status.dwCurrentState = SERVICE_STOP_PENDING; 
164         SetServiceStatus(statushandle, &status);
165         return NO_ERROR;
166 }
167
168 VOID WINAPI run_service(DWORD argc, LPTSTR* argv) {
169         int err = 1;
170         extern int main2(int argc, char **argv);
171
172
173         status.dwServiceType = SERVICE_WIN32; 
174         status.dwControlsAccepted = SERVICE_ACCEPT_STOP | SERVICE_ACCEPT_SHUTDOWN;
175         status.dwWin32ExitCode = 0; 
176         status.dwServiceSpecificExitCode = 0; 
177         status.dwCheckPoint = 0; 
178
179         statushandle = RegisterServiceCtrlHandlerEx(identname, controlhandler, NULL); 
180
181         if (!statushandle) {
182                 logger(LOG_ERR, "System call `%s' failed: %s", "RegisterServiceCtrlHandlerEx", winerror(GetLastError()));
183                 err = 1;
184         } else {
185                 status.dwWaitHint = 30000; 
186                 status.dwCurrentState = SERVICE_START_PENDING; 
187                 SetServiceStatus(statushandle, &status);
188
189                 status.dwWaitHint = 0; 
190                 status.dwCurrentState = SERVICE_RUNNING;
191                 SetServiceStatus(statushandle, &status);
192
193                 err = main2(argc, argv);
194
195                 status.dwWaitHint = 0;
196                 status.dwCurrentState = SERVICE_STOPPED; 
197                 //status.dwWin32ExitCode = err; 
198                 SetServiceStatus(statushandle, &status);
199         }
200
201         return;
202 }
203
204 bool init_service(void) {
205         SERVICE_TABLE_ENTRY services[] = {
206                 {identname, run_service},
207                 {NULL, NULL}
208         };
209
210         if(!StartServiceCtrlDispatcher(services)) {
211                 if(GetLastError() == ERROR_FAILED_SERVICE_CONTROLLER_CONNECT) {
212                         return false;
213                 }
214                 else
215                         logger(LOG_ERR, "System call `%s' failed: %s", "StartServiceCtrlDispatcher", winerror(GetLastError()));
216         }
217
218         return true;
219 }
220 #endif
221
222 /*
223   Detach from current terminal
224 */
225 bool detach(void) {
226 #ifndef HAVE_MINGW
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 }