Merge branch 'master' of git://tinc-vpn.org/tinc into 1.1
[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(SIGALRM, SIG_IGN);
228         signal(SIGPIPE, SIG_IGN);
229         signal(SIGUSR1, SIG_IGN);
230         signal(SIGUSR2, SIG_IGN);
231         signal(SIGWINCH, SIG_IGN);
232
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         return true;
255 }
256
257 bool execute_script(const char *name, char **envp) {
258 #ifdef HAVE_SYSTEM
259         int status, len;
260         char *scriptname;
261         int i;
262
263 #ifndef HAVE_MINGW
264         len = xasprintf(&scriptname, "\"%s/%s\"", confbase, name);
265 #else
266         len = xasprintf(&scriptname, "\"%s/%s.bat\"", confbase, name);
267 #endif
268         if(len < 0)
269                 return false;
270
271         scriptname[len - 1] = '\0';
272
273 #ifndef HAVE_TUNEMU
274         /* First check if there is a script */
275
276         if(access(scriptname + 1, F_OK)) {
277                 free(scriptname);
278                 return true;
279         }
280 #endif
281
282         ifdebug(STATUS) logger(LOG_INFO, "Executing script %s", name);
283
284 #ifdef HAVE_PUTENV
285         /* Set environment */
286         
287         for(i = 0; envp[i]; i++)
288                 putenv(envp[i]);
289 #endif
290
291         scriptname[len - 1] = '\"';
292         status = system(scriptname);
293
294         free(scriptname);
295
296         /* Unset environment */
297
298         for(i = 0; envp[i]; i++) {
299                 char *e = strchr(envp[i], '=');
300                 if(e) {
301                         char p[e - envp[i] + 1];
302                         strncpy(p, envp[i], e - envp[i]);
303                         p[e - envp[i]] = '\0';
304                         putenv(p);
305                 }
306         }
307
308 #ifdef WEXITSTATUS
309         if(status != -1) {
310                 if(WIFEXITED(status)) { /* Child exited by itself */
311                         if(WEXITSTATUS(status)) {
312                                 logger(LOG_ERR, "Script %s exited with non-zero status %d",
313                                            name, WEXITSTATUS(status));
314                                 return false;
315                         }
316                 } else if(WIFSIGNALED(status)) {        /* Child was killed by a signal */
317                         logger(LOG_ERR, "Script %s was killed by signal %d (%s)",
318                                    name, WTERMSIG(status), strsignal(WTERMSIG(status)));
319                         return false;
320                 } else {                        /* Something strange happened */
321                         logger(LOG_ERR, "Script %s terminated abnormally", name);
322                         return false;
323                 }
324         } else {
325                 logger(LOG_ERR, "System call `%s' failed: %s", "system", strerror(errno));
326                 return false;
327         }
328 #endif
329 #endif
330         return true;
331 }