Parser.pm

filter: Statementstmt 90.6% 427 / 471 Branchbran 70.5% 151 / 214 Conditioncond 65.4% 36 / 55 MC/DCmcdc 35.7% 10 / 28 Subroutinesub 84.1% 53 / 63 Podpod 70.8% 34 / 48 totaltotal 80.8% 711 / 879 CC 127 SCAR 24.7
CC
127
Cov
83%
decode_headers
30.0
hunt_for_uuencode
27.1
process_singlepart
24.2
CRAP 11.8
« Entity.pm ↑ Summary WordDecoder.pm »
1 package MIME::Parser;
2  
3 =head1 NAME
4  
5 MIME::Parser - experimental class for parsing MIME streams
6  
7  
8 =head1 SYNOPSIS
9  
10 Before reading further, you should see L<MIME::Tools> to make sure that
11 you understand where this module fits into the grand scheme of things.
12 Go on, do it now. I'll wait.
13  
14 Ready? Ok...
15  
16 =head2 Basic usage examples
17  
18 ### Create a new parser object:
19 my $parser = new MIME::Parser;
20  
21 ### Tell it where to put things:
22 $parser->output_under("/tmp");
23  
24 ### Parse an input filehandle:
25 $entity = $parser->parse(\*STDIN);
26  
27 ### Congratulations: you now have a (possibly multipart) MIME entity!
28 $entity->dump_skeleton; # for debugging
29  
30  
31 =head2 Examples of input
32  
33 ### Parse from filehandles:
34 $entity = $parser->parse(\*STDIN);
35 $entity = $parser->parse(IO::File->new("some command|");
36  
37 ### Parse from any object that supports getline() and read():
38 $entity = $parser->parse($myHandle);
39  
40 ### Parse an in-core MIME message:
41 $entity = $parser->parse_data($message);
42  
43 ### Parse an MIME message in a file:
44 $entity = $parser->parse_open("/some/file.msg");
45  
46 ### Parse an MIME message out of a pipeline:
47 $entity = $parser->parse_open("gunzip - < file.msg.gz |");
48  
49 ### Parse already-split input (as "deliver" would give it to you):
50 $entity = $parser->parse_two("msg.head", "msg.body");
51  
52  
53 =head2 Examples of output control
54  
55 ### Keep parsed message bodies in core (default outputs to disk):
56 $parser->output_to_core(1);
57  
58 ### Output each message body to a one-per-message directory:
59 $parser->output_under("/tmp");
60  
61 ### Output each message body to the same directory:
62 $parser->output_dir("/tmp");
63  
64 ### Change how nameless message-component files are named:
65 $parser->output_prefix("msg");
66  
67 ### Put temporary files somewhere else
68 $parser->tmp_dir("/var/tmp/mytmpdir");
69  
70 =head2 Examples of error recovery
71  
72 ### Normal mechanism:
73 eval { $entity = $parser->parse(\*STDIN) };
74 if ($@) {
75 $results = $parser->results;
76 $decapitated = $parser->last_head; ### get last top-level head
77 }
78  
79 ### Ultra-tolerant mechanism:
80 $parser->ignore_errors(1);
81 $entity = eval { $parser->parse(\*STDIN) };
82 $error = ($@ || $parser->last_error);
83  
84 ### Cleanup all files created by the parse:
85 eval { $entity = $parser->parse(\*STDIN) };
86 ...
87 $parser->filer->purge;
88  
89  
90 =head2 Examples of parser options
91  
92 ### Automatically attempt to RFC 2047-decode the MIME headers?
93 $parser->decode_headers(1); ### default is false
94  
95 ### Parse contained "message/rfc822" objects as nested MIME streams?
96 $parser->extract_nested_messages(0); ### default is true
97  
98 ### Look for uuencode in "text" messages, and extract it?
99 $parser->extract_uuencode(1); ### default is false
100  
101 ### Should we forgive normally-fatal errors?
102 $parser->ignore_errors(0); ### default is true
103  
104  
105 =head2 Miscellaneous examples
106  
107 ### Convert a Mail::Internet object to a MIME::Entity:
108 my $data = join('', (@{$mail->header}, "\n", @{$mail->body}));
109 $entity = $parser->parse_data(\$data);
110  
111  
112  
113 =head1 DESCRIPTION
114  
115 You can inherit from this class to create your own subclasses
116 that parse MIME streams into MIME::Entity objects.
117  
118  
119 =head1 PUBLIC INTERFACE
120  
121 =cut
122  
123 #------------------------------
124  
125 26 require 5.004;
126  
127 ### Pragmas:
128 26 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
129 26 ▶use vars (qw($VERSION $CAT $CRLF));
Subroutine BEGIN: called CC=1 SCAR=0.0
130  
131 ### core Perl modules
132 26 ▶use IO::File;
Subroutine BEGIN: called CC=1 SCAR=0.0
133 26 ▶use File::Spec;
Subroutine BEGIN: called CC=1 SCAR=0.0
134 26 ▶use File::Path;
Subroutine BEGIN: called CC=1 SCAR=0.0
135 26 ▶use Config qw(%Config);
Subroutine BEGIN: called CC=1 SCAR=0.0
136 26 ▶use Carp;
Subroutine BEGIN: called CC=1 SCAR=0.0
137  
138 ### Kit modules:
139 26 ▶use MIME::Tools qw(:config :utils :msgtypes usage tmpopen );
Subroutine BEGIN: called CC=1 SCAR=0.0
140 26 ▶use MIME::Head;
Subroutine BEGIN: called CC=1 SCAR=0.0
141 26 ▶use MIME::Body;
Subroutine BEGIN: called CC=1 SCAR=0.0
142 26 ▶use MIME::Entity;
Subroutine BEGIN: called CC=1 SCAR=0.0
143 26 ▶use MIME::Decoder;
Subroutine BEGIN: called CC=1 SCAR=0.0
144 26 ▶use MIME::Parser::Reader;
Subroutine BEGIN: called CC=1 SCAR=0.0
145 26 ▶use MIME::Parser::Filer;
Subroutine BEGIN: called CC=1 SCAR=0.0
146 26 ▶use MIME::Parser::Results;
Subroutine BEGIN: called CC=1 SCAR=0.0
147  
148 #------------------------------
149 #
150 # Globals
151 #
152 #------------------------------
153  
154 ### The package version, both in 1.23 style *and* usable by MakeMaker:
155 26 $VERSION = "5.522";
156  
157 ### How to catenate:
158 26 $CAT = '/bin/cat';
159  
160 ### The CRLF sequence:
161 26 $CRLF = "\015\012";
162  
163 ### Who am I?
164 26 my $ME = 'MIME::Parser';
165  
166 #------------------------------------------------------------
167  
168 =head2 Construction
169  
170 =over 4
171  
172 =cut
173  
174 #------------------------------
175  
176 =item new ARGS...
177  
178 I<Class method.>
179 Create a new parser object.
180 Once you do this, you can then set up various parameters
181 before doing the actual parsing. For example:
182  
183 my $parser = new MIME::Parser;
184 $parser->output_dir("/tmp");
185 $parser->output_prefix("msg1");
186 my $entity = $parser->parse(\*STDIN);
187  
188 Any arguments are passed into C<init()>.
189 Don't override this in your subclasses; override init() instead.
190  
191 =cut
192  
193 55 ▶sub new {
Subroutine new: called CC=1 SCAR=0.0
Pod documented
194 55 my $self = bless {}, shift;
195 55 $self->init(@_);
196 }
197  
198 #------------------------------
199  
200 =item init ARGS...
201  
202 I<Instance method.>
203 Initiallize a new MIME::Parser object.
204 This is automatically sent to a new object; you may want to override it.
205 If you override this, be sure to invoke the inherited method.
206  
207 =cut
208  
209 55 ▶sub init {
Subroutine init: called CC=1 SCAR=0.0
Pod documented
210 55 my $self = shift;
211  
212 55 $self->{MP5_DecodeHeaders} = 0;
213 55 $self->{MP5_DecodeBodies} = 1;
214 55 $self->{MP5_Interface} = {};
215 55 $self->{MP5_ParseNested} = 'NEST';
216 55 $self->{MP5_TmpToCore} = 0;
217 55 $self->{MP5_IgnoreErrors} = 1;
218 55 $self->{MP5_UUDecode} = 0;
219 55 $self->{MP5_MaxParts} = 1000;
220 55 $self->{MP5_MaxDepth} = 64;
221 55 $self->{MP5_TmpDir} = undef;
222 55 $self->{MP5_AmbiguousContent} = 0;
223  
224 55 $self->interface(ENTITY_CLASS => 'MIME::Entity');
225 55 $self->interface(HEAD_CLASS => 'MIME::Head');
226  
227 55 $self->output_dir(".");
228  
229 55 $self;
230 }
231  
232 #------------------------------
233  
234 =item init_parse
235  
236 I<Instance method.>
237 Invoked automatically whenever one of the top-level parse() methods
238 is called, to reset the parser to a "ready" state.
239  
240 =cut
241  
242 95 ▶sub init_parse {
Subroutine init_parse: called CC=1 SCAR=0.0
Pod documented
243 95 my $self = shift;
244  
245 95 $self->{MP5_Results} = new MIME::Parser::Results;
246  
247 95 $self->{MP5_Filer}->results($self->{MP5_Results});
248 95 $self->{MP5_Filer}->purgeable([]);
249 95 $self->{MP5_Filer}->init_parse();
250 94 $self->{MP5_NumParts} = 0;
251 94 $self->{MP5_AmbiguousContent} = 0;
252 94 1;
253 }
254  
255 =back
256  
257 =cut
258  
259  
260  
261  
262  
263 #------------------------------------------------------------
264  
265 =head2 Altering how messages are parsed
266  
267 =over 4
268  
269 =cut
270  
271 #------------------------------
272  
273 =item decode_headers [YESNO]
274  
275 I<Instance method.>
276 Controls whether the parser will attempt to decode all the MIME headers
277 (as per RFC 2047) the moment it sees them. B<This is not advisable
278 for two very important reasons:>
279  
280 =over
281  
282 =item *
283  
284 B<It screws up the extraction of information from MIME fields.>
285 If you fully decode the headers into bytes, you can inadvertently
286 transform a parseable MIME header like this:
287  
288 Content-type: text/plain; filename="=?ISO-8859-1?Q?Hi=22Ho?="
289  
290 into unparseable gobbledygook; in this case:
291  
292 Content-type: text/plain; filename="Hi"Ho"
293  
294 =item *
295  
296 B<It is information-lossy.> An encoded string which contains
297 both Latin-1 and Cyrillic characters will be turned into a binary
298 mishmosh which simply can't be rendered.
299  
300 =back
301  
302 B<History.>
303 This method was once the only out-of-the-box way to deal with attachments
304 whose filenames had non-ASCII characters. However, since MIME-tools 5.4xx
305 this is no longer necessary.
306  
307 B<Parameters.>
308 If YESNO is true, decoding is done. However, you will get a warning
309 unless you use one of the special "true" values:
310  
311 "I_NEED_TO_FIX_THIS"
312 Just shut up and do it. Not recommended.
313 Provided only for those who need to keep old scripts functioning.
314  
315 "I_KNOW_WHAT_I_AM_DOING"
316 Just shut up and do it. Not recommended.
317 Provided for those who REALLY know what they are doing.
318  
319 If YESNO is false (the default), no attempt at decoding will be done.
320 With no argument, just returns the current setting.
321 B<Remember:> you can always decode the headers I<after> the parsing
322 has completed (see L<MIME::Head::decode()|MIME::Head/decode>), or
323 decode the words on demand (see L<MIME::Words>).
324  
325 =cut
326  
327 0 ▶sub decode_headers {
Subroutine decode_headers: not called CC=5 SCAR=34.0
Pod documented
328 0 my ($self, $yesno) = @_;
329 0 ▶ if (@_ > 1) {
Branch: 1 branch
BranchTrueFalseTotal
if (@_ > 1) 0 0 0
330 0 $self->{MP5_DecodeHeaders} = $yesno;
331 0 ▶ if ($yesno) {
Branch: 1 branch
BranchTrueFalseTotal
if ($yesno) 0 0 0
332 0 ▶ if (($yesno eq "I_KNOW_WHAT_I_AM_DOING") ||
Branch: 1 branch
BranchTrueFalseTotal
if ($yesno eq 'I_KNOW_WHAT_I_AM_DOING' or $yesno eq 'I_NEED_TO_FIX_THIS') { } 0 0 0
Condition0%0/3
$yesno eq "I_KNOW_WHAT_I_AM_DOING" or $yesno eq "I_NEED_TO_FIX_THIS"
l!l&&r!l&&!r
000
MC/DC0%0/2
$yesno eq "I_KNOW_WHAT_I_AM_DOING" or $yesno eq "I_NEED_TO_FIX_THIS"
$yesno eq "I_KNOW_WHAT_I_AM_DOING" $yesno eq "I_NEED_TO_FIX_THIS"
Truth table0%0/3
A or B
A= $yesno eq "I_KNOW_WHAT_I_AM_DOING"B= $yesno eq "I_NEED_TO_FIX_THIS"
ABresult
1X1
011
000
333 ($yesno eq "I_NEED_TO_FIX_THIS")) {
334 ### ok
335 }
336 else {
337 0 $self->whine("as of 5.4xx, decode_headers() should NOT be ".
338 "set true... if you are doing this to make sure ".
339 "that non-ASCII filenames are translated, ".
340 "that's now done automatically; for all else, ".
341 "use MIME::Words.");
342 }
343 }
344 }
345 0 $self->{MP5_DecodeHeaders};
346 }
347  
348 #------------------------------
349  
350 =item extract_nested_messages OPTION
351  
352 I<Instance method.>
353 Some MIME messages will contain a part of type C<message/rfc822>
354 ,C<message/partial> or C<message/external-body>:
355 literally, the text of an embedded mail/news/whatever message.
356 This option controls whether (and how) we parse that embedded message.
357  
358 If the OPTION is false, we treat such a message just as if it were a
359 C<text/plain> document, without attempting to decode its contents.
360  
361 If the OPTION is true (the default), the body of the C<message/rfc822>
362 or C<message/partial> part is parsed by this parser, creating an
363 entity object. What happens then is determined by the actual OPTION:
364  
365 =over 4
366  
367 =item NEST or 1
368  
369 The default setting.
370 The contained message becomes the sole "part" of the C<message/rfc822>
371 entity (as if the containing message were a special kind of
372 "multipart" message).
373 You can recover the sub-entity by invoking the L<parts()|MIME::Entity/parts>
374 method on the C<message/rfc822> entity.
375  
376 =item REPLACE
377  
378 The contained message replaces the C<message/rfc822> entity, as though
379 the C<message/rfc822> "container" never existed.
380  
381 B<Warning:> notice that, with this option, all the header information
382 in the C<message/rfc822> header is lost. This might seriously bother
383 you if you're dealing with a top-level message, and you've just lost
384 the sender's address and the subject line. C<:-/>.
385  
386 =back
387  
388 I<Thanks to Andreas Koenig for suggesting this method.>
389  
390 =cut
391  
392 51 ▶sub extract_nested_messages {
Subroutine extract_nested_messages: called CC=2 SCAR=6.9
Pod documented
393 51 my ($self, $option) = @_;
394 51 ▶ $self->{MP5_ParseNested} = $option if (@_ > 1);
Branch: 1 branch
BranchTrueFalseTotal
if @_ > 1 25 26 51
395 51 $self->{MP5_ParseNested};
396 }
397  
398 0 ▶sub parse_nested_messages {
Subroutine parse_nested_messages: not called CC=1 SCAR=6.9
Pod undocumented
399 0 usage "parse_nested_messages() is now extract_nested_messages()";
400 0 shift->extract_nested_messages(@_);
401 }
402  
403 #------------------------------
404  
405 =item extract_uuencode [YESNO]
406  
407 I<Instance method.>
408 If set true, then whenever we are confronted with a message
409 whose effective content-type is "text/plain" and whose encoding
410 is 7bit/8bit/binary, we scan the encoded body to see if it contains
411 uuencoded data (generally given away by a "begin XXX" line).
412  
413 If it does, we explode the uuencoded message into a multipart,
414 where the text before the first "begin XXX" becomes the first part,
415 and all "begin...end" sections following become the subsequent parts.
416 The filename (if given) is accessible through the normal means.
417  
418 =cut
419  
420 4351 ▶sub extract_uuencode {
Subroutine extract_uuencode: called CC=2 SCAR=6.9
Pod documented
421 4351 my ($self, $yesno) = @_;
422 4351 ▶ $self->{MP5_UUDecode} = $yesno if @_ > 1;
Branch: 1 branch
BranchTrueFalseTotal
if @_ > 1 25 4326 4351
423 4351 $self->{MP5_UUDecode};
424 }
425  
426 #------------------------------
427  
428 =item ignore_errors [YESNO]
429  
430 I<Instance method.>
431 Controls whether the parser will attempt to ignore normally-fatal
432 errors, treating them as warnings and continuing with the parse.
433  
434 If YESNO is true (the default), many syntax errors are tolerated.
435 If YESNO is false, fatal errors throw exceptions.
436 With no argument, just returns the current setting.
437  
438 =cut
439  
440 25 ▶sub ignore_errors {
Subroutine ignore_errors: called CC=2 SCAR=7.1
Pod documented
441 25 my ($self, $yesno) = @_;
442 25 ▶ $self->{MP5_IgnoreErrors} = $yesno if (@_ > 1);
Branch: 1 branch
BranchTrueFalseTotal
if @_ > 1 25 0 25
443 25 $self->{MP5_IgnoreErrors};
444 }
445  
446  
447 #------------------------------
448  
449 =item decode_bodies [YESNO]
450  
451 I<Instance method.>
452 Controls whether the parser should decode entity bodies or not.
453 If this is set to a false value (default is true), all entity bodies
454 will be kept as-is in the original content-transfer encoding.
455  
456 To prevent double encoding on the output side MIME::Body->is_encoded
457 is set, which tells MIME::Body not to encode the data again, if encoded
458 data was requested. This is in particular useful, when it's important that
459 the content B<must not> be modified, e.g. if you want to calculate
460 OpenPGP signatures from it.
461  
462 B<WARNING>: the semantics change significantly if you parse MIME
463 messages with this option set, because MIME::Entity resp. MIME::Body
464 *always* see encoded data now, while the default behaviour is
465 working with *decoded* data (and encoding it only if you request it).
466 You need to decode the data yourself, if you want to have it decoded.
467  
468 So use this option only if you exactly know, what you're doing, and
469 that you're sure, that you really need it.
470  
471 =cut
472  
473 4370 ▶sub decode_bodies {
Subroutine decode_bodies: called CC=2 SCAR=6.9
Pod documented
474 4370 my ($self, $yesno) = @_;
475 4370 ▶ $self->{MP5_DecodeBodies} = $yesno if (@_ > 1);
Branch: 1 branch
BranchTrueFalseTotal
if @_ > 1 3 4367 4370
476 4370 $self->{MP5_DecodeBodies};
477 }
478  
479 #------------------------------
480 #
481 # MESSAGES...
482 #
483  
484 #------------------------------
485 #
486 # debug MESSAGE...
487 #
488 27759 ▶sub debug {
Subroutine debug: called CC=3 SCAR=18.1
Pod undocumented
489 27759 my $self = shift;
490 27759 ▶ if (MIME::Tools->debugging()) {
Branch: 1 branch
BranchTrueFalseTotal
if ("MIME::Tools"->debugging) 0 27759 27759
491 0 ▶ if (my $r = $self->{MP5_Results}) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $r = $self->{"MP5_Results"}) 0 0 0
492 0 unshift @_, $r->indent;
493 0 $r->msg($M_DEBUG, @_);
494 }
495 0 MIME::Tools::debug(@_);
496 }
497 }
498  
499 #------------------------------
500 #
501 # whine PROBLEM...
502 #
503 9 ▶sub whine {
Subroutine whine: called CC=2 SCAR=7.0
Pod undocumented
504 9 my $self = shift;
505 9 ▶ if (my $r = $self->{MP5_Results}) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $r = $self->{"MP5_Results"}) 9 0 9
506 9 unshift @_, $r->indent;
507 9 $r->msg($M_WARNING, @_);
508 }
509 9 &MIME::Tools::whine(@_);
510 }
511  
512 #------------------------------
513 #
514 # error PROBLEM...
515 #
516 # Possibly-forgivable parse error occurred.
517 # Raises a fatal exception unless we are ignoring errors.
518 #
519 113 ▶sub error {
Subroutine error: called CC=3 SCAR=11.2
Pod documented
520 113 my $self = shift;
521 113 ▶ if (my $r = $self->{MP5_Results}) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $r = $self->{"MP5_Results"}) 113 0 113
522 113 unshift @_, $r->indent;
523 113 $r->msg($M_ERROR, @_);
524 }
525 113 &MIME::Tools::error(@_);
526 113 ▶ $self->{MP5_IgnoreErrors} ? return undef : die @_;
Branch: 1 branch
BranchTrueFalseTotal
$self->{'MP5_IgnoreErrors'} ? : 113 0 113
527 }
528  
529  
530  
531  
532 #------------------------------
533 #
534 # PARSING...
535 #
536  
537 #------------------------------
538 #
539 # process_preamble IN, READER, ENTITY
540 #
541 # I<Instance method.>
542 # Dispose of a multipart message's preamble.
543 #
544 1795 ▶sub process_preamble {
Subroutine process_preamble: called CC=4 SCAR=13.9
Pod undocumented
545 1795 my ($self, $in, $rdr, $ent) = @_;
546  
547 ### Sanity:
548 1795 ▶ ($rdr->has_bounds) or die "$ME: internal logic error";
Branch: 1 branch
BranchTrueFalseTotal
$rdr->has_bounds or die "${ME}: internal logic error" 1795 0 1795
549  
550 ### Parse preamble:
551 1795 my @saved;
552 1795 my $data = '';
553 1795 ▶ open(my $fh, '>', \$data) or die $!;
Branch: 1 branch
BranchTrueFalseTotal
open my $fh, ">", \$data or die $! 1795 0 1795
554 1795 $rdr->read_chunk($in, $fh, 1);
555 1795 close $fh;
556  
557 # Ugh. Horrible. If the preamble consists only of CRLF, squash it down
558 # to the empty string. Else, remove the trailing CRLF.
559 1795 ▶ if( $data =~ m/^(\r\n|\n\r|\n|\r)\z/ ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($data =~ /^(\r\n|\n\r|\n|\r)\z/) { } 5 1790 1795
560 5 @saved = ('');
561 } else {
562 1790 $data =~ s/(\r\n|\n\r|\n|\r)\z//;
563 1790 @saved = split(/^/, $data);
564 }
565 1795 $ent->preamble(\@saved);
566 1795 1;
567 }
568  
569 #------------------------------
570 #
571 # process_epilogue IN, READER, ENTITY
572 #
573 # I<Instance method.>
574 # Dispose of a multipart message's epilogue.
575 #
576 1126 ▶sub process_epilogue {
Subroutine process_epilogue: called CC=1 SCAR=0.0
Pod undocumented
577 1126 my ($self, $in, $rdr, $ent) = @_;
578 1126 $self->debug("process_epilogue");
579  
580 ### Parse epilogue:
581 1126 my @saved;
582 1126 $rdr->read_lines($in, \@saved);
583 1126 $ent->epilogue(\@saved);
584 1126 1;
585 }
586  
587 #------------------------------
588 #
589 # process_to_bound IN, READER, OUT
590 #
591 # I<Instance method.>
592 # Dispose of the next chunk into the given output stream OUT.
593 #
594 2137 ▶sub process_to_bound {
Subroutine process_to_bound: called CC=1 SCAR=0.0
Pod undocumented
595 2137 my ($self, $in, $rdr, $out) = @_;
596  
597 ### Parse:
598 2137 $rdr->read_chunk($in, $out);
599 2137 1;
600 }
601  
602 #------------------------------
603 #
604 # process_header IN, READER
605 #
606 # I<Instance method.>
607 # Process and return the next header.
608 # Return undef if, instead of a header, the encapsulation boundary is found.
609 # Fatal exception on failure.
610 #
611 3975 ▶sub process_header {
Subroutine process_header: called CC=8 SCAR=21.0
Pod undocumented
612 3975 my ($self, $in, $rdr) = @_;
613 3975 $self->debug("process_header");
614  
615 ### Parse and save the (possibly empty) header, up to and including the
616 ### blank line that terminates it:
617 3975 my $head = $self->interface('HEAD_CLASS')->new;
618  
619 ### Read the lines of the header.
620 ### We localize IO inside here, so that we can support the IO:: interface
621 3975 my @headlines;
622 3975 my $hdr_rdr = $rdr->spawn;
623 3975 $hdr_rdr->add_terminator("");
624 3975 $hdr_rdr->add_terminator("\r"); ### sigh
625  
626 3975 my $headstr = '';
627 3975 ▶ open(my $outfh, '>:scalar', \$headstr) or die $!;
Branch: 1 branch
BranchTrueFalseTotal
open my $outfh, ">:scalar", \$headstr or die $! 3975 0 3975
628 3975 $hdr_rdr->read_chunk($in, $outfh, 0, 1);
629 3975 close $outfh;
630  
631 ### How did we do?
632 3975 ▶ if ($hdr_rdr->eos_type eq 'DELIM') {
Branch: 1 branch
BranchTrueFalseTotal
if ($hdr_rdr->eos_type eq "DELIM") 2 3973 3975
633 2 $self->whine("bogus part, without CRLF before body");
634 2 return undef;
635 }
636 3973 ▶ ($hdr_rdr->eos_type eq 'DONE') or
Branch: 1 branch
BranchTrueFalseTotal
$hdr_rdr->eos_type eq "DONE" or $self->error("unexpected end of header\n") 3972 1 3973
637 $self->error("unexpected end of header\n");
638  
639 # Free memory used by hdr_rdr and undo any changes it made
640 # to terminators
641 3973 $hdr_rdr = undef;
642  
643 ### If header line begins with a UTF-8 Byte-Order mark, remove it.
644 3973 $headstr =~ s/^\x{EF}\x{BB}\x{BF}//;
645  
646 ### Extract the header (note that zero-size headers are admissible!):
647 3973 ▶ open(my $readfh, '<:scalar', \$headstr) or die $!;
Branch: 1 branch
BranchTrueFalseTotal
open my $readfh, "<:scalar", \$headstr or die $! 3973 0 3973
648 3973 $head->read( $readfh );
649  
650 3973 ▶ unless( $readfh->eof() ) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($readfh->eof) 0 3973 3973
651 # Not entirely correct, since ->read consumes the line it gives up on.
652 # it's actually the line /before/ the one we get with ->getline
653 0 $self->error("couldn't parse head; error near:\n", $readfh->getline());
654 }
655  
656  
657 ### If desired, auto-decode the header as per RFC 2047
658 ### This shouldn't affect non-encoded headers; however, it will decode
659 ### headers with international characters. WARNING: currently, the
660 ### character-set information is LOST after decoding.
661 3973 ▶ $head->decode($self->{MP5_DecodeHeaders}) if $self->{MP5_DecodeHeaders};
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"MP5_DecodeHeaders"} 0 3973 3973
662  
663 ### If this is the top-level head, save it:
664 3973 ▶ $self->results->top_head($head) if !$self->results->top_head;
Branch: 1 branch
BranchTrueFalseTotal
unless $self->results->top_head 94 3879 3973
665  
666 3973 return $head;
667 }
668  
669 #------------------------------
670 #
671 # process_multipart IN, READER, ENTITY
672 #
673 # I<Instance method.>
674 # Process the multipart body, and return the state.
675 # Fatal exception on failure.
676 # Invoked by process_part().
677 #
678 1800 ▶sub process_multipart {
Subroutine process_multipart: called CC=12 SCAR=24.8
Pod undocumented
679 1800 my ($self, $in, $rdr, $ent) = @_;
680 1800 my $head = $ent->head;
681  
682 1800 $self->debug("process_multipart...");
683  
684 ### Get actual type and subtype from the header:
685 1800 my ($type, $subtype) = (split('/', $head->mime_type, -1), '');
686  
687 ### If this was a type "multipart/digest", then the RFCs say we
688 ### should default the parts to have type "message/rfc822".
689 ### Thanks to Carsten Heyl for suggesting this...
690 1800 ▶ my $retype = (($subtype eq 'digest') ? 'message/rfc822' : '');
Branch: 1 branch
BranchTrueFalseTotal
$subtype eq 'digest' ? : 1 1799 1800
691  
692 ### Get the boundaries for the parts:
693 1800 my $bound = $head->multipart_boundary;
694 1800 ▶ if (!defined($bound) || ($bound =~ /[\r\n]/)) {
Branch: 1 branch
BranchTrueFalseTotal
if (not defined $bound or $bound =~ /[\r\n]/) 3 1797 1800
Condition66%2/3
not defined $bound or $bound =~ /[\r\n]/
l!l&&r!l&&!r
301797
MC/DC50%1/2
not defined $bound or $bound =~ /[\r\n]/
not defined $bound $bound =~ /[\r\n]/
Truth table66%2/3
not(A) or B
A= not defined $boundB= $bound =~ /[\r\n]/
ABresult
1X1
011
000
695 3 $self->error("multipart boundary is missing, or contains CR or LF\n");
696 3 $ent->effective_type("application/x-unparseable-multipart");
697 3 return $self->process_singlepart($in, $rdr, $ent);
698 }
699 1797 my $part_rdr = $rdr->spawn->add_boundary($bound);
700  
701 1797 ▶ if ($self->{MP5_MaxDepth} > 0 && $part_rdr->depth() > $self->{MP5_MaxDepth}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"MP5_MaxDepth"} > 0 and $part_rdr->depth > $self->{"MP5_MaxDepth"}) 2 1795 1797
Condition100%3/3
$self->{"MP5_MaxDepth"} > 0 and $part_rdr->depth > $self->{"MP5_MaxDepth"}
!ll&&!rl&&r
50012952
MC/DC100%2/2
$self->{"MP5_MaxDepth"} > 0 and $part_rdr->depth > $self->{"MP5_MaxDepth"}
$self->{"MP5_MaxDepth"} > 0 $part_rdr->depth > $self->{"MP5_MaxDepth"}
Truth table100%3/3
A and B
A= $self->{"MP5_MaxDepth"} > 0B= $part_rdr->depth > $self->{"MP5_MaxDepth"}
ABresult
0X0
100
111
702 2 $self->whine("MIME parts nested too deeply");
703 2 return undef;
704 }
705 ### Prepare to parse:
706 1795 my $eos_type;
707 my $more_parts;
708  
709 ### Parse preamble...
710 1795 $self->process_preamble($in, $part_rdr, $ent);
711  
712 ### ...and look at how we finished up:
713 1795 $eos_type = $part_rdr->eos_type;
714 1795 ▶ if ($eos_type eq 'DELIM'){ $more_parts = 1 }
Branch: 2 branches
BranchTrueFalseTotal
if ($eos_type eq 'DELIM') { } 1792 3 1795
elsif ($eos_type eq 'CLOSE') { } 1 2 3
715 1 elsif ($eos_type eq 'CLOSE'){ $self->whine("empty multipart message\n");
716 1 $more_parts = 0; }
717 2 else { $self->error("unexpected end of preamble\n");
718 2 return 1; }
719  
720 ### Parse parts:
721 1793 my $partno = 0;
722 1793 my $part;
723 1793 ▶ while ($more_parts) {
Branch: 1 branch
BranchTrueFalseTotal
if ($more_parts) 3869 1126 4995
724 3869 ++$partno;
725 3869 $self->debug("parsing part $partno...");
726  
727 ### Parse the next part, and add it to the entity...
728 3869 my $part = $self->process_part($in, $part_rdr, Retype=>$retype);
729 3869 ▶ return undef unless defined($part);
Branch: 1 branch
BranchTrueFalseTotal
unless defined $part 564 3305 3869
730  
731 3305 $ent->add_part($part);
732  
733 ### ...and look at how we finished up:
734 3305 $eos_type = $part_rdr->eos_type;
735 3305 ▶ if ($eos_type eq 'DELIM') { $more_parts = 1 }
Branch: 2 branches
BranchTrueFalseTotal
if ($eos_type eq 'DELIM') { } 2077 1228 3305
elsif ($eos_type eq 'CLOSE') { } 1125 103 1228
736 1125 elsif ($eos_type eq 'CLOSE') { $more_parts = 0; }
737 103 else { $self->error("unexpected end of parts ".
738 "before epilogue\n");
739 103 return 1; }
740 }
741  
742 # We have to free $part_rdr here because we rely on the destructor
743 # to remove its boundaries from the parent reader's copy of the
744 # boundary hash.
745 1126 $part_rdr = undef;
746  
747 ### Parse epilogue...
748 ### (note that we use the *parent's* reader here, which does not
749 ### know about the boundaries in this multipart!)
750 1126 $self->process_epilogue($in, $rdr, $ent);
751  
752 ### ...and there's no need to look at how we finished up!
753 1126 1;
754 }
755  
756 #------------------------------
757 #
758 # process_singlepart IN, READER, ENTITY
759 #
760 # I<Instance method.>
761 # Process the singlepart body. Returns true.
762 # Fatal exception on failure.
763 # Invoked by process_part().
764 #
765 2163 ▶sub process_singlepart {
Subroutine process_singlepart: called CC=22 SCAR=31.9
Pod undocumented
766 2163 my ($self, $in, $rdr, $ent) = @_;
767 2163 my $head = $ent->head;
768  
769 2163 $self->debug("process_singlepart...");
770  
771 ### Obtain a filehandle for reading the encoded information:
772 ### We have two different approaches, based on whether or not we
773 ### have to contend with boundaries.
774 2163 my $ENCODED; ### handle
775 2163 ▶ my $can_shortcut = (!$rdr->has_bounds and !$self->{MP5_UUDecode});
Condition100%3/3
$rdr->has_bounds || $self->{'MP5_UUDecode'}
l!l&&r!l&&!r
2136126
MC/DC100%2/2
$rdr->has_bounds || $self->{'MP5_UUDecode'}
$rdr->has_bounds $self->{'MP5_UUDecode'}
Truth table100%3/3
A || B
A= $rdr->has_boundsB= $self->{'MP5_UUDecode'}
ABresult
1X1
011
000
776 2163 ▶ if ($can_shortcut) {
Branch: 1 branch
BranchTrueFalseTotal
if ($can_shortcut) { } 26 2137 2163
777 26 $self->debug("taking shortcut");
778  
779 26 $ENCODED = $in;
780 26 $rdr->eos('EOF'); ### be sure to bogus-up the reader state to EOF:
781 }
782 else {
783  
784 2137 $self->debug("using temp file");
785 2137 $ENCODED = $self->new_tmpfile();
786  
787 ### Read encoded body until boundary (or EOF)...
788 2137 $self->process_to_bound($in, $rdr, $ENCODED);
789  
790 ### ...and look at how we finished up.
791 ### If we have bounds, we want DELIM or CLOSE.
792 ### Otherwise, we want EOF (and that's all we'd get, anyway!).
793 2137 ▶ if ($rdr->has_bounds) {
Branch: 1 branch
BranchTrueFalseTotal
if ($rdr->has_bounds) 2136 1 2137
794 2136 ▶ ($rdr->eos_type =~ /^(DELIM|CLOSE)$/) or
Branch: 1 branch
BranchTrueFalseTotal
$rdr->eos_type =~ /^(DELIM|CLOSE)$/ or $self->error("part did not end with expected boundary\n") 2132 4 2136
795 $self->error("part did not end with expected boundary\n");
796 }
797  
798 ### Flush and rewind encoded buffer, so we can read it:
799 2137 ▶ $ENCODED->flush or die "$ME: can't flush: $!";
Branch: 1 branch
BranchTrueFalseTotal
$ENCODED->flush or die "${ME}: can't flush: $!" 2137 0 2137
800 2137 ▶ $ENCODED->seek(0, 0) or die "$ME: can't seek: $!";
Branch: 1 branch
BranchTrueFalseTotal
$ENCODED->seek(0, 0) or die "${ME}: can't seek: $!" 2137 0 2137
801 }
802  
803 ### Get a content-decoder to decode this part's encoding:
804 2163 my $encoding = $head->mime_encoding;
805 2163 my $decoder = new MIME::Decoder $encoding;
806 2163 ▶ if (!$decoder) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($decoder) 0 2163 2163
807 0 $self->whine("Unsupported encoding '$encoding': using 'binary'... \n".
808 "The entity will have an effective MIME type of \n".
809 "application/octet-stream."); ### as per RFC-2045
810 0 $ent->effective_type('application/octet-stream');
811 0 $decoder = new MIME::Decoder 'binary';
812 0 $encoding = 'binary';
813 }
814  
815 ### Data should be stored encoded / as-is?
816 2163 ▶ if ( !$self->decode_bodies ) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($self->decode_bodies) 7 2156 2163
817 7 $decoder = new MIME::Decoder 'binary';
818 7 $encoding = 'binary';
819 }
820  
821 ### If desired, sidetrack to troll for UUENCODE:
822 2163 $self->debug("extract uuencode? ", $self->extract_uuencode);
823 2163 $self->debug("encoding? ", $encoding);
824 2163 $self->debug("effective type? ", $ent->effective_type);
825  
826 2163 ▶ if ($self->extract_uuencode and
Branch: 1 branch
BranchTrueFalseTotal
if ($self->extract_uuencode and $encoding =~ /^(7bit|8bit|binary)\Z/ and $ent->effective_type =~ m[^(?:text/plain|application/mac-binhex40|application/mac-binhex)\Z]) 3 2160 2163
Condition66%4/6
$self->extract_uuencode and $encoding =~ /^(7bit|8bit|binary)\Z/ and $ent->effective_type =~ m[^(?:text/plain|application/mac-binhex40|application/mac-binhex)\Z]
!ll&&!rl&&r
216003
$self->extract_uuencode and $encoding =~ /^(7bit|8bit|binary)\Z/
!ll&&!rl&&r
216003
MC/DC33%1/3
$self->extract_uuencode and $encoding =~ /^(7bit|8bit|binary)\Z/ and $ent->effective_type =~ m[^(?:text/plain|application/mac-binhex40|application/mac-binhex)\Z]
$self->extract_uuencode $encoding =~ /^(7bit|8bit|binary)\Z/ $ent->effective_type =~ m[^(?:text/plain|application/mac-binhex40|application/mac-binhex)\Z]
Truth table50%2/4
A and B and C
A= $self->extract_uuencodeB= $encoding =~ /^(7bit|8bit|binary)\Z/C= $ent->effective_type =~ m[^(?:text/plain|application/mac-binhex40|application/mac-binhex)\Z]
ABCresult
0XX0
10X0
1100
1111
827 ($encoding =~ /^(7bit|8bit|binary)\Z/) and
828 ($ent->effective_type =~
829 m{^(?:text/plain|application/mac-binhex40|application/mac-binhex)\Z})) {
830 ### Hunt for it:
831 3 my $uu_ent = eval { $self->hunt_for_uuencode($ENCODED, $ent) };
832 3 ▶ if ($uu_ent) { ### snark
Branch: 1 branch
BranchTrueFalseTotal
if ($uu_ent) { } 2 1 3
833 2 %$ent = %$uu_ent;
834 2 return 1;
835 }
836 else { ### boojum
837 1 $self->whine("while hunting for uuencode: $@");
838 1 ▶ $ENCODED->seek(0,0) or die "$ME: can't seek: $!";
Branch: 1 branch
BranchTrueFalseTotal
$ENCODED->seek(0, 0) or die "${ME}: can't seek: $!" 1 0 1
839 }
840 }
841  
842 ### Open a new bodyhandle for outputting the data:
843 2161 ▶ my $body = $self->new_body_for($head) or die "$ME: no body"; # gotta die
Branch: 1 branch
BranchTrueFalseTotal
my $body = $self->new_body_for($head) or die "${ME}: no body" 2161 0 2161
844 2161 ▶ $body->binmode(1) or die "$ME: can't set to binmode: $!"
Branch: 1 branch
BranchTrueFalseTotal
unless textual_type($ent->effective_type) or not $self->decode_bodies 42 2119 2161
Condition75%6/8
textual_type($ent->effective_type) || !$self->decode_bodies || ($body->binmode(1) || die("${ME}: can't set to binmode: $!"))
l!l
2119420
textual_type($ent->effective_type) or not $self->decode_bodies
l!l&&r!l&&!r
2118142
$body->binmode(1) or die "${ME}: can't set to binmode: $!"
l!l
420
MC/DC0%0/3
textual_type($ent->effective_type) || !$self->decode_bodies || ($body->binmode(1) || die("${ME}: can't set to binmode: $!"))
textual_type($ent->effective_type) not $self->decode_bodies $body->binmode(1)
Truth table50%2/4
A or not(B) || C
A= textual_type($ent->effective_type)B= not $self->decode_bodiesC= $body->binmode(1)
ABCresult
1XX1
01X1
0011
0000
845 unless textual_type($ent->effective_type) or !$self->decode_bodies;
846 2161 ▶ $body->is_encoded(1) if !$self->decode_bodies;
Branch: 1 branch
BranchTrueFalseTotal
unless $self->decode_bodies 7 2154 2161
847  
848 ### Decode and save the body (using the decoder):
849 2161 ▶ my $DECODED = $body->open("w") or die "$ME: body not opened: $!";
Branch: 1 branch
BranchTrueFalseTotal
my $DECODED = $body->open("w") or die "${ME}: body not opened: $!" 2161 0 2161
850 2161 eval { $decoder->decode($ENCODED, $DECODED); };
851 2161 ▶ $@ and $self->error($@);
Branch: 1 branch
BranchTrueFalseTotal
$@ and $self->error($@) 0 2161 2161
852 2161 ▶ $DECODED->close or die "$ME: can't close: $!";
Branch: 1 branch
BranchTrueFalseTotal
$DECODED->close or die "${ME}: can't close: $!" 2161 0 2161
853  
854 ### Success! Remember where we put stuff:
855 2161 $ent->bodyhandle($body);
856  
857 ### Done!
858 2161 1;
859 }
860  
861 #------------------------------
862 #
863 # hunt_for_uuencode ENCODED, ENTITY
864 #
865 # I<Instance method.>
866 # Try to detect and dispatch embedded uuencode as a fake multipart message.
867 # Returns new entity or undef.
868 #
869 3 ▶sub hunt_for_uuencode {
Subroutine hunt_for_uuencode: called CC=23 SCAR=33.0
Pod undocumented
870 3 my ($self, $ENCODED, $ent) = @_;
871 3 my ($good, $how_encoded);
872 3 local $_;
873 3 $self->debug("sniffing around for UUENCODE");
874  
875 ### Heuristic:
876 3 ▶ $ENCODED->seek(0,0) or die "$ME: can't seek: $!";
Branch: 1 branch
BranchTrueFalseTotal
$ENCODED->seek(0, 0) or die "${ME}: can't seek: $!" 3 0 3
877 3 ▶ while (defined($_ = $ENCODED->getline)) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined($_ = $ENCODED->getline)) 18 1 19
878 18 ▶ if ($good = /^begin [0-7]{3}/) {
Branch: 1 branch
BranchTrueFalseTotal
if ($good = /^begin [0-7]{3}/) 2 16 18
879 2 $how_encoded = 'uu';
880 2 last;
881 }
882 16 ▶ if ($good = /^\(This file must be converted with/i) {
Branch: 1 branch
BranchTrueFalseTotal
if ($good = /^\(This file must be converted with/i) 0 16 16
883 0 $how_encoded = 'binhex';
884 0 last;
885 }
886 }
887 3 ▶ $good or do { $self->debug("no one made the cut"); return 0 };
Branch: 1 branch
BranchTrueFalseTotal
$good or do { $self->debug("no one made the cut"); return 0 } 2 1 3
888  
889 # If a decoder doesn't exist for this type, forget it!
890 2 ▶ my $decoder = MIME::Decoder->new(($how_encoded eq 'uu')?'x-uuencode'
Branch: 1 branch
BranchTrueFalseTotal
$how_encoded eq 'uu' ? : 2 0 2
891 :'binhex');
892 2 ▶ unless (defined($decoder)) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $decoder) 0 2 2
893 0 $self->debug("No decoder for $how_encoded attachments");
894 0 return 0;
895 }
896  
897 ### New entity:
898 2 my $top_ent = $ent->dup; ### no data yet
899 2 $top_ent->make_multipart;
900 2 my @parts;
901  
902 ### Made the first cut; on to the real stuff:
903 2 ▶ $ENCODED->seek(0,0) or die "$ME: can't seek: $!";
Branch: 1 branch
BranchTrueFalseTotal
$ENCODED->seek(0, 0) or die "${ME}: can't seek: $!" 2 0 2
904 2 $self->whine("Found a $how_encoded attachment");
905 2 my $pre;
906 2 while (1) {
907 6 my $bin_data = '';
908  
909 ### Try next part:
910 6 my $out = IO::File->new(\$bin_data, '>:');
911 6 ▶ eval { $decoder->decode($ENCODED, $out) }; last if $@;
Branch: 1 branch
BranchTrueFalseTotal
if $@ 2 4 6
912 4 my $preamble = $decoder->last_preamble;
913 4 my $filename = $decoder->last_filename;
914 4 my $mode = $decoder->last_mode;
915  
916 ### Get probable type:
917 4 my $type = 'application/octet-stream';
918 4 ▶ my ($ext) = $filename =~ /\.(\w+)\Z/; $ext = lc($ext || '');
Condition50%1/2
$ext || ''
l!l
40
MC/DC0%0/1
$ext || ''
$ext
Truth table50%1/2
A
A= $ext
Aresult
11
00
919 4 ▶ if ($ext =~ /^(gif|jpe?g|xbm|xpm|png)\Z/) { $type = "image/$1" }
Branch: 1 branch
BranchTrueFalseTotal
if ($ext =~ /^(gif|jpe?g|xbm|xpm|png)\Z/) 4 0 4
920  
921 ### If we got our first preamble, create the text portion:
922 4 ▶ if (@$preamble and
Branch: 1 branch
BranchTrueFalseTotal
if (@$preamble and grep /\S/, @$preamble and not @parts) 2 2 4
Condition66%4/6
@$preamble and grep /\S/, @$preamble and not @parts
!ll&&!rl&&r
202
@$preamble and grep /\S/, @$preamble
!ll&&!rl&&r
022
MC/DC33%1/3
@$preamble and grep /\S/, @$preamble and not @parts
@$preamble grep /\S/, @$preamble not @parts
Truth table50%2/4
A and B and not(C)
A= @$preambleB= grep /\S/, @$preambleC= not @parts
ABCresult
0XX0
10X0
1100
1111
923 (grep /\S/, @$preamble) and
924 !@parts) {
925 2 my $txt_ent = $self->interface('ENTITY_CLASS')->new;
926  
927 2 MIME::Entity->build(Type => "text/plain",
928 Data => "");
929 2 $txt_ent->bodyhandle($self->new_body_for($txt_ent->head));
930 2 ▶ my $io = $txt_ent->bodyhandle->open("w") or die "$ME: can't create: $!";
Branch: 1 branch
BranchTrueFalseTotal
my $io = $txt_ent->bodyhandle->open("w") or die "${ME}: can't create: $!" 2 0 2
931 2 ▶ $io->print(@$preamble) or die "$ME: can't print: $!";
Branch: 1 branch
BranchTrueFalseTotal
$io->print(@$preamble) or die "${ME}: can't print: $!" 2 0 2
932 2 ▶ $io->close or die "$ME: can't close: $!";
Branch: 1 branch
BranchTrueFalseTotal
$io->close or die "${ME}: can't close: $!" 2 0 2
933 2 push @parts, $txt_ent;
934 }
935  
936 ### Create the attachment:
937 ### We use the x-unix-mode convention from "dtmail 1.2.1 SunOS 5.6".
938 4 if (1) {
939 4 my $bin_ent = MIME::Entity->build(Type=>$type,
940 Filename=>$filename,
941 Data=>"");
942 4 $bin_ent->head->mime_attr('Content-type.x-unix-mode' => "0$mode");
943 4 $bin_ent->bodyhandle($self->new_body_for($bin_ent->head));
944 4 ▶ $bin_ent->bodyhandle->binmode(1) or die "$ME: can't set to binmode: $!";
Branch: 1 branch
BranchTrueFalseTotal
$bin_ent->bodyhandle->binmode(1) or die "${ME}: can't set to binmode: $!" 4 0 4
945 4 ▶ my $io = $bin_ent->bodyhandle->open("w") or die "$ME: can't create: $!";
Branch: 1 branch
BranchTrueFalseTotal
my $io = $bin_ent->bodyhandle->open("w") or die "${ME}: can't create: $!" 4 0 4
946 4 ▶ $io->print($bin_data) or die "$ME: can't print: $!";
Branch: 1 branch
BranchTrueFalseTotal
$io->print($bin_data) or die "${ME}: can't print: $!" 4 0 4
947 4 ▶ $io->close or die "$ME: can't close: $!";
Branch: 1 branch
BranchTrueFalseTotal
$io->close or die "${ME}: can't close: $!" 4 0 4
948 4 push @parts, $bin_ent;
949 }
950 }
951  
952 ### Did we get anything?
953 2 ▶ @parts or return undef;
Branch: 1 branch
BranchTrueFalseTotal
@parts or return undef 2 0 2
954 ### Set the parts and a nice preamble:
955 2 $top_ent->parts(\@parts);
956 2 $top_ent->preamble
957 (["The following is a multipart MIME message which was extracted\n",
958 "from a $how_encoded-encoded message.\n"]);
959 2 $top_ent;
960 }
961  
962 #------------------------------
963 #
964 # process_message IN, READER, ENTITY
965 #
966 # I<Instance method.>
967 # Process the singlepart body, and return true.
968 # Fatal exception on failure.
969 # Invoked by process_part().
970 #
971 13 ▶sub process_message {
Subroutine process_message: called CC=4 SCAR=14.1
Pod undocumented
972 13 my ($self, $in, $rdr, $ent) = @_;
973 13 my $head = $ent->head;
974  
975 13 $self->debug("process_message");
976  
977 ### Verify the encoding restrictions:
978 13 my $encoding = $head->mime_encoding;
979 13 ▶ if ($encoding !~ /^(7bit|8bit|binary)$/) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($encoding =~ /^(7bit|8bit|binary)$/) 0 13 13
980 0 $self->error("illegal encoding [$encoding] for MIME type ".
981 $head->mime_type."\n");
982 0 $encoding = 'binary';
983 }
984  
985 ### Parse the message:
986 13 my $msg = $self->process_part($in, $rdr);
987 13 ▶ return undef unless defined($msg);
Branch: 1 branch
BranchTrueFalseTotal
unless defined $msg 0 13 13
988  
989 ### How to handle nested messages?
990 13 ▶ if ($self->extract_nested_messages eq 'REPLACE') {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->extract_nested_messages eq 'REPLACE') { } 1 12 13
991 1 %$ent = %$msg; ### shallow replace
992 1 %$msg = ();
993 }
994 else { ### "NEST" or generic 1:
995 12 $ent->bodyhandle(undef);
996 12 $ent->add_part($msg);
997 }
998 13 1;
999 }
1000  
1001 #------------------------------
1002 #
1003 # process_part IN, READER, [OPTSHASH...]
1004 #
1005 # I<Instance method.>
1006 # The real back-end engine.
1007 # See the documentation up top for the overview of the algorithm.
1008 # The OPTSHASH can contain:
1009 #
1010 # Retype => retype this part to the given content-type
1011 #
1012 # Return the entity.
1013 # Fatal exception on failure. Returns undef if message to complex
1014 #
1015 3976 ▶sub process_part {
Subroutine process_part: called CC=20 SCAR=30.8
Pod undocumented
1016 3976 my ($self, $in, $rdr, %p) = @_;
1017  
1018 3976 ▶ if ($self->{MP5_MaxParts} > 0) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"MP5_MaxParts"} > 0) 2474 1502 3976
1019 2474 $self->{MP5_NumParts}++;
1020 2474 ▶ if ($self->{MP5_NumParts} > $self->{MP5_MaxParts}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"MP5_NumParts"} > $self->{"MP5_MaxParts"}) 1 2473 2474
1021 1 $self->whine("Too many MIME parts");
1022 1 return undef;
1023 }
1024 }
1025  
1026 3975 ▶ $rdr ||= MIME::Parser::Reader->new;
Condition66%2/3
$rdr ||= "MIME::Parser::Reader"->new
l!l&&r!l&&!r
3881940
MC/DC0%0/2
$rdr ||= "MIME::Parser::Reader"->new
$rdr "MIME::Parser::Reader"->new
Truth table66%2/3
A ||= B
A= $rdrB= "MIME::Parser::Reader"->new
ABresult
1X1
011
000
1027 #debug "process_part";
1028 3975 $self->results->level(+1);
1029  
1030 ### Create a new entity:
1031 3975 my $ent = $self->interface('ENTITY_CLASS')->new;
1032  
1033 ### Parse and add the header:
1034 3975 my $head = $self->process_header($in, $rdr);
1035 3975 ▶ if (not defined $head) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $head) 2 3973 3975
1036 2 $self->debug("bogus empty part");
1037 2 $head = $self->interface('HEAD_CLASS')->new;
1038 2 $head->mime_type('text/plain');
1039 2 $ent->head($head);
1040 2 $ent->bodyhandle($self->new_body_for($head));
1041 2 ▶ $ent->bodyhandle->open("w")->close or die "$ME: can't close: $!";
Branch: 1 branch
BranchTrueFalseTotal
$ent->bodyhandle->open("w")->close or die "${ME}: can't close: $!" 2 0 2
1042 2 ▶ if (!$self->{MP5_AmbiguousContent}) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($self->{"MP5_AmbiguousContent"}) 2 0 2
1043 2 ▶ if ($ent->head->ambiguous_content) {
Branch: 1 branch
BranchTrueFalseTotal
if ($ent->head->ambiguous_content) 0 2 2
1044 0 $self->{MP5_AmbiguousContent} = 1;
1045 }
1046 }
1047 2 $self->results->level(-1);
1048 2 return $ent;
1049 }
1050 3973 $ent->head($head);
1051  
1052 ### Tweak the content-type based on context from our parent...
1053 ### For example, multipart/digest messages default to type message/rfc822:
1054 3973 ▶ $head->mime_type($p{Retype}) if $p{Retype};
Branch: 1 branch
BranchTrueFalseTotal
if $p{"Retype"} 2 3971 3973
1055  
1056 # We have the header, so that's enough to check for
1057 # ambiguous content...
1058 3973 ▶ if (!$self->{MP5_AmbiguousContent}) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($self->{"MP5_AmbiguousContent"}) 3956 17 3973
1059 3956 ▶ if ($ent->head->ambiguous_content) {
Branch: 1 branch
BranchTrueFalseTotal
if ($ent->head->ambiguous_content) 23 3933 3956
1060 23 $self->{MP5_AmbiguousContent} = 1;
1061 }
1062 }
1063 ### Get the MIME type and subtype:
1064 3973 my ($type, $subtype) = (split('/', $head->mime_type, -1), '');
1065 3973 $self->debug("type = $type, subtype = $subtype");
1066  
1067 ### Handle, according to the MIME type:
1068 3973 ▶ if ($type eq 'multipart') {
Branch: 2 branches
BranchTrueFalseTotal
if ($type eq 'multipart') { } 1800 2173 3973
elsif ("$type/$subtype" eq 'message/rfc822' || "$type/$subtype" eq 'message/external-body' || "$type/$subtype" eq 'message/partial' && defined $head->mime_attr('content-type.number') && $head->mime_attr('content-type.number') == 1 and $self->extract_nested_messages) { } 13 2160 2173
1069 1800 ▶ return undef unless defined($self->process_multipart($in, $rdr, $ent));
Branch: 1 branch
BranchTrueFalseTotal
unless defined $self->process_multipart($in, $rdr, $ent) 566 1234 1800
1070 }
1071 ▶ elsif (("$type/$subtype" eq "message/rfc822" ||
Condition53%8/15
"$type/$subtype" eq "message/rfc822" || "$type/$subtype" eq "message/external-body" || "$type/$subtype" eq "message/partial" && defined $head->mime_attr("content-type.number") && $head->mime_attr("content-type.number") == 1 and $self->extract_nested_messages
!ll&&!rl&&r
2160013
"$type/$subtype" eq "message/rfc822" or "$type/$subtype" eq "message/external-body" or "$type/$subtype" eq "message/partial" and defined $head->mime_attr("content-type.number") and $head->mime_attr("content-type.number") == 1
l!l&&r!l&&!r
1302160
"$type/$subtype" eq "message/rfc822" or "$type/$subtype" eq "message/external-body"
l!l&&r!l&&!r
1302160
"$type/$subtype" eq "message/partial" and defined $head->mime_attr("content-type.number") and $head->mime_attr("content-type.number") == 1
!ll&&!rl&&r
216000
"$type/$subtype" eq "message/partial" and defined $head->mime_attr("content-type.number")
!ll&&!rl&&r
216000
MC/DC16%1/6
"$type/$subtype" eq "message/rfc822" || "$type/$subtype" eq "message/external-body" || "$type/$subtype" eq "message/partial" && defined $head->mime_attr("content-type.number") && $head->mime_attr("content-type.number") == 1 and $self->extract_nested_messages
"$type/$subtype" eq "message/rfc822" "$type/$subtype" eq "message/external-body" "$type/$subtype" eq "message/partial" defined $head->mime_attr("content-type.number") $head->mime_attr("content-type.number") == 1 $self->extract_nested_messages
Truth table22%2/9
A or B or C and D and E and F
A= "$type/$subtype" eq "message/rfc822"B= "$type/$subtype" eq "message/external-body"C= "$type/$subtype" eq "message/partial"D= defined $head->mime_attr("content-type.number")E= $head->mime_attr("content-type.number") == 1F= $self->extract_nested_messages
ABCDEFresult
000XXX0
0010XX0
00110X0
1XXXX00
01XXX00
0011100
1XXXX11
01XXX11
0011111
1072 "$type/$subtype" eq "message/external-body" ||
1073 ("$type/$subtype" eq "message/partial" && defined($head->mime_attr("content-type.number")) && $head->mime_attr("content-type.number") == 1)) &&
1074 $self->extract_nested_messages) {
1075 13 $self->debug("attempting to process a nested message");
1076 13 ▶ return undef unless defined($self->process_message($in, $rdr, $ent));
Branch: 1 branch
BranchTrueFalseTotal
unless defined $self->process_message($in, $rdr, $ent) 0 13 13
1077 }
1078 else {
1079 2160 $self->process_singlepart($in, $rdr, $ent);
1080 }
1081  
1082 ### Done (we hope!):
1083 3407 $self->results->level(-1);
1084 3407 return $ent;
1085 }
1086  
1087  
1088  
1089 =back
1090  
1091 =head2 Parsing an input source
1092  
1093 =over 4
1094  
1095 =cut
1096  
1097 #------------------------------
1098  
1099 =item parse_data DATA
1100  
1101 I<Instance method.>
1102 Parse a MIME message that's already in core. This internally creates an "in
1103 memory" filehandle on a Perl scalar value using PerlIO
1104  
1105 You may supply the DATA in any of a number of ways...
1106  
1107 =over 4
1108  
1109 =item *
1110  
1111 B<A scalar> which holds the message. A reference to this scalar will be used
1112 internally.
1113  
1114 =item *
1115  
1116 B<A ref to a scalar> which holds the message. This reference will be used
1117 internally.
1118  
1119 =item *
1120  
1121 B<DEPRECATED>
1122  
1123 B<A ref to an array of scalars.> The array is internally concatenated into a
1124 temporary string, and a reference to the new string is used internally.
1125  
1126 It is much more efficient to pass in a scalar reference, so please consider
1127 refactoring your code to use that interface instead. If you absolutely MUST
1128 pass an array, you may be better off using IO::ScalarArray in the calling code
1129 to generate a filehandle, and passing that filehandle to I<parse()>
1130  
1131 =back
1132  
1133 Returns the parsed MIME::Entity on success.
1134  
1135 =cut
1136  
1137 29 ▶sub parse_data {
Subroutine parse_data: called CC=6 SCAR=18.9
Pod documented
1138 29 my ($self, $data) = @_;
1139  
1140 29 ▶ if (!defined($data)) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $data) 0 29 29
1141 0 croak "parse_data: No data passed";
1142 }
1143  
1144 ### Get data as a scalar:
1145 29 my $io;
1146  
1147 29 ▶ if (! ref $data ) {
Branch: 3 branches
BranchTrueFalseTotal
if (not ref $data) { } 27 2 29
elsif (ref $data eq 'SCALAR') { } 1 1 2
elsif (ref $data eq 'ARRAY') { } 1 0 1
1148 27 $io = IO::File->new(\$data, '<:');
1149 } elsif( ref $data eq 'SCALAR' ) {
1150 1 $io = IO::File->new($data, '<:');
1151 } elsif( ref $data eq 'ARRAY' ) {
1152 # Passing arrays is deprecated now that we've nuked IO::ScalarArray
1153 # but for backwards compatibility we still support it by joining the
1154 # array lines to a scalar and doing scalar IO on it.
1155 1 my $tmp_data = join('', @$data);
1156 1 $io = IO::File->new(\$tmp_data, '<:');
1157 } else {
1158 0 croak "parse_data: wrong argument ref type: ", ref($data);
1159 }
1160  
1161 29 ▶ if (!$io) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($io) 0 29 29
1162 0 croak "parse_data: unable to open in-memory file handle";
1163 }
1164  
1165 ### Parse!
1166 29 return $self->parse($io);
1167 }
1168  
1169 #------------------------------
1170  
1171 =item parse INSTREAM
1172  
1173 I<Instance method.>
1174 Takes a MIME-stream and splits it into its component entities.
1175  
1176 The INSTREAM can be given as an IO::File, a globref filehandle (like
1177 C<\*STDIN>), or as I<any> blessed object conforming to the IO::
1178 interface (which minimally implements getline() and read()).
1179  
1180 Returns the parsed MIME::Entity on success.
1181 Throws exception on failure. If the message contained too many
1182 parts (as set by I<max_parts>) or was nested too deeply (as
1183 set by I<max_depth>), returns undef.
1184  
1185 =cut
1186  
1187 95 ▶sub parse {
Subroutine parse: called CC=1 SCAR=0.0
Pod documented
1188 95 my $self = shift;
1189 95 my $in = shift;
1190 95 my $entity;
1191 95 local $/ = "\n"; ### just to be safe
1192  
1193 95 local $\ = undef; # CPAN ticket #71041
1194 95 $self->init_parse;
1195 94 $entity = $self->process_part($in, undef); ### parse!
1196  
1197 94 $entity;
1198 }
1199  
1200 ### Backcompat:
1201 0 ▶sub read {
Subroutine read: not called CC=1 SCAR=6.9
Pod documented
1202 0 shift->parse(@_);
1203 }
1204 0 ▶sub parse_FH {
Subroutine parse_FH: not called CC=1 SCAR=6.9
Pod undocumented
1205 0 shift->parse(@_);
1206 }
1207  
1208 #------------------------------
1209  
1210 =item parse_open EXPR
1211  
1212 I<Instance method.>
1213 Convenience front-end onto C<parse()>.
1214 Simply give this method any expression that may be sent as the second
1215 argument to open() to open a filehandle for reading.
1216  
1217 Returns the parsed MIME::Entity on success.
1218 Throws exception on failure.
1219  
1220 =cut
1221  
1222 53 ▶sub parse_open {
Subroutine parse_open: called CC=3 SCAR=11.2
Pod documented
1223 53 my ($self, $expr) = @_;
1224 53 my $ent;
1225  
1226 53 ▶ my $io = IO::File->new($expr) or die "$ME: couldn't open $expr: $!";
Branch: 1 branch
BranchTrueFalseTotal
my $io = "IO::File"->new($expr) or die "${ME}: couldn't open ${expr}: $!" 53 0 53
1227 53 $ent = $self->parse($io);
1228 53 ▶ $io->close or die "$ME: can't close: $!";
Branch: 1 branch
BranchTrueFalseTotal
$io->close or die "${ME}: can't close: $!" 53 0 53
1229 53 $ent;
1230 }
1231  
1232 ### Backcompat:
1233 0 ▶sub parse_in {
Subroutine parse_in: not called CC=1 SCAR=6.9
Pod undocumented
1234 0 usage "parse_in() is now parse_open()";
1235 0 shift->parse_open(@_);
1236 }
1237  
1238 #------------------------------
1239  
1240 =item parse_two HEADFILE, BODYFILE
1241  
1242 I<Instance method.>
1243 Convenience front-end onto C<parse_open()>, intended for programs
1244 running under mail-handlers like B<deliver>, which splits the incoming
1245 mail message into a header file and a body file.
1246 Simply give this method the paths to the respective files.
1247  
1248 B<Warning:> it is assumed that, once the files are cat'ed together,
1249 there will be a blank line separating the head part and the body part.
1250  
1251 B<Warning:> new implementation slurps files into line array
1252 for portability, instead of using 'cat'. May be an issue if
1253 your messages are large.
1254  
1255 Returns the parsed MIME::Entity on success.
1256 Throws exception on failure.
1257  
1258 =cut
1259  
1260 1 ▶sub parse_two {
Subroutine parse_two: called CC=4 SCAR=14.0
Pod documented
1261 1 my ($self, $headfile, $bodyfile) = @_;
1262 1 my $data;
1263 1 foreach ($headfile, $bodyfile) {
1264 2 ▶ open IN, "<$_" or die "$ME: open $_: $!";
Branch: 1 branch
BranchTrueFalseTotal
open IN, "<$_" or die "${ME}: open ${_}: $!" 2 0 2
1265 2 $data .= do { local $/; <IN> };
1266 2 ▶ close IN or die "$ME: can't close: $!";
Branch: 1 branch
BranchTrueFalseTotal
close IN or die "${ME}: can't close: $!" 2 0 2
1267 }
1268 1 return $self->parse_data($data);
1269 }
1270  
1271 =back
1272  
1273 =cut
1274  
1275  
1276  
1277  
1278 #------------------------------------------------------------
1279  
1280 =head2 Specifying output destination
1281  
1282 B<Warning:> in 5.212 and before, this was done by methods
1283 of MIME::Parser. However, since many users have requested
1284 fine-tuned control over how this is done, the logic has been split
1285 off from the parser into its own class, MIME::Parser::Filer
1286 Every MIME::Parser maintains an instance of a MIME::Parser::Filer
1287 subclass to manage disk output (see L<MIME::Parser::Filer> for details.)
1288  
1289 The benefit to this is that the MIME::Parser code won't be
1290 confounded with a lot of garbage related to disk output.
1291 The drawback is that the way you override the default behavior
1292 will change.
1293  
1294 For now, all the normal public-interface methods are still provided,
1295 but many are only stubs which create or delegate to the underlying
1296 MIME::Parser::Filer object.
1297  
1298 =over 4
1299  
1300 =cut
1301  
1302 #------------------------------
1303  
1304 =item filer [FILER]
1305  
1306 I<Instance method.>
1307 Get/set the FILER object used to manage the output of files to disk.
1308 This will be some subclass of L<MIME::Parser::Filer|MIME::Parser::Filer>.
1309  
1310 =cut
1311  
1312 337 ▶sub filer {
Subroutine filer: called CC=2 SCAR=6.9
Pod documented
1313 337 my ($self, $filer) = @_;
1314 337 ▶ if (@_ > 1) {
Branch: 1 branch
BranchTrueFalseTotal
if (@_ > 1) 90 247 337
1315 90 $self->{MP5_Filer} = $filer;
1316 90 $filer->results($self->results); ### but we still need in init_parse
1317 }
1318 337 $self->{MP5_Filer};
1319 }
1320  
1321 #------------------------------
1322  
1323 =item output_dir DIRECTORY
1324  
1325 I<Instance method.>
1326 Causes messages to be filed directly into the given DIRECTORY.
1327 It does this by setting the underlying L<filer()|/filer> to
1328 a new instance of MIME::Parser::FileInto, and passing the arguments
1329 into that class' new() method.
1330  
1331 B<Note:> Since this method replaces the underlying
1332 filer, you must invoke it I<before> doing changing any attributes
1333 of the filer, like the output prefix; otherwise those changes
1334 will be lost.
1335  
1336 =cut
1337  
1338 91 ▶sub output_dir {
Subroutine output_dir: called CC=2 SCAR=6.9
Pod documented
1339 91 my ($self, @init) = @_;
1340 91 ▶ if (@_ > 1) {
Branch: 1 branch
BranchTrueFalseTotal
if (@_ > 1) { } 85 6 91
1341 85 $self->filer(MIME::Parser::FileInto->new(@init));
1342 }
1343 else {
1344 6 &MIME::Tools::whine("0-arg form of output_dir is deprecated.");
1345 6 return $self->filer->output_dir;
1346 }
1347 }
1348  
1349 #------------------------------
1350  
1351 =item output_under BASEDIR, OPTS...
1352  
1353 I<Instance method.>
1354 Causes messages to be filed directly into subdirectories of the given
1355 BASEDIR, one subdirectory per message. It does this by setting the
1356 underlying L<filer()|/filer> to a new instance of MIME::Parser::FileUnder,
1357 and passing the arguments into that class' new() method.
1358  
1359 B<Note:> Since this method replaces the underlying
1360 filer, you must invoke it I<before> doing changing any attributes
1361 of the filer, like the output prefix; otherwise those changes
1362 will be lost.
1363  
1364 =cut
1365  
1366 5 ▶sub output_under {
Subroutine output_under: called CC=2 SCAR=8.4
Pod documented
1367 5 my ($self, @init) = @_;
1368 5 ▶ if (@_ > 1) {
Branch: 1 branch
BranchTrueFalseTotal
if (@_ > 1) { } 5 0 5
1369 5 $self->filer(MIME::Parser::FileUnder->new(@init));
1370 }
1371 else {
1372 0 &MIME::Tools::whine("0-arg form of output_under is deprecated.");
1373 0 return $self->filer->output_dir;
1374 }
1375 }
1376  
1377 #------------------------------
1378  
1379 =item output_path HEAD
1380  
1381 I<Instance method, DEPRECATED.>
1382 Given a MIME head for a file to be extracted, come up with a good
1383 output pathname for the extracted file.
1384 Identical to the preferred form:
1385  
1386 $parser->filer->output_path(...args...);
1387  
1388 We just delegate this to the underlying L<filer()|/filer> object.
1389  
1390 =cut
1391  
1392 91 ▶sub output_path {
Subroutine output_path: called CC=1 SCAR=0.0
Pod documented
1393 91 my $self = shift;
1394 ### We use it, so don't warn!
1395 ### &MIME::Tools::whine("output_path deprecated in MIME::Parser");
1396 91 $self->filer->output_path(@_);
1397 }
1398  
1399 #------------------------------
1400  
1401 =item output_prefix [PREFIX]
1402  
1403 I<Instance method, DEPRECATED.>
1404 Get/set the short string that all filenames for extracted body-parts
1405 will begin with (assuming that there is no better "recommended filename").
1406 Identical to the preferred form:
1407  
1408 $parser->filer->output_prefix(...args...);
1409  
1410 We just delegate this to the underlying L<filer()|/filer> object.
1411  
1412 =cut
1413  
1414 0 ▶sub output_prefix {
Subroutine output_prefix: not called CC=1 SCAR=6.9
Pod documented
1415 0 my $self = shift;
1416 0 &MIME::Tools::whine("output_prefix deprecated in MIME::Parser");
1417 0 $self->filer->output_prefix(@_);
1418 }
1419  
1420 #------------------------------
1421  
1422 =item evil_filename NAME
1423  
1424 I<Instance method, DEPRECATED.>
1425 Identical to the preferred form:
1426  
1427 $parser->filer->evil_filename(...args...);
1428  
1429 We just delegate this to the underlying L<filer()|/filer> object.
1430  
1431 =cut
1432  
1433 2 ▶sub evil_filename {
Subroutine evil_filename: called CC=1 SCAR=0.0
Pod documented
1434 2 my $self = shift;
1435 2 &MIME::Tools::whine("evil_filename deprecated in MIME::Parser");
1436 2 $self->filer->evil_filename(@_);
1437 }
1438  
1439 #------------------------------
1440  
1441 =item max_parts NUM
1442  
1443 I<Instance method.>
1444 Limits the number of MIME parts we will parse.
1445  
1446 Messages with many MIME parts can cause excessive memory consumption,
1447 so parsing will abort and return undef if a message contains more
1448 than NUM parts. The default is 1000.
1449  
1450 If NUM is set to -1, then no maximum limit is enforced.
1451  
1452 With no argument, returns the current setting as an integer
1453  
1454 =cut
1455  
1456 4 ▶sub max_parts {
Subroutine max_parts: called CC=2 SCAR=7.0
Pod documented
1457 4 my($self, $num) = @_;
1458 4 ▶ if (@_ > 1) {
Branch: 1 branch
BranchTrueFalseTotal
if (@_ > 1) 4 0 4
1459 4 $self->{MP5_MaxParts} = $num;
1460 }
1461 4 return $self->{MP5_MaxParts};
1462 }
1463  
1464 =item max_depth NUM
1465  
1466 I<Instance method.>
1467 Limits the depth of nested MIME parts we will parse.
1468  
1469 Messages with many nested MIME parts can cause excessive memory
1470 consumption, so parsing will abort and return undef if a message is
1471 nested to a level more than NUM levels deep. The default is 64.
1472 Only multipart nesting counts; message/rfc822 parts nest within the
1473 limit set by max_parts.
1474  
1475 If NUM is set to -1, then no maximum limit is enforced.
1476  
1477 With no argument, returns the current setting as an integer
1478  
1479 =cut
1480  
1481 4 ▶sub max_depth {
Subroutine max_depth: called CC=2 SCAR=7.0
Pod documented
1482 4 my($self, $num) = @_;
1483 4 ▶ if (@_ > 1) {
Branch: 1 branch
BranchTrueFalseTotal
if (@_ > 1) 4 0 4
1484 4 $self->{MP5_MaxDepth} = $num;
1485 }
1486 4 return $self->{MP5_MaxDepth};
1487 }
1488  
1489 #------------------------------
1490  
1491 =item output_to_core YESNO
1492  
1493 I<Instance method.>
1494 Normally, instances of this class output all their decoded body
1495 data to disk files (via MIME::Body::File). However, you can change
1496 this behaviour by invoking this method before parsing:
1497  
1498 If YESNO is false (the default), then all body data goes
1499 to disk files.
1500  
1501 If YESNO is true, then all body data goes to in-core data structures
1502 This is a little risky (what if someone emails you an MPEG or a tar
1503 file, hmmm?) but people seem to want this bit of noose-shaped rope,
1504 so I'm providing it.
1505 Note that setting this attribute true I<does not> mean that parser-internal
1506 temporary files are avoided! Use L<tmp_to_core()|/tmp_to_core> for that.
1507  
1508 With no argument, returns the current setting as a boolean.
1509  
1510 =cut
1511  
1512 2222 ▶sub output_to_core {
Subroutine output_to_core: called CC=4 SCAR=13.9
Pod documented
1513 2222 my ($self, $yesno) = @_;
1514 2222 ▶ if (@_ > 1) {
Branch: 1 branch
BranchTrueFalseTotal
if (@_ > 1) 53 2169 2222
1515 53 ▶ $yesno = 0 if ($yesno and $yesno eq 'NONE');
Branch: 1 branch
BranchTrueFalseTotal
if $yesno and $yesno eq "NONE" 2 51 53
Condition100%3/3
$yesno and $yesno eq "NONE"
!ll&&!rl&&r
28232
MC/DC100%2/2
$yesno and $yesno eq "NONE"
$yesno $yesno eq "NONE"
Truth table100%3/3
A and B
A= $yesnoB= $yesno eq "NONE"
ABresult
0X0
100
111
1516 53 $self->{MP5_FilerToCore} = $yesno;
1517 }
1518 2222 $self->{MP5_FilerToCore};
1519 }
1520  
1521  
1522 =item tmp_recycling
1523  
1524 I<Instance method, DEPRECATED.>
1525  
1526 This method is a no-op to preserve the pre-5.421 API.
1527  
1528 The tmp_recycling() feature was removed in 5.421 because it had never actually
1529 worked. Please update your code to stop using it.
1530  
1531 =cut
1532  
1533 sub tmp_recycling
1534 1 ▶{
Subroutine tmp_recycling: called CC=1 SCAR=0.0
Pod documented
1535 1 return;
1536 }
1537  
1538  
1539  
1540 #------------------------------
1541  
1542 =item tmp_to_core [YESNO]
1543  
1544 I<Instance method.>
1545 Should L<new_tmpfile()|/new_tmpfile> create real temp files, or
1546 use fake in-core ones? Normally we allow the creation of temporary
1547 disk files, since this allows us to handle huge attachments even when
1548 core is limited.
1549  
1550 If YESNO is true, we implement new_tmpfile() via in-core handles.
1551 If YESNO is false (the default), we use real tmpfiles.
1552 With no argument, just returns the current setting.
1553  
1554 =cut
1555  
1556 0 ▶sub tmp_to_core {
Subroutine tmp_to_core: not called CC=2 SCAR=17.9
Pod documented
1557 0 my ($self, $yesno) = @_;
1558 0 ▶ $self->{MP5_TmpToCore} = $yesno if (@_ > 1);
Branch: 1 branch
BranchTrueFalseTotal
if @_ > 1 0 0 0
1559 0 $self->{MP5_TmpToCore};
1560 }
1561  
1562 #------------------------------
1563  
1564 =item use_inner_files [YESNO]
1565  
1566 I<REMOVED>.
1567  
1568 I<Instance method.>
1569  
1570 MIME::Parser no longer supports IO::InnerFile, but this method is retained for
1571 backwards compatibility. It does nothing.
1572  
1573 The original reasoning for IO::InnerFile was that inner files were faster than
1574 "in-core" temp files. At the time, the "in-core" tempfile support was
1575 implemented with IO::Scalar from the IO-Stringy distribution, which used the
1576 tie() interface to wrap a scalar with the appropriate IO::Handle operations.
1577 The penalty for this was fairly hefty, and IO::InnerFile actually was faster.
1578  
1579 Nowadays, MIME::Parser uses Perl's built in ability to open a filehandle on an
1580 in-memory scalar variable via PerlIO. Benchmarking shows that IO::InnerFile is
1581 slightly slower than using in-memory temporary files, and is slightly faster
1582 than on-disk temporary files. Both measurements are within a few percent of
1583 each other. Since there's no real benefit, and since the IO::InnerFile abuse
1584 was fairly hairy and evil ("writes" to it were faked by extending the size of
1585 the inner file with the assumption that the only data you'd ever ->print() to
1586 it would be the line from the "outer" file, for example) it's been removed.
1587  
1588 =cut
1589  
1590 0 ▶sub use_inner_files {
Subroutine use_inner_files: not called CC=1 SCAR=6.9
Pod documented
1591 0 return 0;
1592 }
1593  
1594 =back
1595  
1596 =cut
1597  
1598  
1599 #------------------------------------------------------------
1600  
1601 =head2 Specifying classes to be instantiated
1602  
1603 =over 4
1604  
1605 =cut
1606  
1607 #------------------------------
1608  
1609 =item interface ROLE,[VALUE]
1610  
1611 I<Instance method.>
1612 During parsing, the parser normally creates instances of certain classes,
1613 like MIME::Entity. However, you may want to create a parser subclass
1614 that uses your own experimental head, entity, etc. classes (for example,
1615 your "head" class may provide some additional MIME-field-oriented methods).
1616  
1617 If so, then this is the method that your subclass should invoke during
1618 init. Use it like this:
1619  
1620 package MyParser;
1621 @ISA = qw(MIME::Parser);
1622 ...
1623 sub init {
1624 my $self = shift;
1625 $self->SUPER::init(@_); ### do my parent's init
1626 $self->interface(ENTITY_CLASS => 'MIME::MyEntity');
1627 $self->interface(HEAD_CLASS => 'MIME::MyHead');
1628 $self; ### return
1629 }
1630  
1631 With no VALUE, returns the VALUE currently associated with that ROLE.
1632  
1633 =cut
1634  
1635 8064 ▶sub interface {
Subroutine interface: called CC=2 SCAR=6.9
Pod documented
1636 8064 my ($self, $role, $value) = @_;
1637 8064 ▶ $self->{MP5_Interface}{$role} = $value if (defined($value));
Branch: 1 branch
BranchTrueFalseTotal
if defined $value 110 7954 8064
1638 8064 $self->{MP5_Interface}{$role};
1639 }
1640  
1641 #------------------------------
1642  
1643 =item new_body_for HEAD
1644  
1645 I<Instance method.>
1646 Based on the HEAD of a part we are parsing, return a new
1647 body object (any desirable subclass of MIME::Body) for
1648 receiving that part's data.
1649  
1650 If you set the C<output_to_core> option to false before parsing
1651 (the default), then we call C<output_path()> and create a
1652 new MIME::Body::File on that filename.
1653  
1654 If you set the C<output_to_core> option to true before parsing,
1655 then you get a MIME::Body::InCore instead.
1656  
1657 If you want the parser to do something else entirely, you can
1658 override this method in a subclass.
1659  
1660 =cut
1661  
1662 2169 ▶sub new_body_for {
Subroutine new_body_for: called CC=2 SCAR=6.9
Pod documented
1663 2169 my ($self, $head) = @_;
1664  
1665 2169 ▶ if ($self->output_to_core) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->output_to_core) { } 2072 97 2169
1666 2072 $self->debug("outputting body to core");
1667 2072 return (new MIME::Body::InCore);
1668 }
1669 else {
1670 97 my $outpath = $self->output_path($head);
1671 97 $self->debug("outputting body to disk file: $outpath");
1672 97 $self->filer->purgeable($outpath); ### we plan to use it
1673 97 return (new MIME::Body::File $outpath);
1674 }
1675 }
1676  
1677 #------------------------------
1678  
1679 =pod
1680  
1681 =back
1682  
1683 =head2 Temporary File Creation
1684  
1685 =over
1686  
1687 =item tmp_dir DIRECTORY
1688  
1689 I<Instance method.>
1690 Causes any temporary files created by this parser to be created in the
1691 given DIRECTORY.
1692  
1693 If called without arguments, returns current value.
1694  
1695 The default value is undef, which will cause new_tmpfile() to use the
1696 system default temporary directory.
1697  
1698 =cut
1699  
1700 sub tmp_dir
1701 2140 ▶{
Subroutine tmp_dir: called CC=2 SCAR=7.6
Pod documented
1702 2140 my ($self, $dirname) = @_;
1703 2140 ▶ if ( $dirname ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($dirname) 0 2140 2140
1704 0 $self->{MP5_TmpDir} = $dirname;
1705 }
1706  
1707 2140 return $self->{MP5_TmpDir};
1708 }
1709  
1710 =item new_tmpfile
1711  
1712 I<Instance method.>
1713 Return an IO handle to be used to hold temporary data during a parse.
1714  
1715 The default uses MIME::Tools::tmpopen() to create a new temporary file,
1716 unless L<tmp_to_core()|/tmp_to_core> dictates otherwise, but you can
1717 override this. You shouldn't need to.
1718  
1719 The location for temporary files can be changed on a per-parser basis
1720 with L<tmp_dir()>.
1721  
1722 If you do override this, make certain that the object you return is
1723 set for binmode(), and is able to handle the following methods:
1724  
1725 read(BUF, NBYTES)
1726 getline()
1727 getlines()
1728 print(@ARGS)
1729 flush()
1730 seek(0, 0)
1731  
1732 Fatal exception if the stream could not be established.
1733  
1734 =cut
1735  
1736 2140 ▶sub new_tmpfile {
Subroutine new_tmpfile: called CC=6 SCAR=18.1
Pod documented
1737 2140 my ($self) = @_;
1738  
1739 2140 my $io;
1740 2140 ▶ if ($self->{MP5_TmpToCore}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{'MP5_TmpToCore'}) { } 1 2139 2140
1741 1 my $var;
1742 1 ▶ $io = IO::File->new(\$var, '+>:') or die "$ME: Can't open in-core tmpfile: $!";
Branch: 1 branch
BranchTrueFalseTotal
$io = "IO::File"->new(\$var, "+>:") or die "${ME}: Can't open in-core tmpfile: $!" 1 0 1
1743 } else {
1744 2139 my $args = {};
1745 2139 ▶ if( $self->tmp_dir ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->tmp_dir) 1 2138 2139
1746 1 $args->{DIR} = $self->tmp_dir;
1747 }
1748 2139 ▶ $io = tmpopen( $args ) or die "$ME: can't open tmpfile: $!\n";
Branch: 1 branch
BranchTrueFalseTotal
$io = tmpopen($args) or die "${ME}: can't open tmpfile: $!\n" 2139 0 2139
1749 2139 ▶ binmode($io) or die "$ME: can't set to binmode: $!";
Branch: 1 branch
BranchTrueFalseTotal
binmode $io or die "${ME}: can't set to binmode: $!" 2139 0 2139
1750 }
1751 2140 return $io;
1752 }
1753  
1754 =back
1755  
1756 =cut
1757  
1758  
1759  
1760  
1761  
1762  
1763 #------------------------------------------------------------
1764  
1765 =head2 Parse results and error recovery
1766  
1767 =over 4
1768  
1769 =cut
1770  
1771 #------------------------------
1772  
1773 =item last_error
1774  
1775 I<Instance method.>
1776 Return the error (if any) that we ignored in the last parse.
1777  
1778 =cut
1779  
1780 0 ▶sub last_error {
Subroutine last_error: not called CC=1 SCAR=6.9
Pod documented
1781 0 join '', shift->results->errors;
1782 }
1783  
1784 =item ambiguous_content
1785  
1786 I<Instance method.>
1787 Returns true if the most recently parsed message has one or more
1788 entities with ambiguous content. See the documentation of
1789 C<MIME::Entity>'s C<ambiguous_content> method for details.
1790  
1791 Note that while these two calls to ambuguous_content return the same
1792 thing:
1793  
1794 $entity = $parser->parse($whatever_stream);
1795 $parser->ambuguous_content();
1796 $entity->ambuguous_content();
1797  
1798 the former is faster because it simply returns the results that were
1799 detected during the parse, while the latter actually executes the code
1800 that checks for ambiguous content again.
1801  
1802 Messages with ambiguous content should be treated as a security risk.
1803 In particular, if MIME::Parser is used in an email security tool,
1804 ambiguous messages should not be delivered to end-users.
1805  
1806 =cut
1807 17 ▶sub ambiguous_content {
Subroutine ambiguous_content: called CC=1 SCAR=0.0
Pod documented
1808 17 my ($self) = @_;
1809 17 return $self->{MP5_AmbiguousContent};
1810 }
1811  
1812 #------------------------------
1813  
1814 =item last_head
1815  
1816 I<Instance method.>
1817 Return the top-level MIME header of the last stream we attempted to parse.
1818 This is useful for replying to people who sent us bad MIME messages.
1819  
1820 ### Parse an input stream:
1821 eval { $entity = $parser->parse(\*STDIN) };
1822 if (!$entity) { ### parse failed!
1823 my $decapitated = $parser->last_head;
1824 ...
1825 }
1826  
1827 =cut
1828  
1829 0 ▶sub last_head {
Subroutine last_head: not called CC=1 SCAR=6.9
Pod documented
1830 0 shift->results->top_head;
1831 }
1832  
1833 #------------------------------
1834  
1835 =item results
1836  
1837 I<Instance method.>
1838 Return an object containing lots of info from the last entity parsed.
1839 This will be an instance of class
1840 L<MIME::Parser::Results|MIME::Parser::Results>.
1841  
1842 =cut
1843  
1844 11567 ▶sub results {
Subroutine results: called CC=1 SCAR=0.0
Pod documented
1845 11567 shift->{MP5_Results};
1846 }
1847  
1848  
1849 =back
1850  
1851 =cut
1852  
1853  
1854 #------------------------------
1855 26 1;
1856 __END__
« Entity.pm ↑ Summary WordDecoder.pm »