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