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