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