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