Message.pm untested

filter: Statementstmt 0.0% 0 / 169 Branchbran 0.0% 0 / 38 Conditioncond 0.0% 0 / 16 MC/DCmcdc 0.0% 0 / 9 Subroutinesub 0.0% 0 / 42 Podpod 0.0% 0 / 20 totaltotal 0.0% 0 / 294 CC 20 SCAR 23.1
CC
20
Cov
0%
authenticated
42.0
parse
20.0
control
20.0
CRAP 10.0
1 #
2 # Courier::Message class
3 #
4 # (C) 2003-2008 Julian Mehnle <julian@mehnle.net>
5 # $Id: Message.pm 210 2008-03-21 19:30:31Z julian $
6 #
7 ###############################################################################
8  
9 =head1 NAME
10  
11 Courier::Message - Class implementing an interface to a mail message in the
12 Courier MTA's message queue.
13  
14 =cut
15  
16 package Courier::Message;
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  
29 use overload
30 '""' => \&text;
31  
32 use Encode;
33 use IO::File;
34 #use MIME::Words::Better;
35  
36 use Error ':try';
37  
38 use constant TRUE => (0 == 0);
39 use constant FALSE => not TRUE;
40  
41 use constant fallback_8bit_char_encoding => 'windows-1252';
42  
43 =head1 SYNOPSIS
44  
45 use Courier::Message;
46
47 my $message = Courier::Message->new(
48 file_name => $message_file_name,
49 control_file_names => \@control_file_names,
50 );
51
52 # File names:
53 my $message_file_name = $message->file_name;
54 my @control_file_names = $message->control_file_names;
55
56 # Message data properties:
57 my $raw_message_text = $message->text;
58 my $header_hash = $message->header;
59 my $header_field = $message->header($field);
60 my $raw_body = $message->body;
61
62 # Control properties:
63 my $control_hash = $message->control;
64 my $is_authenticated = $message->authenticated;
65 my $authenticated_user = $message->authenticated_user;
66 my $is_trusted = $message->trusted;
67 my $sender = $message->sender;
68 my @recipients = $message->recipients;
69 my $remote_host = $message->remote_host;
70 my $remote_host_name = $message->remote_host_name;
71  
72 =head1 DESCRIPTION
73  
74 B<Courier::Message> encapsulates a mail message that is stored in the Courier
75 MTA's message queue, including the belonging control file(s), and provides an
76 easy to use, read-only interface through its message data and control
77 properties. For light-weight calling of library functions or external
78 commands, the message and control file names may be retrieved without causing
79 the files to be parsed by B<Courier::Message>.
80  
81 =cut
82  
83 # Implementation:
84 ###############################################################################
85  
86 =head2 Constructor
87  
88 The following constructor is provided:
89  
90 =over
91  
92 =item B<new(%options)>: returns I<Courier::Message>
93  
94 Creates a new C<Courier::Message> object from the given message file name and
95 zero or more control file names.
96  
97 %options is a list of key/value pairs representing any of the following
98 options:
99  
100 =over
101  
102 =item B<file_name>
103  
104 I<Required>. The absolute file name of the message file.
105  
106 =item B<control_file_names>
107  
108 I<Required>. An array-ref containing the absolute file name(s) of zero or more
109 control files belonging to the message.
110  
111 =back
112  
113 =cut
114  
115 sub new {
116 my ($class, %options) = @_;
117 my $self = { %options };
118 return bless($self, $class);
119 }
120  
121 =back
122  
123 =head2 Instance methods
124  
125 =head3 File names
126  
127 The following file name accessors are provided:
128  
129 =over
130  
131 =item B<file_name>: returns I<string>
132  
133 Returns the absolute file name of the message file.
134  
135 =cut
136  
137 sub file_name {
138 my ($self) = @_;
139 return $self->{file_name};
140 }
141  
142 =item B<control_file_names>: returns I<list> of I<string>
143  
144 Returns the absolute file names of the control files belonging to the message.
145  
146 =cut
147  
148 sub control_file_names {
149 my ($self) = @_;
150 return @{$self->{control_file_names}};
151 }
152  
153 =back
154  
155 =head3 Message data properties
156  
157 =over
158  
159 =item B<text>: returns I<string>; throws Perl exceptions
160  
161 Reads the message text from the message file into memory once. Returns the raw
162 message text as bytes (see L<bytes>, and L<PerlIO/"bytes">). Throws a Perl
163 exception if the message file cannot be read.
164  
165 =cut
166  
167 sub text {
168 my ($self) = @_;
169
170 if (not defined($self->{text})) {
171 # Read message text from file:
172 local $/;
173 my $message_file = IO::File->new($self->{file_name}, '<:bytes');
174 $self->{text} = <$message_file>;
175 }
176
177 return $self->{text};
178 }
179  
180 =begin comment
181  
182 =item B<parse>: returns I<Courier::Message>
183  
184 Parses the message text once by doing the following: splits the message text
185 into header and body; tries to interpret the header as UTF-8, falling back to
186 a legacy 8-bit character encoding; parses header fields from the header;
187 decodes any MIME encoded words in field values. Saves the parsed header fields
188 and the message text in the message object. Returns the message object.
189  
190 =end comment
191  
192 =cut
193  
194 sub parse {
195 my ($self) = @_;
196
197 if (
198 not defined($self->{header}) or
199 not defined($self->{body})
200 ) {
201 # Parse header and body from message text:
202 my $text = $self->text;
203 my ($header_text, $body_text) = ($text =~ /^(.*?\n)\n(.*)$/s);
204
205 my $header = {};
206 if (defined($header_text)) {
207 # UTF-8-ify the header text,
208 # trying to interpret it as UTF-8 first,
209 # falling back to the preset 8-bit character encoding if unsuccessful:
210 my $header_text_utf8 = eval {
211 Encode::decode('UTF-8', $header_text, Encode::FB_CROAK)
212 # We explicitly use the strict form of UTF-8 introduced in Perl 5.8.7
213 # in order to sanitize input data and prevent invalid UTF-8 code.
214 };
215 $header_text =
216 (not $@) ?
217 $header_text_utf8
218 : Encode::decode($self->fallback_8bit_char_encoding, $header_text);
219
220 # Unfold header lines:
221 $header_text =~ s/\n(?=\s)//g;
222
223 # Parse header lines into a hash of arrays:
224 while ($header_text =~ /^([\w-]+):[ \t]*(.*)$/mg) {
225 my ($field, $value) = (lc($1), $2);
226 try {
227 $value = MIME::Words::Better::decode($value, $self->fallback_8bit_char_encoding);
228 };
229 push(@{$header->{$field}}, $value);
230 }
231 }
232
233 $self->{header} = $header;
234 $self->{body} = $body_text;
235 }
236
237 return $self;
238 }
239  
240 =item B<header>: returns I<hash-ref> of I<string>
241  
242 =item B<header($field)>: returns I<list> of I<string>
243  
244 Parses the message header once by doing the following: tries to interpret the
245 header as I<UTF-8>, falling back to the 8-bit legacy encoding I<Windows-1252>
246 (a superset of I<ISO-8859-1>) and decoding that to I<UTF-8>; parses header
247 fields from the header; and decodes any MIME encoded words in field values. If
248 no field name is specified, returns a hash-ref containing all header fields and
249 array-refs of their values. If a (case I<in>sensitive) field name is
250 specified, in list context returns a list of the values of all header fields of
251 that name, in the order they occurred in the message header, or in scalar
252 context returns the value of the first header field of that name (or B<undef>
253 if no such header field exists).
254  
255 =cut
256  
257 sub header {
258 my ($self, @field) = @_;
259
260 my $header = $self->parse()->{header};
261 if (@field) {
262 my $field_values = $header->{lc($field[0])} || [];
263 return wantarray ? @$field_values : $field_values->[0];
264 }
265 else {
266 return $header;
267 }
268 }
269  
270 =item B<body>: returns I<string>
271  
272 Returns the raw message body as bytes (see L<bytes>, and L<PerlIO/"bytes">).
273  
274 =cut
275  
276 sub body {
277 my ($self) = @_;
278 return $self->parse()->{body};
279 }
280  
281 =begin comment
282  
283 =item B<subject>: returns I<string>
284  
285 Returns the decoded value of the message's "Subject" header field.
286  
287 =end comment
288  
289 =cut
290  
291 sub subject {
292 my ($self) = @_;
293 return $self->header('subject');
294 }
295  
296 =back
297  
298 =head3 Control properties
299  
300 =over
301  
302 =item B<control>: returns I<hash-ref> of I<string>; throws Perl exceptions
303  
304 =item B<control($field)>: returns I<list> of I<string>; throws Perl exceptions
305  
306 Reads and parses all of the message's control files once. If a (case
307 sensitive) field name (i.e. record type) is specified, returns a list of the
308 values of all control fields of that name, in the order they occurred in the
309 control file(s). If no field name is specified, returns a hash-ref containing
310 all control fields and array-refs of their values. Throws a Perl exception if
311 any of the control files cannot be read.
312  
313 =cut
314  
315 sub control {
316 my ($self, @field) = @_;
317
318 my $control = $self->{control};
319
320 if (not defined($control)) {
321 # Read control files:
322 foreach my $control_file_name (@{$self->{control_file_names}}) {
323 my $control_file = IO::File->new($control_file_name);
324 while (my $record = <$control_file>) {
325 $record =~ /^(\w)(.*)$/;
326 my ($field, $value) = ($1, $2);
327 push(@{$control->{$field}}, $value);
328 }
329 }
330
331 # Store control information:
332 $self->{control} = $control;
333 }
334
335 if (@field) {
336 my $field_values = $control->{$field[0]} || [];
337 return wantarray ? @$field_values : $field_values->[0];
338 }
339 else {
340 return $control;
341 }
342 }
343  
344 =begin comment
345  
346 =item B<control_f>: returns I<string>
347  
348 Parses the HELO string, the remote host, and the remote host name from the C<f>
349 control record and stores them into the message object.
350  
351 =end comment
352  
353 =cut
354  
355 sub control_f {
356 my ($self, @field) = @_;
357
358 if (
359 not defined($self->{remote_host}) or
360 not defined($self->{remote_host_name}) or
361 not defined($self->{remote_host_helo})
362 ) {
363 $self->control('f') =~ /^dns; (.*) \((?:(.*?) )?\[(.*?)\]\)$/;
364 $self->{remote_host} = $3;
365 $self->{remote_host_name} = $2;
366 $self->{remote_host_helo} = $1;
367 }
368
369 return @field ? $self->{$field[0]} : $self->control('f');
370 }
371  
372 =item B<authenticated>: returns I<boolean>
373  
374 Returns the authentication information (guaranteed to be a B<true> value) if
375 the message has been submitted by an authenticated user. Returns B<false>
376 otherwise.
377  
378 I<Note>: The authentication status and information is currently determined and
379 taken from the message's first (i.e. the trustworthy) "Received" header field.
380 This is guaranteed to work correctly, but is not very elegant, so this is
381 subject to change. As soon as Courier supports storing the complete
382 authentication info (including the authenticated user name) in a control field,
383 I<that> will be the preferred source. This mostly just means that the
384 I<format> of the authentication info will probably change in the future.
385  
386 =cut
387  
388 sub authenticated {
389 my ($self) = @_;
390
391 return $self->{authenticated}
392 if defined($self->{authenticated});
393
394 # Starting from Courier 0.57.1, the mere authentication status could be
395 # determined from the 'u' control field ("smtp" vs. "authsmtp") -- but not
396 # the authenticated user name. So we do not make use of it for now.
397
398 TRY: {
399 # Get first "Received" header (and only the first!):
400 my $received = $self->header('received');
401
402 last TRY if not defined($received);
403 last TRY if not $received =~ /^from\s+\S+\s+\(.*?\)\s+\((.*?)\)\s+by/i;
404 # from HELO (HOST+IP) (PARAMS) by ...
405 my %params = map(
406 /^([\w-]+):\s*(.*)$/ ? (lc($1) => $2) : (),
407 split(/,\s+/, $1)
408 );
409
410 return $self->{authenticated} = $params{auth}
411 # Authenticated!
412 if defined($params{auth});
413 }
414
415 return $self->{authenticated} = '';
416 # Not authenticated.
417 }
418  
419 =item B<authenticated_user>: returns I<string>
420  
421 Returns the user name that was used for authentication during submission of the
422 message. Returns B<undef> if no authentication took place.
423  
424 =cut
425  
426 sub authenticated_user {
427 my ($self) = @_;
428
429 return $self->{authenticated_user}
430 if defined($self->{authenticated_user});
431
432 my $authenticated = $self->authenticated;
433
434 if (
435 defined($self->authenticated) and
436 $self->authenticated =~ /^\S+\s+(\S+)$/
437 # METHOD IDENTITY
438 ) {
439 return $self->{authenticated_user} = $1;
440 }
441 else {
442 return $self->{authenticated_user} = undef;
443 }
444 }
445  
446 =item B<trusted>: returns I<boolean>
447  
448 Returns a boolean value indicating whether the message is trusted. Currently,
449 trusted messages are defined to be messages directly submitted by an
450 authenticated user. For details on how the authenticated status is determined,
451 see the description of the C<authenticated> property.
452  
453 =cut
454  
455 sub trusted {
456 my ($self) = @_;
457 return $self->authenticated ? TRUE : FALSE;
458 }
459  
460 =item B<sender>: returns I<string>
461  
462 Returns the message's envelope sender (from the "MAIL FROM" SMTP command).
463  
464 =cut
465  
466 sub sender {
467 my ($self) = @_;
468 return $self->control('s');
469 }
470  
471 =item B<recipients>: returns I<list> of I<string>
472  
473 Returns all of the message's envelope recipients (from the "RCPT TO" SMTP
474 commands).
475  
476 =cut
477  
478 sub recipients {
479 my ($self) = @_;
480 return $self->control('r');
481 }
482  
483 =item B<remote_host>: returns I<string>
484  
485 Returns the IP address of the SMTP client that submitted the message.
486  
487 =cut
488  
489 sub remote_host {
490 my ($self) = @_;
491 return $self->control_f('remote_host');
492 }
493  
494 =item B<remote_host_name>: returns I<string>
495  
496 Returns the host name (gained by Courier through a DNS reverse lookup) of the
497 SMTP client that submitted the message, if available.
498  
499 =cut
500  
501 sub remote_host_name {
502 my ($self) = @_;
503 return $self->control_f('remote_host_name');
504 }
505  
506 =item B<remote_host_helo>: returns I<string>
507  
508 Returns the HELO string that the SMTP client specified, if available.
509  
510 =cut
511  
512 sub remote_host_helo {
513 my ($self) = @_;
514 return $self->control_f('remote_host_helo');
515 }
516  
517 =back
518  
519 =head1 SEE ALSO
520  
521 For AVAILABILITY, SUPPORT, and LICENSE information, see
522 L<Courier::Filter::Overview>.
523  
524 =head1 AUTHOR
525  
526 Julian Mehnle <julian@mehnle.net>
527  
528 =cut
529  
530  
531 #
532 # MIME::Words replacement functions
533 #
534 # (C) 2004-2008 Julian Mehnle <julian@mehnle.net>
535 #
536 ###############################################################################
537  
538 package MIME::Words::Better;
539  
540 use warnings;
541 use strict;
542  
543 use base 'Exporter';
544  
545 our @EXPORT = qw(decode_mimewords);
546  
547 use Encode ();
548 use MIME::Base64 ();
549 use MIME::QuotedPrint ();
550  
551 use Error ':try';
552  
553 use constant TRUE => (0 == 0);
554 use constant FALSE => not TRUE;
555  
556 use constant fallback_char_encoding => 'utf-8';
557  
558 # MIME encoded words grammar (RFC 2047, section 2):
559 use constant encoded_word_pattern => qr{
560 =\? ([\w-]+) (?:\*([\w-]+))? \? ([\w]) \? ([^?]*?) \?=
561 # Charset Language Encoding Chunk
562 }ox;
563  
564 sub decode_mimewords {
565 my ($text, $fallback_char_encoding) = @_;
566
567 # Drop whitespace between two encoded words:
568 $text =~ s/(${\encoded_word_pattern})\s+(${\encoded_word_pattern})/$1$6/;
569
570 $text =~ s[(${\encoded_word_pattern})] {
571 my ($encoded_word, $char_enc, $xfer_enc, $chunk) = ($1, $2, lc($4), $5);
572 my $decoded_word;
573
574 $char_enc =
575 Encode::resolve_alias($char_enc) ||
576 $fallback_char_encoding ||
577 fallback_char_encoding;
578
579 try {
580 if ($xfer_enc eq 'b') {
581 # Base 64!
582 $chunk = MIME::Base64::decode($chunk);
583 }
584 elsif ($xfer_enc eq 'q') {
585 # Quoted Printable!
586 $chunk =~ tr/_/\x{20}/;
587 $chunk = MIME::QuotedPrint::decode($chunk);
588 }
589
590 $decoded_word = Encode::decode($char_enc, $chunk);
591 }
592 otherwise {
593 # The chunk contains invalid characters, leave the encoded word as is:
594 $decoded_word = $encoded_word;
595 };
596
597 $decoded_word;
598 }eg;
599
600 return $text;
601 }
602  
603 BEGIN {
604 no warnings 'once';
605 *decode = \&decode_mimewords;
606 }
607  
608 TRUE;