Replace hard-code with new ScriptsInterpreter configuration property.
[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 "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     char *aInterpreter = NULL;
362
363 #ifndef HAVE_MINGW
364         len = xasprintf(&scriptname, "\"%s/%s\"", confbase, name);
365 #else
366         len = xasprintf(&scriptname, "\"%s/%s.bat\"", confbase, name);
367 #endif
368         if(len < 0)
369                 return false;
370
371         scriptname[len - 1] = '\0';
372
373 #ifndef HAVE_TUNEMU
374         /* First check if there is a script */
375
376         if(access(scriptname + 1, F_OK)) {
377                 free(scriptname);
378                 return true;
379         }
380 #endif
381
382     // Custom scripts interpreter
383     if(get_config_string(lookup_config(config_tree, "ScriptsInterpreter"), &aInterpreter))
384     {
385         // Force custom scripts interpreter allowing execution of scripts on android without execution flag (such as on /sdcard)
386         free(scriptname);
387         len = xasprintf(&scriptname, "%s \"%s/%s\"", aInterpreter, confbase, name);
388         if(len < 0)
389         {
390             free(aInterpreter);
391             return false;
392         }
393     }
394     free(aInterpreter);
395
396         ifdebug(STATUS) logger(LOG_INFO, "Executing script %s", name);
397
398 #ifdef HAVE_PUTENV
399         /* Set environment */
400         
401         for(i = 0; envp[i]; i++)
402                 putenv(envp[i]);
403 #endif
404
405         scriptname[len - 1] = '\"';
406         status = system(scriptname);
407
408         free(scriptname);
409
410         /* Unset environment */
411
412         for(i = 0; envp[i]; i++) {
413                 char *e = strchr(envp[i], '=');
414                 if(e) {
415                         char p[e - envp[i] + 1];
416                         strncpy(p, envp[i], e - envp[i]);
417                         p[e - envp[i]] = '\0';
418                         putenv(p);
419                 }
420         }
421
422 #ifdef WEXITSTATUS
423         if(status != -1) {
424                 if(WIFEXITED(status)) { /* Child exited by itself */
425                         if(WEXITSTATUS(status)) {
426                                 logger(LOG_ERR, "Script %s exited with non-zero status %d",
427                                            name, WEXITSTATUS(status));
428                                 return false;
429                         }
430                 } else if(WIFSIGNALED(status)) {        /* Child was killed by a signal */
431                         logger(LOG_ERR, "Script %s was killed by signal %d (%s)",
432                                    name, WTERMSIG(status), strsignal(WTERMSIG(status)));
433                         return false;
434                 } else {                        /* Something strange happened */
435                         logger(LOG_ERR, "Script %s terminated abnormally", name);
436                         return false;
437                 }
438         } else {
439                 logger(LOG_ERR, "System call `%s' failed: %s", "system", strerror(errno));
440                 return false;
441         }
442 #endif
443 #endif
444         return true;
445 }
446
447
448 /*
449   Signal handlers.
450 */
451
452 #ifndef HAVE_MINGW
453 static RETSIGTYPE sigterm_handler(int a) {
454         logger(LOG_NOTICE, "Got %s signal", "TERM");
455         if(running)
456                 running = false;
457         else
458                 exit(1);
459 }
460
461 static RETSIGTYPE sigquit_handler(int a) {
462         logger(LOG_NOTICE, "Got %s signal", "QUIT");
463         if(running)
464                 running = false;
465         else
466                 exit(1);
467 }
468
469 static RETSIGTYPE fatal_signal_square(int a) {
470         logger(LOG_ERR, "Got another fatal signal %d (%s): not restarting.", a,
471                    strsignal(a));
472         exit(1);
473 }
474
475 static RETSIGTYPE fatal_signal_handler(int a) {
476         struct sigaction act;
477         logger(LOG_ERR, "Got fatal signal %d (%s)", a, strsignal(a));
478
479         if(do_detach) {
480                 logger(LOG_NOTICE, "Trying to re-execute in 5 seconds...");
481
482                 act.sa_handler = fatal_signal_square;
483                 act.sa_mask = emptysigset;
484                 act.sa_flags = 0;
485                 sigaction(SIGSEGV, &act, NULL);
486
487                 close_network_connections();
488                 sleep(5);
489                 remove_pid(pidfilename);
490                 execvp(g_argv[0], g_argv);
491         } else {
492                 logger(LOG_NOTICE, "Not restarting.");
493                 exit(1);
494         }
495 }
496
497 static RETSIGTYPE sighup_handler(int a) {
498         logger(LOG_NOTICE, "Got %s signal", "HUP");
499         sighup = true;
500 }
501
502 static RETSIGTYPE sigint_handler(int a) {
503         logger(LOG_NOTICE, "Got %s signal", "INT");
504
505         if(saved_debug_level != -1) {
506                 logger(LOG_NOTICE, "Reverting to old debug level (%d)",
507                         saved_debug_level);
508                 debug_level = saved_debug_level;
509                 saved_debug_level = -1;
510         } else {
511                 logger(LOG_NOTICE,
512                         "Temporarily setting debug level to 5.  Kill me with SIGINT again to go back to level %d.",
513                         debug_level);
514                 saved_debug_level = debug_level;
515                 debug_level = 5;
516         }
517 }
518
519 static RETSIGTYPE sigalrm_handler(int a) {
520         logger(LOG_NOTICE, "Got %s signal", "ALRM");
521         sigalrm = true;
522 }
523
524 static RETSIGTYPE sigusr1_handler(int a) {
525         dump_connections();
526 }
527
528 static RETSIGTYPE sigusr2_handler(int a) {
529         devops.dump_stats();
530         dump_nodes();
531         dump_edges();
532         dump_subnets();
533 }
534
535 static RETSIGTYPE sigwinch_handler(int a) {
536         do_purge = true;
537 }
538
539 static RETSIGTYPE unexpected_signal_handler(int a) {
540         logger(LOG_WARNING, "Got unexpected signal %d (%s)", a, strsignal(a));
541 }
542
543 static RETSIGTYPE ignore_signal_handler(int a) {
544         ifdebug(SCARY_THINGS) logger(LOG_DEBUG, "Ignored signal %d (%s)", a, strsignal(a));
545 }
546
547 static struct {
548         int signal;
549         void (*handler)(int);
550 } sighandlers[] = {
551         {SIGHUP, sighup_handler},
552         {SIGTERM, sigterm_handler},
553         {SIGQUIT, sigquit_handler},
554         {SIGSEGV, fatal_signal_handler},
555         {SIGBUS, fatal_signal_handler},
556         {SIGILL, fatal_signal_handler},
557         {SIGPIPE, ignore_signal_handler},
558         {SIGINT, sigint_handler},
559         {SIGUSR1, sigusr1_handler},
560         {SIGUSR2, sigusr2_handler},
561         {SIGCHLD, ignore_signal_handler},
562         {SIGALRM, sigalrm_handler},
563         {SIGWINCH, sigwinch_handler},
564         {SIGABRT, SIG_DFL},
565         {0, NULL}
566 };
567 #endif
568
569 void setup_signals(void) {
570 #ifndef HAVE_MINGW
571         int i;
572         struct sigaction act;
573
574         sigemptyset(&emptysigset);
575         act.sa_handler = NULL;
576         act.sa_mask = emptysigset;
577         act.sa_flags = 0;
578
579         /* Set a default signal handler for every signal, errors will be
580            ignored. */
581         for(i = 1; i < NSIG; i++) {
582                 if(!do_detach)
583                         act.sa_handler = SIG_DFL;
584                 else
585                         act.sa_handler = unexpected_signal_handler;
586                 sigaction(i, &act, NULL);
587         }
588
589         /* If we didn't detach, allow coredumps */
590         if(!do_detach)
591                 sighandlers[3].handler = SIG_DFL;
592
593         /* Then, for each known signal that we want to catch, assign a
594            handler to the signal, with error checking this time. */
595         for(i = 0; sighandlers[i].signal; i++) {
596                 act.sa_handler = sighandlers[i].handler;
597                 if(sigaction(sighandlers[i].signal, &act, NULL) < 0)
598                         fprintf(stderr, "Installing signal handler for signal %d (%s) failed: %s\n",
599                                         sighandlers[i].signal, strsignal(sighandlers[i].signal),
600                                         strerror(errno));
601         }
602 #endif
603 }