Fix a few compiler errors/warnings.
[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 "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", (int)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         extern int main2(int argc, char **argv);
139
140         status.dwServiceType = SERVICE_WIN32;
141         status.dwControlsAccepted = SERVICE_ACCEPT_STOP | SERVICE_ACCEPT_SHUTDOWN;
142         status.dwWin32ExitCode = 0;
143         status.dwServiceSpecificExitCode = 0;
144         status.dwCheckPoint = 0;
145
146         statushandle = RegisterServiceCtrlHandlerEx(identname, controlhandler, NULL);
147
148         if (!statushandle) {
149                 logger(DEBUG_ALWAYS, LOG_ERR, "System call `%s' failed: %s", "RegisterServiceCtrlHandlerEx", winerror(GetLastError()));
150         } else {
151                 status.dwWaitHint = 30000;
152                 status.dwCurrentState = SERVICE_START_PENDING;
153                 SetServiceStatus(statushandle, &status);
154
155                 status.dwWaitHint = 0;
156                 status.dwCurrentState = SERVICE_RUNNING;
157                 SetServiceStatus(statushandle, &status);
158
159                 main2(argc, argv);
160
161                 status.dwWaitHint = 0;
162                 status.dwCurrentState = SERVICE_STOPPED;
163                 SetServiceStatus(statushandle, &status);
164         }
165
166         return;
167 }
168
169 bool init_service(void) {
170         SERVICE_TABLE_ENTRY services[] = {
171                 {identname, run_service},
172                 {NULL, NULL}
173         };
174
175         if(!StartServiceCtrlDispatcher(services)) {
176                 if(GetLastError() == ERROR_FAILED_SERVICE_CONTROLLER_CONNECT) {
177                         return false;
178                 }
179                 else
180                         logger(DEBUG_ALWAYS, LOG_ERR, "System call `%s' failed: %s", "StartServiceCtrlDispatcher", winerror(GetLastError()));
181         }
182
183         return true;
184 }
185 #endif
186
187 /*
188   Detach from current terminal
189 */
190 bool detach(void) {
191 #ifndef HAVE_MINGW
192         signal(SIGPIPE, SIG_IGN);
193         signal(SIGUSR1, SIG_IGN);
194         signal(SIGUSR2, SIG_IGN);
195         signal(SIGWINCH, SIG_IGN);
196
197         closelogger();
198 #endif
199
200         if(do_detach) {
201 #ifndef HAVE_MINGW
202                 if(daemon(0, 0)) {
203                         logger(DEBUG_ALWAYS, LOG_ERR, "Couldn't detach from terminal: %s", strerror(errno));
204                         return false;
205                 }
206 #else
207                 if(!statushandle)
208                         exit(!install_service());
209 #endif
210         }
211
212         openlogger(identname, use_logfile?LOGMODE_FILE:(do_detach?LOGMODE_SYSLOG:LOGMODE_STDERR));
213
214         logger(DEBUG_ALWAYS, LOG_NOTICE, "tincd %s (%s %s) starting, debug level %d",
215                            VERSION, __DATE__, __TIME__, debug_level);
216
217         return true;
218 }
219
220 bool execute_script(const char *name, char **envp) {
221 #ifdef HAVE_SYSTEM
222         char *scriptname;
223         char *command;
224
225         xasprintf(&scriptname, "%s" SLASH "%s%s", confbase, name, scriptextension);
226
227         /* First check if there is a script */
228
229         if(access(scriptname, F_OK)) {
230                 free(scriptname);
231                 return true;
232         }
233
234         logger(DEBUG_STATUS, LOG_INFO, "Executing script %s", name);
235
236 #ifdef HAVE_PUTENV
237         /* Set environment */
238
239         for(int i = 0; envp[i]; i++)
240                 putenv(envp[i]);
241 #endif
242
243         if(scriptinterpreter)
244                 xasprintf(&command, "%s \"%s\"", scriptinterpreter, scriptname);
245         else
246                 xasprintf(&command, "\"%s\"", scriptname);
247
248         int status = system(command);
249
250         free(command);
251         free(scriptname);
252
253         /* Unset environment */
254
255         for(int i = 0; envp[i]; i++) {
256                 char *e = strchr(envp[i], '=');
257                 if(e) {
258                         char p[e - envp[i] + 1];
259                         strncpy(p, envp[i], e - envp[i]);
260                         p[e - envp[i]] = '\0';
261                         putenv(p);
262                 }
263         }
264
265 #ifdef WEXITSTATUS
266         if(status != -1) {
267                 if(WIFEXITED(status)) {          /* Child exited by itself */
268                         if(WEXITSTATUS(status)) {
269                                 logger(DEBUG_ALWAYS, LOG_ERR, "Script %s exited with non-zero status %d",
270                                            name, WEXITSTATUS(status));
271                                 return false;
272                         }
273                 } else if(WIFSIGNALED(status)) { /* Child was killed by a signal */
274                         logger(DEBUG_ALWAYS, LOG_ERR, "Script %s was killed by signal %d (%s)",
275                                    name, WTERMSIG(status), strsignal(WTERMSIG(status)));
276                         return false;
277                 } else {                         /* Something strange happened */
278                         logger(DEBUG_ALWAYS, LOG_ERR, "Script %s terminated abnormally", name);
279                         return false;
280                 }
281         } else {
282                 logger(DEBUG_ALWAYS, LOG_ERR, "System call `%s' failed: %s", "system", strerror(errno));
283                 return false;
284         }
285 #endif
286 #endif
287         return true;
288 }