Filter.pm untested

filter: Statementstmt 0.0% 0 / 155 Branchbran 0.0% 0 / 50 Conditioncond 0.0% 0 / 51 MC/DCmcdc 0.0% 0 / 33 Subroutinesub 0.0% 0 / 27 Podpod 0.0% 0 / 14 totaltotal 0.0% 0 / 330 CC 26 SCAR 34.6
CC
26
Cov
0%
consult_modules
90.0
handle_connection
72.0
new
30.0
CRAP 31.9
1 #
2 # Courier::Filter
3 # A purely Perl-based filter framework for the Courier MTA.
4 #
5 # (C) 2003-2008 Julian Mehnle <julian@mehnle.net>
6 # $Id: Filter.pm 210 2008-03-21 19:30:31Z julian $
7 #
8 ###############################################################################
9  
10 =head1 NAME
11  
12 Courier::Filter - Purely Perl-based mail filter framework for the Courier MTA
13  
14 =cut
15  
16 package Courier::Filter;
17  
18 =head1 VERSION
19  
20 0.200
21  
22 =cut
23  
24 use version; our $VERSION = qv('0.200');
25  
26 use warnings;
27 use strict;
28 #use threads;
29 #BEGIN { require threads if ... }
30  
31 use Error ':try';
32  
33 use IO::Handle;
34 use IO::Socket::UNIX;
35 use IO::Select;
36  
37 use Courier::Config;
38 use Courier::Message;
39 use Courier::Error;
40  
41 use constant TRUE => (0 == 0);
42 use constant FALSE => not TRUE;
43  
44 =head1 SYNOPSIS
45  
46 use Courier::Filter;
47 use Courier::Filter::Logger::Moo;
48 use Courier::Filter::Module::Foo;
49 use Courier::Filter::Module::Bar;
50  
51 my $filter = Courier::Filter->new(
52 mandatory => 1,
53 logger => Courier::Filter::Logger::Moo->new( ... ),
54 modules => [
55 Courier::Filter::Module::Foo->new( ... ),
56 Courier::Filter::Module::Bar->new( ... )
57 ],
58 testing => 0,
59 debugging => 0
60 );
61
62 my $exit_code = $filter->run() || 0;
63  
64 exit($exit_code);
65  
66 =head1 DESCRIPTION
67  
68 B<For an architectural and administrative overview of the B<Courier::Filter>
69 framework, see L<Courier::Filter::Overview>.>
70  
71 The B<Courier::Filter> class is the heart of the Courier::Filter framework. To
72 drive a B<courierfilter> filter process, create a B<Courier::Filter> object,
73 passing the filter modules and loggers you want to use to the constructor, and
74 call the C<run()> method.
75  
76 Courier::Filter will then take care of creating the courierfilter socket in the
77 right place in a safe manner, listening for connections from Courier, asking
78 filter modules for consideration of messages, notifying Courier of whether
79 messages should be accepted or rejected, logging message rejections, catching
80 and logging errors, and finally removing the socket when being terminated by
81 Courier.
82  
83 =cut
84  
85 # Implementation:
86 ###############################################################################
87  
88 =head2 Constructor
89  
90 The following constructor is provided:
91  
92 =over
93  
94 =item B<new(%options)>: returns I<Courier::Filter>; throws I<Courier::Error>,
95 Perl exceptions
96  
97 Creates a new C<Courier::Filter> object. Also creates the courierfilter socket
98 in the right place in a safe manner.
99  
100 %options is a list of key/value pairs representing any of the following
101 options:
102  
103 =over
104  
105 =item B<name>
106  
107 The name of the filter process. Used to build the socket name. Defaults to
108 the base name of the process (C<$0>).
109  
110 =item B<mandatory>
111  
112 A boolean value controlling whether the filter process should act as a
113 mandatory courierfilter. If B<true>, users will not be able to bypass the
114 filter modules in this filter process from their individual B<localmailfilter>
115 filters. Technically, this controls whether the courierfilter socket will be
116 created in the C<allfilters> (B<true>) or the C<filters> (B<false>) directory
117 in Courier's run-time state directory (see L<Courier::Config/"runtime_dir">).
118 Defaults to B<true>.
119  
120 =begin comment
121  
122 =item B<threads>
123  
124 The number of worker threads that should be employed for considering messages.
125 If B<undef> or B<0>, no multi-threading will be used and everything (socket
126 connection handling, message consideration, and logging) will be done in a
127 single thread. The unthreaded mode is is the most memory-conserving mode and
128 is generally the best choice for single-processor systems. Otherwise, i.e. if
129 set to B<a positive number>, a pool of an according number of worker threads
130 will be employed for considering messages. The worker threads are created
131 during the startup of Courier::Filter and process messages that are dispatched
132 to them by the main thread. Logging is also done in a single separate thread.
133 The multi-threaded mode requires a certain amount of memory for each thread but
134 is a viable way to distribute work on multi-processor systems. No more than
135 two threads per processor are recommended. Defaults to B<undef>.
136  
137 =end comment
138  
139 =item B<logger>
140  
141 A B<Courier::Filter::Logger> object that will be used for logging message
142 rejections and error messages. You may override this for individual filter
143 modules for which you do not want the global logger to be used. If no logger
144 is specified, logging is disabled.
145  
146 =item B<modules>
147  
148 I<Required>. A so-called B<filter module group> structure. A module group is
149 a reference to an array that may contain filter module objects (i.e. instances
150 of sub-classes of B<Courier::Filter::Module>), as well as other module groups.
151 Thus, a module group is essentially a tree structure with filter modules as its
152 leaves. When considering messages, Courier::Filter walks the tree in a
153 recursive-descent, depth-first order, asking every filter module for
154 consideration of the message's acceptability.
155  
156 For instance, given the following filter module group:
157  
158 [$m1, $m2, [$m3, [$m4, $m5]], $m6]
159  
160 Courier::Filter queries the filter modules in ascending order from 1 to 6.
161  
162 The acceptability result returned by each module determines how Courier::Filter
163 proceeds with considering the current message:
164  
165 =over
166  
167 =item *
168  
169 If a module states an B<explicit reject>, Courier::Filter aborts the
170 consideration process and rejects the message.
171  
172 =item *
173  
174 If a module states an B<implicit accept>, Courier::Filter just proceeds to the
175 next module in turn.
176  
177 =item *
178  
179 If a module states an B<explicit accept>, Courier::Filter skips the rest of the
180 current module group and proceeds to the next item in the superordinate module
181 group, assuming the whole group to be an implicit accept.
182  
183 =back
184  
185 For instance, take the nested filter module group from above:
186  
187 [$m1, $m2, [$m3, [$m4, $m5]], $m6]
188 | | '---g3---'| |
189 | '----group 2----' |
190 '------------group 1-------------'
191  
192 Let's assume Courier::Filter queries the filter module $m3. If $m3 states an
193 B<explicit reject>, the consideration process is aborted and the current
194 message is rejected. If $m3 states an B<implicit accept>, Courier::Filter
195 proceeds to $m4. If $m3 states an B<explicit accept>, the rest of group 2
196 (including all of group 3) is skipped and the acceptability result of group 2
197 is assumed an implicit accept, so Courier::Filter proceeds to $m6.
198  
199 If no B<explicit reject> has occured when Courier::Filter reaches the end of
200 the main module group, or a module in the main group states an B<explicit
201 accept>, the message is accepted.
202  
203 Using nested groups of filter modules with normal or inverse polarity, it
204 should be possible to implement sufficiently complex filtering policies to
205 satisfy very most needs.
206  
207 =item B<trusting>
208  
209 A boolean value controlling whether the I<whole> filter process should I<not>
210 apply any filtering to trusted messages. For details on how the trusted status
211 is determined, see the description of the C<trusted> property in
212 Courier::Message. In most MTA configurations, this option can be used to
213 white-list so-called outbound messages. Defaults to B<false>.
214  
215 =item B<testing>
216  
217 A boolean value controlling whether the I<whole> filter process should run in
218 "testing" mode. In testing mode, planned message rejections will be logged as
219 usual, but no messages will actually be rejected. Defaults to B<false>.
220  
221 NOTE: You may also enable testing mode on individual filter module objects,
222 see L<Courier::Filter::Module/"new">. Enabling testing mode globally is not
223 the same as individually enabling testing mode on all filter modules, though.
224 When global testing mode is enabled, Courier::Filter only ignores the I<final>
225 result, but still follows the rules of the normal consideration process, e.g.
226 aborting as soon as a filter module states an B<explicit reject>, etc. When an
227 individual filter module is in testing mode, its I<individual> result is
228 ignored, and the consideration process is continued with the next filter
229 module. So individually enabling testing mode on all filter modules allows you
230 to thoroughly test the correctness and performance of all installed filter
231 modules, or even to gather stochastically indepent statistics on the hit/miss
232 rates of your filter modules.
233  
234 =item B<debugging>
235  
236 A boolean value controlling whether extra debugging information should be
237 logged by Courier::Filter. Defaults to B<false>. You need to enable debugging
238 mode for filter modules separately.
239  
240 =for comment
241 TODO: Filter modules' debugging mode should really default to Courier::Filter's
242 global debugging mode.
243  
244 =back
245  
246 =cut
247  
248 sub new {
249 my ($class, %options) = @_;
250
251 $0 =~ m{([^/]+)$};
252 my $name = $options{name} || $1;
253 my $mandatory = defined($options{mandatory}) ? $options{mandatory} : TRUE;
254 my $threads = $options{threads};
255 my $logger = $options{logger};
256 my $modules = [ @{$options{modules}} ] || [];
257 my $trusting = $options{trusting};
258 my $testing = $options{testing};
259 my $debugging = $options{debugging};
260
261 my $socket_dir =
262 Courier::Config->runtime_dir . '/' .
263 ( $mandatory ? 'allfilters' : 'filters' );
264 my $socket_dir_unused =
265 Courier::Config->runtime_dir . '/' .
266 ( !$mandatory ? 'allfilters' : 'filters' );
267
268 my $socket_prename = "$socket_dir/.$name";
269 my $socket_name = "$socket_dir/$name";
270 my $socket_prename_unused = "$socket_dir_unused/.$name";
271 my $socket_name_unused = "$socket_dir_unused/$name";
272
273 if (-e $socket_name) {
274 -S $socket_name
275 or throw Courier::Error("$socket_name already exists but is not a socket");
276
277 # Try to connect to socket to see if it is alive or
278 # if it is left over from a crashed Courier::Filter:
279 my $test_socket = IO::Socket::UNIX->new( Peer => $socket_name );
280
281 not defined($test_socket)
282 or throw Courier::Error("Live socket $socket_name found -- is Courier::Filter already running?");
283
284 # Socket exists but is dead. Remove it:
285 unlink($socket_name);
286 }
287
288 unlink($socket_prename);
289 unlink($socket_prename_unused);
290 unlink($socket_name_unused);
291
292 my $socket = IO::Socket::UNIX->new(
293 Local => $socket_prename,
294 Listen => SOMAXCONN
295 )
296 or throw Courier::Error("Unable to create socket $socket_prename");
297
298 rename($socket_prename, $socket_name)
299 or unlink($socket_prename),
300 throw Courier::Error("Unable to rename socket $socket_prename to $socket_name");
301
302 chmod(0660, $socket_name)
303 or throw Courier::Error("Unable to chmod socket $socket_name");
304
305 IO::Handle->new_from_fd(3, '>')->close();
306
307 my $filter = {
308 name => $name,
309 mandatory => $mandatory,
310 threads => $threads,
311 logger => $logger,
312 modules => $modules,
313 trusting => $trusting,
314 testing => $testing,
315 debugging => $debugging,
316 socket => $socket,
317 socket_name => $socket_name,
318 terminate => FALSE
319 };
320
321 return bless($filter, $class);
322 }
323  
324 =back
325  
326 =begin comment
327  
328 =head2 Destructor
329  
330 The following destructor is provided:
331  
332 =over
333  
334 =item B<destroy>
335  
336 Removes the courierfilter socket when the B<Courier::Filter> object is
337 destroyed. There is no need to call this explicitly.
338  
339 =end comment
340  
341 =cut
342  
343 sub destroy {
344 my ($filter) = @_;
345
346 return if not $filter->{terminate};
347
348 $filter->{'socket'}->close();
349 unlink($filter->{socket_name});
350
351 # Dissolve worker thread pool:
352 # foreach my $thread (threads->list) {
353 # $thread->join()
354 # if $thread->tid and $thread != threads->self;
355 # }
356
357 return;
358 }
359  
360 =begin comment
361  
362 =back
363  
364 =end comment
365  
366 =head2 Instance methods
367  
368 The following instance methods are provided:
369  
370 =over
371  
372 =item B<run>: throws I<Courier::Error>, Perl exceptions
373  
374 Runs the Courier::Filter. Listens for connections from Courier on the
375 courierfilter socket, asks the configured filter modules for consideration of
376 messages, notifies Courier of whether messages should be accepted or rejected,
377 and logs message rejections. When Courier requests termination of the
378 courierfilter, removes the socket and returns.
379  
380 =cut
381  
382 sub run {
383 my ($filter) = @_;
384 my $class = ref($filter);
385
386 my $socket = $filter->{'socket'};
387 my $select = IO::Select->new(\*STDIN, $socket);
388
389 while (not $filter->{terminate}) {
390
391 # Wait for incoming connection requests
392 # or EOF from STDIN:
393 ########################################
394
395 my @ready_handles = $select->can_read();
396
397 foreach my $handle (@ready_handles) {
398 if ($handle == $socket) {
399 # Incoming connection request.
400 $filter->handle_connection($socket);
401 # threads->new(\&handle_connection, $filter, $socket)->detach();
402 }
403 elsif ($handle == \*STDIN and STDIN->eof()) {
404 # STDIN got closed.
405 $filter->{terminate} = TRUE;
406 }
407 else {
408 # Received data from unknown handle or from STDIN.
409 # This shouldn't happen.
410 throw Courier::Error("Received data from unknown handle or from STDIN");
411 }
412 }
413 }
414
415 return;
416 }
417  
418 =begin comment
419  
420 =item B<handle_connection($socket)>: returns I<string>, I<string>; throws Perl
421 exceptions
422  
423 Handles a single incoming connection to the courierfilter socket. Reads the
424 message file name and zero or more control file names from the connection.
425 Asks filter modules for consideration of the message's acceptability, and
426 notifies Courier of whether the message should be accepted or rejected. Also
427 returns the SMTP status response I<text> and I<code> given to Courier.
428  
429 =end comment
430  
431 =cut
432  
433 sub handle_connection {
434 my ($filter, $socket) = @_;
435 my $class = ref($filter);
436
437 my $connection = $socket->accept();
438
439 my $message_file_name;
440 my @control_file_names;
441
442 while (my $file_name = <$connection>) {
443 chomp($file_name);
444 last unless $file_name;
445
446 # Normalize file name:
447 $file_name =
448 Courier::Config->runtime_dir . '/tmp/' . $file_name
449 if $file_name !~ m(^/);
450
451 if (not defined($message_file_name)) {
452 $message_file_name = $file_name;
453 }
454 else {
455 push(@control_file_names, $file_name);
456 }
457 }
458
459 return
460 if not defined($message_file_name);
461
462 my $message = Courier::Message->new(
463 file_name => $message_file_name,
464 control_file_names => \@control_file_names,
465 filter => $filter
466 );
467
468 my ($result, $code);
469
470 # BEGIN XXX
471 #STDERR->print(
472 # "DEBUG: authenticated_user = '" .
473 # ($message->authenticated_user || '(undef)') .
474 # "'\n"
475 #);
476 # END XXX
477
478 ($result, $code) = $filter->consult_modules($filter->modules, $message)
479 if $filter->testing
480 or not ($filter->trusting and $message->trusted);
481
482 ($result, $code) = (undef, undef)
483 if $filter->testing
484 or ($filter->trusting and $message->trusted);
485
486 if ($result) {
487 $code ||= 550;
488 }
489 else {
490 $result = 'Ok';
491 $code ||= 200;
492 }
493
494 my @lines = split(/\n/, $result);
495 my $last_line = pop(@lines);
496 $connection->print("$code-$_\n") foreach @lines;
497 $connection->print("$code $last_line\n");
498
499 $connection->close();
500
501 return ($result, $code);
502 }
503  
504 =begin comment
505  
506 =item B<consult_modules>: returns I<string>, I<string>
507  
508 Walks the given modules group structure in a recursive-descent, depth-first
509 order, and asks every filter module for consideration of the given message's
510 acceptability. Returns the group's acceptability result.
511  
512 =end comment
513  
514 =cut
515  
516 sub consult_modules {
517 my ($filter, $modules, $message) = @_;
518
519 ref($modules) eq 'ARRAY'
520 or throw Courier::Error('Invalid modules group structure, array-ref expected');
521  
522 foreach my $module (@$modules) {
523 my ($result, @code);
524
525 if (UNIVERSAL::isa($module, 'Courier::Filter::Module')) {
526 # Single module, make it consider the message:
527
528 next if $module->trusting and $message->trusted;
529 # ...except when the module trusts the message.
530
531 my $logger = $module->logger || $filter->logger;
532  
533 ($result, @code) = eval { $module->consider($message) };
534 if ($@) {
535 $logger->log_error(ref($module) . ': ' . $@) if $logger;
536 ($result, @code) = ('Mail filters temporarily unavailable.', 432);
537 }
538
539 # Log rejection:
540 $logger->log_rejected_message($message, $result)
541 if $result and $logger;
542  
543 # Ignore result if module is in testing mode:
544 next if $module->testing;
545 }
546 else {
547 # Something else, try to interpret it as a modules group:
548 ($result, @code) = $filter->consult_modules($module, $message);
549 }
550
551 return $result ? ($result, @code) : undef
552 if defined($result);
553 }
554  
555 return undef;
556 }
557  
558 =item B<name>: returns I<string>
559  
560 Returns the name of the filter process, as set through the constructor's
561 C<name> option.
562  
563 =cut
564  
565 sub name {
566 my ($filter) = @_;
567 # Read-only!
568 return $filter->{name};
569 }
570  
571 =item B<mandatory>: returns I<boolean>
572  
573 Returns a boolean value indicating whether the filter process is a mandatory
574 courierfilter, as set through the constructor's C<mandatory> option.
575  
576 =cut
577  
578 sub mandatory {
579 my ($filter) = @_;
580 # Read-only!
581 return $filter->{mandatory};
582 }
583  
584 =begin comment
585  
586 =item B<threads>: returns I<integer>
587  
588 Returns the number of filter threads, as set through the constructor's
589 C<threads> option.
590  
591 =end comment
592  
593 =cut
594  
595 sub threads {
596 my ($filter) = @_;
597 # Read-only!
598 return $filter->{threads};
599 }
600  
601 =item B<logger>: returns I<Courier::Filter::Logger>
602  
603 =item B<logger($logger)>: returns I<Courier::Filter::Logger>
604  
605 If C<$logger> is specified, installs a new global logger. Returns the (newly)
606 configured global logger.
607  
608 =cut
609  
610 sub logger {
611 my ($filter, @logger) = @_;
612 $filter->{logger} = $logger[0]
613 if @logger;
614 return $filter->{logger};
615 }
616  
617 =item B<modules>: returns I<array-ref>
618  
619 =item B<modules(\@modules)>: returns I<array-ref>
620  
621 If C<\@modules> is specified, installs a new filter module group structure.
622 Returns the (newly) configured filter modules group structure.
623  
624 =cut
625  
626 sub modules {
627 my ($filter, @modules) = @_;
628 $filter->{modules} = $modules[0]
629 if @modules;
630 return $filter->{modules};
631 }
632  
633 =item B<trusting>: returns I<boolean>
634  
635 Returns a boolean value indicating the trusting mode, as set through the
636 constructor's C<trusting> option.
637  
638 =cut
639  
640 sub trusting {
641 my ($filter) = @_;
642 # Read-only!
643 return $filter->{trusting};
644 }
645  
646 =item B<testing>: returns I<boolean>
647  
648 Returns a boolean value indicating the global testing mode, as set through the
649 constructor's C<testing> option.
650  
651 =cut
652  
653 sub testing {
654 my ($filter) = @_;
655 # Read-only!
656 return $filter->{testing};
657 }
658  
659 =item B<debugging>: returns I<boolean>
660  
661 =item B<debugging($debugging)>: returns I<boolean>
662  
663 If C<$debugging> is specified, sets the global debugging mode. Returns a
664 boolean value indicating the (newly) configured global debugging mode.
665  
666 =cut
667  
668 sub debugging {
669 my ($filter, @debugging) = @_;
670 $filter->{debugging} = $debugging[0]
671 if @debugging;
672 return $filter->{debugging};
673 }
674  
675 =back
676  
677 =cut
678  
679 BEGIN {
680 no warnings 'once';
681 *DESTROY = \&destroy;
682 }
683  
684 =head1 SEE ALSO
685  
686 L<courier-filter-perl>, L<Courier::Filter::Overview>,
687 L<Courier::Filter::Module>, L<Courier::Filter::Logger>
688  
689 For AVAILABILITY, SUPPORT, and LICENSE information, see
690 L<Courier::Filter::Overview>.
691  
692 =head1 REFERENCES
693  
694 =over
695  
696 =item The B<courierfilter> interface
697  
698 L<http://www.courier-mta.org/courierfilter.html>
699  
700 =back
701  
702 =head1 AUTHOR
703  
704 Julian Mehnle <julian@mehnle.net>
705  
706 =cut
707  
708 TRUE;