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