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