Basic patch for android cross-compilation.
[oweals/tinc.git] / 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 "device.h"
26 #include "edge.h"
27 #include "logger.h"
28 #include "net.h"
29 #include "node.h"
30 #include "pidfile.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 sighup = false;
39 bool sigalrm = false;
40
41 extern char *identname;
42 extern char *pidfilename;
43 extern char **g_argv;
44 extern bool use_logfile;
45
46 #ifndef HAVE_MINGW
47 static sigset_t emptysigset;
48 #endif
49
50 static int saved_debug_level = -1;
51
52 static void memory_full(int size) {
53         logger(LOG_ERR, "Memory exhausted (couldn't allocate %d bytes), exitting.", size);
54         exit(1);
55 }
56
57 /* Some functions the less gifted operating systems might lack... */
58
59 #ifdef HAVE_MINGW
60 extern char *identname;
61 extern char *program_name;
62 extern char **g_argv;
63
64 static SC_HANDLE manager = NULL;
65 static SC_HANDLE service = NULL;
66 static SERVICE_STATUS status = {0};
67 static SERVICE_STATUS_HANDLE statushandle = 0;
68
69 bool install_service(void) {
70         char command[4096] = "\"";
71         char **argp;
72         bool space;
73         SERVICE_DESCRIPTION description = {"Virtual Private Network daemon"};
74
75         manager = OpenSCManager(NULL, NULL, SC_MANAGER_ALL_ACCESS);
76         if(!manager) {
77                 logger(LOG_ERR, "Could not open service manager: %s", winerror(GetLastError()));
78                 return false;
79         }
80
81         if(!strchr(program_name, '\\')) {
82                 GetCurrentDirectory(sizeof command - 1, command + 1);
83                 strncat(command, "\\", sizeof command - strlen(command));
84         }
85
86         strncat(command, program_name, sizeof command - strlen(command));
87
88         strncat(command, "\"", sizeof command - strlen(command));
89
90         for(argp = g_argv + 1; *argp; argp++) {
91                 space = strchr(*argp, ' ');
92                 strncat(command, " ", sizeof command - strlen(command));
93                 
94                 if(space)
95                         strncat(command, "\"", sizeof command - strlen(command));
96                 
97                 strncat(command, *argp, sizeof command - strlen(command));
98
99                 if(space)
100                         strncat(command, "\"", sizeof command - strlen(command));
101         }
102
103         service = CreateService(manager, identname, identname,
104                         SERVICE_ALL_ACCESS, SERVICE_WIN32_OWN_PROCESS, SERVICE_AUTO_START, SERVICE_ERROR_NORMAL,
105                         command, NULL, NULL, NULL, NULL, NULL);
106         
107         if(!service) {
108                 DWORD lasterror = GetLastError();
109                 logger(LOG_ERR, "Could not create %s service: %s", identname, winerror(lasterror));
110                 if(lasterror != ERROR_SERVICE_EXISTS)
111                         return false;
112         }
113
114         if(service) {
115                 ChangeServiceConfig2(service, SERVICE_CONFIG_DESCRIPTION, &description);
116                 logger(LOG_INFO, "%s service installed", identname);
117         } else {
118                 service = OpenService(manager, identname, SERVICE_ALL_ACCESS);
119         }
120
121         if(!StartService(service, 0, NULL))
122                 logger(LOG_WARNING, "Could not start %s service: %s", identname, winerror(GetLastError()));
123         else
124                 logger(LOG_INFO, "%s service started", identname);
125
126         return true;
127 }
128
129 bool remove_service(void) {
130         manager = OpenSCManager(NULL, NULL, SC_MANAGER_ALL_ACCESS);
131         if(!manager) {
132                 logger(LOG_ERR, "Could not open service manager: %s", winerror(GetLastError()));
133                 return false;
134         }
135
136         service = OpenService(manager, identname, SERVICE_ALL_ACCESS);
137
138         if(!service) {
139                 logger(LOG_ERR, "Could not open %s service: %s", identname, winerror(GetLastError()));
140                 return false;
141         }
142
143         if(!ControlService(service, SERVICE_CONTROL_STOP, &status))
144                 logger(LOG_ERR, "Could not stop %s service: %s", identname, winerror(GetLastError()));
145         else
146                 logger(LOG_INFO, "%s service stopped", identname);
147
148         if(!DeleteService(service)) {
149                 logger(LOG_ERR, "Could not remove %s service: %s", identname, winerror(GetLastError()));
150                 return false;
151         }
152
153         logger(LOG_INFO, "%s service removed", identname);
154
155         return true;
156 }
157
158 DWORD WINAPI controlhandler(DWORD request, DWORD type, LPVOID boe, LPVOID bah) {
159         switch(request) {
160                 case SERVICE_CONTROL_INTERROGATE:
161                         SetServiceStatus(statushandle, &status);
162                         return NO_ERROR;
163                 case SERVICE_CONTROL_STOP:
164                         logger(LOG_NOTICE, "Got %s request", "SERVICE_CONTROL_STOP");
165                         break;
166                 case SERVICE_CONTROL_SHUTDOWN:
167                         logger(LOG_NOTICE, "Got %s request", "SERVICE_CONTROL_SHUTDOWN");
168                         break;
169                 default:
170                         logger(LOG_WARNING, "Got unexpected request %d", request);
171                         return ERROR_CALL_NOT_IMPLEMENTED;
172         }
173
174         if(running) {
175                 running = false;
176                 status.dwWaitHint = 30000; 
177                 status.dwCurrentState = SERVICE_STOP_PENDING; 
178                 SetServiceStatus(statushandle, &status);
179                 return NO_ERROR;
180         } else {
181                 status.dwWaitHint = 0; 
182                 status.dwCurrentState = SERVICE_STOPPED; 
183                 SetServiceStatus(statushandle, &status);
184                 exit(1);
185         }
186
187 }
188
189 VOID WINAPI run_service(DWORD argc, LPTSTR* argv) {
190         int err = 1;
191         extern int main2(int argc, char **argv);
192
193
194         status.dwServiceType = SERVICE_WIN32; 
195         status.dwControlsAccepted = SERVICE_ACCEPT_STOP | SERVICE_ACCEPT_SHUTDOWN;
196         status.dwWin32ExitCode = 0; 
197         status.dwServiceSpecificExitCode = 0; 
198         status.dwCheckPoint = 0; 
199
200         statushandle = RegisterServiceCtrlHandlerEx(identname, controlhandler, NULL); 
201
202         if (!statushandle) {
203                 logger(LOG_ERR, "System call `%s' failed: %s", "RegisterServiceCtrlHandlerEx", winerror(GetLastError()));
204                 err = 1;
205         } else {
206                 status.dwWaitHint = 30000; 
207                 status.dwCurrentState = SERVICE_START_PENDING; 
208                 SetServiceStatus(statushandle, &status);
209
210                 status.dwWaitHint = 0; 
211                 status.dwCurrentState = SERVICE_RUNNING;
212                 SetServiceStatus(statushandle, &status);
213
214                 err = main2(argc, argv);
215
216                 status.dwWaitHint = 0;
217                 status.dwCurrentState = SERVICE_STOPPED; 
218                 //status.dwWin32ExitCode = err; 
219                 SetServiceStatus(statushandle, &status);
220         }
221
222         return;
223 }
224
225 bool init_service(void) {
226         SERVICE_TABLE_ENTRY services[] = {
227                 {identname, run_service},
228                 {NULL, NULL}
229         };
230
231         if(!StartServiceCtrlDispatcher(services)) {
232                 if(GetLastError() == ERROR_FAILED_SERVICE_CONTROLLER_CONNECT) {
233                         return false;
234                 }
235                 else
236                         logger(LOG_ERR, "System call `%s' failed: %s", "StartServiceCtrlDispatcher", winerror(GetLastError()));
237         }
238
239         return true;
240 }
241 #endif
242
243 #ifndef HAVE_MINGW
244 /*
245   check for an existing tinc for this net, and write pid to pidfile
246 */
247 static bool write_pidfile(void) {
248         pid_t pid;
249
250         pid = check_pid(pidfilename);
251
252         if(pid) {
253                 if(netname)
254                         fprintf(stderr, "A tincd is already running for net `%s' with pid %ld.\n",
255                                         netname, (long)pid);
256                 else
257                         fprintf(stderr, "A tincd is already running with pid %ld.\n", (long)pid);
258                 return false;
259         }
260
261         /* if it's locked, write-protected, or whatever */
262         if(!write_pid(pidfilename)) {
263                 fprintf(stderr, "Could write pid file %s: %s\n", pidfilename, strerror(errno));
264                 return false;
265         }
266
267         return true;
268 }
269 #endif
270
271 /*
272   kill older tincd for this net
273 */
274 bool kill_other(int signal) {
275 #ifndef HAVE_MINGW
276         pid_t pid;
277
278         pid = read_pid(pidfilename);
279
280         if(!pid) {
281                 if(netname)
282                         fprintf(stderr, "No other tincd is running for net `%s'.\n",
283                                         netname);
284                 else
285                         fprintf(stderr, "No other tincd is running.\n");
286                 return false;
287         }
288
289         errno = 0;                                      /* No error, sometimes errno is only changed on error */
290
291         /* ESRCH is returned when no process with that pid is found */
292         if(kill(pid, signal) && errno == ESRCH) {
293                 if(netname)
294                         fprintf(stderr, "The tincd for net `%s' is no longer running. ",
295                                         netname);
296                 else
297                         fprintf(stderr, "The tincd is no longer running. ");
298
299                 fprintf(stderr, "Removing stale lock file.\n");
300                 remove_pid(pidfilename);
301         }
302
303         return true;
304 #else
305         return remove_service();
306 #endif
307 }
308
309 /*
310   Detach from current terminal, write pidfile, kill parent
311 */
312 bool detach(void) {
313         setup_signals();
314
315         /* First check if we can open a fresh new pidfile */
316
317 #ifndef HAVE_MINGW
318         if(!write_pidfile())
319                 return false;
320
321         /* If we succeeded in doing that, detach */
322
323         closelogger();
324 #endif
325
326         if(do_detach) {
327 #ifndef HAVE_MINGW
328                 if(daemon(0, 0)) {
329                         fprintf(stderr, "Couldn't detach from terminal: %s",
330                                         strerror(errno));
331                         return false;
332                 }
333
334                 /* Now UPDATE the pid in the pidfile, because we changed it... */
335
336                 if(!write_pid(pidfilename)) {
337                         fprintf(stderr, "Could not write pid file %s: %s\n", pidfilename, strerror(errno));
338                         return false;
339                 }
340 #else
341                 if(!statushandle)
342                         exit(install_service());
343 #endif
344         }
345
346         openlogger(identname, use_logfile?LOGMODE_FILE:(do_detach?LOGMODE_SYSLOG:LOGMODE_STDERR));
347
348         logger(LOG_NOTICE, "tincd %s (%s %s) starting, debug level %d",
349                            VERSION, __DATE__, __TIME__, debug_level);
350
351         xalloc_fail_func = memory_full;
352
353         return true;
354 }
355
356 bool execute_script(const char *name, char **envp) {
357 #ifdef HAVE_SYSTEM
358         int status, len;
359         char *scriptname;
360         int i;
361
362 #ifndef HAVE_MINGW
363         len = xasprintf(&scriptname, "\"%s/%s\"", confbase, name);
364 #else
365         len = xasprintf(&scriptname, "\"%s/%s.bat\"", confbase, name);
366 #endif
367         if(len < 0)
368                 return false;
369
370         scriptname[len - 1] = '\0';
371
372 #ifndef HAVE_TUNEMU
373         /* First check if there is a script */
374
375         if(access(scriptname + 1, F_OK)) {
376                 free(scriptname);
377                 return true;
378         }
379     else
380     {
381         // Ugly hard-code allowing execution of scripts on android without execution flag (such as on /sdcard)
382         free(scriptname);
383         len = xasprintf(&scriptname, "/system/bin/sh \"%s/%s\"", confbase, name);
384         if(len < 0)
385         {
386             return false;
387         }
388     }
389 #endif
390
391         ifdebug(STATUS) logger(LOG_INFO, "Executing script %s", name);
392
393 #ifdef HAVE_PUTENV
394         /* Set environment */
395         
396         for(i = 0; envp[i]; i++)
397                 putenv(envp[i]);
398 #endif
399
400         scriptname[len - 1] = '\"';
401         status = system(scriptname);
402
403         free(scriptname);
404
405         /* Unset environment */
406
407         for(i = 0; envp[i]; i++) {
408                 char *e = strchr(envp[i], '=');
409                 if(e) {
410                         char p[e - envp[i] + 1];
411                         strncpy(p, envp[i], e - envp[i]);
412                         p[e - envp[i]] = '\0';
413                         putenv(p);
414                 }
415         }
416
417 #ifdef WEXITSTATUS
418         if(status != -1) {
419                 if(WIFEXITED(status)) { /* Child exited by itself */
420                         if(WEXITSTATUS(status)) {
421                                 logger(LOG_ERR, "Script %s exited with non-zero status %d",
422                                            name, WEXITSTATUS(status));
423                                 return false;
424                         }
425                 } else if(WIFSIGNALED(status)) {        /* Child was killed by a signal */
426                         logger(LOG_ERR, "Script %s was killed by signal %d (%s)",
427                                    name, WTERMSIG(status), strsignal(WTERMSIG(status)));
428                         return false;
429                 } else {                        /* Something strange happened */
430                         logger(LOG_ERR, "Script %s terminated abnormally", name);
431                         return false;
432                 }
433         } else {
434                 logger(LOG_ERR, "System call `%s' failed: %s", "system", strerror(errno));
435                 return false;
436         }
437 #endif
438 #endif
439         return true;
440 }
441
442
443 /*
444   Signal handlers.
445 */
446
447 #ifndef HAVE_MINGW
448 static RETSIGTYPE sigterm_handler(int a) {
449         logger(LOG_NOTICE, "Got %s signal", "TERM");
450         if(running)
451                 running = false;
452         else
453                 exit(1);
454 }
455
456 static RETSIGTYPE sigquit_handler(int a) {
457         logger(LOG_NOTICE, "Got %s signal", "QUIT");
458         if(running)
459                 running = false;
460         else
461                 exit(1);
462 }
463
464 static RETSIGTYPE fatal_signal_square(int a) {
465         logger(LOG_ERR, "Got another fatal signal %d (%s): not restarting.", a,
466                    strsignal(a));
467         exit(1);
468 }
469
470 static RETSIGTYPE fatal_signal_handler(int a) {
471         struct sigaction act;
472         logger(LOG_ERR, "Got fatal signal %d (%s)", a, strsignal(a));
473
474         if(do_detach) {
475                 logger(LOG_NOTICE, "Trying to re-execute in 5 seconds...");
476
477                 act.sa_handler = fatal_signal_square;
478                 act.sa_mask = emptysigset;
479                 act.sa_flags = 0;
480                 sigaction(SIGSEGV, &act, NULL);
481
482                 close_network_connections();
483                 sleep(5);
484                 remove_pid(pidfilename);
485                 execvp(g_argv[0], g_argv);
486         } else {
487                 logger(LOG_NOTICE, "Not restarting.");
488                 exit(1);
489         }
490 }
491
492 static RETSIGTYPE sighup_handler(int a) {
493         logger(LOG_NOTICE, "Got %s signal", "HUP");
494         sighup = true;
495 }
496
497 static RETSIGTYPE sigint_handler(int a) {
498         logger(LOG_NOTICE, "Got %s signal", "INT");
499
500         if(saved_debug_level != -1) {
501                 logger(LOG_NOTICE, "Reverting to old debug level (%d)",
502                         saved_debug_level);
503                 debug_level = saved_debug_level;
504                 saved_debug_level = -1;
505         } else {
506                 logger(LOG_NOTICE,
507                         "Temporarily setting debug level to 5.  Kill me with SIGINT again to go back to level %d.",
508                         debug_level);
509                 saved_debug_level = debug_level;
510                 debug_level = 5;
511         }
512 }
513
514 static RETSIGTYPE sigalrm_handler(int a) {
515         logger(LOG_NOTICE, "Got %s signal", "ALRM");
516         sigalrm = true;
517 }
518
519 static RETSIGTYPE sigusr1_handler(int a) {
520         dump_connections();
521 }
522
523 static RETSIGTYPE sigusr2_handler(int a) {
524         devops.dump_stats();
525         dump_nodes();
526         dump_edges();
527         dump_subnets();
528 }
529
530 static RETSIGTYPE sigwinch_handler(int a) {
531         do_purge = true;
532 }
533
534 static RETSIGTYPE unexpected_signal_handler(int a) {
535         logger(LOG_WARNING, "Got unexpected signal %d (%s)", a, strsignal(a));
536 }
537
538 static RETSIGTYPE ignore_signal_handler(int a) {
539         ifdebug(SCARY_THINGS) logger(LOG_DEBUG, "Ignored signal %d (%s)", a, strsignal(a));
540 }
541
542 static struct {
543         int signal;
544         void (*handler)(int);
545 } sighandlers[] = {
546         {SIGHUP, sighup_handler},
547         {SIGTERM, sigterm_handler},
548         {SIGQUIT, sigquit_handler},
549         {SIGSEGV, fatal_signal_handler},
550         {SIGBUS, fatal_signal_handler},
551         {SIGILL, fatal_signal_handler},
552         {SIGPIPE, ignore_signal_handler},
553         {SIGINT, sigint_handler},
554         {SIGUSR1, sigusr1_handler},
555         {SIGUSR2, sigusr2_handler},
556         {SIGCHLD, ignore_signal_handler},
557         {SIGALRM, sigalrm_handler},
558         {SIGWINCH, sigwinch_handler},
559         {SIGABRT, SIG_DFL},
560         {0, NULL}
561 };
562 #endif
563
564 void setup_signals(void) {
565 #ifndef HAVE_MINGW
566         int i;
567         struct sigaction act;
568
569         sigemptyset(&emptysigset);
570         act.sa_handler = NULL;
571         act.sa_mask = emptysigset;
572         act.sa_flags = 0;
573
574         /* Set a default signal handler for every signal, errors will be
575            ignored. */
576         for(i = 1; i < NSIG; i++) {
577                 if(!do_detach)
578                         act.sa_handler = SIG_DFL;
579                 else
580                         act.sa_handler = unexpected_signal_handler;
581                 sigaction(i, &act, NULL);
582         }
583
584         /* If we didn't detach, allow coredumps */
585         if(!do_detach)
586                 sighandlers[3].handler = SIG_DFL;
587
588         /* Then, for each known signal that we want to catch, assign a
589            handler to the signal, with error checking this time. */
590         for(i = 0; sighandlers[i].signal; i++) {
591                 act.sa_handler = sighandlers[i].handler;
592                 if(sigaction(sighandlers[i].signal, &act, NULL) < 0)
593                         fprintf(stderr, "Installing signal handler for signal %d (%s) failed: %s\n",
594                                         sighandlers[i].signal, strsignal(sighandlers[i].signal),
595                                         strerror(errno));
596         }
597 #endif
598 }