d81fdd693608d9f11b5b9fe465ada80a7c55fef4
[oweals/tinc.git] / 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.68 2003/08/08 19:56:11 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
89         manager = OpenSCManager(NULL, NULL, SC_MANAGER_ALL_ACCESS);
90         if(!manager) {
91                 logger(LOG_ERR, _("Could not open service manager: %s"), winerror(GetLastError()));
92                 return false;
93         }
94
95         if(!strchr(program_name, '\\')) {
96                 GetCurrentDirectory(sizeof(command), command);
97                 strncat(command, "\\", sizeof(command));
98         }
99
100         strncat(command, program_name, sizeof(command));
101         for(argp = g_argv + 1; *argp; argp++) {
102                 space = strchr(*argp, ' ');
103                 strncat(command, " ", sizeof(command));
104                 
105                 if(space)
106                         strncat(command, "\"", sizeof(command));
107                 
108                 strncat(command, *argp, sizeof(command));
109
110                 if(space)
111                         strncat(command, "\"", sizeof(command));
112         }
113
114         service = CreateService(manager, identname, identname,
115                         SERVICE_ALL_ACCESS, SERVICE_WIN32_OWN_PROCESS, SERVICE_AUTO_START, SERVICE_ERROR_NORMAL,
116                         command, "NDIS", NULL, NULL, NULL, NULL);
117         
118         if(!service) {
119                 logger(LOG_ERR, _("Could not create %s service: %s"), identname, winerror(GetLastError()));
120                 return false;
121         }
122
123         logger(LOG_INFO, _("%s service installed"), identname);
124
125         if(!StartService(service, 0, NULL))
126                 logger(LOG_WARNING, _("Could not start %s service: %s"), identname, winerror(GetLastError()));
127         else
128                 logger(LOG_INFO, _("%s service started"), identname);
129
130         return true;
131 }
132
133 bool remove_service(void) {
134         manager = OpenSCManager(NULL, NULL, SC_MANAGER_ALL_ACCESS);
135         if(!manager) {
136                 logger(LOG_ERR, _("Could not open service manager: %s"), winerror(GetLastError()));
137                 return false;
138         }
139
140         service = OpenService(manager, identname, SERVICE_ALL_ACCESS);
141
142         if(!service) {
143                 logger(LOG_ERR, _("Could not open %s service: %s"), identname, winerror(GetLastError()));
144                 return false;
145         }
146
147         if(!ControlService(service, SERVICE_CONTROL_STOP, &status))
148                 logger(LOG_ERR, _("Could not stop %s service: %s"), identname, winerror(GetLastError()));
149         else
150                 logger(LOG_INFO, _("%s service stopped"), identname);
151
152         if(!DeleteService(service)) {
153                 logger(LOG_ERR, _("Could not remove %s service: %s"), identname, winerror(GetLastError()));
154                 return false;
155         }
156
157         logger(LOG_INFO, _("%s service removed"), identname);
158
159         return true;
160 }
161
162 DWORD WINAPI controlhandler(DWORD request, DWORD type, LPVOID boe, LPVOID bah) {
163         switch(request) {
164                 case SERVICE_CONTROL_STOP:
165                         logger(LOG_NOTICE, _("Got %s request"), "SERVICE_CONTROL_STOP");
166                         running = false;
167                         break;
168                 case SERVICE_CONTROL_SHUTDOWN:
169                         logger(LOG_NOTICE, _("Got %s request"), "SERVICE_CONTROL_SHUTDOWN");
170                         running = false;
171                         break;
172                 default:
173                         logger(LOG_WARNING, _("Got unexpected request %d"), request);
174                         return ERROR_CALL_NOT_IMPLEMENTED;
175         }
176
177         if(!running) {
178                 status.dwWaitHint = 30000; 
179                 status.dwCurrentState = SERVICE_STOP_PENDING; 
180                 SetServiceStatus(statushandle, &status);
181         }
182
183         return NO_ERROR;
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         int 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 %d.\n"),
256                                         netname, pid);
257                 else
258                         fprintf(stderr, _("A tincd is already running with pid %d.\n"), pid);
259                 return false;
260         }
261
262         /* if it's locked, write-protected, or whatever */
263         if(!write_pid(pidfilename))
264                 return false;
265
266         return true;
267 }
268 #endif
269
270 /*
271   kill older tincd for this net
272 */
273 bool kill_other(int signal)
274 {
275 #ifndef HAVE_MINGW
276         int pid;
277
278         cp();
279
280         pid = read_pid(pidfilename);
281
282         if(!pid) {
283                 if(netname)
284                         fprintf(stderr, _("No other tincd is running for net `%s'.\n"),
285                                         netname);
286                 else
287                         fprintf(stderr, _("No other tincd is running.\n"));
288                 return false;
289         }
290
291         errno = 0;                                      /* No error, sometimes errno is only changed on error */
292
293         /* ESRCH is returned when no process with that pid is found */
294         if(kill(pid, signal) && errno == ESRCH) {
295                 if(netname)
296                         fprintf(stderr, _("The tincd for net `%s' is no longer running. "),
297                                         netname);
298                 else
299                         fprintf(stderr, _("The tincd is no longer running. "));
300
301                 fprintf(stderr, _("Removing stale lock file.\n"));
302                 remove_pid(pidfilename);
303         }
304
305         return true;
306 #else
307         return remove_service();
308 #endif
309 }
310
311 /*
312   Detach from current terminal, write pidfile, kill parent
313 */
314 bool detach(void)
315 {
316         cp();
317
318         setup_signals();
319
320         /* First check if we can open a fresh new pidfile */
321
322 #ifndef HAVE_MINGW
323         if(!write_pidfile())
324                 return false;
325
326         /* If we succeeded in doing that, detach */
327
328         closelogger();
329 #endif
330
331         if(do_detach) {
332 #ifndef HAVE_MINGW
333                 if(daemon(0, 0)) {
334                         fprintf(stderr, _("Couldn't detach from terminal: %s"),
335                                         strerror(errno));
336                         return false;
337                 }
338
339                 /* Now UPDATE the pid in the pidfile, because we changed it... */
340
341                 if(!write_pid(pidfilename))
342                         return false;
343 #else
344                 if(!statushandle)
345                         exit(install_service());
346 #endif
347         }
348
349         openlogger(identname, use_logfile?LOGMODE_FILE:(do_detach?LOGMODE_SYSLOG:LOGMODE_STDERR));
350
351         logger(LOG_NOTICE, _("tincd %s (%s %s) starting, debug level %d"),
352                            VERSION, __DATE__, __TIME__, debug_level);
353
354         xalloc_fail_func = memory_full;
355
356         return true;
357 }
358
359 bool execute_script(const char *name, char **envp)
360 {
361 #ifdef HAVE_SYSTEM
362         pid_t pid;
363         int status;
364         struct stat s;
365         char *scriptname;
366
367         cp();
368
369         asprintf(&scriptname, "\"%s/%s\"", confbase, name);
370
371 #ifndef HAVE_MINGW
372         /* First check if there is a script */
373
374         if(stat(scriptname, &s))
375                 return true;
376
377         ifdebug(STATUS) logger(LOG_INFO, _("Executing script %s"), name);
378 #endif
379
380 #ifdef HAVE_PUTENV
381         /* Set environment */
382         
383         while(*envp)
384                 putenv(*envp++);
385 #endif
386
387         status = system(scriptname);
388
389         free(scriptname);
390
391         /* Unset environment? */
392
393 #ifdef WEXITSTATUS
394         if(status != -1) {
395                 if(WIFEXITED(status)) { /* Child exited by itself */
396                         if(WEXITSTATUS(status)) {
397                                 logger(LOG_ERR, _("Process %d (%s) exited with non-zero status %d"),
398                                            pid, name, WEXITSTATUS(status));
399                                 return false;
400                         }
401                 } else if(WIFSIGNALED(status)) {        /* Child was killed by a signal */
402                         logger(LOG_ERR, _("Process %d (%s) was killed by signal %d (%s)"), pid,
403                                    name, WTERMSIG(status), strsignal(WTERMSIG(status)));
404                         return false;
405                 } else {                        /* Something strange happened */
406                         logger(LOG_ERR, _("Process %d (%s) terminated abnormally"), pid,
407                                    name);
408                         return false;
409                 }
410         } else {
411                 logger(LOG_ERR, _("System call `%s' failed: %s"), "system",
412                            strerror(errno));
413                 return false;
414         }
415 #endif
416 #endif
417         return true;
418 }
419
420
421 /*
422   Signal handlers.
423 */
424
425 #ifndef HAVE_MINGW
426 static RETSIGTYPE sigterm_handler(int a)
427 {
428         logger(LOG_NOTICE, _("Got %s signal"), "TERM");
429         running = false;
430 }
431
432 static RETSIGTYPE sigquit_handler(int a)
433 {
434         logger(LOG_NOTICE, _("Got %s signal"), "QUIT");
435         running = false;
436 }
437
438 static RETSIGTYPE fatal_signal_square(int a)
439 {
440         logger(LOG_ERR, _("Got another fatal signal %d (%s): not restarting."), a,
441                    strsignal(a));
442         cp_trace();
443         exit(1);
444 }
445
446 static RETSIGTYPE fatal_signal_handler(int a)
447 {
448         struct sigaction act;
449         logger(LOG_ERR, _("Got fatal signal %d (%s)"), a, strsignal(a));
450         cp_trace();
451
452         if(do_detach) {
453                 logger(LOG_NOTICE, _("Trying to re-execute in 5 seconds..."));
454
455                 act.sa_handler = fatal_signal_square;
456                 act.sa_mask = emptysigset;
457                 act.sa_flags = 0;
458                 sigaction(SIGSEGV, &act, NULL);
459
460                 close_network_connections();
461                 sleep(5);
462                 remove_pid(pidfilename);
463                 execvp(g_argv[0], g_argv);
464         } else {
465                 logger(LOG_NOTICE, _("Not restarting."));
466                 exit(1);
467         }
468 }
469
470 static RETSIGTYPE sighup_handler(int a)
471 {
472         logger(LOG_NOTICE, _("Got %s signal"), "HUP");
473         sighup = true;
474 }
475
476 static RETSIGTYPE sigint_handler(int a)
477 {
478         logger(LOG_NOTICE, _("Got %s signal"), "INT");
479
480         if(saved_debug_level != -1) {
481                 logger(LOG_NOTICE, _("Reverting to old debug level (%d)"),
482                         saved_debug_level);
483                 debug_level = saved_debug_level;
484                 saved_debug_level = -1;
485         } else {
486                 logger(LOG_NOTICE,
487                         _("Temporarily setting debug level to 5.  Kill me with SIGINT again to go back to level %d."),
488                         debug_level);
489                 saved_debug_level = debug_level;
490                 debug_level = 5;
491         }
492 }
493
494 static RETSIGTYPE sigalrm_handler(int a)
495 {
496         logger(LOG_NOTICE, _("Got %s signal"), "ALRM");
497         sigalrm = true;
498 }
499
500 static RETSIGTYPE sigusr1_handler(int a)
501 {
502         dump_connections();
503 }
504
505 static RETSIGTYPE sigusr2_handler(int a)
506 {
507         dump_device_stats();
508         dump_nodes();
509         dump_edges();
510         dump_subnets();
511 }
512
513 static RETSIGTYPE sigwinch_handler(int a)
514 {
515         do_purge = true;
516 }
517
518 static RETSIGTYPE unexpected_signal_handler(int a)
519 {
520         logger(LOG_WARNING, _("Got unexpected signal %d (%s)"), a, strsignal(a));
521         cp_trace();
522 }
523
524 static RETSIGTYPE ignore_signal_handler(int a)
525 {
526         ifdebug(SCARY_THINGS) logger(LOG_DEBUG, _("Ignored signal %d (%s)"), a, strsignal(a));
527 }
528
529 static struct {
530         int signal;
531         void (*handler)(int);
532 } sighandlers[] = {
533         {SIGHUP, sighup_handler},
534         {SIGTERM, sigterm_handler},
535         {SIGQUIT, sigquit_handler},
536         {SIGSEGV, fatal_signal_handler},
537         {SIGBUS, fatal_signal_handler},
538         {SIGILL, fatal_signal_handler},
539         {SIGPIPE, ignore_signal_handler},
540         {SIGINT, sigint_handler},
541         {SIGUSR1, sigusr1_handler},
542         {SIGUSR2, sigusr2_handler},
543         {SIGCHLD, ignore_signal_handler},
544         {SIGALRM, sigalrm_handler},
545         {SIGWINCH, sigwinch_handler},
546         {0, NULL}
547 };
548 #endif
549
550 void setup_signals(void)
551 {
552 #ifndef HAVE_MINGW
553         int i;
554         struct sigaction act;
555
556         sigemptyset(&emptysigset);
557         act.sa_handler = NULL;
558         act.sa_mask = emptysigset;
559         act.sa_flags = 0;
560
561         /* Set a default signal handler for every signal, errors will be
562            ignored. */
563         for(i = 0; i < NSIG; i++) {
564                 if(!do_detach)
565                         act.sa_handler = SIG_DFL;
566                 else
567                         act.sa_handler = unexpected_signal_handler;
568                 sigaction(i, &act, NULL);
569         }
570
571         /* If we didn't detach, allow coredumps */
572         if(!do_detach)
573                 sighandlers[3].handler = SIG_DFL;
574
575         /* Then, for each known signal that we want to catch, assign a
576            handler to the signal, with error checking this time. */
577         for(i = 0; sighandlers[i].signal; i++) {
578                 act.sa_handler = sighandlers[i].handler;
579                 if(sigaction(sighandlers[i].signal, &act, NULL) < 0)
580                         fprintf(stderr, _("Installing signal handler for signal %d (%s) failed: %s\n"),
581                                         sighandlers[i].signal, strsignal(sighandlers[i].signal),
582                                         strerror(errno));
583         }
584 #endif
585 }