blib/lib/Mail/DMARC/Base.pm untested

filter: Statementstmt 0.0% 0 / 207 Branchbran 0.0% 0 / 116 Conditioncond 0.0% 0 / 51 MC/DCmcdc 0.0% 0 / 27 Subroutinesub 0.0% 0 / 38 Podpod 0.0% 0 / 25 totaltotal 0.0% 0 / 464 CC 59 SCAR 35.9
CC
59
Cov
0%
has_dns_rr
132.0
get_config
56.0
is_public_suffix
56.0
CRAP 36.2
1 package Mail::DMARC::Base;
2 use strict;
3 use warnings;
4 use feature 'signatures';
5 no warnings 'experimental::args_array_with_signatures'; ## no critic (ProhibitNoWarnings)
6  
7 our $VERSION = '2.20260827';
8  
9 use Carp;
10 use Config::Tiny;
11 use File::ShareDir;
12 use HTTP::Tiny;
13 use IO::File;
14 use Net::DNS::Resolver;
15 use Socket;
16 require URI::_idna;
17  
18 sub new( $class, @args ) {
19 croak "invalid args" if @args % 2 != 0;
20 return bless {
21 config_file => 'mail-dmarc.ini',
22 @args, # this may override config_file
23 }, $class;
24 }
25  
26 my $_fake_time;
27  
28 sub time ($self) { ## no critic
29 # Ability to return a fake time for testing
30 my $time
31 = defined $Mail::DMARC::Base::_fake_time
32 ? $Mail::DMARC::Base::_fake_time
33 : time;
34 return $time;
35 }
36  
37 sub set_fake_time ( $self, $time ) {
38 $Mail::DMARC::Base::_fake_time = $time;
39 return;
40 }
41  
42 sub config( $self, $file = undef, @too_many ) {
43 croak "invalid args" if @too_many;
44 return $self->{config} if ref $self->{config} && !$file;
45 return $self->{config} = $self->get_config($file);
46 }
47  
48 sub get_prefix( $self, $subdir = undef ) {
49 return
50 map { $_ . ( $subdir ? $subdir : '' ) } qw[ /usr/local/ /opt/local/ / ./ ];
51 }
52  
53 sub get_sharefile( $self, $file ) {
54 my $match = File::ShareDir::dist_file( 'Mail-DMARC', $file );
55 print "using $match for $file\n" if $self->verbose;
56 return $match;
57 }
58  
59 sub get_config( $self, $file = undef ) {
60 $file ||= $ENV{MAIL_DMARC_CONFIG_FILE} || $self->{config_file};
61 croak if !$file;
62 return Config::Tiny->read($file) if -r $file; # fully qualified
63  
64 # search <prefix>/etc and the mail/ subdir where mail daemons (and
65 # FreeBSD ports, e.g. authentication_milter) conventionally install it
66 foreach my $d ( map { ( $_, "$_/mail" ) } $self->get_prefix('etc') ) {
67 next if !-d $d;
68 next if !-e "$d/$file";
69 croak "unreadable file: $d/$file" if !-r "$d/$file";
70 return Config::Tiny->read("$d/$file");
71 }
72  
73 if ( $file ne 'mail-dmarc.ini' ) {
74 croak "unable to find requested config file $file\n";
75 }
76  
77 carp "no mail-dmarc.ini found; using bundled defaults.\n";
78 return Config::Tiny->read( $self->get_sharefile('mail-dmarc.ini') );
79 }
80  
81 sub any_inet_ntop( $self, $ip_bin ) {
82 $ip_bin or croak "missing IP in request";
83  
84 if ( length $ip_bin == 16 ) {
85 return Socket::inet_ntop( AF_INET6, $ip_bin );
86 }
87  
88 return Socket::inet_ntop( AF_INET, $ip_bin );
89 }
90  
91 sub any_inet_pton( $self, $ip_txt ) {
92 $ip_txt or croak "missing IP in request";
93  
94 if ( $ip_txt =~ /:/ ) {
95 return Socket::inet_pton( AF_INET6, $ip_txt )
96 || croak "invalid IPv6: $ip_txt";
97 }
98  
99 return Socket::inet_pton( AF_INET, $ip_txt )
100 || croak "invalid IPv4: $ip_txt";
101 }
102  
103 {
104 my $public_suffixes;
105 my $public_suffixes_stamp;
106  
107 sub get_public_suffix_list($self) {
108 if ($public_suffixes) { return $public_suffixes; }
109 no warnings 'once'; ## no critic
110 $Mail::DMARC::psl_loads++;
111 my $file = $self->find_psl_file();
112 $public_suffixes_stamp = ( stat($file) )[9];
113  
114 open my $fh, '<:encoding(UTF-8)', $file
115 or croak "unable to open $file for read: $!\n";
116  
117 # load PSL into hash for fast lookups, esp. for long running daemons
118 my %psl = map { $_ => 1 }
119 grep { $_ !~ /^[\/\s]/ } # weed out comments & whitespace
120 map { chomp($_); $_ } ## no critic, remove line endings
121 <$fh>;
122 close $fh;
123 return $public_suffixes = \%psl;
124 }
125  
126 sub check_public_suffix_list($self) {
127 my $file = $self->find_psl_file();
128 my $new_public_suffixes_stamp = ( stat($file) )[9];
129 if ( $new_public_suffixes_stamp != $public_suffixes_stamp ) {
130 $public_suffixes = undef;
131 $self->get_public_suffix_list();
132 return 1;
133 }
134 return 0;
135 }
136 }
137  
138 sub is_public_suffix( $self, $zone ) {
139 croak "missing zone name!" if !$zone;
140  
141 my $public_suffixes = $self->get_public_suffix_list();
142  
143 $zone = URI::_idna::decode( $zone, 0 ) // $zone if $zone =~ /xn--/;
144  
145 # Check for exception rules
146 return 0 if $public_suffixes->{"!$zone"};
147  
148 # Check for direct match
149 return 1 if $public_suffixes->{$zone};
150  
151 # Check for wildcard match
152 my @labels = split /\./, $zone;
153 if ( @labels > 1 ) {
154 my $wildcard = join '.', '*', (@labels)[ 1 .. scalar(@labels) - 1 ];
155 return 1 if $public_suffixes->{$wildcard};
156 }
157  
158 return 0;
159 }
160  
161 sub update_psl_file( $self, $dryrun = undef ) {
162 my $psl_file = $self->find_psl_file();
163  
164 die "No Public Suffix List file found\n" if ( !$psl_file );
165 die "Public suffix list file $psl_file not found\n" if ( !-f $psl_file );
166 die "Cannot write to Public Suffix List file $psl_file\n" if ( !-w $psl_file );
167  
168 my $url = 'https://publicsuffix.org/list/effective_tld_names.dat';
169 if ($dryrun) {
170 print
171 "Will attempt to update the Public Suffix List file at $psl_file (dryrun mode)\n";
172 return;
173 }
174  
175 my $response = HTTP::Tiny->new->mirror( $url, $psl_file );
176 my $content = $response->{'content'};
177 if ( !$response->{'success'} ) {
178 my $status = $response->{'status'};
179 die
180 "HTTP Request for Public Suffix List file failed with error $status ($content)\n";
181 }
182 else {
183 if ( $response->{'status'} eq '304' ) {
184 print "Public Suffix List file $psl_file not modified\n";
185 }
186 else {
187 print "Public Suffix List file $psl_file updated\n";
188 }
189 }
190 return;
191 }
192  
193 sub find_psl_file($self) {
194 my $file
195 = $self->config->{dns}{public_suffix_list} || 'share/public_suffix_list';
196 if ( $file =~ /^\// && -f $file && -r $file ) {
197 print "using $file for Public Suffix List\n" if $self->verbose;
198 return $file;
199 }
200  
201 foreach my $path ( $self->get_prefix($file) ) {
202 if ( -f $path && -r $path ) {
203 print "using $path for Public Suffix List\n"; # if $self->verbose;
204 return $path;
205 }
206 }
207  
208 # Fallback to included suffic list
209 return $self->get_sharefile('public_suffix_list');
210 }
211  
212 sub has_dns_rr( $self, $type, $domain ) {
213 my @matches;
214 my $res = $self->get_resolver();
215 my $query = $res->query( $domain, $type ) or do {
216 return 0 if !wantarray;
217 return @matches;
218 };
219 for my $rr ( $query->answer ) {
220 next if $rr->type ne $type;
221 push @matches,
222 $rr->type eq 'A' ? $rr->address
223 : $rr->type eq 'PTR' ? $rr->ptrdname
224 : $rr->type eq 'NS' ? $rr->nsdname
225 : $rr->type eq 'TXT' ? $rr->txtdata
226 : $rr->type eq 'SPF' ? $rr->txtdata
227 : $rr->type eq 'AAAA' ? $rr->address
228 : $rr->type eq 'MX' ? $rr->exchange
229 : $rr->answer;
230 }
231 return scalar @matches if !wantarray;
232 return @matches;
233 }
234  
235 sub epoch_to_iso( $self, $epoch ) {
236 my @fields = localtime($epoch);
237  
238 my $ss = sprintf( "%02i", $fields[0] ); # seconds
239 my $mn = sprintf( "%02i", $fields[1] ); # minutes
240 my $hh = sprintf( "%02i", $fields[2] ); # hours (24 hour clock)
241  
242 my $dd = sprintf( "%02i", $fields[3] ); # day of month
243 my $mm = sprintf( "%02i", $fields[4] + 1 ); # month
244 my $yy = ( $fields[5] + 1900 ); # year
245  
246 return "$yy-$mm-$dd" . 'T' . "$hh:$mn:$ss";
247 }
248  
249 sub get_resolver( $self, $timeout = undef, $retrans = undef ) {
250 $timeout ||= $self->config->{dns}{timeout} || 5;
251 $retrans ||= $self->config->{dns}{retrans} || 5;
252 return $self->{resolver} if defined $self->{resolver};
253 $self->{resolver} = Net::DNS::Resolver->new( dnsrch => 0 );
254 $self->{resolver}->tcp_timeout($timeout);
255 $self->{resolver}->udp_timeout($timeout);
256 $self->{resolver}->retrans($retrans);
257 return $self->{resolver};
258 }
259  
260 sub set_resolver( $self, $resolver ) {
261 $self->{resolver} = $resolver;
262 return;
263 }
264  
265 sub to_ascii_domain( $self, $domain ) {
266 return $domain unless $domain =~ /[^\x00-\x7F]/; # fast path: ASCII only
267 # Convert each U-label to its A-label (punycode) equivalent per RFC 8616 §6
268 my @ascii_labels = map {
269 if (/[^\x00-\x7F]/) {
270 my $ascii = eval { URI::_idna::encode($_) };
271 $ascii // $_;
272 }
273 else {
274 $_;
275 }
276 } split /\./, $domain;
277 return join '.', @ascii_labels;
278 }
279  
280 sub is_valid_ip( $self, $ip ) {
281 return 0 if !defined $ip;
282  
283 my $family = $ip =~ /:/ ? AF_INET6 : AF_INET;
284 return defined Socket::inet_pton( $family, $ip ) ? 1 : 0;
285 }
286  
287 # RFC 1101
288 my $dotted_quad = qr/(?:25[0-5]|2[0-4][0-9]|[0-1]?[0-9]{1,2})/;
289 my $not_an_ip = qr/(?!(?:$dotted_quad[.]$dotted_quad[.]$dotted_quad[.]$dotted_quad)(?:[.]|$))/;
290 my $host_label = qr/$not_an_ip[A-Za-z0-9](?:[-A-Za-z0-9]{0,61}[A-Za-z0-9])?/;
291  
292 sub is_valid_domain( $self, $domain ) {
293 return 0 if $domain !~ /^$host_label(?:\.$host_label)*$/x;
294 my $tld = ( split /\./, $domain )[-1];
295 return 1 if $self->is_public_suffix($tld);
296 return 0 if $domain eq 'localhost';
297 return 0 if $tld eq 'localdomain';
298 return 0 if -1 == index( $domain, '.' );
299 $tld = join( '.', ( split /\./, $domain )[ -2, -1 ] );
300 return 1 if $self->is_public_suffix($tld);
301 return 0;
302 }
303  
304 sub is_valid_spf_scope( $self, $scope ) {
305 return if !defined $scope;
306 return lc $scope if grep { lc $scope eq $_ } qw/ mfrom helo /;
307 carp "$scope is not a valid SPF scope";
308 return;
309 }
310  
311 sub is_valid_spf_result( $self, $result ) {
312 return if !defined $result;
313 return 1
314 if grep { lc $result eq $_ }
315 qw/ fail neutral none pass permerror softfail temperror /;
316 carp "$result is not a valid SPF result";
317 return;
318 }
319  
320 sub slurp( $self, $file ) {
321 open my $FH, '<', $file or croak "unable to read $file: $!";
322 my $contents = do { local $/; <$FH> }; ## no critic (Local)
323 close $FH;
324 return $contents;
325 }
326  
327 sub verbose( $self, $val = undef ) {
328 return $self->{verbose} if @_ == 1;
329 return $self->{verbose} = $val;
330 }
331  
332 1;
333  
334 __END__
335  
336 =pod
337  
338 =head1 NAME
339  
340 Mail::DMARC::Base - DMARC utility functions
341  
342 =head1 VERSION
343  
344 version 2.20260827
345  
346 =head1 METHODS
347  
348 =head2 is_public_suffix
349  
350 Determines if part of a domain is a Top Level Domain (TLD). Examples of TLDs are com, net, org, co.ok, am, and us.
351  
352 Determination is made by consulting a Public Suffix List. The included PSL is from mozilla.org. See http://publicsuffix.org/list/ for more information, and a link to download the latest PSL.
353  
354 =head2 update_psl_file
355  
356 Download a new Public Suffix List file from mozilla and update the installed file with the new copy.
357  
358 =head2 has_dns_rr
359  
360 Determine if a DNS Resource Record of the specified type exists at the DNS name provided.
361  
362 =head2 get_resolver
363  
364 Returns a (cached) Net::DNS::Resolver object
365  
366 =head2 set_resolver
367  
368 Set the Net::DNS::Resolver object to be used for lookups
369  
370 =head2 is_valid_ip
371  
372 Determines if the supplied IP address is a valid IPv4 or IPv6 address.
373  
374 =head2 is_valid_domain
375  
376 Determine if a string is a legal RFC 1034 or 1101 host name.
377  
378 Half the reason to test for domain validity is to shave seconds off our processing time by not having to process DNS queries for illegal host names. The other half is to raise exceptions if methods are being called incorrectly.
379  
380 =head1 SEE ALSO
381  
382 Mozilla Public Suffix List: http://publicsuffix.org/list/
383  
384 =head1 AUTHORS
385  
386 =over 4
387  
388 =item *
389  
390 Matt Simerson <msimerson@cpan.org>
391  
392 =item *
393  
394 Davide Migliavacca <shari@cpan.org>
395  
396 =item *
397  
398 Marc Bradshaw <marc@marcbradshaw.net>
399  
400 =back
401  
402 =head1 COPYRIGHT AND LICENSE
403  
404 This software is copyright (c) 2026 by Matt Simerson.
405  
406 This is free software; you can redistribute it and/or modify it under
407 the same terms as the Perl 5 programming language system itself.
408  
409 =cut