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