More fixes for Windows.
[tinc] / src / process.c
1 /*
2     process.c -- process management functions
3     Copyright (C) 1999-2005 Ivo Timmermans,
4                   2000-2012 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 "event.h"
29 #include "logger.h"
30 #include "net.h"
31 #include "node.h"
32 #include "process.h"
33 #include "subnet.h"
34 #include "utils.h"
35 #include "xalloc.h"
36
37 /* If zero, don't detach from the terminal. */
38 bool do_detach = true;
39 bool sigalrm = false;
40
41 extern char *identname;
42 extern char **g_argv;
43 extern bool use_logfile;
44
45 /* Some functions the less gifted operating systems might lack... */
46
47 #ifdef HAVE_MINGW
48 extern char *identname;
49 extern char *program_name;
50 extern char **g_argv;
51
52 static SC_HANDLE manager = NULL;
53 static SC_HANDLE service = NULL;
54 static SERVICE_STATUS status = {0};
55 static SERVICE_STATUS_HANDLE statushandle = 0;
56
57 static bool install_service(void) {
58         char command[4096] = "\"";
59         SERVICE_DESCRIPTION description = {"Virtual Private Network daemon"};
60
61         manager = OpenSCManager(NULL, NULL, SC_MANAGER_ALL_ACCESS);
62         if(!manager) {
63                 logger(DEBUG_ALWAYS, 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(char **argp = g_argv + 1; *argp; argp++) {
77                 char *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(DEBUG_ALWAYS, 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(DEBUG_ALWAYS, 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(DEBUG_ALWAYS, LOG_WARNING, "Could not start %s service: %s", identname, winerror(GetLastError()));
109         else
110                 logger(DEBUG_ALWAYS, LOG_INFO, "%s service started", identname);
111
112         return true;
113 }
114
115 DWORD WINAPI controlhandler(DWORD request, DWORD type, LPVOID boe, LPVOID bah) {
116         switch(request) {
117                 case SERVICE_CONTROL_INTERROGATE:
118                         SetServiceStatus(statushandle, &status);
119                         return NO_ERROR;
120                 case SERVICE_CONTROL_STOP:
121                         logger(DEBUG_ALWAYS, LOG_NOTICE, "Got %s request", "SERVICE_CONTROL_STOP");
122                         break;
123                 case SERVICE_CONTROL_SHUTDOWN:
124                         logger(DEBUG_ALWAYS, LOG_NOTICE, "Got %s request", "SERVICE_CONTROL_SHUTDOWN");
125                         break;
126                 default:
127                         logger(DEBUG_ALWAYS, LOG_WARNING, "Got unexpected request %d", (int)request);
128                         return ERROR_CALL_NOT_IMPLEMENTED;
129         }
130
131         event_exit();
132         status.dwWaitHint = 30000;
133         status.dwCurrentState = SERVICE_STOP_PENDING;
134         SetServiceStatus(statushandle, &status);
135         return NO_ERROR;
136 }
137
138 VOID WINAPI run_service(DWORD argc, LPTSTR* argv) {
139         extern int main2(int argc, char **argv);
140
141         status.dwServiceType = SERVICE_WIN32;
142         status.dwControlsAccepted = SERVICE_ACCEPT_STOP | SERVICE_ACCEPT_SHUTDOWN;
143         status.dwWin32ExitCode = 0;
144         status.dwServiceSpecificExitCode = 0;
145         status.dwCheckPoint = 0;
146
147         statushandle = RegisterServiceCtrlHandlerEx(identname, controlhandler, NULL);
148
149         if (!statushandle) {
150                 logger(DEBUG_ALWAYS, LOG_ERR, "System call `%s' failed: %s", "RegisterServiceCtrlHandlerEx", winerror(GetLastError()));
151         } else {
152                 status.dwWaitHint = 30000;
153                 status.dwCurrentState = SERVICE_START_PENDING;
154                 SetServiceStatus(statushandle, &status);
155
156                 status.dwWaitHint = 0;
157                 status.dwCurrentState = SERVICE_RUNNING;
158                 SetServiceStatus(statushandle, &status);
159
160                 main2(argc, argv);
161
162                 status.dwWaitHint = 0;
163                 status.dwCurrentState = SERVICE_STOPPED;
164                 SetServiceStatus(statushandle, &status);
165         }
166
167         return;
168 }
169
170 bool init_service(void) {
171         SERVICE_TABLE_ENTRY services[] = {
172                 {identname, run_service},
173                 {NULL, NULL}
174         };
175
176         if(!StartServiceCtrlDispatcher(services)) {
177                 if(GetLastError() == ERROR_FAILED_SERVICE_CONTROLLER_CONNECT) {
178                         return false;
179                 }
180                 else
181                         logger(DEBUG_ALWAYS, LOG_ERR, "System call `%s' failed: %s", "StartServiceCtrlDispatcher", winerror(GetLastError()));
182         }
183
184         return true;
185 }
186 #endif
187
188 /*
189   Detach from current terminal
190 */
191 bool detach(void) {
192 #ifndef HAVE_MINGW
193         signal(SIGPIPE, SIG_IGN);
194         signal(SIGUSR1, SIG_IGN);
195         signal(SIGUSR2, SIG_IGN);
196         signal(SIGWINCH, SIG_IGN);
197
198         closelogger();
199 #endif
200
201         if(do_detach) {
202 #ifndef HAVE_MINGW
203                 if(daemon(0, 0)) {
204                         logger(DEBUG_ALWAYS, LOG_ERR, "Couldn't detach from terminal: %s", strerror(errno));
205                         return false;
206                 }
207 #else
208                 if(!statushandle)
209                         exit(!install_service());
210 #endif
211         }
212
213         openlogger(identname, use_logfile?LOGMODE_FILE:(do_detach?LOGMODE_SYSLOG:LOGMODE_STDERR));
214
215         logger(DEBUG_ALWAYS, LOG_NOTICE, "tincd %s (%s %s) starting, debug level %d",
216                            VERSION, __DATE__, __TIME__, debug_level);
217
218         return true;
219 }
220
221 bool execute_script(const char *name, char **envp) {
222 #ifdef HAVE_SYSTEM
223         char *scriptname;
224         char *command;
225
226         xasprintf(&scriptname, "%s" SLASH "%s%s", confbase, name, scriptextension);
227
228         /* First check if there is a script */
229
230         if(access(scriptname, F_OK)) {
231                 free(scriptname);
232                 return true;
233         }
234
235         logger(DEBUG_STATUS, LOG_INFO, "Executing script %s", name);
236
237 #ifdef HAVE_PUTENV
238         /* Set environment */
239
240         for(int i = 0; envp[i]; i++)
241                 putenv(envp[i]);
242 #endif
243
244         if(scriptinterpreter)
245                 xasprintf(&command, "%s \"%s\"", scriptinterpreter, scriptname);
246         else
247                 xasprintf(&command, "\"%s\"", scriptname);
248
249         int status = system(command);
250
251         free(command);
252         free(scriptname);
253
254         /* Unset environment */
255
256         for(int i = 0; envp[i]; i++) {
257                 char *e = strchr(envp[i], '=');
258                 if(e) {
259                         char p[e - envp[i] + 1];
260                         strncpy(p, envp[i], e - envp[i]);
261                         p[e - envp[i]] = '\0';
262                         putenv(p);
263                 }
264         }
265
266 #ifdef WEXITSTATUS
267         if(status != -1) {
268                 if(WIFEXITED(status)) {          /* Child exited by itself */
269                         if(WEXITSTATUS(status)) {
270                                 logger(DEBUG_ALWAYS, LOG_ERR, "Script %s exited with non-zero status %d",
271                                            name, WEXITSTATUS(status));
272                                 return false;
273                         }
274                 } else if(WIFSIGNALED(status)) { /* Child was killed by a signal */
275                         logger(DEBUG_ALWAYS, LOG_ERR, "Script %s was killed by signal %d (%s)",
276                                    name, WTERMSIG(status), strsignal(WTERMSIG(status)));
277                         return false;
278                 } else {                         /* Something strange happened */
279                         logger(DEBUG_ALWAYS, LOG_ERR, "Script %s terminated abnormally", name);
280                         return false;
281                 }
282         } else {
283                 logger(DEBUG_ALWAYS, LOG_ERR, "System call `%s' failed: %s", "system", strerror(errno));
284                 return false;
285         }
286 #endif
287 #endif
288         return true;
289 }