Parser.pm

filter: Statementstmt 88.9% 419 / 471 Branchbran 68.6% 147 / 214 Conditioncond 65.4% 36 / 55 MC/DCmcdc 35.7% 10 / 28 Subroutinesub 82.5% 52 / 63 Podpod 70.8% 34 / 48 totaltotal 79.4% 698 / 879 CC 127 SCAR 25.1
CC
127
Cov
81%
decode_headers
30.0
hunt_for_uuencode
27.1
process_part
26.2
CRAP 12.3
« 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 22 require 5.004;
126  
127 ### Pragmas:
128 22 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
129 22 ▶use vars (qw($VERSION $CAT $CRLF));
Subroutine BEGIN: called CC=1 SCAR=0.0
130  
131 ### core Perl modules
132 22 ▶use IO::File;
Subroutine BEGIN: called CC=1 SCAR=0.0
133 22 ▶use File::Spec;
Subroutine BEGIN: called CC=1 SCAR=0.0
134 22 ▶use File::Path;
Subroutine BEGIN: called CC=1 SCAR=0.0
135 22 ▶use Config qw(%Config);
Subroutine BEGIN: called CC=1 SCAR=0.0
136 22 ▶use Carp;
Subroutine BEGIN: called CC=1 SCAR=0.0
137  
138 ### Kit modules:
139 22 ▶use MIME::Tools qw(:config :utils :msgtypes usage tmpopen );
Subroutine BEGIN: called CC=1 SCAR=0.0
140 22 ▶use MIME::Head;
Subroutine BEGIN: called CC=1 SCAR=0.0
141 22 ▶use MIME::Body;
Subroutine BEGIN: called CC=1 SCAR=0.0
142 22 ▶use MIME::Entity;
Subroutine BEGIN: called CC=1 SCAR=0.0
143 22 ▶use MIME::Decoder;
Subroutine BEGIN: called CC=1 SCAR=0.0
144 22 ▶use MIME::Parser::Reader;
Subroutine BEGIN: called CC=1 SCAR=0.0
145 22 ▶use MIME::Parser::Filer;
Subroutine BEGIN: called CC=1 SCAR=0.0
146 22 ▶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 22 $VERSION = "5.520";
156  
157 ### How to catenate:
158 22 $CAT = '/bin/cat';
159  
160 ### The CRLF sequence:
161 22 $CRLF = "\015\012";
162  
163 ### Who am I?
164 22 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 51 ▶sub new {
Subroutine new: called CC=1 SCAR=0.0
Pod documented
194 51 my $self = bless {}, shift;
195 51 $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 51 ▶sub init {
Subroutine init: called CC=1 SCAR=0.0
Pod documented
210 51 my $self = shift;
211  
212 51 $self->{MP5_DecodeHeaders} = 0;
213 51 $self->{MP5_DecodeBodies} = 1;
214 51 $self->{MP5_Interface} = {};
215 51 $self->{MP5_ParseNested} = 'NEST';
216 51 $self->{MP5_TmpToCore} = 0;
217 51 $self->{MP5_IgnoreErrors} = 1;
218 51 $self->{MP5_UUDecode} = 0;
219 51 $self->{MP5_MaxParts} = -1;
220 51 $self->{MP5_MaxDepth} = -1;
221 51 $self->{MP5_TmpDir} = undef;
222 51 $self->{MP5_AmbiguousContent} = 0;
223  
224 51 $self->interface(ENTITY_CLASS => 'MIME::Entity');
225 51 $self->interface(HEAD_CLASS => 'MIME::Head');
226  
227 51 $self->output_dir(".");
228  
229 51 $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 78 ▶sub init_parse {
Subroutine init_parse: called CC=1 SCAR=0.0
Pod documented
243 78 my $self = shift;
244  
245 78 $self->{MP5_Results} = new MIME::Parser::Results;
246  
247 78 $self->{MP5_Filer}->results($self->{MP5_Results});
248 78 $self->{MP5_Filer}->purgeable([]);
249 78 $self->{MP5_Filer}->init_parse();
250 78 $self->{MP5_NumParts} = 0;
251 78 $self->{MP5_AmbiguousContent} = 0;
252 78 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 327 ▶sub extract_uuencode {
Subroutine extract_uuencode: called CC=2 SCAR=6.9
Pod documented
421 327 my ($self, $yesno) = @_;
422 327 ▶ $self->{MP5_UUDecode} = $yesno if @_ > 1;
Branch: 1 branch
BranchTrueFalseTotal
if @_ > 1 25 302 327
423 327 $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 343 ▶sub decode_bodies {
Subroutine decode_bodies: called CC=2 SCAR=6.9
Pod documented
474 343 my ($self, $yesno) = @_;
475 343 ▶ $self->{MP5_DecodeBodies} = $yesno if (@_ > 1);
Branch: 1 branch
BranchTrueFalseTotal
if @_ > 1 3 340 343
476 343 $self->{MP5_DecodeBodies};
477 }
478  
479 #------------------------------
480 #
481 # MESSAGES...
482 #
483  
484 #------------------------------
485 #
486 # debug MESSAGE...
487 #
488 8645 ▶sub debug {
Subroutine debug: called CC=3 SCAR=18.1
Pod undocumented
489 8645 my $self = shift;
490 8645 ▶ if (MIME::Tools->debugging()) {
Branch: 1 branch
BranchTrueFalseTotal
if ("MIME::Tools"->debugging) 0 8645 8645
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 6 ▶sub whine {
Subroutine whine: called CC=2 SCAR=7.0
Pod undocumented
504 6 my $self = shift;
505 6 ▶ if (my $r = $self->{MP5_Results}) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $r = $self->{"MP5_Results"}) 6 0 6
506 6 unshift @_, $r->indent;
507 6 $r->msg($M_WARNING, @_);
508 }
509 6 &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 11 ▶sub error {
Subroutine error: called CC=3 SCAR=11.2
Pod documented
520 11 my $self = shift;
521 11 ▶ if (my $r = $self->{MP5_Results}) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $r = $self->{"MP5_Results"}) 11 0 11
522 11 unshift @_, $r->indent;
523 11 $r->msg($M_ERROR, @_);
524 }
525 11 &MIME::Tools::error(@_);
526 11 ▶ $self->{MP5_IgnoreErrors} ? return undef : die @_;
Branch: 1 branch
BranchTrueFalseTotal
$self->{'MP5_IgnoreErrors'} ? : 11 0 11
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 1559 ▶sub process_preamble {
Subroutine process_preamble: called CC=4 SCAR=13.9
Pod undocumented
545 1559 my ($self, $in, $rdr, $ent) = @_;
546  
547 ### Sanity:
548 1559 ▶ ($rdr->has_bounds) or die "$ME: internal logic error";
Branch: 1 branch
BranchTrueFalseTotal
$rdr->has_bounds or die "${ME}: internal logic error" 1559 0 1559
549  
550 ### Parse preamble:
551 1559 my @saved;
552 1559 my $data = '';
553 1559 ▶ open(my $fh, '>', \$data) or die $!;
Branch: 1 branch
BranchTrueFalseTotal
open my $fh, ">", \$data or die $! 1559 0 1559
554 1559 $rdr->read_chunk($in, $fh, 1);
555 1559 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 1559 ▶ if( $data =~ m/^(\r\n|\n\r|\n|\r)\z/ ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($data =~ /^(\r\n|\n\r|\n|\r)\z/) { } 4 1555 1559
560 4 @saved = ('');
561 } else {
562 1555 $data =~ s/(\r\n|\n\r|\n|\r)\z//;
563 1555 @saved = split(/^/, $data);
564 }
565 1559 $ent->preamble(\@saved);
566 1559 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 1055 ▶sub process_epilogue {
Subroutine process_epilogue: called CC=1 SCAR=0.0
Pod undocumented
577 1055 my ($self, $in, $rdr, $ent) = @_;
578 1055 $self->debug("process_epilogue");
579  
580 ### Parse epilogue:
581 1055 my @saved;
582 1055 $rdr->read_lines($in, \@saved);
583 1055 $ent->epilogue(\@saved);
584 1055 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 130 ▶sub process_to_bound {
Subroutine process_to_bound: called CC=1 SCAR=0.0
Pod undocumented
595 130 my ($self, $in, $rdr, $out) = @_;
596  
597 ### Parse:
598 130 $rdr->read_chunk($in, $out);
599 130 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 1726 ▶sub process_header {
Subroutine process_header: called CC=8 SCAR=21.0
Pod undocumented
612 1726 my ($self, $in, $rdr) = @_;
613 1726 $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 1726 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 1726 my @headlines;
622 1726 my $hdr_rdr = $rdr->spawn;
623 1726 $hdr_rdr->add_terminator("");
624 1726 $hdr_rdr->add_terminator("\r"); ### sigh
625  
626 1726 my $headstr = '';
627 1726 ▶ open(my $outfh, '>:scalar', \$headstr) or die $!;
Branch: 1 branch
BranchTrueFalseTotal
open my $outfh, ">:scalar", \$headstr or die $! 1726 0 1726
628 1726 $hdr_rdr->read_chunk($in, $outfh, 0, 1);
629 1726 close $outfh;
630  
631 ### How did we do?
632 1726 ▶ if ($hdr_rdr->eos_type eq 'DELIM') {
Branch: 1 branch
BranchTrueFalseTotal
if ($hdr_rdr->eos_type eq "DELIM") 2 1724 1726
633 2 $self->whine("bogus part, without CRLF before body");
634 2 return undef;
635 }
636 1724 ▶ ($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") 1723 1 1724
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 1724 $hdr_rdr = undef;
642  
643 ### If header line begins with a UTF-8 Byte-Order mark, remove it.
644 1724 $headstr =~ s/^\x{EF}\x{BB}\x{BF}//;
645  
646 ### Extract the header (note that zero-size headers are admissible!):
647 1724 ▶ open(my $readfh, '<:scalar', \$headstr) or die $!;
Branch: 1 branch
BranchTrueFalseTotal
open my $readfh, "<:scalar", \$headstr or die $! 1724 0 1724
648 1724 $head->read( $readfh );
649  
650 1724 ▶ unless( $readfh->eof() ) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($readfh->eof) 0 1724 1724
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 1724 ▶ $head->decode($self->{MP5_DecodeHeaders}) if $self->{MP5_DecodeHeaders};
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"MP5_DecodeHeaders"} 0 1724 1724
662  
663 ### If this is the top-level head, save it:
664 1724 ▶ $self->results->top_head($head) if !$self->results->top_head;
Branch: 1 branch
BranchTrueFalseTotal
unless $self->results->top_head 78 1646 1724
665  
666 1724 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 1561 ▶sub process_multipart {
Subroutine process_multipart: called CC=12 SCAR=24.8
Pod undocumented
679 1561 my ($self, $in, $rdr, $ent) = @_;
680 1561 my $head = $ent->head;
681  
682 1561 $self->debug("process_multipart...");
683  
684 ### Get actual type and subtype from the header:
685 1561 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 1561 ▶ my $retype = (($subtype eq 'digest') ? 'message/rfc822' : '');
Branch: 1 branch
BranchTrueFalseTotal
$subtype eq 'digest' ? : 1 1560 1561
691  
692 ### Get the boundaries for the parts:
693 1561 my $bound = $head->multipart_boundary;
694 1561 ▶ if (!defined($bound) || ($bound =~ /[\r\n]/)) {
Branch: 1 branch
BranchTrueFalseTotal
if (not defined $bound or $bound =~ /[\r\n]/) 1 1560 1561
Condition66%2/3
not defined $bound or $bound =~ /[\r\n]/
l!l&&r!l&&!r
101560
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 1 $self->error("multipart boundary is missing, or contains CR or LF\n");
696 1 $ent->effective_type("application/x-unparseable-multipart");
697 1 return $self->process_singlepart($in, $rdr, $ent);
698 }
699 1560 my $part_rdr = $rdr->spawn->add_boundary($bound);
700  
701 1560 ▶ 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"}) 1 1559 1560
Condition100%3/3
$self->{"MP5_MaxDepth"} > 0 and $part_rdr->depth > $self->{"MP5_MaxDepth"}
!ll&&!rl&&r
5609991
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 1 $self->error("MIME parts nested too deeply");
703 1 return undef;
704 }
705 ### Prepare to parse:
706 1559 my $eos_type;
707 my $more_parts;
708  
709 ### Parse preamble...
710 1559 $self->process_preamble($in, $part_rdr, $ent);
711  
712 ### ...and look at how we finished up:
713 1559 $eos_type = $part_rdr->eos_type;
714 1559 ▶ if ($eos_type eq 'DELIM'){ $more_parts = 1 }
Branch: 2 branches
BranchTrueFalseTotal
if ($eos_type eq 'DELIM') { } 1556 3 1559
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 1557 my $partno = 0;
722 1557 my $part;
723 1557 ▶ while ($more_parts) {
Branch: 1 branch
BranchTrueFalseTotal
if ($more_parts) 1635 1055 2690
724 1635 ++$partno;
725 1635 $self->debug("parsing part $partno...");
726  
727 ### Parse the next part, and add it to the entity...
728 1635 my $part = $self->process_part($in, $part_rdr, Retype=>$retype);
729 1635 ▶ return undef unless defined($part);
Branch: 1 branch
BranchTrueFalseTotal
unless defined $part 499 1136 1635
730  
731 1136 $ent->add_part($part);
732  
733 ### ...and look at how we finished up:
734 1136 $eos_type = $part_rdr->eos_type;
735 1136 ▶ if ($eos_type eq 'DELIM') { $more_parts = 1 }
Branch: 2 branches
BranchTrueFalseTotal
if ($eos_type eq 'DELIM') { } 79 1057 1136
elsif ($eos_type eq 'CLOSE') { } 1054 3 1057
736 1054 elsif ($eos_type eq 'CLOSE') { $more_parts = 0; }
737 3 else { $self->error("unexpected end of parts ".
738 "before epilogue\n");
739 3 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 1055 $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 1055 $self->process_epilogue($in, $rdr, $ent);
751  
752 ### ...and there's no need to look at how we finished up!
753 1055 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 151 ▶sub process_singlepart {
Subroutine process_singlepart: called CC=22 SCAR=31.9
Pod undocumented
766 151 my ($self, $in, $rdr, $ent) = @_;
767 151 my $head = $ent->head;
768  
769 151 $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 151 my $ENCODED; ### handle
775 151 ▶ my $can_shortcut = (!$rdr->has_bounds and !$self->{MP5_UUDecode});
Condition100%3/3
$rdr->has_bounds || $self->{'MP5_UUDecode'}
l!l&&r!l&&!r
129121
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 151 ▶ if ($can_shortcut) {
Branch: 1 branch
BranchTrueFalseTotal
if ($can_shortcut) { } 21 130 151
777 21 $self->debug("taking shortcut");
778  
779 21 $ENCODED = $in;
780 21 $rdr->eos('EOF'); ### be sure to bogus-up the reader state to EOF:
781 }
782 else {
783  
784 130 $self->debug("using temp file");
785 130 $ENCODED = $self->new_tmpfile();
786  
787 ### Read encoded body until boundary (or EOF)...
788 130 $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 130 ▶ if ($rdr->has_bounds) {
Branch: 1 branch
BranchTrueFalseTotal
if ($rdr->has_bounds) 129 1 130
794 129 ▶ ($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") 126 3 129
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 130 ▶ $ENCODED->flush or die "$ME: can't flush: $!";
Branch: 1 branch
BranchTrueFalseTotal
$ENCODED->flush or die "${ME}: can't flush: $!" 130 0 130
800 130 ▶ $ENCODED->seek(0, 0) or die "$ME: can't seek: $!";
Branch: 1 branch
BranchTrueFalseTotal
$ENCODED->seek(0, 0) or die "${ME}: can't seek: $!" 130 0 130
801 }
802  
803 ### Get a content-decoder to decode this part's encoding:
804 151 my $encoding = $head->mime_encoding;
805 151 my $decoder = new MIME::Decoder $encoding;
806 151 ▶ if (!$decoder) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($decoder) 0 151 151
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 151 ▶ if ( !$self->decode_bodies ) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($self->decode_bodies) 7 144 151
817 7 $decoder = new MIME::Decoder 'binary';
818 7 $encoding = 'binary';
819 }
820  
821 ### If desired, sidetrack to troll for UUENCODE:
822 151 $self->debug("extract uuencode? ", $self->extract_uuencode);
823 151 $self->debug("encoding? ", $encoding);
824 151 $self->debug("effective type? ", $ent->effective_type);
825  
826 151 ▶ 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 148 151
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
14803
$self->extract_uuencode and $encoding =~ /^(7bit|8bit|binary)\Z/
!ll&&!rl&&r
14803
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 149 ▶ 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" 149 0 149
844 149 ▶ $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 39 110 149
Condition75%6/8
textual_type($ent->effective_type) || !$self->decode_bodies || ($body->binmode(1) || die("${ME}: can't set to binmode: $!"))
l!l
110390
textual_type($ent->effective_type) or not $self->decode_bodies
l!l&&r!l&&!r
109139
$body->binmode(1) or die "${ME}: can't set to binmode: $!"
l!l
390
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 149 ▶ $body->is_encoded(1) if !$self->decode_bodies;
Branch: 1 branch
BranchTrueFalseTotal
unless $self->decode_bodies 7 142 149
847  
848 ### Decode and save the body (using the decoder):
849 149 ▶ 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: $!" 149 0 149
850 149 eval { $decoder->decode($ENCODED, $DECODED); };
851 149 ▶ $@ and $self->error($@);
Branch: 1 branch
BranchTrueFalseTotal
$@ and $self->error($@) 0 149 149
852 149 ▶ $DECODED->close or die "$ME: can't close: $!";
Branch: 1 branch
BranchTrueFalseTotal
$DECODED->close or die "${ME}: can't close: $!" 149 0 149
853  
854 ### Success! Remember where we put stuff:
855 149 $ent->bodyhandle($body);
856  
857 ### Done!
858 149 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 1726 ▶sub process_part {
Subroutine process_part: called CC=20 SCAR=32.7
Pod undocumented
1016 1726 my ($self, $in, $rdr, %p) = @_;
1017  
1018 1726 ▶ if ($self->{MP5_MaxParts} > 0) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"MP5_MaxParts"} > 0) 0 1726 1726
1019 0 $self->{MP5_NumParts}++;
1020 0 ▶ if ($self->{MP5_NumParts} > $self->{MP5_MaxParts}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"MP5_NumParts"} > $self->{"MP5_MaxParts"}) 0 0 0
1021 0 $self->error("Too many MIME parts");
1022 # Return UNDEF if msg too complex
1023 0 return undef;
1024 }
1025 }
1026  
1027 1726 ▶ $rdr ||= MIME::Parser::Reader->new;
Condition66%2/3
$rdr ||= "MIME::Parser::Reader"->new
l!l&&r!l&&!r
1648780
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
1028 #debug "process_part";
1029 1726 $self->results->level(+1);
1030  
1031 ### Create a new entity:
1032 1726 my $ent = $self->interface('ENTITY_CLASS')->new;
1033  
1034 ### Parse and add the header:
1035 1726 my $head = $self->process_header($in, $rdr);
1036 1726 ▶ if (not defined $head) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $head) 2 1724 1726
1037 2 $self->debug("bogus empty part");
1038 2 $head = $self->interface('HEAD_CLASS')->new;
1039 2 $head->mime_type('text/plain');
1040 2 $ent->head($head);
1041 2 $ent->bodyhandle($self->new_body_for($head));
1042 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
1043 2 ▶ if (!$self->{MP5_AmbiguousContent}) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($self->{"MP5_AmbiguousContent"}) 2 0 2
1044 2 ▶ if ($ent->head->ambiguous_content) {
Branch: 1 branch
BranchTrueFalseTotal
if ($ent->head->ambiguous_content) 0 2 2
1045 0 $self->{MP5_AmbiguousContent} = 1;
1046 }
1047 }
1048 2 $self->results->level(-1);
1049 2 return $ent;
1050 }
1051 1724 $ent->head($head);
1052  
1053 ### Tweak the content-type based on context from our parent...
1054 ### For example, multipart/digest messages default to type message/rfc822:
1055 1724 ▶ $head->mime_type($p{Retype}) if $p{Retype};
Branch: 1 branch
BranchTrueFalseTotal
if $p{"Retype"} 2 1722 1724
1056  
1057 # We have the header, so that's enough to check for
1058 # ambiguous content...
1059 1724 ▶ if (!$self->{MP5_AmbiguousContent}) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($self->{"MP5_AmbiguousContent"}) 1711 13 1724
1060 1711 ▶ if ($ent->head->ambiguous_content) {
Branch: 1 branch
BranchTrueFalseTotal
if ($ent->head->ambiguous_content) 16 1695 1711
1061 16 $self->{MP5_AmbiguousContent} = 1;
1062 }
1063 }
1064 ### Get the MIME type and subtype:
1065 1724 my ($type, $subtype) = (split('/', $head->mime_type, -1), '');
1066 1724 $self->debug("type = $type, subtype = $subtype");
1067  
1068 ### Handle, according to the MIME type:
1069 1724 ▶ if ($type eq 'multipart') {
Branch: 2 branches
BranchTrueFalseTotal
if ($type eq 'multipart') { } 1561 163 1724
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 150 163
1070 1561 ▶ return undef unless defined($self->process_multipart($in, $rdr, $ent));
Branch: 1 branch
BranchTrueFalseTotal
unless defined $self->process_multipart($in, $rdr, $ent) 500 1061 1561
1071 }
1072 ▶ 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
150013
"$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
130150
"$type/$subtype" eq "message/rfc822" or "$type/$subtype" eq "message/external-body"
l!l&&r!l&&!r
130150
"$type/$subtype" eq "message/partial" and defined $head->mime_attr("content-type.number") and $head->mime_attr("content-type.number") == 1
!ll&&!rl&&r
15000
"$type/$subtype" eq "message/partial" and defined $head->mime_attr("content-type.number")
!ll&&!rl&&r
15000
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
1073 "$type/$subtype" eq "message/external-body" ||
1074 ("$type/$subtype" eq "message/partial" && defined($head->mime_attr("content-type.number")) && $head->mime_attr("content-type.number") == 1)) &&
1075 $self->extract_nested_messages) {
1076 13 $self->debug("attempting to process a nested message");
1077 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
1078 }
1079 else {
1080 150 $self->process_singlepart($in, $rdr, $ent);
1081 }
1082  
1083 ### Done (we hope!):
1084 1224 $self->results->level(-1);
1085 1224 return $ent;
1086 }
1087  
1088  
1089  
1090 =back
1091  
1092 =head2 Parsing an input source
1093  
1094 =over 4
1095  
1096 =cut
1097  
1098 #------------------------------
1099  
1100 =item parse_data DATA
1101  
1102 I<Instance method.>
1103 Parse a MIME message that's already in core. This internally creates an "in
1104 memory" filehandle on a Perl scalar value using PerlIO
1105  
1106 You may supply the DATA in any of a number of ways...
1107  
1108 =over 4
1109  
1110 =item *
1111  
1112 B<A scalar> which holds the message. A reference to this scalar will be used
1113 internally.
1114  
1115 =item *
1116  
1117 B<A ref to a scalar> which holds the message. This reference will be used
1118 internally.
1119  
1120 =item *
1121  
1122 B<DEPRECATED>
1123  
1124 B<A ref to an array of scalars.> The array is internally concatenated into a
1125 temporary string, and a reference to the new string is used internally.
1126  
1127 It is much more efficient to pass in a scalar reference, so please consider
1128 refactoring your code to use that interface instead. If you absolutely MUST
1129 pass an array, you may be better off using IO::ScalarArray in the calling code
1130 to generate a filehandle, and passing that filehandle to I<parse()>
1131  
1132 =back
1133  
1134 Returns the parsed MIME::Entity on success.
1135  
1136 =cut
1137  
1138 13 ▶sub parse_data {
Subroutine parse_data: called CC=6 SCAR=18.9
Pod documented
1139 13 my ($self, $data) = @_;
1140  
1141 13 ▶ if (!defined($data)) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $data) 0 13 13
1142 0 croak "parse_data: No data passed";
1143 }
1144  
1145 ### Get data as a scalar:
1146 13 my $io;
1147  
1148 13 ▶ if (! ref $data ) {
Branch: 3 branches
BranchTrueFalseTotal
if (not ref $data) { } 11 2 13
elsif (ref $data eq 'SCALAR') { } 1 1 2
elsif (ref $data eq 'ARRAY') { } 1 0 1
1149 11 $io = IO::File->new(\$data, '<:');
1150 } elsif( ref $data eq 'SCALAR' ) {
1151 1 $io = IO::File->new($data, '<:');
1152 } elsif( ref $data eq 'ARRAY' ) {
1153 # Passing arrays is deprecated now that we've nuked IO::ScalarArray
1154 # but for backwards compatibility we still support it by joining the
1155 # array lines to a scalar and doing scalar IO on it.
1156 1 my $tmp_data = join('', @$data);
1157 1 $io = IO::File->new(\$tmp_data, '<:');
1158 } else {
1159 0 croak "parse_data: wrong argument ref type: ", ref($data);
1160 }
1161  
1162 13 ▶ if (!$io) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($io) 0 13 13
1163 0 croak "parse_data: unable to open in-memory file handle";
1164 }
1165  
1166 ### Parse!
1167 13 return $self->parse($io);
1168 }
1169  
1170 #------------------------------
1171  
1172 =item parse INSTREAM
1173  
1174 I<Instance method.>
1175 Takes a MIME-stream and splits it into its component entities.
1176  
1177 The INSTREAM can be given as an IO::File, a globref filehandle (like
1178 C<\*STDIN>), or as I<any> blessed object conforming to the IO::
1179 interface (which minimally implements getline() and read()).
1180  
1181 Returns the parsed MIME::Entity on success.
1182 Throws exception on failure. If the message contained too many
1183 parts (as set by I<max_parts>) or was nested too deeply (as
1184 set by I<max_depth>), returns undef.
1185  
1186 =cut
1187  
1188 78 ▶sub parse {
Subroutine parse: called CC=1 SCAR=0.0
Pod documented
1189 78 my $self = shift;
1190 78 my $in = shift;
1191 78 my $entity;
1192 78 local $/ = "\n"; ### just to be safe
1193  
1194 78 local $\ = undef; # CPAN ticket #71041
1195 78 $self->init_parse;
1196 78 $entity = $self->process_part($in, undef); ### parse!
1197  
1198 78 $entity;
1199 }
1200  
1201 ### Backcompat:
1202 0 ▶sub read {
Subroutine read: not called CC=1 SCAR=6.9
Pod documented
1203 0 shift->parse(@_);
1204 }
1205 0 ▶sub parse_FH {
Subroutine parse_FH: not called CC=1 SCAR=6.9
Pod undocumented
1206 0 shift->parse(@_);
1207 }
1208  
1209 #------------------------------
1210  
1211 =item parse_open EXPR
1212  
1213 I<Instance method.>
1214 Convenience front-end onto C<parse()>.
1215 Simply give this method any expression that may be sent as the second
1216 argument to open() to open a filehandle for reading.
1217  
1218 Returns the parsed MIME::Entity on success.
1219 Throws exception on failure.
1220  
1221 =cut
1222  
1223 52 ▶sub parse_open {
Subroutine parse_open: called CC=3 SCAR=11.2
Pod documented
1224 52 my ($self, $expr) = @_;
1225 52 my $ent;
1226  
1227 52 ▶ 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}: $!" 52 0 52
1228 52 $ent = $self->parse($io);
1229 52 ▶ $io->close or die "$ME: can't close: $!";
Branch: 1 branch
BranchTrueFalseTotal
$io->close or die "${ME}: can't close: $!" 52 0 52
1230 52 $ent;
1231 }
1232  
1233 ### Backcompat:
1234 0 ▶sub parse_in {
Subroutine parse_in: not called CC=1 SCAR=6.9
Pod undocumented
1235 0 usage "parse_in() is now parse_open()";
1236 0 shift->parse_open(@_);
1237 }
1238  
1239 #------------------------------
1240  
1241 =item parse_two HEADFILE, BODYFILE
1242  
1243 I<Instance method.>
1244 Convenience front-end onto C<parse_open()>, intended for programs
1245 running under mail-handlers like B<deliver>, which splits the incoming
1246 mail message into a header file and a body file.
1247 Simply give this method the paths to the respective files.
1248  
1249 B<Warning:> it is assumed that, once the files are cat'ed together,
1250 there will be a blank line separating the head part and the body part.
1251  
1252 B<Warning:> new implementation slurps files into line array
1253 for portability, instead of using 'cat'. May be an issue if
1254 your messages are large.
1255  
1256 Returns the parsed MIME::Entity on success.
1257 Throws exception on failure.
1258  
1259 =cut
1260  
1261 1 ▶sub parse_two {
Subroutine parse_two: called CC=4 SCAR=14.0
Pod documented
1262 1 my ($self, $headfile, $bodyfile) = @_;
1263 1 my $data;
1264 1 foreach ($headfile, $bodyfile) {
1265 2 ▶ open IN, "<$_" or die "$ME: open $_: $!";
Branch: 1 branch
BranchTrueFalseTotal
open IN, "<$_" or die "${ME}: open ${_}: $!" 2 0 2
1266 2 $data .= do { local $/; <IN> };
1267 2 ▶ close IN or die "$ME: can't close: $!";
Branch: 1 branch
BranchTrueFalseTotal
close IN or die "${ME}: can't close: $!" 2 0 2
1268 }
1269 1 return $self->parse_data($data);
1270 }
1271  
1272 =back
1273  
1274 =cut
1275  
1276  
1277  
1278  
1279 #------------------------------------------------------------
1280  
1281 =head2 Specifying output destination
1282  
1283 B<Warning:> in 5.212 and before, this was done by methods
1284 of MIME::Parser. However, since many users have requested
1285 fine-tuned control over how this is done, the logic has been split
1286 off from the parser into its own class, MIME::Parser::Filer
1287 Every MIME::Parser maintains an instance of a MIME::Parser::Filer
1288 subclass to manage disk output (see L<MIME::Parser::Filer> for details.)
1289  
1290 The benefit to this is that the MIME::Parser code won't be
1291 confounded with a lot of garbage related to disk output.
1292 The drawback is that the way you override the default behavior
1293 will change.
1294  
1295 For now, all the normal public-interface methods are still provided,
1296 but many are only stubs which create or delegate to the underlying
1297 MIME::Parser::Filer object.
1298  
1299 =over 4
1300  
1301 =cut
1302  
1303 #------------------------------
1304  
1305 =item filer [FILER]
1306  
1307 I<Instance method.>
1308 Get/set the FILER object used to manage the output of files to disk.
1309 This will be some subclass of L<MIME::Parser::Filer|MIME::Parser::Filer>.
1310  
1311 =cut
1312  
1313 329 ▶sub filer {
Subroutine filer: called CC=2 SCAR=6.9
Pod documented
1314 329 my ($self, $filer) = @_;
1315 329 ▶ if (@_ > 1) {
Branch: 1 branch
BranchTrueFalseTotal
if (@_ > 1) 84 245 329
1316 84 $self->{MP5_Filer} = $filer;
1317 84 $filer->results($self->results); ### but we still need in init_parse
1318 }
1319 329 $self->{MP5_Filer};
1320 }
1321  
1322 #------------------------------
1323  
1324 =item output_dir DIRECTORY
1325  
1326 I<Instance method.>
1327 Causes messages to be filed directly into the given DIRECTORY.
1328 It does this by setting the underlying L<filer()|/filer> to
1329 a new instance of MIME::Parser::FileInto, and passing the arguments
1330 into that class' new() method.
1331  
1332 B<Note:> Since this method replaces the underlying
1333 filer, you must invoke it I<before> doing changing any attributes
1334 of the filer, like the output prefix; otherwise those changes
1335 will be lost.
1336  
1337 =cut
1338  
1339 87 ▶sub output_dir {
Subroutine output_dir: called CC=2 SCAR=6.9
Pod documented
1340 87 my ($self, @init) = @_;
1341 87 ▶ if (@_ > 1) {
Branch: 1 branch
BranchTrueFalseTotal
if (@_ > 1) { } 81 6 87
1342 81 $self->filer(MIME::Parser::FileInto->new(@init));
1343 }
1344 else {
1345 6 &MIME::Tools::whine("0-arg form of output_dir is deprecated.");
1346 6 return $self->filer->output_dir;
1347 }
1348 }
1349  
1350 #------------------------------
1351  
1352 =item output_under BASEDIR, OPTS...
1353  
1354 I<Instance method.>
1355 Causes messages to be filed directly into subdirectories of the given
1356 BASEDIR, one subdirectory per message. It does this by setting the
1357 underlying L<filer()|/filer> to a new instance of MIME::Parser::FileUnder,
1358 and passing the arguments into that class' new() method.
1359  
1360 B<Note:> Since this method replaces the underlying
1361 filer, you must invoke it I<before> doing changing any attributes
1362 of the filer, like the output prefix; otherwise those changes
1363 will be lost.
1364  
1365 =cut
1366  
1367 3 ▶sub output_under {
Subroutine output_under: called CC=2 SCAR=8.4
Pod documented
1368 3 my ($self, @init) = @_;
1369 3 ▶ if (@_ > 1) {
Branch: 1 branch
BranchTrueFalseTotal
if (@_ > 1) { } 3 0 3
1370 3 $self->filer(MIME::Parser::FileUnder->new(@init));
1371 }
1372 else {
1373 0 &MIME::Tools::whine("0-arg form of output_under is deprecated.");
1374 0 return $self->filer->output_dir;
1375 }
1376 }
1377  
1378 #------------------------------
1379  
1380 =item output_path HEAD
1381  
1382 I<Instance method, DEPRECATED.>
1383 Given a MIME head for a file to be extracted, come up with a good
1384 output pathname for the extracted file.
1385 Identical to the preferred form:
1386  
1387 $parser->filer->output_path(...args...);
1388  
1389 We just delegate this to the underlying L<filer()|/filer> object.
1390  
1391 =cut
1392  
1393 90 ▶sub output_path {
Subroutine output_path: called CC=1 SCAR=0.0
Pod documented
1394 90 my $self = shift;
1395 ### We use it, so don't warn!
1396 ### &MIME::Tools::whine("output_path deprecated in MIME::Parser");
1397 90 $self->filer->output_path(@_);
1398 }
1399  
1400 #------------------------------
1401  
1402 =item output_prefix [PREFIX]
1403  
1404 I<Instance method, DEPRECATED.>
1405 Get/set the short string that all filenames for extracted body-parts
1406 will begin with (assuming that there is no better "recommended filename").
1407 Identical to the preferred form:
1408  
1409 $parser->filer->output_prefix(...args...);
1410  
1411 We just delegate this to the underlying L<filer()|/filer> object.
1412  
1413 =cut
1414  
1415 0 ▶sub output_prefix {
Subroutine output_prefix: not called CC=1 SCAR=6.9
Pod documented
1416 0 my $self = shift;
1417 0 &MIME::Tools::whine("output_prefix deprecated in MIME::Parser");
1418 0 $self->filer->output_prefix(@_);
1419 }
1420  
1421 #------------------------------
1422  
1423 =item evil_filename NAME
1424  
1425 I<Instance method, DEPRECATED.>
1426 Identical to the preferred form:
1427  
1428 $parser->filer->evil_filename(...args...);
1429  
1430 We just delegate this to the underlying L<filer()|/filer> object.
1431  
1432 =cut
1433  
1434 2 ▶sub evil_filename {
Subroutine evil_filename: called CC=1 SCAR=0.0
Pod documented
1435 2 my $self = shift;
1436 2 &MIME::Tools::whine("evil_filename deprecated in MIME::Parser");
1437 2 $self->filer->evil_filename(@_);
1438 }
1439  
1440 #------------------------------
1441  
1442 =item max_parts NUM
1443  
1444 I<Instance method.>
1445 Limits the number of MIME parts we will parse.
1446  
1447 Normally, instances of this class parse a message to the bitter end.
1448 Messages with many MIME parts can cause excessive memory consumption.
1449 If you invoke this method, parsing will abort and return undef if a
1450 message contains more than NUM parts.
1451  
1452 If NUM is set to -1 (the default), then no maximum limit is enforced.
1453  
1454 With no argument, returns the current setting as an integer
1455  
1456 =cut
1457  
1458 0 ▶sub max_parts {
Subroutine max_parts: not called CC=2 SCAR=17.9
Pod documented
1459 0 my($self, $num) = @_;
1460 0 ▶ if (@_ > 1) {
Branch: 1 branch
BranchTrueFalseTotal
if (@_ > 1) 0 0 0
1461 0 $self->{MP5_MaxParts} = $num;
1462 }
1463 0 return $self->{MP5_MaxParts};
1464 }
1465  
1466 =item max_depth NUM
1467  
1468 I<Instance method.>
1469 Limits the depth of nested MIME parts we will parse.
1470  
1471 Normally, instances of this class parse a message to the bitter end.
1472 Messages with many nested MIME parts can cause excessive memory
1473 consumption. If you invoke this method, parsing will abort and return
1474 undef if a message is nested to a level more than NUM lexels deep.
1475  
1476 If NUM is set to -1 (the default), then no maximum limit is enforced.
1477  
1478 With no argument, returns the current setting as an integer
1479  
1480 =cut
1481  
1482 2 ▶sub max_depth {
Subroutine max_depth: called CC=2 SCAR=7.0
Pod documented
1483 2 my($self, $num) = @_;
1484 2 ▶ if (@_ > 1) {
Branch: 1 branch
BranchTrueFalseTotal
if (@_ > 1) 2 0 2
1485 2 $self->{MP5_MaxDepth} = $num;
1486 }
1487 2 return $self->{MP5_MaxDepth};
1488 }
1489  
1490 #------------------------------
1491  
1492 =item output_to_core YESNO
1493  
1494 I<Instance method.>
1495 Normally, instances of this class output all their decoded body
1496 data to disk files (via MIME::Body::File). However, you can change
1497 this behaviour by invoking this method before parsing:
1498  
1499 If YESNO is false (the default), then all body data goes
1500 to disk files.
1501  
1502 If YESNO is true, then all body data goes to in-core data structures
1503 This is a little risky (what if someone emails you an MPEG or a tar
1504 file, hmmm?) but people seem to want this bit of noose-shaped rope,
1505 so I'm providing it.
1506 Note that setting this attribute true I<does not> mean that parser-internal
1507 temporary files are avoided! Use L<tmp_to_core()|/tmp_to_core> for that.
1508  
1509 With no argument, returns the current setting as a boolean.
1510  
1511 =cut
1512  
1513 207 ▶sub output_to_core {
Subroutine output_to_core: called CC=4 SCAR=13.9
Pod documented
1514 207 my ($self, $yesno) = @_;
1515 207 ▶ if (@_ > 1) {
Branch: 1 branch
BranchTrueFalseTotal
if (@_ > 1) 50 157 207
1516 50 ▶ $yesno = 0 if ($yesno and $yesno eq 'NONE');
Branch: 1 branch
BranchTrueFalseTotal
if $yesno and $yesno eq "NONE" 2 48 50
Condition100%3/3
$yesno and $yesno eq "NONE"
!ll&&!rl&&r
28202
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
1517 50 $self->{MP5_FilerToCore} = $yesno;
1518 }
1519 207 $self->{MP5_FilerToCore};
1520 }
1521  
1522  
1523 =item tmp_recycling
1524  
1525 I<Instance method, DEPRECATED.>
1526  
1527 This method is a no-op to preserve the pre-5.421 API.
1528  
1529 The tmp_recycling() feature was removed in 5.421 because it had never actually
1530 worked. Please update your code to stop using it.
1531  
1532 =cut
1533  
1534 sub tmp_recycling
1535 1 ▶{
Subroutine tmp_recycling: called CC=1 SCAR=0.0
Pod documented
1536 1 return;
1537 }
1538  
1539  
1540  
1541 #------------------------------
1542  
1543 =item tmp_to_core [YESNO]
1544  
1545 I<Instance method.>
1546 Should L<new_tmpfile()|/new_tmpfile> create real temp files, or
1547 use fake in-core ones? Normally we allow the creation of temporary
1548 disk files, since this allows us to handle huge attachments even when
1549 core is limited.
1550  
1551 If YESNO is true, we implement new_tmpfile() via in-core handles.
1552 If YESNO is false (the default), we use real tmpfiles.
1553 With no argument, just returns the current setting.
1554  
1555 =cut
1556  
1557 0 ▶sub tmp_to_core {
Subroutine tmp_to_core: not called CC=2 SCAR=17.9
Pod documented
1558 0 my ($self, $yesno) = @_;
1559 0 ▶ $self->{MP5_TmpToCore} = $yesno if (@_ > 1);
Branch: 1 branch
BranchTrueFalseTotal
if @_ > 1 0 0 0
1560 0 $self->{MP5_TmpToCore};
1561 }
1562  
1563 #------------------------------
1564  
1565 =item use_inner_files [YESNO]
1566  
1567 I<REMOVED>.
1568  
1569 I<Instance method.>
1570  
1571 MIME::Parser no longer supports IO::InnerFile, but this method is retained for
1572 backwards compatibility. It does nothing.
1573  
1574 The original reasoning for IO::InnerFile was that inner files were faster than
1575 "in-core" temp files. At the time, the "in-core" tempfile support was
1576 implemented with IO::Scalar from the IO-Stringy distribution, which used the
1577 tie() interface to wrap a scalar with the appropriate IO::Handle operations.
1578 The penalty for this was fairly hefty, and IO::InnerFile actually was faster.
1579  
1580 Nowadays, MIME::Parser uses Perl's built in ability to open a filehandle on an
1581 in-memory scalar variable via PerlIO. Benchmarking shows that IO::InnerFile is
1582 slightly slower than using in-memory temporary files, and is slightly faster
1583 than on-disk temporary files. Both measurements are within a few percent of
1584 each other. Since there's no real benefit, and since the IO::InnerFile abuse
1585 was fairly hairy and evil ("writes" to it were faked by extending the size of
1586 the inner file with the assumption that the only data you'd ever ->print() to
1587 it would be the line from the "outer" file, for example) it's been removed.
1588  
1589 =cut
1590  
1591 0 ▶sub use_inner_files {
Subroutine use_inner_files: not called CC=1 SCAR=6.9
Pod documented
1592 0 return 0;
1593 }
1594  
1595 =back
1596  
1597 =cut
1598  
1599  
1600 #------------------------------------------------------------
1601  
1602 =head2 Specifying classes to be instantiated
1603  
1604 =over 4
1605  
1606 =cut
1607  
1608 #------------------------------
1609  
1610 =item interface ROLE,[VALUE]
1611  
1612 I<Instance method.>
1613 During parsing, the parser normally creates instances of certain classes,
1614 like MIME::Entity. However, you may want to create a parser subclass
1615 that uses your own experimental head, entity, etc. classes (for example,
1616 your "head" class may provide some additional MIME-field-oriented methods).
1617  
1618 If so, then this is the method that your subclass should invoke during
1619 init. Use it like this:
1620  
1621 package MyParser;
1622 @ISA = qw(MIME::Parser);
1623 ...
1624 sub init {
1625 my $self = shift;
1626 $self->SUPER::init(@_); ### do my parent's init
1627 $self->interface(ENTITY_CLASS => 'MIME::MyEntity');
1628 $self->interface(HEAD_CLASS => 'MIME::MyHead');
1629 $self; ### return
1630 }
1631  
1632 With no VALUE, returns the VALUE currently associated with that ROLE.
1633  
1634 =cut
1635  
1636 3558 ▶sub interface {
Subroutine interface: called CC=2 SCAR=6.9
Pod documented
1637 3558 my ($self, $role, $value) = @_;
1638 3558 ▶ $self->{MP5_Interface}{$role} = $value if (defined($value));
Branch: 1 branch
BranchTrueFalseTotal
if defined $value 102 3456 3558
1639 3558 $self->{MP5_Interface}{$role};
1640 }
1641  
1642 #------------------------------
1643  
1644 =item new_body_for HEAD
1645  
1646 I<Instance method.>
1647 Based on the HEAD of a part we are parsing, return a new
1648 body object (any desirable subclass of MIME::Body) for
1649 receiving that part's data.
1650  
1651 If you set the C<output_to_core> option to false before parsing
1652 (the default), then we call C<output_path()> and create a
1653 new MIME::Body::File on that filename.
1654  
1655 If you set the C<output_to_core> option to true before parsing,
1656 then you get a MIME::Body::InCore instead.
1657  
1658 If you want the parser to do something else entirely, you can
1659 override this method in a subclass.
1660  
1661 =cut
1662  
1663 157 ▶sub new_body_for {
Subroutine new_body_for: called CC=2 SCAR=6.9
Pod documented
1664 157 my ($self, $head) = @_;
1665  
1666 157 ▶ if ($self->output_to_core) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->output_to_core) { } 61 96 157
1667 61 $self->debug("outputting body to core");
1668 61 return (new MIME::Body::InCore);
1669 }
1670 else {
1671 96 my $outpath = $self->output_path($head);
1672 96 $self->debug("outputting body to disk file: $outpath");
1673 96 $self->filer->purgeable($outpath); ### we plan to use it
1674 96 return (new MIME::Body::File $outpath);
1675 }
1676 }
1677  
1678 #------------------------------
1679  
1680 =pod
1681  
1682 =back
1683  
1684 =head2 Temporary File Creation
1685  
1686 =over
1687  
1688 =item tmp_dir DIRECTORY
1689  
1690 I<Instance method.>
1691 Causes any temporary files created by this parser to be created in the
1692 given DIRECTORY.
1693  
1694 If called without arguments, returns current value.
1695  
1696 The default value is undef, which will cause new_tmpfile() to use the
1697 system default temporary directory.
1698  
1699 =cut
1700  
1701 sub tmp_dir
1702 133 ▶{
Subroutine tmp_dir: called CC=2 SCAR=7.6
Pod documented
1703 133 my ($self, $dirname) = @_;
1704 133 ▶ if ( $dirname ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($dirname) 0 133 133
1705 0 $self->{MP5_TmpDir} = $dirname;
1706 }
1707  
1708 133 return $self->{MP5_TmpDir};
1709 }
1710  
1711 =item new_tmpfile
1712  
1713 I<Instance method.>
1714 Return an IO handle to be used to hold temporary data during a parse.
1715  
1716 The default uses MIME::Tools::tmpopen() to create a new temporary file,
1717 unless L<tmp_to_core()|/tmp_to_core> dictates otherwise, but you can
1718 override this. You shouldn't need to.
1719  
1720 The location for temporary files can be changed on a per-parser basis
1721 with L<tmp_dir()>.
1722  
1723 If you do override this, make certain that the object you return is
1724 set for binmode(), and is able to handle the following methods:
1725  
1726 read(BUF, NBYTES)
1727 getline()
1728 getlines()
1729 print(@ARGS)
1730 flush()
1731 seek(0, 0)
1732  
1733 Fatal exception if the stream could not be established.
1734  
1735 =cut
1736  
1737 133 ▶sub new_tmpfile {
Subroutine new_tmpfile: called CC=6 SCAR=18.1
Pod documented
1738 133 my ($self) = @_;
1739  
1740 133 my $io;
1741 133 ▶ if ($self->{MP5_TmpToCore}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{'MP5_TmpToCore'}) { } 1 132 133
1742 1 my $var;
1743 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
1744 } else {
1745 132 my $args = {};
1746 132 ▶ if( $self->tmp_dir ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->tmp_dir) 1 131 132
1747 1 $args->{DIR} = $self->tmp_dir;
1748 }
1749 132 ▶ $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" 132 0 132
1750 132 ▶ binmode($io) or die "$ME: can't set to binmode: $!";
Branch: 1 branch
BranchTrueFalseTotal
binmode $io or die "${ME}: can't set to binmode: $!" 132 0 132
1751 }
1752 133 return $io;
1753 }
1754  
1755 =back
1756  
1757 =cut
1758  
1759  
1760  
1761  
1762  
1763  
1764 #------------------------------------------------------------
1765  
1766 =head2 Parse results and error recovery
1767  
1768 =over 4
1769  
1770 =cut
1771  
1772 #------------------------------
1773  
1774 =item last_error
1775  
1776 I<Instance method.>
1777 Return the error (if any) that we ignored in the last parse.
1778  
1779 =cut
1780  
1781 0 ▶sub last_error {
Subroutine last_error: not called CC=1 SCAR=6.9
Pod documented
1782 0 join '', shift->results->errors;
1783 }
1784  
1785 =item ambiguous_content
1786  
1787 I<Instance method.>
1788 Returns true if the most recently parsed message has one or more
1789 entities with ambiguous content. See the documentation of
1790 C<MIME::Entity>'s C<ambiguous_content> method for details.
1791  
1792 Note that while these two calls to ambuguous_content return the same
1793 thing:
1794  
1795 $entity = $parser->parse($whatever_stream);
1796 $parser->ambuguous_content();
1797 $entity->ambuguous_content();
1798  
1799 the former is faster because it simply returns the results that were
1800 detected during the parse, while the latter actually executes the code
1801 that checks for ambiguous content again.
1802  
1803 Messages with ambiguous content should be treated as a security risk.
1804 In particular, if MIME::Parser is used in an email security tool,
1805 ambiguous messages should not be delivered to end-users.
1806  
1807 =cut
1808 17 ▶sub ambiguous_content {
Subroutine ambiguous_content: called CC=1 SCAR=0.0
Pod documented
1809 17 my ($self) = @_;
1810 17 return $self->{MP5_AmbiguousContent};
1811 }
1812  
1813 #------------------------------
1814  
1815 =item last_head
1816  
1817 I<Instance method.>
1818 Return the top-level MIME header of the last stream we attempted to parse.
1819 This is useful for replying to people who sent us bad MIME messages.
1820  
1821 ### Parse an input stream:
1822 eval { $entity = $parser->parse(\*STDIN) };
1823 if (!$entity) { ### parse failed!
1824 my $decapitated = $parser->last_head;
1825 ...
1826 }
1827  
1828 =cut
1829  
1830 0 ▶sub last_head {
Subroutine last_head: not called CC=1 SCAR=6.9
Pod documented
1831 0 shift->results->top_head;
1832 }
1833  
1834 #------------------------------
1835  
1836 =item results
1837  
1838 I<Instance method.>
1839 Return an object containing lots of info from the last entity parsed.
1840 This will be an instance of class
1841 L<MIME::Parser::Results|MIME::Parser::Results>.
1842  
1843 =cut
1844  
1845 4863 ▶sub results {
Subroutine results: called CC=1 SCAR=0.0
Pod documented
1846 4863 shift->{MP5_Results};
1847 }
1848  
1849  
1850 =back
1851  
1852 =cut
1853  
1854  
1855 #------------------------------
1856 22 1;
1857 __END__
« Entity.pm ↑ Summary WordDecoder.pm »