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