Remove unused functions and variables.
[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 "node.h"
30 #include "process.h"
31 #include "subnet.h"
32 #include "utils.h"
33 #include "xalloc.h"
34
35 /* If zero, don't detach from the terminal. */
36 bool do_detach = true;
37 bool sigalrm = false;
38
39 extern char *identname;
40 extern char **g_argv;
41 extern bool use_logfile;
42
43 /* Some functions the less gifted operating systems might lack... */
44
45 #ifdef HAVE_MINGW
46 extern char *identname;
47 extern char *program_name;
48 extern char **g_argv;
49
50 static SC_HANDLE manager = NULL;
51 static SC_HANDLE service = NULL;
52 static SERVICE_STATUS status = {0};
53 static SERVICE_STATUS_HANDLE statushandle = 0;
54
55 bool install_service(void) {
56         char command[4096] = "\"";
57         char **argp;
58         bool space;
59         SERVICE_DESCRIPTION description = {"Virtual Private Network daemon"};
60
61         manager = OpenSCManager(NULL, NULL, SC_MANAGER_ALL_ACCESS);
62         if(!manager) {
63                 logger(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(argp = g_argv + 1; *argp; argp++) {
77                 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(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(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(LOG_WARNING, "Could not start %s service: %s", identname, winerror(GetLastError()));
109         else
110                 logger(LOG_INFO, "%s service started", identname);
111
112         return true;
113 }
114
115 bool remove_service(void) {
116         manager = OpenSCManager(NULL, NULL, SC_MANAGER_ALL_ACCESS);
117         if(!manager) {
118                 logger(LOG_ERR, "Could not open service manager: %s", winerror(GetLastError()));
119                 return false;
120         }
121
122         service = OpenService(manager, identname, SERVICE_ALL_ACCESS);
123
124         if(!service) {
125                 logger(LOG_ERR, "Could not open %s service: %s", identname, winerror(GetLastError()));
126                 return false;
127         }
128
129         if(!ControlService(service, SERVICE_CONTROL_STOP, &status))
130                 logger(LOG_ERR, "Could not stop %s service: %s", identname, winerror(GetLastError()));
131         else
132                 logger(LOG_INFO, "%s service stopped", identname);
133
134         if(!DeleteService(service)) {
135                 logger(LOG_ERR, "Could not remove %s service: %s", identname, winerror(GetLastError()));
136                 return false;
137         }
138
139         logger(LOG_INFO, "%s service removed", identname);
140
141         return true;
142 }
143
144 DWORD WINAPI controlhandler(DWORD request, DWORD type, LPVOID boe, LPVOID bah) {
145         switch(request) {
146                 case SERVICE_CONTROL_INTERROGATE:
147                         SetServiceStatus(statushandle, &status);
148                         return NO_ERROR;
149                 case SERVICE_CONTROL_STOP:
150                         logger(LOG_NOTICE, "Got %s request", "SERVICE_CONTROL_STOP");
151                         break;
152                 case SERVICE_CONTROL_SHUTDOWN:
153                         logger(LOG_NOTICE, "Got %s request", "SERVICE_CONTROL_SHUTDOWN");
154                         break;
155                 default:
156                         logger(LOG_WARNING, "Got unexpected request %d", request);
157                         return ERROR_CALL_NOT_IMPLEMENTED;
158         }
159
160         event_loopexit(NULL);
161         status.dwWaitHint = 30000; 
162         status.dwCurrentState = SERVICE_STOP_PENDING; 
163         SetServiceStatus(statushandle, &status);
164         return NO_ERROR;
165 }
166
167 VOID WINAPI run_service(DWORD argc, LPTSTR* argv) {
168         int err = 1;
169         extern int main2(int argc, char **argv);
170
171
172         status.dwServiceType = SERVICE_WIN32; 
173         status.dwControlsAccepted = SERVICE_ACCEPT_STOP | SERVICE_ACCEPT_SHUTDOWN;
174         status.dwWin32ExitCode = 0; 
175         status.dwServiceSpecificExitCode = 0; 
176         status.dwCheckPoint = 0; 
177
178         statushandle = RegisterServiceCtrlHandlerEx(identname, controlhandler, NULL); 
179
180         if (!statushandle) {
181                 logger(LOG_ERR, "System call `%s' failed: %s", "RegisterServiceCtrlHandlerEx", winerror(GetLastError()));
182                 err = 1;
183         } else {
184                 status.dwWaitHint = 30000; 
185                 status.dwCurrentState = SERVICE_START_PENDING; 
186                 SetServiceStatus(statushandle, &status);
187
188                 status.dwWaitHint = 0; 
189                 status.dwCurrentState = SERVICE_RUNNING;
190                 SetServiceStatus(statushandle, &status);
191
192                 err = main2(argc, argv);
193
194                 status.dwWaitHint = 0;
195                 status.dwCurrentState = SERVICE_STOPPED; 
196                 //status.dwWin32ExitCode = err; 
197                 SetServiceStatus(statushandle, &status);
198         }
199
200         return;
201 }
202
203 bool init_service(void) {
204         SERVICE_TABLE_ENTRY services[] = {
205                 {identname, run_service},
206                 {NULL, NULL}
207         };
208
209         if(!StartServiceCtrlDispatcher(services)) {
210                 if(GetLastError() == ERROR_FAILED_SERVICE_CONTROLLER_CONNECT) {
211                         return false;
212                 }
213                 else
214                         logger(LOG_ERR, "System call `%s' failed: %s", "StartServiceCtrlDispatcher", winerror(GetLastError()));
215         }
216
217         return true;
218 }
219 #endif
220
221 /*
222   Detach from current terminal
223 */
224 bool detach(void) {
225         setup_signals();
226
227 #ifndef HAVE_MINGW
228         closelogger();
229 #endif
230
231         if(do_detach) {
232 #ifndef HAVE_MINGW
233                 if(daemon(0, 0)) {
234                         fprintf(stderr, "Couldn't detach from terminal: %s",
235                                         strerror(errno));
236                         return false;
237                 }
238 #else
239                 if(!statushandle)
240                         exit(install_service());
241 #endif
242         }
243
244         openlogger(identname, use_logfile?LOGMODE_FILE:(do_detach?LOGMODE_SYSLOG:LOGMODE_STDERR));
245
246         logger(LOG_NOTICE, "tincd %s (%s %s) starting, debug level %d",
247                            VERSION, __DATE__, __TIME__, debug_level);
248
249         return true;
250 }
251
252 bool execute_script(const char *name, char **envp) {
253 #ifdef HAVE_SYSTEM
254         int status, len;
255         char *scriptname;
256         int i;
257
258 #ifndef HAVE_MINGW
259         len = xasprintf(&scriptname, "\"%s/%s\"", confbase, name);
260 #else
261         len = xasprintf(&scriptname, "\"%s/%s.bat\"", confbase, name);
262 #endif
263         if(len < 0)
264                 return false;
265
266         scriptname[len - 1] = '\0';
267
268 #ifndef HAVE_TUNEMU
269         /* First check if there is a script */
270
271         if(access(scriptname + 1, F_OK)) {
272                 free(scriptname);
273                 return true;
274         }
275 #endif
276
277         ifdebug(STATUS) logger(LOG_INFO, "Executing script %s", name);
278
279 #ifdef HAVE_PUTENV
280         /* Set environment */
281         
282         for(i = 0; envp[i]; i++)
283                 putenv(envp[i]);
284 #endif
285
286         scriptname[len - 1] = '\"';
287         status = system(scriptname);
288
289         free(scriptname);
290
291         /* Unset environment */
292
293         for(i = 0; envp[i]; i++) {
294                 char *e = strchr(envp[i], '=');
295                 if(e) {
296                         char p[e - envp[i] + 1];
297                         strncpy(p, envp[i], e - envp[i]);
298                         p[e - envp[i]] = '\0';
299                         putenv(p);
300                 }
301         }
302
303 #ifdef WEXITSTATUS
304         if(status != -1) {
305                 if(WIFEXITED(status)) { /* Child exited by itself */
306                         if(WEXITSTATUS(status)) {
307                                 logger(LOG_ERR, "Script %s exited with non-zero status %d",
308                                            name, WEXITSTATUS(status));
309                                 return false;
310                         }
311                 } else if(WIFSIGNALED(status)) {        /* Child was killed by a signal */
312                         logger(LOG_ERR, "Script %s was killed by signal %d (%s)",
313                                    name, WTERMSIG(status), strsignal(WTERMSIG(status)));
314                         return false;
315                 } else {                        /* Something strange happened */
316                         logger(LOG_ERR, "Script %s terminated abnormally", name);
317                         return false;
318                 }
319         } else {
320                 logger(LOG_ERR, "System call `%s' failed: %s", "system", strerror(errno));
321                 return false;
322         }
323 #endif
324 #endif
325         return true;
326 }
327
328
329 /*
330   Signal handlers.
331 */
332
333 #ifndef HAVE_MINGW
334 static RETSIGTYPE ignore_signal_handler(int a) {
335         ifdebug(SCARY_THINGS) logger(LOG_DEBUG, "Ignored signal %d (%s)", a, strsignal(a));
336 }
337
338 static struct {
339         int signal;
340         void (*handler)(int);
341 } sighandlers[] = {
342         {SIGPIPE, ignore_signal_handler},
343         {SIGCHLD, ignore_signal_handler},
344         {0, NULL}
345 };
346 #endif
347
348 void setup_signals(void) {
349 #ifndef HAVE_MINGW
350         int i;
351         struct sigaction act = {{NULL}};
352
353         sigemptyset(&act.sa_mask);
354
355         for(i = 0; sighandlers[i].signal; i++) {
356                 act.sa_handler = sighandlers[i].handler;
357                 if(sigaction(sighandlers[i].signal, &act, NULL) < 0)
358                         fprintf(stderr, "Installing signal handler for signal %d (%s) failed: %s\n",
359                                         sighandlers[i].signal, strsignal(sighandlers[i].signal),
360                                         strerror(errno));
361         }
362 #endif
363 }