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