Parser/Filer.pm

filter: Statementstmt 91.9% 159 / 173 Branchbran 69.4% 50 / 72 Conditioncond 48.7% 20 / 41 MC/DCmcdc 13.6% 3 / 22 Subroutinesub 93.9% 31 / 33 Podpod 78.9% 15 / 19 totaltotal 77.2% 278 / 360 CC 53 SCAR 17.1
CC
53
Cov
80%
exorcise_filename
10.3
output_filename
9.9
evil_filename
8.9
CRAP 5.5
« Decoder/UU.pm ↑ Summary Decoder/NBit.pm »
1 package MIME::Parser::Filer;
2  
3 =head1 NAME
4  
5 MIME::Parser::Filer - manage file-output of the parser
6  
7  
8 =head1 SYNOPSIS
9  
10 Before reading further, you should see L<MIME::Parser> 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... now read L<"DESCRIPTION"> below, and everything else
15 should make sense.
16  
17  
18 =head2 Public interface
19  
20 ### Create a "filer" of the desired class:
21 my $filer = MIME::Parser::FileInto->new($dir);
22 my $filer = MIME::Parser::FileUnder->new($basedir);
23 ...
24  
25 ### Want added security? Don't let outsiders name your files:
26 $filer->ignore_filename(1);
27  
28 ### Prepare for the parsing of a new top-level message:
29 $filer->init_parse;
30  
31 ### Return the path where this message's data should be placed:
32 $path = $filer->output_path($head);
33  
34  
35 =head2 Semi-public interface
36  
37 These methods might be overridden or ignored in some subclasses,
38 so they don't all make sense in all circumstances:
39  
40 ### Tweak the mapping from content-type to extension:
41 $emap = $filer->output_extension_map;
42 $emap->{"text/html"} = ".htm";
43  
44  
45  
46  
47 =head1 DESCRIPTION
48  
49  
50 =head2 How this class is used when parsing
51  
52 When a MIME::Parser decides that it wants to output a file to disk,
53 it uses its "Filer" object -- an instance of a MIME::Parser::Filer
54 subclass -- to determine where to put the file.
55  
56 Every parser has a single Filer object, which it uses for all
57 parsing. You can get the Filer for a given $parser like this:
58  
59 $filer = $parser->filer;
60  
61 At the beginning of each C<parse()>, the filer's internal state
62 is reset by the parser:
63  
64 $parser->filer->init_parse;
65  
66 The parser can then get a path for each entity in the message
67 by handing that entity's header (a MIME::Head) to the filer
68 and having it do the work, like this:
69  
70 $new_file = $parser->filer->output_path($head);
71  
72 Since it's nice to be able to clean up after a parse (especially
73 a failed parse), the parser tells the filer when it has actually
74 used a path:
75  
76 $parser->filer->purgeable($new_file);
77  
78 Then, if you want to clean up the files which were created for a
79 particular parse (and also any directories that the Filer created),
80 you would do this:
81  
82 $parser->filer->purge;
83  
84  
85  
86 =head2 Writing your own subclasses
87  
88 There are two standard "Filer" subclasses (see below):
89 B<MIME::Parser::FileInto>, which throws all files from all parses
90 into the same directory, and B<MIME::Parser::FileUnder> (preferred), which
91 creates a subdirectory for each message. Hopefully, these will be
92 sufficient for most uses, but just in case...
93  
94 The only method you have to override is L<output_path()|/output_path>:
95  
96 $filer->output_path($head);
97  
98 This method is invoked by MIME::Parser when it wants to put a
99 decoded message body in an output file. The method should return a
100 path to the file to create. Failure is indicated by throwing an
101 exception.
102  
103 The path returned by C<output_path()> should be "ready for open()":
104 any necessary parent directories need to exist at that point.
105 These directories can be created by the Filer, if course, and they
106 should be marked as B<purgeable()> if a purge should delete them.
107  
108 Actually, if your issue is more I<where> the files go than
109 what they're named, you can use the default L<output_path()|/output_path>
110 method and just override one of its components:
111  
112 $dir = $filer->output_dir($head);
113 $name = $filer->output_filename($head);
114 ...
115  
116  
117  
118 =head1 PUBLIC INTERFACE
119  
120  
121 =head2 MIME::Parser::Filer
122  
123 This is the abstract superclass of all "filer" objects.
124  
125 =over 4
126  
127 =cut
128  
129 27 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
130  
131 ### Kit modules:
132 27 ▶use MIME::Tools qw(:msgtypes);
Subroutine BEGIN: called CC=1 SCAR=0.0
133 27 ▶use File::Spec;
Subroutine BEGIN: called CC=1 SCAR=0.0
134 27 ▶use File::Path qw(rmtree);
Subroutine BEGIN: called CC=1 SCAR=0.0
135 27 ▶use MIME::WordDecoder;
Subroutine BEGIN: called CC=1 SCAR=0.0
136  
137 ### Output path uniquifiers:
138 27 my $GFileNo = 0;
139 27 my $GSubdirNo = 0;
140  
141 ### Map content-type to extension.
142 ### If we can't map "major/minor", we try "major/*", then use "*/*".
143 27 my %DefaultTypeToExt =
144 qw(
145  
146 application/andrew-inset .ez
147 application/octet-stream .bin
148 application/oda .oda
149 application/pdf .pdf
150 application/pgp .pgp
151 application/postscript .ps
152 application/rtf .rtf
153 application/x-bcpio .bcpio
154 application/x-chess-pgn .pgn
155 application/x-cpio .cpio
156 application/x-csh .csh
157 application/x-dvi .dvi
158 application/x-gtar .gtar
159 application/x-gunzip .gz
160 application/x-hdf .hdf
161 application/x-latex .latex
162 application/x-mif .mif
163 application/x-netcdf .cdf
164 application/x-netcdf .nc
165 application/x-sh .sh
166 application/x-shar .shar
167 application/x-sv4cpio .sv4cpio
168 application/x-sv4crc .sv4crc
169 application/x-tar .tar
170 application/x-tcl .tcl
171 application/x-tex .tex
172 application/x-texinfo .texi
173 application/x-troff .roff
174 application/x-troff .tr
175 application/x-troff-man .man
176 application/x-troff-me .me
177 application/x-troff-ms .ms
178 application/x-ustar .ustar
179 application/x-wais-source .src
180 application/zip .zip
181  
182 audio/basic .snd
183 audio/ulaw .au
184 audio/x-aiff .aiff
185 audio/x-wav .wav
186  
187 image/gif .gif
188 image/ief .ief
189 image/jpeg .jpg
190 image/png .png
191 image/xbm .xbm
192 image/tiff .tif
193 image/x-cmu-raster .ras
194 image/x-portable-anymap .pnm
195 image/x-portable-bitmap .pbm
196 image/x-portable-graymap .pgm
197 image/x-portable-pixmap .ppm
198 image/x-rgb .rgb
199 image/x-xbitmap .xbm
200 image/x-xpixmap .xpm
201 image/x-xwindowdump .xwd
202  
203 text/* .txt
204 text/html .html
205 text/plain .txt
206 text/richtext .rtx
207 text/tab-separated-values .tsv
208 text/x-setext .etx
209 text/x-vcard .vcf
210  
211 video/mpeg .mpg
212 video/quicktime .mov
213 video/x-msvideo .avi
214 video/x-sgi-movie .movie
215  
216 message/* .msg
217  
218 */* .dat
219  
220 );
221  
222 #------------------------------
223  
224 =item new INITARGS...
225  
226 I<Class method, constructor.>
227 Create a new outputter for the given parser.
228 Any subsequent arguments are given to init(), which subclasses should
229 override for their own use (the default init does nothing).
230  
231 =cut
232  
233 91 ▶sub new {
Subroutine new: called CC=1 SCAR=0.0
Pod documented
234 91 my ($class, @initargs) = @_;
235 91 my $self = bless {
236 MPF_Prefix => "msg",
237 MPF_Dir => ".",
238 MPF_Ext => { %DefaultTypeToExt },
239 MPF_Purgeable => [], ### files created by the last parse
240  
241 MPF_MaxName => 80, ### max filename before treated as evil
242 MPF_TrimRoot => 14, ### trim root to this length
243 MPF_TrimExt => 3, ### trim extension to this length
244 }, $class;
245 91 $self->init(@initargs);
246 91 $self;
247 }
248  
249 1 ▶sub init {
Subroutine init: called CC=1 SCAR=0.0
Pod documented
250 ### no-op
251 }
252  
253 #------------------------------
254 # My PID, but untainted
255 #
256 sub untainted_pid
257 58 ▶{
Subroutine untainted_pid: called CC=2 SCAR=8.1
Pod undocumented
258 58 ▶ if ($$ =~ /^(\d+)$/) {
Branch: 1 branch
BranchTrueFalseTotal
if ($$ =~ /^(\d+)$/) 58 0 58
259 58 return $1;
260 }
261 # Can't happen...
262 0 return "0";
263 }
264  
265 #------------------------------
266 #
267 # cleanup_dir
268 #
269 # Instance method, private.
270 # Cleanup a directory, defaulting empty to "."
271 #
272 90 ▶sub cleanup_dir {
Subroutine cleanup_dir: called CC=4 SCAR=15.2
Pod undocumented
273 90 my ($self, $dir) = @_;
274 90 ▶ $dir = '.' if (!defined($dir) || ($dir eq '')); # coerce empty to "."
Branch: 1 branch
BranchTrueFalseTotal
if not defined $dir or $dir eq "" 0 90 90
Condition33%1/3
not defined $dir or $dir eq ""
l!l&&r!l&&!r
0090
MC/DC0%0/2
not defined $dir or $dir eq ""
not defined $dir $dir eq ""
Truth table33%1/3
not(A) or B
A= not defined $dirB= $dir eq ""
ABresult
1X1
011
000
275 90 ▶ $dir = '/.' if ($dir eq '/'); # coerce "/" so "$dir/$filename" works
Branch: 1 branch
BranchTrueFalseTotal
if $dir eq "/" 0 90 90
276 90 $dir =~ s|/$||; # be nice: get rid of any trailing "/"
277 90 $dir;
278 }
279  
280 #------------------------------
281  
282 =item results RESULTS
283  
284 I<Instance method.>
285 Link this filer to a MIME::Parser::Results object which will
286 tally the messages. Notice that we avoid linking it to the
287 parser to avoid circular reference!
288  
289 =cut
290  
291 185 ▶sub results {
Subroutine results: called CC=2 SCAR=7.1
Pod documented
292 185 my ($self, $results) = @_;
293 185 ▶ $self->{MPF_Results} = $results if (@_ > 1);
Branch: 1 branch
BranchTrueFalseTotal
if @_ > 1 185 0 185
294 185 $self->{MPF_Results};
295 }
296  
297 ### Log debug messages:
298 301 ▶sub debug {
Subroutine debug: called CC=3 SCAR=18.1
Pod undocumented
299 301 my $self = shift;
300 301 ▶ if (MIME::Tools->debugging()) {
Branch: 1 branch
BranchTrueFalseTotal
if ("MIME::Tools"->debugging) 0 301 301
301 0 ▶ if ($self->{MPF_Results}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"MPF_Results"}) 0 0 0
302 0 unshift @_, $self->{MPF_Results}->indent;
303 0 $self->{MPF_Results}->msg($M_DEBUG, @_);
304 }
305 0 MIME::Tools::debug(@_);
306 }
307 }
308  
309 ### Log warning messages:
310 10 ▶sub whine {
Subroutine whine: called CC=2 SCAR=7.0
Pod undocumented
311 10 my $self = shift;
312 10 ▶ if ($self->{MPF_Results}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"MPF_Results"}) 10 0 10
313 10 unshift @_, $self->{MPF_Results}->indent;
314 10 $self->{MPF_Results}->msg($M_WARNING, @_);
315 }
316 10 MIME::Tools::whine(@_);
317 }
318  
319 #------------------------------
320  
321 =item init_parse
322  
323 I<Instance method.>
324 Prepare to start parsing a new message.
325 Subclasses should always be sure to invoke the inherited method.
326  
327 =cut
328  
329 95 ▶sub init_parse {
Subroutine init_parse: called CC=1 SCAR=0.0
Pod documented
330 95 my $self = shift;
331 95 $self->{MPF_Purgeable} = [];
332 }
333  
334 #------------------------------
335  
336 =item evil_filename FILENAME
337  
338 I<Instance method.>
339 Is this an evil filename; i.e., one which should not be used
340 in generating a disk file name? It is if any of these are true:
341  
342 * it is empty or entirely whitespace
343 * it contains leading or trailing whitespace
344 * it is a string of dots: ".", "..", etc.
345 * it contains characters not in the set: "A" - "Z", "a" - "z",
346 "0" - "9", "-", "_", "+", "=", ".", ",", "@", "#",
347 "$", and " ".
348 * it is too long
349  
350 If you just want to change this behavior, you should override
351 this method in the subclass of MIME::Parser::Filer that you use.
352  
353 B<Warning:> at the time this method is invoked, the FILENAME has
354 already been unmime'd into the local character set.
355 If you're using any character set other than ASCII, ISO-8859-*,
356 or UTF-8, the interpretation of the "path" characters might be
357 very different, and you will probably need to override this method.
358 See L<MIME::WordDecoder/unmime> for more details.
359  
360 B<Note:> subclasses of MIME::Parser::Filer which override
361 output_path() might not consult this method; note, however, that
362 the built-in subclasses do consult it.
363  
364 I<Thanks to Andrew Pimlott for finding a real dumb bug in the original
365 version. Thanks to Nickolay Saukh for noting that evil is in the
366 eye of the beholder.>
367  
368 =cut
369  
370 80 ▶sub evil_filename {
Subroutine evil_filename: called CC=8 SCAR=21.8
Pod documented
371 80 my ($self, $name) = @_;
372  
373 80 $self->debug("is this evil? '$name'");
374  
375 80 ▶ return 1 if (!defined($name) or ($name eq '')); ### empty
Branch: 1 branch
BranchTrueFalseTotal
if not defined $name or $name eq "" 0 80 80
Condition33%1/3
not defined $name or $name eq ""
l!l&&r!l&&!r
0080
MC/DC0%0/2
not defined $name or $name eq ""
not defined $name $name eq ""
Truth table33%1/3
not(A) or B
A= not defined $nameB= $name eq ""
ABresult
1X1
011
000
376 80 ▶ return 1 if ($name =~ m{(^\s)|(\s+\Z)}); ### leading/trailing whitespace
Branch: 1 branch
BranchTrueFalseTotal
if $name =~ /(^\s)|(\s+\Z)/ 10 70 80
377 70 ▶ return 1 if ($name =~ m{^\.+\Z}); ### dots
Branch: 1 branch
BranchTrueFalseTotal
if $name =~ /^\.+\Z/ 4 66 70
378 66 ▶ return 1 if ($name =~ /[^-A-Z0-9_+=.,@\#\$\% ]/i); # Only allow good chars
Branch: 1 branch
BranchTrueFalseTotal
if $name =~ /[^-A-Z0-9_+=.,\@\#\$\% ]/i 13 53 66
379 return 1 if ($self->{MPF_MaxName} and
380 53 ▶ (length($name) > $self->{MPF_MaxName}));
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"MPF_MaxName"} and length $name > $self->{"MPF_MaxName"} 0 53 53
Condition33%1/3
$self->{"MPF_MaxName"} and length $name > $self->{"MPF_MaxName"}
!ll&&!rl&&r
0530
MC/DC0%0/2
$self->{"MPF_MaxName"} and length $name > $self->{"MPF_MaxName"}
$self->{"MPF_MaxName"} length $name > $self->{"MPF_MaxName"}
Truth table33%1/3
A and B
A= $self->{"MPF_MaxName"}B= length $name > $self->{"MPF_MaxName"}
ABresult
0X0
100
111
381 53 $self->debug("it's ok");
382 53 0;
383 }
384  
385 #------------------------------
386  
387 =item exorcise_filename FILENAME
388  
389 I<Instance method.>
390 If a given filename is evil (see L</evil_filename>) we try to
391 rescue it by performing some basic operations: shortening it,
392 removing bad characters, etc., and checking each against
393 evil_filename().
394  
395 Returns the exorcised filename (which is guaranteed to not
396 be evil), or undef if it could not be salvaged.
397  
398 B<Warning:> at the time this method is invoked, the FILENAME has
399 already been unmime'd into the local character set.
400 If you're using anything character set other than ASCII, ISO-8859-*,
401 or UTF-8, the interpretation of the "path" characters might be very
402 very different, and you will probably need to override this method.
403 See L<MIME::WordDecoder/unmime> for more details.
404  
405 =cut
406  
407 13 ▶sub exorcise_filename {
Subroutine exorcise_filename: called CC=10 SCAR=23.3
Pod documented
408 13 my ($self, $fname) = @_;
409  
410 ### Isolate to last path element:
411 13 my $last = $fname;
412  
413 ### Path separators are / or \
414 13 $last =~ s{^.*[/\\]}{};
415  
416 ### Convert semi-evil characters to underscores
417 13 $last =~ s/[\/\\\[\]:]/_/g;
418 13 ▶ if ($last and !$self->evil_filename($last)) {
Branch: 1 branch
BranchTrueFalseTotal
if ($last and not $self->evil_filename($last)) 3 10 13
Condition66%2/3
$last and not $self->evil_filename($last)
!ll&&!rl&&r
0103
MC/DC50%1/2
$last and not $self->evil_filename($last)
$last not $self->evil_filename($last)
Truth table66%2/3
A and not(B)
A= $lastB= not $self->evil_filename($last)
ABresult
0X0
100
111
419 3 $self->debug("looks like I can use the last path element");
420 3 return $last;
421 }
422  
423 ### Break last element into root and extension, and truncate:
424 10 ▶ my ($root, $ext) = (($last =~ /^(.*)\.([^\.]+)\Z/)
Branch: 1 branch
BranchTrueFalseTotal
$last =~ /^(.*)\.([^\.]+)\Z/ ? : 5 5 10
425 ? ($1, $2)
426 : ($last, ''));
427 ### Delete leading and trailing whitespace
428 10 $root =~ s/^\s+//;
429 10 $ext =~ s/\s+$//;
430 10 ▶ $root = substr($root, 0, ($self->{MPF_TrimRoot} || 14));
Condition50%1/2
$self->{'MPF_TrimRoot'} || 14
l!l
100
MC/DC0%0/1
$self->{'MPF_TrimRoot'} || 14
$self->{'MPF_TrimRoot'}
Truth table50%1/2
A
A= $self->{'MPF_TrimRoot'}
Aresult
11
00
431 10 ▶ $ext = substr($ext, 0, ($self->{MPF_TrimExt} || 3));
Condition50%1/2
$self->{'MPF_TrimExt'} || 3
l!l
100
MC/DC0%0/1
$self->{'MPF_TrimExt'} || 3
$self->{'MPF_TrimExt'}
Truth table50%1/2
A
A= $self->{'MPF_TrimExt'}
Aresult
11
00
432 10 ▶ $ext =~ /^\w+$/ or $ext = "dat";
Branch: 1 branch
BranchTrueFalseTotal
$ext =~ /^\w+$/ or $ext = "dat" 4 6 10
433 10 ▶ my $trunc = $root . ($ext ? ".$ext" : '');
Branch: 1 branch
BranchTrueFalseTotal
$ext ? : 10 0 10
434 10 ▶ if (!$self->evil_filename($trunc)) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($self->evil_filename($trunc)) 6 4 10
435 6 $self->debug("looks like I can use the truncated last path element");
436 6 return $trunc;
437 }
438  
439 ### Remove all bad characters
440 4 $trunc =~ s/([^-A-Z0-9_+=.,@\#\$ ])/sprintf("%%%02X", unpack("C", $1))/ige;
441 4 ▶ if (!$self->evil_filename($trunc)) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($self->evil_filename($trunc)) 4 0 4
442 4 $self->debug("looks like I can use a munged version of the truncated last path element");
443 4 return $trunc;
444 }
445  
446 ### Hope that works:
447 0 undef;
448 }
449  
450 #------------------------------
451  
452 =item find_unused_path DIR, FILENAME
453  
454 I<Instance method, subclasses only.>
455 We have decided on an output directory and tentative filename,
456 but there is a chance that it might already exist. Keep
457 adding a numeric suffix "-1", "-2", etc. to the filename
458 until an unused path is found, and then return that path.
459  
460 The suffix is actually added before the first "." in the filename
461 is there is one; for example:
462  
463 picture.gif archive.tar.gz readme
464 picture-1.gif archive-1.tar.gz readme-1
465 picture-2.gif archive-2.tar.gz readme-2
466 ... ... ...
467 picture-10.gif
468 ...
469  
470 This can be a costly operation, and risky if you don't want files
471 renamed, so it is in your best interest to minimize situations
472 where these kinds of collisions occur. Unfortunately, if
473 a multipart message gives all of its parts the same recommended
474 filename, and you are placing them all in the same directory,
475 this method might be unavoidable.
476  
477 =cut
478  
479 91 ▶sub find_unused_path {
Subroutine find_unused_path: called CC=4 SCAR=13.9
Pod documented
480 91 my ($self, $dir, $fname) = @_;
481 91 my $i = 0;
482 91 while (1) {
483  
484 ### Create suffixed name (from filename), and see if we can use it:
485 97 ▶ my $suffix = ($i ? "-$i" : "");
Branch: 1 branch
BranchTrueFalseTotal
$i ? : 6 91 97
486 97 my $sname = $fname; $sname =~ s/^(.*?)(\.|\Z)/$1$suffix$2/;
487 97 my $path = File::Spec->catfile($dir, $sname);
488 97 ▶ if (! -e $path) { ### it's good!
Branch: 1 branch
BranchTrueFalseTotal
unless (-e $path) 91 6 97
489 91 ▶ $i and $self->whine("collision with $fname in $dir: using $path");
Branch: 1 branch
BranchTrueFalseTotal
$i and $self->whine("collision with $fname in ${dir}: using $path") 5 86 91
490 91 return $path;
491 }
492 6 $self->debug("$path already taken");
493 6 } continue { ++$i; }
494 }
495  
496 #------------------------------
497  
498 =item ignore_filename [YESNO]
499  
500 I<Instance method.>
501 Return true if we should always ignore recommended filenames in
502 messages, choosing instead to always generate our own filenames.
503 With argument, sets this value.
504  
505 B<Note:> subclasses of MIME::Parser::Filer which override
506 output_path() might not honor this setting; note, however, that
507 the built-in subclasses honor it.
508  
509 =cut
510  
511 38 ▶sub ignore_filename {
Subroutine ignore_filename: called CC=2 SCAR=7.1
Pod documented
512 38 my $self = shift;
513 38 ▶ $self->{MPF_IgnoreFilename} = $_[0] if @_;
Branch: 1 branch
BranchTrueFalseTotal
if @_ 0 38 38
514 38 $self->{MPF_IgnoreFilename};
515 }
516  
517 #------------------------------
518  
519 =item output_dir HEAD
520  
521 I<Instance method.>
522 Return the output directory for the given header.
523 The default method returns ".".
524  
525 =cut
526  
527 0 ▶sub output_dir {
Subroutine output_dir: not called CC=1 SCAR=6.9
Pod documented
528 0 my ($self, $head) = @_;
529 0 return ".";
530 }
531  
532 #------------------------------
533  
534 =item output_filename HEAD
535  
536 I<Instance method, subclasses only.>
537 A given recommended filename was either not given, or it was judged
538 to be evil. Return a fake name, possibly using information in the
539 message HEADer. Note that this is just the filename, not the full path.
540  
541 Used by L<output_path()|/output_path>.
542 If you're using the default C<output_path()>, you probably don't
543 need to worry about avoiding collisions with existing files;
544 we take care of that in L<find_unused_path()|/find_unused_path>.
545  
546 =cut
547  
548 53 ▶sub output_filename {
Subroutine output_filename: called CC=8 SCAR=22.9
Pod documented
549 53 my ($self, $head) = @_;
550  
551 ### Get the recommended name:
552 53 my $recommended = $head->recommended_filename;
553  
554 ### Get content type:
555 53 ▶ my ($type, $subtype) = split m{/}, $head->mime_type; $subtype ||= '';
Condition100%2/2
$subtype ||= ""
l!l
521
MC/DC100%1/1
$subtype ||= ""
$subtype
Truth table100%2/2
A
A= $subtype
Aresult
11
00
556  
557 ### Get recommended extension, being quite conservative:
558 53 ▶ my $recommended_ext = (($recommended and ($recommended =~ m{(\.\w+)\Z}))
Branch: 1 branch
BranchTrueFalseTotal
$recommended && $recommended =~ /(\.\w+)\Z/ ? : 0 53 53
Condition33%1/3
$recommended and $recommended =~ /(\.\w+)\Z/
!ll&&!rl&&r
5300
MC/DC0%0/2
$recommended and $recommended =~ /(\.\w+)\Z/
$recommended $recommended =~ /(\.\w+)\Z/
Truth table33%1/3
A and B
A= $recommendedB= $recommended =~ /(\.\w+)\Z/
ABresult
0X0
100
111
559 ? $1
560 : undef);
561  
562 ### Try and get an extension, honoring a given one first:
563 my $ext = ($recommended_ext ||
564 $self->{MPF_Ext}{"$type/$subtype"} ||
565 $self->{MPF_Ext}{"$type/*"} ||
566 53 ▶ $self->{MPF_Ext}{"*/*"} ||
Condition54%6/11
$recommended_ext || $self->{'MPF_Ext'}{"$type/$subtype"} || $self->{'MPF_Ext'}{"$type/*"} || $self->{'MPF_Ext'}{'*/*'} || '.dat'
l!l
530
$recommended_ext or $self->{"MPF_Ext"}{"$type/$subtype"} or $self->{"MPF_Ext"}{"$type/*"} or $self->{"MPF_Ext"}{"*/*"}
l!l&&r!l&&!r
5300
$recommended_ext or $self->{"MPF_Ext"}{"$type/$subtype"} or $self->{"MPF_Ext"}{"$type/*"}
l!l&&r!l&&!r
5030
$recommended_ext or $self->{"MPF_Ext"}{"$type/$subtype"}
l!l&&r!l&&!r
0503
MC/DC0%0/4
$recommended_ext || $self->{'MPF_Ext'}{"$type/$subtype"} || $self->{'MPF_Ext'}{"$type/*"} || $self->{'MPF_Ext'}{'*/*'} || '.dat'
$recommended_ext $self->{"MPF_Ext"}{"$type/$subtype"} $self->{"MPF_Ext"}{"$type/*"} $self->{"MPF_Ext"}{"*/*"}
Truth table40%2/5
A or B or C or D
A= $recommended_extB= $self->{"MPF_Ext"}{"$type/$subtype"}C= $self->{"MPF_Ext"}{"$type/*"}D= $self->{"MPF_Ext"}{"*/*"}
ABCDresult
1XXX1
01XX1
001X1
00011
00000
567 ".dat");
568  
569 ### Get a prefix:
570 53 ++$GFileNo;
571 53 return ($self->output_prefix . "-" . untainted_pid() . "-$GFileNo$ext");
572 }
573  
574 #------------------------------
575  
576 =item output_prefix [PREFIX]
577  
578 I<Instance method.>
579 Get the short string that all filenames for extracted body-parts
580 will begin with (assuming that there is no better "recommended filename").
581 The default is F<"msg">.
582  
583 If PREFIX I<is not> given, the current output prefix is returned.
584 If PREFIX I<is> given, the output prefix is set to the new value,
585 and the previous value is returned.
586  
587 Used by L<output_filename()|/output_filename>.
588  
589 B<Note:> subclasses of MIME::Parser::Filer which override
590 output_path() or output_filename() might not honor this setting;
591 note, however, that the built-in subclasses honor it.
592  
593 =cut
594  
595 53 ▶sub output_prefix {
Subroutine output_prefix: called CC=2 SCAR=7.1
Pod documented
596 53 my ($self, $prefix) = @_;
597 53 ▶ $self->{MPF_Prefix} = $prefix if (@_ > 1);
Branch: 1 branch
BranchTrueFalseTotal
if @_ > 1 0 53 53
598 53 $self->{MPF_Prefix};
599 }
600  
601 #------------------------------
602  
603 =item output_type_ext
604  
605 I<Instance method.>
606 Return a reference to the hash used by the default
607 L<output_filename()|/output_filename> for mapping from content-types
608 to extensions when there is no default extension to use.
609  
610 $emap = $filer->output_typemap;
611 $emap->{'text/plain'} = '.txt';
612 $emap->{'text/html'} = '.html';
613 $emap->{'text/*'} = '.txt';
614 $emap->{'*/*'} = '.dat';
615  
616 B<Note:> subclasses of MIME::Parser::Filer which override
617 output_path() or output_filename() might not consult this hash;
618 note, however, that the built-in subclasses consult it.
619  
620 =cut
621  
622 0 ▶sub output_type_ext {
Subroutine output_type_ext: not called CC=1 SCAR=6.9
Pod documented
623 0 my $self = shift;
624 0 return $self->{MPF_Ext};
625 }
626  
627 #------------------------------
628  
629 =item output_path HEAD
630  
631 I<Instance method, subclasses only.>
632 Given a MIME head for a file to be extracted, come up with a good
633 output pathname for the extracted file. This is the only method
634 you need to worry about if you are building a custom filer.
635  
636 The default implementation does a lot of work; subclass
637 implementers I<really> should try to just override its components
638 instead of the whole thing. It works basically as follows:
639  
640 $directory = $self->output_dir($head);
641  
642 $filename = $head->recommended_filename();
643 if (!$filename or
644 $self->ignore_filename() or
645 $self->evil_filename($filename)) {
646 $filename = $self->output_filename($head);
647 }
648  
649 return $self->find_unused_path($directory, $filename);
650  
651 B<Note:> There are many, many, many ways you might want to control
652 the naming of files, based on your application. If you don't like
653 the behavior of this function, you can easily define your own subclass
654 of MIME::Parser::Filer and override it there.
655  
656 B<Note:> Nickolay Saukh pointed out that, given the subjective nature of
657 what is "evil", this function really shouldn't I<warn> about an evil
658 filename, but maybe just issue a I<debug> message. I considered that,
659 but then I thought: if debugging were off, people wouldn't know why
660 (or even if) a given filename had been ignored. In mail robots
661 that depend on externally-provided filenames, this could cause
662 hard-to-diagnose problems. So, the message is still a warning.
663  
664 I<Thanks to Laurent Amon for pointing out problems with the original
665 implementation, and for making some good suggestions. Thanks also to
666 Achim Bohnet for pointing out that there should be a hookless, OO way of
667 overriding the output path.>
668  
669 =cut
670  
671 91 ▶sub output_path {
Subroutine output_path: called CC=7 SCAR=21.0
Pod documented
672 91 my ($self, $head) = @_;
673  
674 ### Get the output directory:
675 91 my $dir = $self->output_dir($head);
676  
677 ### Get the output filename as UTF-8
678 91 my $fname = $head->recommended_filename;
679  
680 ### Can we use it:
681 91 ▶ if (!defined($fname)) {
Branch: 3 branches
BranchTrueFalseTotal
if (not defined $fname) { } 53 38 91
elsif ($self->ignore_filename) { } 0 38 38
elsif ($self->evil_filename($fname)) { } 5 33 38
682 53 $self->debug("no filename recommended: synthesizing our own");
683 53 $fname = $self->output_filename($head);
684 }
685 elsif ($self->ignore_filename) {
686 0 $self->debug("ignoring all external filenames: synthesizing our own");
687 0 $fname = $self->output_filename($head);
688 }
689 elsif ($self->evil_filename($fname)) {
690  
691 ### Can we save it by just taking the last element?
692 5 my $ex = $self->exorcise_filename($fname);
693 5 ▶ if (defined($ex) and !$self->evil_filename($ex)) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $ex and not $self->evil_filename($ex)) { } 5 0 5
Condition33%1/3
defined $ex and not $self->evil_filename($ex)
!ll&&!rl&&r
005
MC/DC0%0/2
defined $ex and not $self->evil_filename($ex)
defined $ex not $self->evil_filename($ex)
Truth table33%1/3
A and not(B)
A= defined $exB= not $self->evil_filename($ex)
ABresult
0X0
100
111
694 5 $self->whine("Provided filename '$fname' is regarded as evil, ",
695 "but I was able to exorcise it and get something ",
696 "usable.");
697 5 $fname = $ex;
698 }
699 else {
700 0 $self->whine("Provided filename '$fname' is regarded as evil; ",
701 "I'm ignoring it and supplying my own.");
702 0 $fname = $self->output_filename($head);
703 }
704 } else {
705 # Untaint $fname... we know it's not evil
706 33 ▶ if ($fname =~ /^(.*)$/) {
Branch: 1 branch
BranchTrueFalseTotal
if ($fname =~ /^(.*)$/) 33 0 33
707 33 $fname = $1;
708 }
709 }
710  
711 91 $self->debug("planning to use '$fname'");
712  
713 ### Resolve collisions and return final path:
714 91 return $self->find_unused_path($dir, $fname);
715 }
716  
717 #------------------------------
718  
719 =item purge
720  
721 I<Instance method, final.>
722 Purge all files/directories created by the last parse.
723 This method simply goes through the purgeable list in reverse order
724 (see L</purgeable>) and removes all existing files/directories in it.
725 You should not need to override this method.
726  
727 =cut
728  
729 26 ▶sub purge {
Subroutine purge: called CC=4 SCAR=14.1
Pod documented
730 26 my ($self) = @_;
731 26 foreach my $path (reverse @{$self->{MPF_Purgeable}}) {
732 73 ▶ (-e $path) or next; ### must check: might delete DIR before DIR/FILE
Branch: 1 branch
BranchTrueFalseTotal
-e $path or next 73 0 73
733 73 rmtree($path, 0, 1);
734 73 ▶ (-e $path) and $self->whine("unable to purge: $path");
Branch: 1 branch
BranchTrueFalseTotal
-e $path and $self->whine("unable to purge: $path") 0 73 73
735 }
736 26 1;
737 }
738  
739 #------------------------------
740  
741 =item purgeable [FILE]
742  
743 I<Instance method, final.>
744 Add FILE to the list of "purgeable" files/directories (those which
745 will be removed if you do a C<purge()>).
746 You should not need to override this method.
747  
748 If FILE is not given, the "purgeable" list is returned.
749 This may be used for more-sophisticated purging.
750  
751 As a special case, invoking this method with a FILE that is an
752 arrayref will replace the purgeable list with a copy of the
753 array's contents, so [] may be used to clear the list.
754  
755 Note that the "purgeable" list is cleared when a parser begins a
756 new parse; therefore, if you want to use purge() to do cleanup,
757 you I<must> do so I<before> starting a new parse!
758  
759 =cut
760  
761 221 ▶sub purgeable {
Subroutine purgeable: called CC=3 SCAR=11.0
Pod documented
762 221 my ($self, $path) = @_;
763 221 ▶ return @{$self->{MPF_Purgeable}} if (@_ == 1);
Branch: 1 branch
BranchTrueFalseTotal
if @_ == 1 25 196 221
764  
765 196 ▶ if (ref($path)) { $self->{MPF_Purgeable} = [ @$path ]; }
Branch: 1 branch
BranchTrueFalseTotal
if (ref $path) { } 95 101 196
766 101 else { push @{$self->{MPF_Purgeable}}, $path; }
767 196 1;
768 }
769  
770 =back
771  
772 =cut
773  
774  
775 #------------------------------------------------------------
776 #------------------------------------------------------------
777  
778 =head2 MIME::Parser::FileInto
779  
780 This concrete subclass of MIME::Parser::Filer supports filing
781 into a given directory.
782  
783 =over 4
784  
785 =cut
786  
787 package MIME::Parser::FileInto;
788  
789 27 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
790 27 ▶use vars qw(@ISA);
Subroutine BEGIN: called CC=1 SCAR=0.0
791 27 @ISA = qw(MIME::Parser::Filer);
792  
793 #------------------------------
794  
795 =item init DIRECTORY
796  
797 I<Instance method, initiallizer.>
798 Set the directory where all files will go.
799  
800 =cut
801  
802 85 ▶sub init {
Subroutine init: called CC=1 SCAR=0.0
803 85 my ($self, $dir) = @_;
804 85 $self->{MPFI_Dir} = $self->cleanup_dir($dir);
805 }
806  
807 #------------------------------
808 #
809 # output_dir HEAD
810 #
811 # I<Instance method, concrete override.>
812 # Return the output directory where the files go.
813 #
814 92 ▶sub output_dir {
Subroutine output_dir: called CC=1 SCAR=0.0
815 92 shift->{MPFI_Dir};
816 }
817  
818 =back
819  
820 =cut
821  
822  
823  
824  
825 #------------------------------------------------------------
826 #------------------------------------------------------------
827  
828 =head2 MIME::Parser::FileUnder
829  
830 This concrete subclass of MIME::Parser::Filer supports filing under
831 a given directory, using one subdirectory per message, but with
832 all message parts in the same directory.
833  
834 =over 4
835  
836 =cut
837  
838 package MIME::Parser::FileUnder;
839  
840 27 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
841 27 ▶use vars qw(@ISA);
Subroutine BEGIN: called CC=1 SCAR=0.0
842 27 @ISA = qw(MIME::Parser::Filer);
843  
844 #------------------------------
845  
846 =item init BASEDIR, OPTSHASH...
847  
848 I<Instance method, initiallizer.>
849 Set the base directory which will contain the message directories.
850 If used, then each parse of begins by creating a new subdirectory
851 of BASEDIR where the actual parts of the message are placed.
852 OPTSHASH can contain the following:
853  
854 =over 4
855  
856 =item DirName
857  
858 Explicitly set the name of the subdirectory which is created.
859 The default is to use the time, process id, and a sequence number,
860 but you might want a predictable directory.
861 A generated directory must not exist yet: if it does, the parse dies.
862  
863 =item Purge
864  
865 Automatically purge the contents of the directory (including all
866 subdirectories) before each parse. This is really only needed if
867 using an explicit DirName, and is provided as a convenience only.
868 Currently we use the 1-arg form of File::Path::rmtree; you should
869 familiarize yourself with the caveats therein.
870  
871 =back
872  
873 The output_dir() will return the path to this message-specific directory
874 until the next parse is begun, so you can do this:
875  
876 use File::Path;
877  
878 $parser->output_under("/tmp");
879 $ent = eval { $parser->parse_open($msg); }; ### parse
880 if (!$ent) { ### parse failed
881 rmtree($parser->output_dir);
882 die "parse failed: $@";
883 }
884 else { ### parse succeeded
885 ...do stuff...
886 }
887  
888 =cut
889  
890 5 ▶sub init {
Subroutine init: called CC=1 SCAR=0.0
891 5 my ($self, $basedir, %opts) = @_;
892  
893 5 $self->{MPFU_Base} = $self->cleanup_dir($basedir);
894 5 $self->{MPFU_DirName} = $opts{DirName};
895 5 $self->{MPFU_Purge} = $opts{Purge};
896 }
897  
898 #------------------------------
899 #
900 # init_parse
901 #
902 # I<Instance method, override.>
903 # Prepare to start parsing a new message.
904 #
905 5 ▶sub init_parse {
Subroutine init_parse: called CC=6 SCAR=18.7
906 5 my $self = shift;
907  
908 ### Invoke inherited method first!
909 5 $self->SUPER::init_parse;
910  
911 ### Determine the subdirectory of their base to use:
912 my $subdir = (defined($self->{MPFU_DirName})
913 ? $self->{MPFU_DirName}
914 5 ▶ : ("msg-" . scalar(time) . "-" .
Branch: 1 branch
BranchTrueFalseTotal
defined $self->{'MPFU_DirName'} ? : 0 5 5
915 MIME::Parser::Filer::untainted_pid() . "-" . $GSubdirNo++));
916 5 $self->debug("subdir = $subdir");
917  
918 ### Determine full path to the per-message output directory:
919 5 $self->{MPFU_Dir} = File::Spec->catfile($self->{MPFU_Base}, $subdir);
920  
921 ### Remove and re-create the per-message output directory:
922 5 ▶ rmtree $self->output_dir if $self->{MPFU_Purge};
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"MPFU_Purge"} 0 5 5
923 # Reuse an existing directory only if the caller named it: a generated
924 # name that already exists may have been planted by another user
925 5 ▶ (defined($self->{MPFU_DirName}) && -d $self->output_dir) or
Branch: 1 branch
BranchTrueFalseTotal
defined $self->{"MPFU_DirName"} and -d $self->output_dir or mkdir $self->output_dir, 448 or die 'mkdir ' . $self->output_dir . ": $!\n" 4 1 5
Condition50%3/6
defined $self->{"MPFU_DirName"} and -d $self->output_dir or mkdir $self->output_dir, 448
l!l&&r!l&&!r
041
defined $self->{"MPFU_DirName"} and -d $self->output_dir
!ll&&!rl&&r
500
MC/DC33%1/3
defined $self->{"MPFU_DirName"} and -d $self->output_dir or mkdir $self->output_dir, 448
defined $self->{"MPFU_DirName"} -d $self->output_dir mkdir $self->output_dir, 448
Truth table40%2/5
A and B or C
A= defined $self->{"MPFU_DirName"}B= -d $self->output_dirC= mkdir $self->output_dir, 448
ABCresult
11X1
0X11
1011
0X00
1000
926 mkdir $self->output_dir, 0700 or
927 die "mkdir ".$self->output_dir.": $!\n";
928  
929 ### Add the per-message output directory to the puregables:
930 4 $self->purgeable($self->output_dir);
931 4 1;
932 }
933  
934 #------------------------------
935 #
936 # output_dir HEAD
937 #
938 # I<Instance method, concrete override.>
939 # Return the output directory that we used for the last parse.
940 #
941 15 ▶sub output_dir {
Subroutine output_dir: called CC=1 SCAR=0.0
942 15 shift->{MPFU_Dir};
943 }
944  
945 =back
946  
947 =cut
948  
949 27 1;
950 __END__
« Decoder/UU.pm ↑ Summary Decoder/NBit.pm »