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