perltidy -b qpsmtpd*

This commit is contained in:
Matt Simerson 2013-04-21 00:34:07 -04:00
parent 73c988ac05
commit 5a0662b64a
4 changed files with 490 additions and 406 deletions

View File

@ -1,6 +1,7 @@
#!/usr/bin/perl #!/usr/bin/perl
use lib "./lib"; use lib "./lib";
BEGIN { BEGIN {
delete $ENV{ENV}; delete $ENV{ENV};
delete $ENV{BASH_ENV}; delete $ENV{BASH_ENV};
@ -14,6 +15,7 @@ BEGIN {
use strict; use strict;
use vars qw($DEBUG); use vars qw($DEBUG);
use FindBin qw(); use FindBin qw();
# TODO: need to make this taint friendly # TODO: need to make this taint friendly
use lib "$FindBin::Bin/lib"; use lib "$FindBin::Bin/lib";
use Danga::Socket; use Danga::Socket;
@ -29,7 +31,8 @@ use List::Util qw(shuffle);
$|++; $|++;
use Socket qw(SOMAXCONN IPPROTO_TCP SO_KEEPALIVE TCP_NODELAY SOL_SOCKET AF_UNIX SOCK_STREAM PF_UNSPEC); use Socket
qw(SOMAXCONN IPPROTO_TCP SO_KEEPALIVE TCP_NODELAY SOL_SOCKET AF_UNIX SOCK_STREAM PF_UNSPEC);
$SIG{'PIPE'} = "IGNORE"; # handled manually $SIG{'PIPE'} = "IGNORE"; # handled manually
@ -86,21 +89,30 @@ GetOptions(
'd|detach' => \$DETACH, 'd|detach' => \$DETACH,
'h|help' => \&help, 'h|help' => \&help,
'config-port=i' => \$CONFIG_PORT, 'config-port=i' => \$CONFIG_PORT,
) || help(); )
|| help();
# detaint the commandline # detaint the commandline
if ($PORT =~ /^(\d+)$/) { $PORT = $1 } else { &help } if ($PORT =~ /^(\d+)$/) { $PORT = $1 }
if ($LOCALADDR =~ /^([\d\w\-.]+)$/) { $LOCALADDR = $1 } else { &help } else { &help }
if ($USER =~ /^([\w\-]+)$/) { $USER = $1 } else { &help } if ($LOCALADDR =~ /^([\d\w\-.]+)$/) { $LOCALADDR = $1 }
if ($PROCS =~ /^(\d+)$/) { $PROCS = $1 } else { &help } else { &help }
if ($USER =~ /^([\w\-]+)$/) { $USER = $1 }
else { &help }
if ($PROCS =~ /^(\d+)$/) { $PROCS = $1 }
else { &help }
sub force_poll { sub force_poll {
$Danga::Socket::HaveEpoll = 0; $Danga::Socket::HaveEpoll = 0;
$Danga::Socket::HaveKQueue = 0; $Danga::Socket::HaveKQueue = 0;
} }
my $POLL = "with " . ($Danga::Socket::HaveEpoll ? "epoll()" : my $POLL = "with "
$Danga::Socket::HaveKQueue ? "kqueue()" : "poll()"); . (
$Danga::Socket::HaveEpoll ? "epoll()"
: $Danga::Socket::HaveKQueue ? "kqueue()"
: "poll()"
);
my $SERVER; my $SERVER;
my $CONFIG_SERVER; my $CONFIG_SERVER;
@ -114,7 +126,8 @@ my %childstatus = ();
if ($PID_FILE && -r $PID_FILE) { if ($PID_FILE && -r $PID_FILE) {
open PID, "<$PID_FILE" open PID, "<$PID_FILE"
or die "open_pidfile $PID_FILE: $!\n"; or die "open_pidfile $PID_FILE: $!\n";
my $running_pid = <PID> || ''; chomp $running_pid; my $running_pid = <PID> || '';
chomp $running_pid;
if ($running_pid =~ /^(\d+)/) { if ($running_pid =~ /^(\d+)/) {
if (kill 0, $running_pid) { if (kill 0, $running_pid) {
die "Found an already running qpsmtpd with pid $running_pid.\n"; die "Found an already running qpsmtpd with pid $running_pid.\n";
@ -141,10 +154,13 @@ sub _fork {
# cope with different versions of Net::DNS # cope with different versions of Net::DNS
eval { eval {
$Net::DNS::Resolver::global{id} = 1; $Net::DNS::Resolver::global{id} = 1;
$Net::DNS::Resolver::global{id} = int(rand(Net::DNS::Resolver::MAX_ID())); $Net::DNS::Resolver::global{id} =
int(rand(Net::DNS::Resolver::MAX_ID()));
# print "Next DNS ID: $Net::DNS::Resolver::global{id}\n"; # print "Next DNS ID: $Net::DNS::Resolver::global{id}\n";
}; };
if ($@) { if ($@) {
# print "Next DNS ID: " . Net::DNS::Header::nextid() . "\n"; # print "Next DNS ID: " . Net::DNS::Header::nextid() . "\n";
} }
@ -155,7 +171,8 @@ sub _fork {
sub spawn_child { sub spawn_child {
my $plugin_loader = shift || Qpsmtpd::SMTP->new; my $plugin_loader = shift || Qpsmtpd::SMTP->new;
socketpair(my $reader, my $writer, AF_UNIX, SOCK_STREAM, PF_UNSPEC) || die "Unable to create a pipe"; socketpair(my $reader, my $writer, AF_UNIX, SOCK_STREAM, PF_UNSPEC)
|| die "Unable to create a pipe";
$writer->autoflush(1); $writer->autoflush(1);
$reader->autoflush(1); $reader->autoflush(1);
@ -174,8 +191,7 @@ sub spawn_child {
Qpsmtpd::PollServer->OtherFds( Qpsmtpd::PollServer->OtherFds(
fileno($reader) => sub { command_handler($reader) }, fileno($reader) => sub { command_handler($reader) },
fileno($SERVER) => \&accept_handler, fileno($SERVER) => \&accept_handler,);
);
$ACCEPT_RSET = Danga::Socket->AddTimer(30, \&reset_num_accept); $ACCEPT_RSET = Danga::Socket->AddTimer(30, \&reset_num_accept);
@ -206,6 +222,7 @@ sub sig_chld {
} }
if ($spawn_count) { if ($spawn_count) {
for (1 .. $spawn_count) { for (1 .. $spawn_count) {
# restart a new child if in poll server mode # restart a new child if in poll server mode
my $pid = spawn_child(); my $pid = spawn_child();
} }
@ -223,34 +240,40 @@ sub HUNTSMAN {
} }
sub run_as_server { sub run_as_server {
# establish SERVER socket, bind and listen. # establish SERVER socket, bind and listen.
$SERVER = IO::Socket::INET->new(LocalPort => $PORT, $SERVER = IO::Socket::INET->new(
LocalPort => $PORT,
LocalAddr => $LOCALADDR, LocalAddr => $LOCALADDR,
Type => SOCK_STREAM, Type => SOCK_STREAM,
Proto => IPPROTO_TCP, Proto => IPPROTO_TCP,
Blocking => 0, Blocking => 0,
Reuse => 1, Reuse => 1,
Listen => SOMAXCONN ) Listen => SOMAXCONN
)
or die "Error creating server $LOCALADDR:$PORT : $@\n"; or die "Error creating server $LOCALADDR:$PORT : $@\n";
IO::Handle::blocking($SERVER, 0); IO::Handle::blocking($SERVER, 0);
binmode($SERVER, ':raw'); binmode($SERVER, ':raw');
$CONFIG_SERVER = IO::Socket::INET->new(LocalPort => $CONFIG_PORT, $CONFIG_SERVER =
IO::Socket::INET->new(
LocalPort => $CONFIG_PORT,
LocalAddr => $CONFIG_LOCALADDR, LocalAddr => $CONFIG_LOCALADDR,
Type => SOCK_STREAM, Type => SOCK_STREAM,
Proto => IPPROTO_TCP, Proto => IPPROTO_TCP,
Blocking => 0, Blocking => 0,
Reuse => 1, Reuse => 1,
Listen => 1 ) Listen => 1
)
or die "Error creating server $CONFIG_LOCALADDR:$CONFIG_PORT : $@\n"; or die "Error creating server $CONFIG_LOCALADDR:$CONFIG_PORT : $@\n";
IO::Handle::blocking($CONFIG_SERVER, 0); IO::Handle::blocking($CONFIG_SERVER, 0);
binmode($CONFIG_SERVER, ':raw'); binmode($CONFIG_SERVER, ':raw');
# Drop priviledges # Drop priviledges
my (undef, undef, $quid, $qgid) = getpwnam $USER or my (undef, undef, $quid, $qgid) = getpwnam $USER
die "unable to determine uid/gid for $USER\n"; or die "unable to determine uid/gid for $USER\n";
my $groups = "$qgid $qgid"; my $groups = "$qgid $qgid";
while (my (undef, undef, $gid, $members) = getgrent) { while (my (undef, undef, $gid, $members) = getgrent) {
my @m = split(/ /, $members); my @m = split(/ /, $members);
@ -260,10 +283,10 @@ sub run_as_server {
} }
endgrent; endgrent;
$) = $groups; $) = $groups;
POSIX::setgid($qgid) or POSIX::setgid($qgid)
die "unable to change gid: $!\n"; or die "unable to change gid: $!\n";
POSIX::setuid($quid) or POSIX::setuid($quid)
die "unable to change uid: $!\n"; or die "unable to change uid: $!\n";
$> = $quid; $> = $quid;
# Load plugins here # Load plugins here
@ -285,15 +308,18 @@ sub run_as_server {
close PID; close PID;
} }
$plugin_loader->log(LOGINFO, 'Running as user '. $plugin_loader->log(LOGINFO,
(getpwuid($>) || $>) . 'Running as user '
', group '. . (getpwuid($>) || $>)
(getgrgid($)) || $))); . ', group '
. (getgrgid($)) || $))
);
$SIG{INT} = $SIG{TERM} = \&HUNTSMAN; $SIG{INT} = $SIG{TERM} = \&HUNTSMAN;
###################### ######################
# more Profiling code # more Profiling code
=pod =pod
$plugin_loader->run_hooks('post-fork'); $plugin_loader->run_hooks('post-fork');
@ -315,18 +341,18 @@ sub run_as_server {
Qpsmtpd::PollServer->EventLoop; Qpsmtpd::PollServer->EventLoop;
exit; exit;
=cut =cut
##################### #####################
for (1 .. $PROCS) { for (1 .. $PROCS) {
my $pid = spawn_child($plugin_loader); my $pid = spawn_child($plugin_loader);
} }
$plugin_loader->log(LOGDEBUG, "Listening on $PORT with $PROCS children $POLL"); $plugin_loader->log(LOGDEBUG,
"Listening on $PORT with $PROCS children $POLL");
$SIG{CHLD} = \&sig_chld; $SIG{CHLD} = \&sig_chld;
$SIG{HUP} = \&sig_hup; $SIG{HUP} = \&sig_hup;
Qpsmtpd::PollServer->OtherFds( Qpsmtpd::PollServer->OtherFds(fileno($CONFIG_SERVER) => \&config_handler,);
fileno($CONFIG_SERVER) => \&config_handler,
);
Qpsmtpd::PollServer->EventLoop; Qpsmtpd::PollServer->EventLoop;
@ -337,6 +363,7 @@ sub run_as_server {
sub config_handler { sub config_handler {
my $csock = $CONFIG_SERVER->accept(); my $csock = $CONFIG_SERVER->accept();
if (!$csock) { if (!$csock) {
# warn("accept failed on config server: $!"); # warn("accept failed on config server: $!");
return; return;
} }
@ -366,9 +393,11 @@ sub command_handler {
} }
sub cmd_hup { sub cmd_hup {
# clear cache # clear cache
print "Clearing cache\n"; print "Clearing cache\n";
Qpsmtpd::clear_config_cache(); Qpsmtpd::clear_config_cache();
# should also reload modules... but can't do that yet. # should also reload modules... but can't do that yet.
} }
@ -391,15 +420,18 @@ use Errno qw(EAGAIN EWOULDBLOCK);
sub _accept_handler { sub _accept_handler {
my $csock = $SERVER->accept(); my $csock = $SERVER->accept();
if (!$csock) { if (!$csock) {
# warn("accept() failed: $!"); # warn("accept() failed: $!");
return; return;
} }
binmode($csock, ':raw'); binmode($csock, ':raw');
printf("Listen child making a Qpsmtpd::PollServer for %d.\n", fileno($csock)) printf("Listen child making a Qpsmtpd::PollServer for %d.\n",
fileno($csock))
if $DEBUG; if $DEBUG;
IO::Handle::blocking($csock, 0); IO::Handle::blocking($csock, 0);
#setsockopt($csock, IPPROTO_TCP, TCP_NODELAY, pack("l", 1)) or die; #setsockopt($csock, IPPROTO_TCP, TCP_NODELAY, pack("l", 1)) or die;
#print "Got connection\n"; #print "Got connection\n";
@ -421,6 +453,7 @@ sub _accept_handler {
sub log { sub log {
my ($level, $message) = @_; my ($level, $message) = @_;
# $level not used yet. this is reimplemented from elsewhere anyway # $level not used yet. this is reimplemented from elsewhere anyway
warn("$$ fd:? $message\n"); warn("$$ fd:? $message\n");
} }

View File

@ -52,7 +52,8 @@ EOT
exit 0; exit 0;
} }
GetOptions('h|help' => \&usage, GetOptions(
'h|help' => \&usage,
'l|listen-address=s' => \@LOCALADDR, 'l|listen-address=s' => \@LOCALADDR,
'c|limit-connections=i' => \$MAXCONN, 'c|limit-connections=i' => \$MAXCONN,
'm|max-from-ip=i' => \$MAXCONNIP, 'm|max-from-ip=i' => \$MAXCONNIP,
@ -61,7 +62,8 @@ GetOptions('h|help' => \&usage,
'pid-file=s' => \$PID_FILE, 'pid-file=s' => \$PID_FILE,
'd|detach' => \$DETACH, 'd|detach' => \$DETACH,
'H|no-rdns' => \$NORDNS, 'H|no-rdns' => \$NORDNS,
) || &usage; )
|| &usage;
# detaint the commandline # detaint the commandline
if ($has_ipv6) { if ($has_ipv6) {
@ -77,23 +79,28 @@ for (0..$#LOCALADDR) {
if ($LOCALADDR[$_] =~ /^(\[.*\]|[\d\w\-.]+)(?::(\d+))?$/) { if ($LOCALADDR[$_] =~ /^(\[.*\]|[\d\w\-.]+)(?::(\d+))?$/) {
if (defined $2) { if (defined $2) {
push @LISTENADDR, {'addr' => $1, 'port' => $2}; push @LISTENADDR, {'addr' => $1, 'port' => $2};
} else { }
else {
my $addr = $1; my $addr = $1;
for (0 .. $#PORT) { for (0 .. $#PORT) {
if ($PORT[$_] =~ /^(\d+)$/) { if ($PORT[$_] =~ /^(\d+)$/) {
push @LISTENADDR, {'addr' => $addr, 'port' => $1}; push @LISTENADDR, {'addr' => $addr, 'port' => $1};
} else { }
else {
&usage; &usage;
} }
} }
} }
} else { }
else {
&usage; &usage;
} }
} }
if ($USER =~ /^([\w\-]+)$/) { $USER = $1 } else { &usage } if ($USER =~ /^([\w\-]+)$/) { $USER = $1 }
if ($MAXCONN =~ /^(\d+)$/) { $MAXCONN = $1 } else { &usage } else { &usage }
if ($MAXCONN =~ /^(\d+)$/) { $MAXCONN = $1 }
else { &usage }
delete $ENV{ENV}; delete $ENV{ENV};
$ENV{PATH} = '/bin:/usr/bin:/var/qmail/bin'; $ENV{PATH} = '/bin:/usr/bin:/var/qmail/bin';
@ -125,30 +132,36 @@ my $server;
# establish SERVER socket(s), bind and listen. # establish SERVER socket(s), bind and listen.
for my $listen_addr (@LISTENADDR) { for my $listen_addr (@LISTENADDR) {
my @Socket_opts = (LocalPort => $listen_addr->{'port'}, my @Socket_opts = (
LocalPort => $listen_addr->{'port'},
LocalAddr => $listen_addr->{'addr'}, LocalAddr => $listen_addr->{'addr'},
Proto => 'tcp', Proto => 'tcp',
Reuse => 1, Reuse => 1,
Blocking => 0, Blocking => 0,
Listen => SOMAXCONN); Listen => SOMAXCONN
);
if ($has_ipv6) { if ($has_ipv6) {
$server = IO::Socket::INET6->new(@Socket_opts) $server = IO::Socket::INET6->new(@Socket_opts)
or die "Creating TCP socket $listen_addr->{'addr'}:$listen_addr->{'port'}: $!\n"; or die
"Creating TCP socket $listen_addr->{'addr'}:$listen_addr->{'port'}: $!\n";
} }
else { else {
$server = IO::Socket::INET->new(@Socket_opts) $server = IO::Socket::INET->new(@Socket_opts)
or die "Creating TCP socket $listen_addr->{'addr'}:$listen_addr->{'port'}: $!\n"; or die
"Creating TCP socket $listen_addr->{'addr'}:$listen_addr->{'port'}: $!\n";
} }
IO::Handle::blocking($server, 0); IO::Handle::blocking($server, 0);
$select->add($server); $select->add($server);
} }
if ($PID_FILE) { if ($PID_FILE) {
if ($PID_FILE =~ m#^(/[\w\d/\-.]+)$#) { $PID_FILE = $1 } else { &usage } if ($PID_FILE =~ m#^(/[\w\d/\-.]+)$#) { $PID_FILE = $1 }
else { &usage }
if (-e $PID_FILE) { if (-e $PID_FILE) {
open PID, "+<$PID_FILE" open PID, "+<$PID_FILE"
or die "open pid_file: $!\n"; or die "open pid_file: $!\n";
my $running_pid = <PID> || ''; chomp $running_pid; my $running_pid = <PID> || '';
chomp $running_pid;
if ($running_pid =~ /(\d+)/) { if ($running_pid =~ /(\d+)/) {
$running_pid = $1; $running_pid = $1;
if (kill 0, $running_pid) { if (kill 0, $running_pid) {
@ -159,7 +172,8 @@ if ($PID_FILE) {
or die "Could not seek back to beginning of $PID_FILE: $!\n"; or die "Could not seek back to beginning of $PID_FILE: $!\n";
truncate PID, 0 truncate PID, 0
or die "Could not truncate $PID_FILE at 0: $!"; or die "Could not truncate $PID_FILE at 0: $!";
} else { }
else {
open PID, ">$PID_FILE" open PID, ">$PID_FILE"
or die "open pid_file: $!\n"; or die "open pid_file: $!\n";
} }
@ -169,8 +183,8 @@ if ($PID_FILE) {
my $qpsmtpd = Qpsmtpd::TcpServer->new(); my $qpsmtpd = Qpsmtpd::TcpServer->new();
# Drop privileges # Drop privileges
my (undef, undef, $quid, $qgid) = getpwnam $USER or my (undef, undef, $quid, $qgid) = getpwnam $USER
die "unable to determine uid/gid for $USER\n"; or die "unable to determine uid/gid for $USER\n";
my $groups = "$qgid $qgid"; my $groups = "$qgid $qgid";
while (my ($name, $passwd, $gid, $members) = getgrent()) { while (my ($name, $passwd, $gid, $members) = getgrent()) {
my @m = split(/ /, $members); my @m = split(/ /, $members);
@ -180,21 +194,24 @@ while (my ($name,$passwd,$gid,$members) = getgrent()) {
} }
endgrent; endgrent;
$) = $groups; $) = $groups;
POSIX::setgid($qgid) or POSIX::setgid($qgid)
die "unable to change gid: $!\n"; or die "unable to change gid: $!\n";
POSIX::setuid($quid) or POSIX::setuid($quid)
die "unable to change uid: $!\n"; or die "unable to change uid: $!\n";
$> = $quid; $> = $quid;
$qpsmtpd->load_plugins; $qpsmtpd->load_plugins;
foreach my $listen_addr (@LISTENADDR) { foreach my $listen_addr (@LISTENADDR) {
::log(LOGINFO,"Listening on $listen_addr->{'addr'}:$listen_addr->{'port'}"); ::log(LOGINFO,
"Listening on $listen_addr->{'addr'}:$listen_addr->{'port'}");
} }
::log(LOGINFO, 'Running as user '. ::log(LOGINFO,
(getpwuid($>) || $>) . 'Running as user '
', group '. . (getpwuid($>) || $>)
(getgrgid($)) || $))); . ', group '
. (getgrgid($)) || $))
);
if ($DETACH) { if ($DETACH) {
open STDIN, '/dev/null' or die "/dev/null: $!"; open STDIN, '/dev/null' or die "/dev/null: $!";
@ -225,7 +242,9 @@ while (1) {
REAPER(); REAPER();
my $running = scalar keys %childstatus; my $running = scalar keys %childstatus;
if ($running >= $MAXCONN) { if ($running >= $MAXCONN) {
::log(LOGINFO,"Too many connections: $running >= $MAXCONN. Waiting one second."); ::log(LOGINFO,
"Too many connections: $running >= $MAXCONN. Waiting one second."
);
sleep(1); sleep(1);
next; next;
} }
@ -235,14 +254,19 @@ while (1) {
my ($client, $hisaddr) = $server->accept; my ($client, $hisaddr) = $server->accept;
if (!$hisaddr) { if (!$hisaddr) {
# possible something condition... # possible something condition...
next; next;
} }
IO::Handle::blocking($client, 1); IO::Handle::blocking($client, 1);
# get local/remote hostname, port and ip address
my ($port, $iaddr, $lport, $laddr, $nto_iaddr, $nto_laddr) = Qpsmtpd::TcpServer::lrpip($server, $client, $hisaddr);
my ($rc, @msg) = $qpsmtpd->run_hooks("pre-connection", # get local/remote hostname, port and ip address
my ($port, $iaddr, $lport, $laddr, $nto_iaddr, $nto_laddr) =
Qpsmtpd::TcpServer::lrpip($server, $client, $hisaddr);
my ($rc, @msg) =
$qpsmtpd->run_hooks(
"pre-connection",
remote_ip => $nto_iaddr, remote_ip => $nto_iaddr,
remote_port => $port, remote_port => $port,
local_ip => $nto_laddr, local_ip => $nto_laddr,
@ -269,6 +293,7 @@ while (1) {
my $pid = safe_fork(); my $pid = safe_fork();
if ($pid) { if ($pid) {
# parent # parent
$childstatus{$pid} = $iaddr; # add to table $childstatus{$pid} = $iaddr; # add to table
# $childstatus{$pid} = 1; # add to table # $childstatus{$pid} = 1; # add to table
@ -276,6 +301,7 @@ while (1) {
close($client); close($client);
next; next;
} }
# otherwise child # otherwise child
close $_ for $select->handles; close $_ for $select->handles;
@ -284,22 +310,25 @@ while (1) {
$SIG{ALRM} = sub { $SIG{ALRM} = sub {
print $client "421 Connection Timed Out\n"; print $client "421 Connection Timed Out\n";
::log(LOGINFO, "Connection Timed Out"); ::log(LOGINFO, "Connection Timed Out");
exit; }; exit;
};
# set enviroment variables # set enviroment variables
($ENV{TCPLOCALIP}, $ENV{TCPREMOTEIP}, $ENV{TCPREMOTEHOST}) = Qpsmtpd::TcpServer::tcpenv($nto_laddr, $nto_iaddr); ($ENV{TCPLOCALIP}, $ENV{TCPREMOTEIP}, $ENV{TCPREMOTEHOST}) =
Qpsmtpd::TcpServer::tcpenv($nto_laddr, $nto_iaddr);
# don't do this! # don't do this!
#$0 = "qpsmtpd-forkserver: $ENV{TCPREMOTEIP} / $ENV{TCPREMOTEHOST}"; #$0 = "qpsmtpd-forkserver: $ENV{TCPREMOTEIP} / $ENV{TCPREMOTEHOST}";
::log(LOGINFO, "Accepted connection $running/$MAXCONN from $ENV{TCPREMOTEIP} / $ENV{TCPREMOTEHOST}"); ::log(LOGINFO,
"Accepted connection $running/$MAXCONN from $ENV{TCPREMOTEIP} / $ENV{TCPREMOTEHOST}"
);
# dup to STDIN/STDOUT # dup to STDIN/STDOUT
POSIX::dup2(fileno($client), 0); POSIX::dup2(fileno($client), 0);
POSIX::dup2(fileno($client), 1); POSIX::dup2(fileno($client), 1);
$qpsmtpd->start_connection $qpsmtpd->start_connection(
(
local_ip => $ENV{TCPLOCALIP}, local_ip => $ENV{TCPLOCALIP},
local_port => $lport, local_port => $lport,
remote_ip => $ENV{TCPREMOTEIP}, remote_ip => $ENV{TCPREMOTEIP},

View File

@ -36,8 +36,7 @@ my $has_ipv6 = Qpsmtpd::TcpServer::has_ipv6;
#get available signals #get available signals
my %sig_num; my %sig_num;
my $i = 0; my $i = 0;
foreach my $sig_name ( split( /\s/, $Config{sig_name} ) ) foreach my $sig_name (split(/\s/, $Config{sig_name})) {
{
$sig_num{$sig_name} = $i++; $sig_num{$sig_name} = $i++;
} }
@ -122,20 +121,24 @@ GetOptions(
'detach' => \$detach, 'detach' => \$detach,
'pid-file=s' => \$pid_file, 'pid-file=s' => \$pid_file,
'help' => \&usage, 'help' => \&usage,
) || &usage; )
|| &usage;
if ($user && $user =~ /^([\w\-]+)$/) { $user = $1 } else { &usage } if ($user && $user =~ /^([\w\-]+)$/) { $user = $1 }
else { &usage }
if (@d_addr) { if (@d_addr) {
for my $i (0 .. $#d_addr) { for my $i (0 .. $#d_addr) {
if ($d_addr[$i] =~ /^(\[.*\]|[\d\w\-.]+)(?::(\d+))?$/) { if ($d_addr[$i] =~ /^(\[.*\]|[\d\w\-.]+)(?::(\d+))?$/) {
$d_addr[$i] = {'addr' => $1, 'port' => $2 || $d_port}; $d_addr[$i] = {'addr' => $1, 'port' => $2 || $d_port};
} else { }
else {
print STDERR "Malformed listen address '$d_addr[$i]'\n"; print STDERR "Malformed listen address '$d_addr[$i]'\n";
&usage; &usage;
} }
} }
} else { }
else {
@d_addr = ({addr => $has_ipv6 ? "[::]" : "0.0.0.0", port => $d_port}); @d_addr = ({addr => $has_ipv6 ? "[::]" : "0.0.0.0", port => $d_port});
} }
@ -151,11 +154,13 @@ $idle_children = $max_children
$chld_pool = $idle_children; $chld_pool = $idle_children;
if ($pid_file) { if ($pid_file) {
if ($pid_file =~ m#^(/[\w\d/\-.]+)$#) { $pid_file = $1 } else { &usage } if ($pid_file =~ m#^(/[\w\d/\-.]+)$#) { $pid_file = $1 }
else { &usage }
if (-e $pid_file) { if (-e $pid_file) {
open PID, "+<$pid_file" open PID, "+<$pid_file"
or die "open pid_file: $!\n"; or die "open pid_file: $!\n";
my $running_pid = <PID> || ''; chomp $running_pid; my $running_pid = <PID> || '';
chomp $running_pid;
if ($running_pid =~ /(\d+)/) { if ($running_pid =~ /(\d+)/) {
$running_pid = $1; $running_pid = $1;
die "Found an already running qpsmtpd with pid $running_pid.\n" die "Found an already running qpsmtpd with pid $running_pid.\n"
@ -176,6 +181,7 @@ run();
#start daemon #start daemon
sub run { sub run {
# get UUID/GUID # get UUID/GUID
my ($quid, $qgid, $groups); my ($quid, $qgid, $groups);
if ($user) { if ($user) {
@ -199,6 +205,7 @@ sub run {
Listen => SOMAXCONN, Listen => SOMAXCONN,
Reuse => 1, Reuse => 1,
); );
# create new socket (used by clients to communicate with daemon) # create new socket (used by clients to communicate with daemon)
my $s; my $s;
if ($has_ipv6) { if ($has_ipv6) {
@ -231,6 +238,7 @@ sub run {
} }
if ($user) { if ($user) {
# change UUID/UGID # change UUID/UGID
$) = $groups; $) = $groups;
POSIX::setgid($qgid) or die "unable to change gid: $!\n"; POSIX::setgid($qgid) or die "unable to change gid: $!\n";
@ -246,6 +254,7 @@ sub run {
# Interrupt handler # Interrupt handler
$SIG{INT} = $SIG{TERM} = sub { $SIG{INT} = $SIG{TERM} = sub {
# terminate daemon (and children) # terminate daemon (and children)
my $sig = shift; my $sig = shift;
@ -271,6 +280,7 @@ sub run {
# Hup handler # Hup handler
$SIG{HUP} = sub { $SIG{HUP} = sub {
# reload qpmstpd plugins # reload qpmstpd plugins
$qpsmtpd = qpsmtpd_instance('restart' => 1); # reload plugins... $qpsmtpd = qpsmtpd_instance('restart' => 1); # reload plugins...
$qpsmtpd->load_plugins; $qpsmtpd->load_plugins;
@ -304,6 +314,7 @@ sub run {
# initialize children (only done at daemon startup) # initialize children (only done at daemon startup)
sub spawn_children { sub spawn_children {
# block signals while new children are being spawned # block signals while new children are being spawned
my $sigset = block_signal(SIGCHLD); my $sigset = block_signal(SIGCHLD);
for (1 .. $chld_pool) { for (1 .. $chld_pool) {
@ -336,6 +347,7 @@ sub reaper {
sub main_loop { sub main_loop {
my $created_children = $idle_children; my $created_children = $idle_children;
while (1) { while (1) {
# if there is no child death to process, then sleep EXPR seconds # if there is no child death to process, then sleep EXPR seconds
# or until signal (i.e. child death) is received # or until signal (i.e. child death) is received
sleep $loop_sleep / ($created_children * 2 + 1) unless @children_term; sleep $loop_sleep / ($created_children * 2 + 1) unless @children_term;
@ -345,6 +357,7 @@ sub main_loop {
# get number of busy children # get number of busy children
if (@children_term) { if (@children_term) {
# remove dead children info from shared memory # remove dead children info from shared memory
$chld_busy = shmem_opt(undef, \@children_term, undef, undef); $chld_busy = shmem_opt(undef, \@children_term, undef, undef);
@children_term = (); @children_term = ();
@ -413,10 +426,12 @@ sub unblock_signal {
# arg0: void # arg0: void
# ret0: void # ret0: void
sub new_child { sub new_child {
# daemonize away from the parent process # daemonize away from the parent process
my $pid; my $pid;
die "Cannot fork child: $!\n" unless defined($pid = fork); die "Cannot fork child: $!\n" unless defined($pid = fork);
if ($pid) { if ($pid) {
# in parent # in parent
$children{$pid} = 1; $children{$pid} = 1;
info("new child, pid: $pid"); info("new child, pid: $pid");
@ -444,6 +459,7 @@ sub new_child {
# continue to accept connections until "old age" is reached # continue to accept connections until "old age" is reached
for (my $i = 0 ; $i < $child_lifetime ; $i++) { for (my $i = 0 ; $i < $child_lifetime ; $i++) {
# accept a connection # accept a connection
if ($pretty) { if ($pretty) {
$ENV{PROCESS} = $0 if not defined $ENV{PROCESS}; # 1st time only $ENV{PROCESS} = $0 if not defined $ENV{PROCESS}; # 1st time only
@ -569,7 +585,8 @@ sub shmem_opt {
my ($chld_shmem, $chld_busy); my ($chld_shmem, $chld_busy);
eval { eval {
$chld_shmem = &shmem($d_port."qpsmtpd", 0); #connect to shared memory hash $chld_shmem =
&shmem($d_port . "qpsmtpd", 0); #connect to shared memory hash
if (tied %{$chld_shmem}) { if (tied %{$chld_shmem}) {
@ -593,13 +610,16 @@ sub shmem_opt {
delete $$chld_shmem{$pid_del}; delete $$chld_shmem{$pid_del};
} }
} }
# add # add
$$chld_shmem{$pid_add_key} = $pid_add_value if ($pid_add_key); $$chld_shmem{$pid_add_key} = $pid_add_value if ($pid_add_key);
# copy # copy
%{$ref_shmem} = %{$chld_shmem} if ($ref_shmem); %{$ref_shmem} = %{$chld_shmem} if ($ref_shmem);
# check # check
if ($check) { if ($check) {
# loop through pid list and delete orphaned processes # loop through pid list and delete orphaned processes
foreach my $pid (keys %{$chld_shmem}) { foreach my $pid (keys %{$chld_shmem}) {
if (!kill 0, $pid) { if (!kill 0, $pid) {
@ -713,7 +733,8 @@ sub qpsmtpd_session {
}; };
# set enviroment variables # set enviroment variables
($ENV{TCPLOCALIP}, $ENV{TCPREMOTEIP}, $ENV{TCPREMOTEHOST}) = Qpsmtpd::TcpServer::tcpenv($nto_laddr, $nto_iaddr); ($ENV{TCPLOCALIP}, $ENV{TCPREMOTEIP}, $ENV{TCPREMOTEHOST}) =
Qpsmtpd::TcpServer::tcpenv($nto_laddr, $nto_iaddr);
# run qpmsptd functions # run qpmsptd functions
$SIG{__DIE__} = 'DEFAULT'; $SIG{__DIE__} = 'DEFAULT';
@ -737,6 +758,7 @@ sub qpsmtpd_session {
# remove pid from shared memory # remove pid from shared memory
unless (defined(shmem_opt(undef, [$$], undef, undef))) { unless (defined(shmem_opt(undef, [$$], undef, undef))) {
# exit because parent is down or shared memory is corrupted # exit because parent is down or shared memory is corrupted
info("parent seems to be down, going to exit"); info("parent seems to be down, going to exit");
exit 1; exit 1;