Debian Codegraph @

bin/amavis-mc

raw ◀ ▶
Source reconstructed at patch state 0 of 1 — not the installed (fully patched) source.
1 Debian patch touch this file
1 #!/usr/bin/perl -T
2 # SPDX-License-Identifier: BSD-2-Clause
3
4 #------------------------------------------------------------------------------
5 # This is amavis-mc, a master (of ceremonies) processes to supervise
6 # supporting service processes (such as amavis-services) used by amavis.
7 #
8 # Author: Mark Martinec <[email protected]>
9 #
10 # Copyright (c) 2012-2014, Mark Martinec
11 # All rights reserved.
12 #
13 # Redistribution and use in source and binary forms, with or without
14 # modification, are permitted provided that the following conditions
15 # are met:
16 # 1. Redistributions of source code must retain the above copyright notice,
17 # this list of conditions and the following disclaimer.
18 # 2. Redistributions in binary form must reproduce the above copyright notice,
19 # this list of conditions and the following disclaimer in the documentation
20 # and/or other materials provided with the distribution.
21 #
22 # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
23 # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
24 # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
25 # ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS
26 # BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
27 # CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
28 # SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
29 # INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
30 # CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
31 # ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
32 # POSSIBILITY OF SUCH DAMAGE.
33 #
34 # The views and conclusions contained in the software and documentation are
35 # those of the authors and should not be interpreted as representing official
36 # policies, either expressed or implied, of the Jozef Stefan Institute.
37
38 # (the above license is the 2-clause BSD license, also known as
39 # a "Simplified BSD License", and pertains to this program only)
40 #
41 # Patches and problem reports are welcome.
42 # The latest version of this program is available at:
43 # http://www.ijs.si/software/amavisd/
44 #------------------------------------------------------------------------------
45
46 use strict;
47 use re 'taint';
48 use warnings;
49 use warnings FATAL => qw(utf8 void);
50 no warnings 'uninitialized';
51
52 use vars qw($VERSION); $VERSION = 2.008002;
53
54 use vars qw($myproduct_name $myversion_id $myversion_date $myversion);
55 BEGIN {
56 $myproduct_name = 'amavis-mc';
57 $myversion_id = '2.9.0'; $myversion_date = '20140506';
58 $myversion = "$myproduct_name-$myversion_id ($myversion_date)";
59 }
60
61 use Errno qw(ESRCH ENOENT);
62 use POSIX qw(:sys_wait_h
63 WIFEXITED WIFSIGNALED WIFSTOPPED WEXITSTATUS WTERMSIG WSTOPSIG);
64 use Time::HiRes qw(time);
65 use IO::File qw(O_RDONLY O_WRONLY O_RDWR O_APPEND O_CREAT O_EXCL);
66 use Unix::Syslog qw(:macros :subs);
67 use Net::Server::Daemonize qw(set_uid set_gid);
68 use Amavis::Util;
69
70 use vars qw(@path @services $daemon_user @daemon_groups $pid_file $log_level
71 $syslog_ident $syslog_facility);
72
73
74 ### USER CONFIGURABLE:
75
76 $daemon_user = 'vscan';
77 @daemon_groups = 'vscan';
78
79 $pid_file = '/var/amavis/amavis-mc.pid';
80
81 $log_level = 0;
82 $syslog_ident = 'amavis-mc';
83 $syslog_facility = LOG_MAIL;
84
85 @path = qw(/usr/local/sbin /usr/local/bin /usr/sbin /sbin /usr/bin /bin);
86
87 @services = (
88 { cmd => 'amavis-services msg-forwarder' },
89 { cmd => 'amavis-services childproc-minder' },
90 { cmd => 'amavis-services snmp-responder' },
91 );
92
93 ### END OF USER CONFIGURABLE
94
95
96 my($interrupted, $syslog_open, $pid_file_created, @pids_exited, %pid2service);
97
98 # Return untainted copy of a string (argument can be a string or a string ref)
99 #
100 sub untaint($) {
101 return undef if !defined $_[0]; # must return undef even in a list context!
102 no re 'taint';
103 local $1; # avoid Perl taint bug: tainted global $1 propagates taintedness
104 (ref($_[0]) ? ${$_[0]} : $_[0]) =~ /^(.*)\z/s;
105 $1;
106 }
107
108 # is message log level below the current log level (i.e. eligible for logging)?
109 #
110 sub ll($) {
111 my($level) = @_;
112 $level <= $log_level;
113 }
114
115 sub do_log($$;@) {
116 # my($level,$errmsg,@args) = @_;
117 my $level = shift;
118 if ($level <= $log_level) {
119 my $errmsg = shift;
120 # treat $errmsg as sprintf format string if additional arguments provided
121 $errmsg = sprintf($errmsg,@_) if @_;
122 if (!$syslog_open) {
123 $errmsg .= "\n";
124 print STDERR $errmsg; # print ignoring I/O status, except SIGPIPE
125 } else {
126 my $prio = $level >= 3 ? LOG_DEBUG # most frequent first
127 : $level >= 1 ? LOG_INFO
128 : $level >= 0 ? LOG_NOTICE
129 : $level >= -1 ? LOG_WARNING
130 : LOG_ERR;
131 syslog($prio, "%s", $errmsg);
132 }
133 }
134 }
135
136 sub find_program_path($$) {
137 my($fv_list, $path_list_ref) = @_;
138 $fv_list = [$fv_list] if !ref $fv_list;
139 my $found;
140 for my $fv (@$fv_list) { # search through alternatives
141 my(@fv_cmd) = split(' ',$fv);
142 my $cmd = $fv_cmd[0];
143 if (!@fv_cmd) {
144 # empty, not available
145 } elsif ($cmd =~ m{^/}s) { # absolute path
146 my $errn = stat($cmd) ? 0 : 0+$!;
147 if ($errn == ENOENT) {
148 # file does not exist
149 } elsif ($errn) {
150 do_log(-1, "find_program_path: %s inaccessible: %s", $cmd,$!);
151 } elsif (-d _) {
152 do_log(0, "find_program_path: %s is a directory", $cmd);
153 } elsif (!-x _) {
154 do_log(0, "find_program_path: %s is not executable", $cmd);
155 } else {
156 $found = join(' ', @fv_cmd);
157 }
158 } elsif ($cmd =~ m{/}s) { # relative path
159 die "find_program_path: relative paths not implemented: @fv_cmd\n";
160 } else { # walk through the specified PATH
161 for my $p (@$path_list_ref) {
162 my $errn = stat("$p/$cmd") ? 0 : 0+$!;
163 if ($errn == ENOENT) {
164 # file does not exist
165 } elsif ($errn) {
166 do_log(-1, "find_program_path: %s/%s inaccessible: %s", $p,$cmd,$!);
167 } elsif (-d _) {
168 do_log(0, "find_program_path: %s/%s is a directory", $p,$cmd);
169 } elsif (!-x _) {
170 do_log(0, "find_program_path: %s/%s is not executable", $p,$cmd);
171 } else {
172 $found = $p . '/' . join(' ', @fv_cmd);
173 last;
174 }
175 }
176 }
177 last if defined $found;
178 }
179 $found;
180 }
181
182 # drop privileges
183 #
184 sub drop_priv(@) {
185 my($desired_user,@desired_groups) = @_;
186 eval {
187 set_gid(@desired_groups) if @desired_groups;
188 set_uid($desired_user) if defined $desired_user;
189 1;
190 } or die "drop_priv: $@";
191 $> != 0 or die "drop_priv: Still running as root, aborting\n";
192 $< != 0 or die "Effective UID changed, but Real UID is 0, aborting\n";
193 }
194
195 sub daemonize() {
196 closelog() if $syslog_open;
197 $syslog_open = 0;
198
199 STDOUT->autoflush(1);
200 STDERR->autoflush(1);
201 close(STDIN) or die "Can't close STDIN: $!";
202
203 my $pid;
204 # the first fork allows the shell to return and allows doing a setsid
205 eval { $pid = fork(); 1 }
206 or do {
207 my($eval_stat) = $@ ne '' ? $@ : "errno=$!"; chomp $eval_stat;
208 die "Error forking #1: $eval_stat";
209 };
210 defined $pid or die "Can't fork #1: $!";
211 if ($pid) { # parent process terminates here
212 POSIX::_exit(0); # avoid END and destructor processing
213 }
214
215 # disassociate from a controlling terminal
216 my $pgid = POSIX::setsid();
217 defined $pgid && $pgid >= 0 or die "Can't start a new session: $!";
218
219 # We are now a session leader. As a session leader, opening a file
220 # descriptor that is a terminal will make it our controlling terminal.
221 # The second fork makes us NOT a session leader. Only session leaders
222 # can acquire a controlling terminal, so we may now open up any file
223 # we wish without worrying that it will become a controlling terminal.
224
225 # second fork prevents from accidentally reacquiring a controlling terminal
226 eval { $pid = fork(); 1 }
227 or do {
228 my($eval_stat) = $@ ne '' ? $@ : "errno=$!"; chomp $eval_stat;
229 die "Error forking #2: $eval_stat";
230 };
231 defined $pid or die "Can't fork #2: $!";
232 if ($pid) { # parent process terminates here
233 POSIX::_exit(0); # avoid END and destructor processing
234 }
235
236 chdir('/') or die "Can't chdir to '/': $!";
237
238 # a daemonized child process, live long and prosper...
239 do_log(2, "Daemonized as process [%s]", $$);
240
241 openlog($syslog_ident, LOG_PID | LOG_NDELAY, $syslog_facility);
242 $syslog_open = 1;
243
244 { # suppress unnecessary warning:
245 # "Filehandle STDIN reopened as STDOUT only for output"
246 # See https://rt.perl.org/rt3/Public/Bug/Display.html?id=23838
247 no warnings 'io';
248 close(STDOUT) or die "Can't close STDOUT: $!";
249 open(STDOUT, '>/dev/null') or die "Can't open /dev/null: $!";
250 close(STDERR) or die "Can't close STDERR: $!";
251 open(STDERR, '>&STDOUT') or die "Can't dup STDOUT: $!";
252 }
253
254 }
255
256 # Run specified command as a subprocess.
257 # Return a process id of a child process.
258 #
259 sub spawn_command($@) {
260 my($cmd, @args) = @_;
261 my $cmd_text = join(' ', $cmd, @args);
262 my $pid;
263 eval {
264 # Note that fork(2) returns ENOMEM on lack of swap space, and EAGAIN when
265 # process limit is reached; we want it to fail in both cases and not obey
266 # the EAGAIN and keep retrying, as perl open() does.
267 $pid = fork(); 1;
268 } or do {
269 my $eval_stat = $@ ne '' ? $@ : "errno=$!"; chomp $eval_stat;
270 die "spawn_command (forking): $eval_stat";
271 };
272 defined($pid) or die "spawn_command: can't fork: $!";
273 if (!$pid) { # child
274 alarm(0); my $interrupt = '';
275 my $h1 = sub { $interrupt = $_[0] };
276 my $h2 = sub { die "Received signal ".$_[0] };
277 @SIG{qw(INT HUP TERM TSTP QUIT USR1 USR2)} = ($h1) x 7;
278 my $err;
279 eval { # die must be caught, otherwise we end up with two running daemons
280 local(@SIG{qw(INT HUP TERM TSTP QUIT USR1 USR2)}) = ($h2) x 7;
281 if ($interrupt ne '') { my $i = $interrupt; $interrupt = ''; die $i }
282 close STDIN; # ignoring errors
283 close STDOUT; # ignoring errors
284 # BEWARE of Perl older that 5.6.0: sockets and pipes were not FD_CLOEXEC
285 exec {$cmd} ($cmd,@args);
286 die "spawn_command: failed to exec $cmd_text: $!";
287 0; # paranoia
288 } or do {
289 $err = $@ ne '' ? $@ : "errno=$!"; chomp $err;
290 };
291 eval {
292 local(@SIG{qw(INT HUP TERM TSTP QUIT USR1 USR2)}) = ($h2) x 7;
293 if ($interrupt ne '') { my $i = $interrupt; $interrupt = ''; die $i }
294 # we're in trouble if stderr was attached to a terminal, but no longer is
295 eval { do_log(-1,"spawn_command: child process [%s]: %s", $$,$err) };
296 } or 1; # ignore failures, make perlcritic happy
297 { # no warnings;
298 POSIX::_exit(6); # avoid END and destructor processing
299 kill('KILL',$$); exit 1; # still kicking? die!
300 }
301 }
302 # parent
303 do_log(5,"spawn_command: [%s] %s", $pid, $cmd_text);
304 $pid; # return the PID of a subprocess
305 }
306
307 sub usage() {
308 my $me = $0; local $1; $me =~ s{([^/]*)\z}{$1}s;
309 "Usage: $me (-h | -V | [-f] [-P pid_file] [-d log_level])";
310 }
311
312 # map process termination status number to an informative string, and
313 # append optional message (dual-valued errno or a string or a number),
314 # returning the resulting string
315 #
316 sub exit_status_str($;$) {
317 my($stat,$errno) = @_; my $str;
318 if (!defined($stat)) {
319 $str = '(no status)';
320 } elsif (WIFEXITED($stat)) {
321 $str = sprintf('exit %d', WEXITSTATUS($stat));
322 } elsif (WIFSTOPPED($stat)) {
323 $str = sprintf('stopped, signal %d', WSTOPSIG($stat));
324 } else {
325 my $sig = WTERMSIG($stat);
326 $str = sprintf('%s, signal %d (%04x)',
327 $sig == 1 ? 'HANGUP' : $sig == 2 ? 'INTERRUPTED' :
328 $sig == 6 ? 'ABORTED' : $sig == 9 ? 'KILLED' :
329 $sig == 15 ? 'TERMINATED' : 'DIED',
330 $sig, $stat);
331 }
332 if (defined $errno) { # deal with dual-valued and plain variables
333 $str .= ', '.$errno if (0+$errno) != 0 || ($errno ne '' && $errno ne '0');
334 }
335 $str;
336 }
337
338 # check errno to be 0 and a process exit status to be in the list of success
339 # status codes, returning true if both are ok, and false otherwise
340 #
341 sub proc_status_ok($;$@) {
342 my($exit_status,$errno,@success) = @_;
343 my $ok = 0;
344 if ((!defined $errno || $errno == 0) && WIFEXITED($exit_status)) {
345 my $j = WEXITSTATUS($exit_status);
346 if (!@success) { $ok = $j==0 } # empty list implies only status 0 is good
347 elsif (grep($_==$j, @success)) { $ok = 1 }
348 }
349 $ok;
350 }
351
352 sub report_terminations($) {
353 my($pids_exited_list) = @_;
354 # note: child_handler may be growing the list at its tail during the loop
355 while (@$pids_exited_list) {
356 my $pid_stat = shift(@$pids_exited_list);
357 next if !$pid_stat; # just in case
358 my($pid,$status,$timestamp) = @$pid_stat;
359 my $serv = delete $pid2service{$pid};
360 if (!$serv) {
361 do_log(-1,'Unknown process [%d] exited: %s',
362 $pid, exit_status_str($status,0));
363 } else {
364 $serv->{status} = $status;
365 $serv->{terminated_at} = $timestamp;
366 my $ll = proc_status_ok($status,0) ? 0 : -1;
367 do_log($ll, 'Process [%d] exited (%s) after %.1f s: %s',
368 $pid, $serv->{cmd},
369 $serv->{terminated_at} - $serv->{started_at},
370 exit_status_str($status,0));
371 }
372 }
373 }
374
375 sub child_handler {
376 my $signal = $_[0];
377 for (;;) {
378 my $child_pid = waitpid(-1,WNOHANG);
379 # PID may be negative on Windows
380 last if !$child_pid || $child_pid == -1;
381 push(@pids_exited, [$child_pid, $?, time]);
382 }
383 $SIG{CHLD} = \&child_handler;
384 };
385
386
387 # main program starts here
388
389 delete @ENV{'PATH', 'IFS', 'CDPATH', 'ENV', 'BASH_ENV'};
390 $ENV{PATH} = join(':',@path) if @path;
391
392 my $foreground = 0;
393 my(@argv) = @ARGV; # preserve @ARGV, may modify @argv
394 while (@argv >= 2 && $argv[0] =~ /^-[dP]\z/ ||
395 @argv >= 1 && $argv[0] =~ /^-/) {
396 my($opt,$val);
397 $opt = shift @argv;
398 $val = shift @argv if $opt !~ /^-[hVf-]\z/; # these take no arguments
399 if ($opt eq '--') {
400 last;
401 } elsif ($opt eq '-h') { # -h (help)
402 die "$myversion\n\n" . usage() . "\n";
403 } elsif ($opt eq '-V') { # -V (version)
404 die "$myversion\n";
405 } elsif ($opt eq '-f') {
406 $foreground = 1;
407 } elsif ($opt eq '-d') { # -d log_level
408 $val =~ /^\d+\z/ or die "Bad value for option -d: $val\n";
409 $log_level = untaint($val);
410 } elsif ($opt eq '-P') { # -P pid_file
411 $pid_file = untaint($val);
412 } else {
413 die "Error in command line options: $opt\n\n" . usage() . "\n";
414 }
415 }
416 !@argv or die sprintf("Error parsing a command line %s\n\n%s\n",
417 join(' ',@ARGV), usage());
418
419 $SIG{'__DIE__' } =
420 sub { if (!$^S) { my($m) = @_; chomp($m); do_log(-1,"_DIE: %s", $m) } };
421 $SIG{'__WARN__'} =
422 sub { my($m) = @_; chomp($m); do_log(0,"_WARN: %s",$m) };
423
424 if ($foreground) {
425 do_log(0,"amavis master process starting in foreground, perl %s", $] );
426 } else { # daemonize
427 openlog($syslog_ident, LOG_PID | LOG_NDELAY, $syslog_facility);
428 $syslog_open = 1;
429 do_log(2,"to be daemonized");
430 daemonize();
431 srand();
432 do_log(0,'amavis master process starting. '.
433 'daemonized as PID [%s], perl %s', $$, $] );
434 }
435
436 if (defined $daemon_user) {
437 drop_priv($daemon_user, @daemon_groups
438 ? @daemon_groups
439 : Amavis::Util::get_user_groups($daemon_user))
440 }
441
442 if (defined $pid_file && $pid_file ne '') {
443 my $pid_file_fh = IO::File->new;
444 $pid_file_fh->open($pid_file, O_CREAT|O_WRONLY, 0640)
445 or die "Can't create PID file $pid_file: $!";
446 $pid_file_fh->print($$."\n")
447 or die "Can't write to PID file $pid_file: $!";
448 $pid_file_fh->close
449 or die "Can't close PID file $pid_file: $!";
450 $pid_file_created = 1;
451 }
452
453 # initialize
454 for my $serv (@services) {
455 $serv->{started_cnt} = 0;
456 $serv->{pid} = $serv->{status} = undef;
457 $serv->{started_at} = $serv->{terminated_at} = undef;
458 my $found = find_program_path($serv->{cmd}, \@path);
459 defined $found
460 or die sprintf("Can't find program %s in path %s\n",
461 $serv->{cmd}, join(':',@path));
462 $serv->{cmd} = $found;
463 }
464
465 $SIG{CHLD} = \&child_handler;
466
467 eval { # catch TERM and INT signals for a controlled shutdown
468 my $h = sub { $interrupted = $_[0]; die "\n" };
469 local $SIG{INT} = $h;
470 local $SIG{TERM} = $h;
471 for (;;) {
472 last if defined $interrupted;
473 for my $serv (@services) {
474 next if $serv->{disabled};
475 report_terminations(\@pids_exited) if @pids_exited;
476 if (defined $serv->{status}) {
477 # process has terminated, clean up
478 $serv->{pid} = undef;
479 $serv->{started_at} = undef;
480 }
481 last if defined $interrupted;
482 if (!defined $serv->{pid}) {
483 # service not running
484 if ($serv->{started_cnt} >= 5) {
485 do_log(-1,'Exceeded restart count, giving up on (%s)', $serv->{cmd});
486 $serv->{disabled} = 1;
487 } elsif (defined $serv->{terminated_at} &&
488 time - $serv->{terminated_at} < 1) {
489 # postpone a restart for at least a second
490 do_log(5, 'Postponing a restart (%s)', $serv->{cmd});
491 } else {
492 my($cmd,@args) = split(' ',$serv->{cmd});
493 $serv->{started_cnt}++;
494 $serv->{status} = $serv->{terminated_at} = undef;
495 $serv->{started_at} = time;
496 my $pid = $serv->{pid} = spawn_command($cmd,@args);
497 do_log(0, 'Process [%d] started: %s', $pid, $serv->{cmd});
498 # to avoid race the signal handler must not be updating %pid2service
499 $pid2service{$pid} = $serv;
500 }
501 }
502 }
503 sleep 5; # sleep may be aborted prematurely by a signal
504 } # until interrupted
505 };
506
507 do_log(0, 'Master process shutting down');
508
509 for my $sig ('TERM', 'KILL') {
510 # terminate or kill child processes
511 for my $serv (@services) {
512 my $pid = $serv->{pid};
513 next if !$pid;
514 my $n = kill($sig,$pid);
515 if ($n == 0 && $! == ESRCH) {
516 # process already gone
517 } elsif ($n == 0) {
518 do_log(-1, "Can't send SIG%s to process [%s]: %s", $sig, $pid, $!);
519 } else {
520 do_log(0, "%s process [%s] (%s)",
521 $sig eq 'TERM' ? 'Terminating' : 'Killing',
522 $pid, $serv->{cmd});
523 }
524 }
525 my $deadline = time + 10; # 10 second grace period
526 while (time < $deadline) {
527 report_terminations(\@pids_exited);
528 sleep 1; # sleep may be aborted prematurely by a signal
529 # stop waiting if all gone
530 last if !grep { $_->{pid} && kill(0, $_->{pid}) } @services;
531 }
532 report_terminations(\@pids_exited);
533 }
534
535 END {
536 do_log(0,'Master process exiting: %s', $interrupted) if defined $interrupted;
537 if ($pid_file_created) {
538 unlink($pid_file)
539 or do_log(-1, "Can't delete a PID file %s: %s", $pid_file, $!);
540 }
541 if ($syslog_open) { closelog(); $syslog_open = 0 }
542 }