Debian Codegraph @

qpsmtpd-async

raw
1 #!/usr/bin/perl
2
3 use lib "./lib";
4
5 BEGIN {
6 delete $ENV{ENV};
7 delete $ENV{BASH_ENV};
8 $ENV{PATH} = '/bin:/usr/bin:/var/qmail/bin:/usr/local/bin';
9 }
10
11 # Profiling - requires Devel::Profiler 0.05
12 #BEGIN { $Devel::Profiler::NO_INIT = 1; }
13 #use Devel::Profiler;
14
15 use strict;
16 use vars qw($DEBUG);
17 use FindBin qw();
18
19 # TODO: need to make this taint friendly
20 use lib "$FindBin::Bin/lib";
21 use Danga::Socket;
22 use Danga::Client;
23 use Qpsmtpd::PollServer;
24 use Qpsmtpd::ConfigServer;
25 use Qpsmtpd::Constants;
26 use IO::Socket;
27 use Carp;
28 use POSIX qw(WNOHANG);
29 use Getopt::Long;
30 use List::Util qw(shuffle);
31
32 $|++;
33
34 use Socket
35 qw(SOMAXCONN IPPROTO_TCP SO_KEEPALIVE TCP_NODELAY SOL_SOCKET AF_UNIX SOCK_STREAM PF_UNSPEC);
36
37 $SIG{'PIPE'} = "IGNORE"; # handled manually
38
39 $DEBUG = 0;
40
41 my $CONFIG_PORT = 20025;
42 my $CONFIG_LOCALADDR = '127.0.0.1';
43
44 my $PORT = 2525;
45 my $LOCALADDR = '0.0.0.0';
46 my $PROCS = 1;
47 my $USER = (getpwuid $>)[0]; # user to suid to
48 $USER = "smtpd" if $USER eq "root";
49 my $PAUSED = 0;
50 my $NUMACCEPT = 20;
51 my $PID_FILE = '';
52 my $ACCEPT_RSET;
53 my $DETACH; # daemonize on startup
54
55 # make sure we don't spend forever doing accept()
56 use constant ACCEPT_MAX => 1000;
57
58 sub reset_num_accept {
59 $NUMACCEPT = 20;
60 }
61
62 sub help {
63 print <<EOT;
64 Usage:
65 qpsmtpd [OPTIONS]
66
67 Options:
68 -l, --listen-address addr : listen on a specific address; default 0.0.0.0
69 -p, --port P : listen on a specific port; default 2525
70 --config-port : config server port; default 20025
71 -u, --user U : run as a particular user; defualt 'smtpd'
72 -j, --procs J : spawn J processes; default 1
73 -d, --detach : detach from controlling terminal (daemonize)
74 --pid-file P : print main servers PID to file P
75
76 -h, --help : this page
77 --use-poll : force use of poll() instead of epoll()/kqueue()
78 EOT
79 exit(0);
80 }
81
82 GetOptions(
83 'p|port=i' => \$PORT,
84 'l|listen-address=s' => \$LOCALADDR,
85 'j|procs=i' => \$PROCS,
86 'v|verbose+' => \$DEBUG,
87 'u|user=s' => \$USER,
88 'pid-file=s' => \$PID_FILE,
89 'd|detach' => \$DETACH,
90 'h|help' => \&help,
91 'config-port=i' => \$CONFIG_PORT,
92 )
93 || help();
94
95 # detaint the commandline
96 if ($PORT =~ /^(\d+)$/) { $PORT = $1 }
97 else { &help }
98 if ($LOCALADDR =~ /^([\d\w\-.]+)$/) { $LOCALADDR = $1 }
99 else { &help }
100 if ($USER =~ /^([\w\-]+)$/) { $USER = $1 }
101 else { &help }
102 if ($PROCS =~ /^(\d+)$/) { $PROCS = $1 }
103 else { &help }
104
105 sub force_poll {
106 $Danga::Socket::HaveEpoll = 0;
107 $Danga::Socket::HaveKQueue = 0;
108 }
109
110 my $POLL = "with "
111 . (
112 $Danga::Socket::HaveEpoll ? "epoll()"
113 : $Danga::Socket::HaveKQueue ? "kqueue()"
114 : "poll()"
115 );
116
117 my $SERVER;
118 my $CONFIG_SERVER;
119
120 use constant READY => 1;
121 use constant ACCEPTING => 2;
122 use constant RESTARTING => 999;
123
124 my %childstatus = ();
125
126 if ($PID_FILE && -r $PID_FILE) {
127 open PID, "<$PID_FILE"
128 or die "open_pidfile $PID_FILE: $!\n";
129 my $running_pid = <PID> || '';
130 chomp $running_pid;
131 if ($running_pid =~ /^(\d+)/) {
132 if (kill 0, $running_pid) {
133 die "Found an already running qpsmtpd with pid $running_pid.\n";
134 }
135 }
136 close(PID);
137 }
138
139 run_as_server();
140 exit(0);
141
142 sub _fork {
143 my $pid = fork;
144 if (!defined($pid)) { die "Cannot fork: $!" }
145 return $pid if $pid;
146
147 # Fixup Net::DNS randomness after fork
148 srand($$ ^ time);
149
150 local $^W;
151 delete $INC{'Net/DNS/Header.pm'};
152 require Net::DNS::Header;
153
154 # cope with different versions of Net::DNS
155 eval {
156 $Net::DNS::Resolver::global{id} = 1;
157 $Net::DNS::Resolver::global{id} =
158 int(rand(Net::DNS::Resolver::MAX_ID()));
159
160 # print "Next DNS ID: $Net::DNS::Resolver::global{id}\n";
161 };
162 if ($@) {
163
164 # print "Next DNS ID: " . Net::DNS::Header::nextid() . "\n";
165 }
166
167 # Fixup lost kqueue after fork
168 $Danga::Socket::HaveKQueue = undef;
169 }
170
171 sub spawn_child {
172 my $plugin_loader = shift || Qpsmtpd::SMTP->new;
173
174 socketpair(my $reader, my $writer, AF_UNIX, SOCK_STREAM, PF_UNSPEC)
175 || die "Unable to create a pipe";
176 $writer->autoflush(1);
177 $reader->autoflush(1);
178
179 if (my $pid = _fork) {
180 $childstatus{$pid} = $writer;
181 return $pid;
182 }
183
184 $SIG{CHLD} = $SIG{INT} = $SIG{TERM} = 'DEFAULT';
185 $SIG{PIPE} = 'IGNORE';
186 $SIG{HUP} = 'IGNORE';
187
188 close $CONFIG_SERVER;
189
190 Qpsmtpd::PollServer->Reset;
191
192 Qpsmtpd::PollServer->OtherFds(
193 fileno($reader) => sub { command_handler($reader) },
194 fileno($SERVER) => \&accept_handler,);
195
196 $ACCEPT_RSET = Danga::Socket->AddTimer(30, \&reset_num_accept);
197
198 $plugin_loader->run_hooks('post-fork');
199
200 Qpsmtpd::PollServer->EventLoop();
201 exit;
202 }
203
204 # Note this is broken on KQueue because it requires that it handle signals itself or it breaks the event loop.
205 sub sig_hup {
206 for my $writer (values %childstatus) {
207 print $writer "hup\n";
208 }
209 }
210
211 sub sig_chld {
212 my $spawn_count = 0;
213 while ((my $child = waitpid(-1, WNOHANG)) > 0) {
214 if (!defined $childstatus{$child}) {
215 next;
216 }
217
218 last unless $child > 0;
219 print "SIGCHLD: child $child died\n";
220 delete $childstatus{$child};
221 $spawn_count++;
222 }
223 if ($spawn_count) {
224 for (1 .. $spawn_count) {
225
226 # restart a new child if in poll server mode
227 my $pid = spawn_child();
228 }
229 }
230 $SIG{CHLD} = \&sig_chld;
231 }
232
233 sub HUNTSMAN {
234 $SIG{CHLD} = 'DEFAULT';
235 kill 'INT' => keys %childstatus;
236 if ($PID_FILE && -e $PID_FILE) {
237 unlink $PID_FILE or ::log(LOGERROR, "unlink: $PID_FILE: $!");
238 }
239 exit(0);
240 }
241
242 sub run_as_server {
243
244 # establish SERVER socket, bind and listen.
245 $SERVER = IO::Socket::INET->new(
246 LocalPort => $PORT,
247 LocalAddr => $LOCALADDR,
248 Type => SOCK_STREAM,
249 Proto => IPPROTO_TCP,
250 Blocking => 0,
251 Reuse => 1,
252 Listen => SOMAXCONN
253 )
254 or die "Error creating server $LOCALADDR:$PORT : $@\n";
255
256 IO::Handle::blocking($SERVER, 0);
257 binmode($SERVER, ':raw');
258
259 $CONFIG_SERVER =
260 IO::Socket::INET->new(
261 LocalPort => $CONFIG_PORT,
262 LocalAddr => $CONFIG_LOCALADDR,
263 Type => SOCK_STREAM,
264 Proto => IPPROTO_TCP,
265 Blocking => 0,
266 Reuse => 1,
267 Listen => 1
268 )
269 or die "Error creating server $CONFIG_LOCALADDR:$CONFIG_PORT : $@\n";
270
271 IO::Handle::blocking($CONFIG_SERVER, 0);
272 binmode($CONFIG_SERVER, ':raw');
273
274 # Drop priviledges
275 my (undef, undef, $quid, $qgid) = getpwnam $USER
276 or die "unable to determine uid/gid for $USER\n";
277 my $groups = "$qgid $qgid";
278 while (my (undef, undef, $gid, $members) = getgrent) {
279 my @m = split(/ /, $members);
280 if (grep { $_ eq $USER } @m) {
281 $groups .= " $gid";
282 }
283 }
284 endgrent;
285 $) = $groups;
286 POSIX::setgid($qgid)
287 or die "unable to change gid: $!\n";
288 POSIX::setuid($quid)
289 or die "unable to change uid: $!\n";
290 $> = $quid;
291
292 # Load plugins here
293 my $plugin_loader = Qpsmtpd::SMTP->new();
294 $plugin_loader->load_plugins;
295
296 if ($DETACH) {
297 open STDIN, '/dev/null' or die "/dev/null: $!";
298 open STDOUT, '>/dev/null' or die "/dev/null: $!";
299 open STDERR, '>&STDOUT' or die "open(stderr): $!";
300 defined(my $pid = fork) or die "fork: $!";
301 exit 0 if $pid;
302 POSIX::setsid or die "setsid: $!";
303 }
304
305 if ($PID_FILE) {
306 open PID, ">$PID_FILE" || die "$PID_FILE: $!";
307 print PID $$, "\n";
308 close PID;
309 }
310
311 $plugin_loader->log(LOGINFO,
312 'Running as user '
313 . (getpwuid($>) || $>)
314 . ', group '
315 . (getgrgid($)) || $))
316 );
317
318 $SIG{INT} = $SIG{TERM} = \&HUNTSMAN;
319
320 ######################
321 # more Profiling code
322
323 =pod
324 $plugin_loader->run_hooks('post-fork');
325
326 Devel::Profiler->set_options(
327 bad_subs => [qw(Danga::Socket::EventLoop)],
328 sub_filter => sub {
329 my ($pkg, $sub) = @_;
330 return 0 if $sub eq 'AUTOLOAD';
331 return 0 if $pkg =~ /ParaDNS::XS/;
332 return 1;
333 },
334 );
335 Devel::Profiler->init();
336
337 Qpsmtpd::PollServer->OtherFds(
338 fileno($SERVER) => \&accept_handler,
339 fileno($CONFIG_SERVER) => \&config_handler, );
340
341 Qpsmtpd::PollServer->EventLoop;
342 exit;
343 =cut
344
345 #####################
346
347 for (1 .. $PROCS) {
348 my $pid = spawn_child($plugin_loader);
349 }
350 $plugin_loader->log(LOGDEBUG,
351 "Listening on $PORT with $PROCS children $POLL");
352 $SIG{CHLD} = \&sig_chld;
353 $SIG{HUP} = \&sig_hup;
354
355 Qpsmtpd::PollServer->OtherFds(fileno($CONFIG_SERVER) => \&config_handler,);
356
357 Qpsmtpd::PollServer->EventLoop;
358
359 exit;
360
361 }
362
363 sub config_handler {
364 my $csock = $CONFIG_SERVER->accept();
365 if (!$csock) {
366
367 # warn("accept failed on config server: $!");
368 return;
369 }
370 binmode($csock, ':raw');
371
372 printf("Config server connection\n") if $DEBUG;
373
374 IO::Handle::blocking($csock, 0);
375 setsockopt($csock, IPPROTO_TCP, TCP_NODELAY, pack("l", 1)) or die;
376
377 my $client = Qpsmtpd::ConfigServer->new($csock);
378 $client->watch_read(1);
379 return;
380 }
381
382 sub command_handler {
383 my $reader = shift;
384
385 chomp(my $command = <$reader>);
386
387 #print "Got command: $command\n";
388
389 my $real_command = "cmd_$command";
390
391 no strict 'refs';
392 $real_command->();
393 }
394
395 sub cmd_hup {
396
397 # clear cache
398 print "Clearing cache\n";
399 Qpsmtpd::clear_config_cache();
400
401 # should also reload modules... but can't do that yet.
402 }
403
404 # Accept all new connections
405 sub accept_handler {
406 for (1 .. $NUMACCEPT) {
407 return unless _accept_handler();
408 }
409
410 # got here because we have accept's left.
411 # So double the number we accept next time.
412 $NUMACCEPT *= 2;
413 $NUMACCEPT = ACCEPT_MAX if $NUMACCEPT > ACCEPT_MAX;
414 $ACCEPT_RSET->cancel if defined $ACCEPT_RSET;
415 $ACCEPT_RSET = Danga::Socket->AddTimer(30, \&reset_num_accept);
416 }
417
418 use Errno qw(EAGAIN EWOULDBLOCK);
419
420 sub _accept_handler {
421 my $csock = $SERVER->accept();
422 if (!$csock) {
423
424 # warn("accept() failed: $!");
425 return;
426 }
427 binmode($csock, ':raw');
428
429 printf("Listen child making a Qpsmtpd::PollServer for %d.\n",
430 fileno($csock))
431 if $DEBUG;
432
433 IO::Handle::blocking($csock, 0);
434
435 #setsockopt($csock, IPPROTO_TCP, TCP_NODELAY, pack("l", 1)) or die;
436
437 #print "Got connection\n";
438 my $client = Qpsmtpd::PollServer->new($csock);
439
440 if ($PAUSED) {
441 $client->write("451 Sorry, this server is currently paused\r\n");
442 $client->close;
443 return 1;
444 }
445
446 $client->process_line("Connect\n");
447 $client->watch_read(1);
448 $client->pause_read();
449 return 1;
450 }
451
452 ########################################################################
453
454 sub log {
455 my ($level, $message) = @_;
456
457 # $level not used yet. this is reimplemented from elsewhere anyway
458 warn("$$ fd:? $message\n");
459 }
460
461 sub pause {
462 my ($pause) = @_;
463 $PAUSED = $pause;
464 }