blib/lib/Net/DNS/SPF/Expander.pm untested

filter: Statementstmt 0.0% 0 / 339 Branchbran 0.0% 0 / 50 Conditioncond 0.0% 0 / 18 MC/DCmcdc n/a Subroutinesub 0.0% 0 / 31 Podpod 0.0% 0 / 24 totaltotal 0.0% 0 / 462 CC 25 SCAR 27.1
CC
25
Cov
0%
_expand_spf_component
42.0
_new_records_from_partition
42.0
_normalize_record_name
20.0
CRAP 15.0
1 package Net::DNS::SPF::Expander;
2 $Net::DNS::SPF::Expander::VERSION = '0.015';
3 use Moose;
4 use IO::All -utf8;
5 use Net::DNS::ZoneFile;
6 use Net::DNS::Resolver;
7 use MooseX::Types::IO::All 'IO_All';
8 use List::AllUtils qw(sum any part first uniq);
9 use Scalar::Util ();
10  
11 with 'MooseX::Getopt';
12  
13 # ABSTRACT: Expands DNS SPF records, so you don't have to.
14 # The problem is that you only get 10 per SPF records,
15 # and recursions count against you. Your record won't
16 # validate.
17  
18 =head1 NAME
19  
20 Net::DNS::SPF::Expander
21  
22 =head1 DESCRIPTION
23  
24 This module expands DNS SPF records, so you don't have to.
25 The problem is that you only get 10 per SPF record,
26 and recursions count against you. Your record won't
27 validate.
28  
29 Let's say you start with this as an SPF record:
30  
31 @ TXT "v=spf1 include:_spf.google.com include:sendgrid.net a:hq1.campusexplorer.com a:hq2.campusexplorer.com a:mail2.campusexplorer.com ~all"
32  
33 You go to http://www.kitterman.com/spf/validate.html and check this record.
34 It passes validation. But later you come back and add salesforce, so that you
35 now have:
36  
37 @ TXT "v=spf1 include:_spf.google.com include:sendgrid.net include:salesforce.com a:hq1.campusexplorer.com a:hq2.campusexplorer.com a:mail2.campusexplorer.com ~all"
38  
39 And now your record fails validation.
40  
41 _spf.google.com takes 3 lookups.
42 _spf1.google.com
43 _spf2.google.com
44 _spf3.google.com
45 sendgrid.net takes 1 lookup.
46 _sendgrid.biz
47 hq1 takes 1 lookup.
48 hq2 takes 1 lookup.
49 mail2 takes 1 lookup.
50  
51 Salesforce adds:
52  
53 _spf.google.com (3 you already did)
54 _spf1.google.com
55 _spf2.google.com
56 _spf3.google.com
57 mx takes 4 lookups.
58 salesforce.com.s8a1.psmtp.com.
59 salesforce.com.s8a2.psmtp.com.
60 salesforce.com.s8b1.psmtp.com.
61 salesforce.com.s8b2.psmtp.com.
62  
63 So now instead of 7 you have 14. The common advice is to
64 expand them, and that is a tedious process. It's especially
65 tedious when, say, salesforce changes their mx record.
66  
67 So this module and the accompanying script attempt
68 to automate this process for you.
69  
70 =head1 SYNOPSIS
71  
72 Using the script:
73  
74 myhost:~/ $ dns-dpf-expander --input_file zone.db
75 myhost:~/ $ ls
76 zone.db zone.db.new zone.db.bak
77  
78 Using the module:
79  
80 {
81 package MyDNSExpander;
82  
83 use Net::DNS::SPF::Expander;
84  
85 my $input_file = '/home/me/project/etc/zone.db';
86 my $expander = Net::DNS::SPF::Expander->new(
87 input_file => $input_file
88 );
89  
90 my $string = $expander->write;
91  
92 1;
93 }
94  
95 =head1 CONFIGURABLE ATTRIBUTES
96  
97 =head2 input_file
98  
99 This is the path and name of the zonefile whose SPF records you want
100 to expand. It must be a valid L<Net::DNS::Zonefile> zonefile.
101  
102 =cut
103  
104 has 'input_file' => (
105 is => 'ro',
106 isa => 'Str',
107 required => 1,
108 );
109  
110 =head2 output_file
111  
112 The path and name of the output file. By default, we tack ".new"
113 onto the end of the original filename.
114  
115 =cut
116  
117 has 'output_file' => (
118 is => 'ro',
119 isa => 'Str',
120 lazy_build => 1,
121 );
122  
123 =head2 backup_file
124  
125 The path and name of the backup file. By default, we tack ".bak"
126 onto the end of the original filename.
127  
128 =cut
129  
130 has 'backup_file' => (
131 is => 'ro',
132 isa => IO_All,
133 lazy_build => 1,
134 coerce => 1,
135 );
136  
137 =head2 nameservers
138  
139 A list of nameservers that will be passed to the resolver.
140  
141 =cut
142  
143 has 'nameservers' => (
144 is => 'ro',
145 isa => 'Maybe[ArrayRef]',
146 );
147  
148 =head2 parsed_file
149  
150 The L<Net::DNS::Zonefile> object created from the input_file.
151  
152 =cut
153  
154 has 'parsed_file' => (
155 is => 'ro',
156 isa => 'Net::DNS::ZoneFile',
157 lazy_build => 1,
158 );
159  
160 =head2 to_expand
161  
162 An arrayref of regexes that we will expand. By default we expand
163 a, mx, include, and redirect records. Configurable.
164  
165 =cut
166  
167 has 'to_expand' => (
168 is => 'ro',
169 isa => 'ArrayRef[RegexpRef]',
170 default => sub {
171 [ qr/^a:/, qr/^mx/, qr/^include/, qr/^redirect/, ];
172 },
173 );
174  
175 =head2 to_copy
176  
177 An arrayref of regexes that we will simply copy over. By default
178 we will copy ip4, ip6, ptr, and exists records. Configurable.
179  
180 =cut
181  
182 has 'to_copy' => (
183 is => 'rw',
184 isa => 'ArrayRef[RegexpRef]',
185 default => sub {
186 [ qr/v=spf1/, qr/^ip4/, qr/^ip6/, qr/^ptr/, qr/^exists/, ];
187 },
188 );
189  
190 =head2 to_ignore
191  
192 An arrayref of regexes that we will ignore. By default we ignore ?all,
193 exp, v=spf1, and ~all.
194  
195 =cut
196  
197 has 'to_ignore' => (
198 is => 'ro',
199 isa => 'ArrayRef[RegexpRef]',
200 default => sub {
201 [ qr/^v=spf1/, qr/^(\??)all/, qr/^exp/, qr/^~all/ ];
202 },
203 );
204  
205 =head2 maximum_record_length
206  
207 We leave out the protocol declaration and the trailing ~all
208 while we are expanding records, so we need to subtract their length
209 from our length calculation.
210  
211 =cut
212  
213 has 'maximum_record_length' => (
214 is => 'ro',
215 isa => 'Int',
216 default => sub {
217 255 - length('v=spf1 ') - length(' ~all') - length('"') - length('"');
218 },
219 );
220  
221 =head2 ttl
222  
223 Default time to live is 10 minutes. Configurable.
224  
225 =cut
226  
227 has 'ttl' => (
228 is => 'ro',
229 isa => 'Str',
230 default => sub {
231 '10M',;
232 },
233 );
234  
235 =head2 origin
236  
237 The origin of the zonefile. We take it from the zonefile,
238 or you can set it if you like.
239  
240 =cut
241  
242 has 'origin' => (
243 is => 'ro',
244 isa => 'Str',
245 lazy_build => 1,
246 );
247  
248 =head1 PRIVATE ATTRIBUTES
249  
250 =head2 _input_file
251  
252 The L<IO::All> object created from the input_file.
253  
254 =cut
255  
256 has '_input_file' => (
257 is => 'ro',
258 isa => IO_All,
259 coerce => 1,
260 lazy_build => 1,
261 );
262  
263 =head2 _resource_records
264  
265 An arrayref of all the L<Net::DNS::RR> resource records
266 found in the entire parsed_file.
267  
268 =cut
269  
270 has '_resource_records' => (
271 is => 'ro',
272 isa => 'Maybe[ArrayRef[Net::DNS::RR]]',
273 lazy_build => 1,
274 );
275  
276 =head2 _spf_records
277  
278 An arrayref of the L<Net::DNS::RR::TXT> or L<Net::DNS::RR::SPF>
279 records found in the entire parsed_file.
280  
281 =cut
282  
283 has '_spf_records' => (
284 is => 'ro',
285 isa => 'Maybe[ArrayRef[Net::DNS::RR]]',
286 lazy_build => 1,
287 );
288  
289 =head2 _resolver
290  
291 What we use to do the DNS lookups and expand the records. A
292 L<Net::DNS::Resolver> object. You can still set environment
293 variables if you want to change the nameserver it uses.
294  
295 =cut
296  
297 has '_resolver' => (
298 is => 'ro',
299 isa => 'Net::DNS::Resolver',
300 lazy_build => 1,
301 );
302  
303 =head2 _expansions
304  
305 This is a hashref representing the expanded SPF records. The keys
306 are the names of the SPF records, and the values are hashrefs.
307 Those are keyed on the include, and the values are arrayrefs of the
308 expanded values. There is also a key called "elements" which gathers
309 all the includes into one place, e.g.,
310  
311 "*.test_zone.com" => {
312 "~all" => undef,
313 elements => [
314 "ip4:216.239.32.0/19", "ip4:64.233.160.0/19",
315 "ip4:66.249.80.0/20", "ip4:72.14.192.0/18",
316 ...
317 ],
318 "include:_spf.google.com" => [
319 "ip4:216.239.32.0/19",
320 "ip4:64.233.160.0/19",
321 ...
322 ],
323 "ip4:96.43.144.0/20" => [ "ip4:96.43.144.0/20" ],
324 "v=spf1" => undef
325 }
326  
327 They are alpha sorted in the final results for predictability in tests.
328  
329 =cut
330  
331 has '_expansions' => (
332 is => 'ro',
333 isa => 'HashRef',
334 lazy_build => 1,
335 );
336  
337 =head2 _lengths_of_expansions
338  
339 We need to know how long the expanded record would be, because
340 SPF records should be less than 256 bytes. If the expanded
341 record would be longer than that, we need to split it into
342 pieces.
343  
344 =cut
345  
346 has '_lengths_of_expansions' => (
347 is => 'ro',
348 isa => 'HashRef',
349 lazy_build => 1,
350 );
351  
352 =head2 _record_class
353  
354 What sort of records are SPF records? IN records.
355  
356 =cut
357  
358 has '_record_class' => (
359 is => 'ro',
360 isa => 'Str',
361 default => sub {
362 'IN',;
363 },
364 );
365  
366 =head1 BUILDERS
367  
368 =head2 _build_resolver
369  
370 Return a L<Net::DNS::Resolver>. Any nameservers will be passed
371 through to the resolver.
372  
373 =cut
374  
375 sub _build__resolver {
376 my $self = shift;
377 my $nameservers = $self->nameservers;
378 my $resolver = Net::DNS::Resolver->new(
379 recurse => 1,
380 ( $nameservers ? ( nameservers => $nameservers ) : () ),
381 );
382 return $resolver;
383 }
384  
385 =head2 _build_origin
386  
387 Extract the origin from parsed_file.
388  
389 =cut
390  
391 sub _build_origin {
392 my $self = shift;
393 return $self->parsed_file->origin;
394 }
395  
396 =head2 _build_expansions
397  
398 =cut
399  
400 sub _build__expansions {
401 my $self = shift;
402 return $self->_expand;
403 }
404  
405 =head2 _build_backup_file
406  
407 Tack a ".bak" onto the end of the input_file.
408  
409 =cut
410  
411 sub _build_backup_file {
412 my $self = shift;
413 my $path = $self->_input_file->filepath;
414 my $name = $self->_input_file->filename;
415 return "${path}${name}.bak";
416 }
417  
418 =head2 _build__input_file
419  
420 Turn the string input_file into a filehandle with
421 L<IO::All>.
422  
423 =cut
424  
425 sub _build__input_file {
426 my $self = shift;
427 return to_IO_All( $self->input_file );
428 }
429  
430 =head2 _build_output_file
431  
432 Tack a ".new" onto the end of the input_file.
433  
434 =cut
435  
436 sub _build_output_file {
437 my $self = shift;
438 my $path = $self->_input_file->filepath;
439 my $name = $self->_input_file->filename;
440 return "${path}${name}.new";
441 }
442  
443 =head2 _build_parsed_file
444  
445 Turn the L<IO::All> filehandle into a L<Net::DNS::Zonefile>
446 object, so that we can extract the SPF records.
447  
448 =cut
449  
450 sub _build_parsed_file {
451 my $self = shift;
452 my $path = $self->_input_file->filepath;
453 my $name = $self->_input_file->filename;
454 return Net::DNS::ZoneFile->new("${path}${name}");
455 }
456  
457 =head2 _build_resource_records
458  
459 Extract all the resource records from the L<Net::DNS::Zonefile>.
460  
461 =cut
462  
463 sub _build__resource_records {
464 my $self = shift;
465 my @resource_records = $self->parsed_file->read;
466 return \@resource_records;
467 }
468  
469 =head2 _build__spf_records
470  
471 Grep through the _resource_records to find the SPF
472 records. They can be both "TXT" and "SPF" records,
473 so we search for the protocol string, v=spf1.
474  
475 =cut
476  
477 sub _build__spf_records {
478 my $self = shift;
479  
480 # This is crude but correct: SPF records can be both TXT and SPF.
481 my @spf_records =
482 grep { $_->txtdata =~ /v=spf1/ }
483 grep { $_->can('txtdata') }
484 @{ $self->_resource_records };
485 return \@spf_records;
486 }
487  
488 =head2 _build__lengths_of_expansions
489  
490 Calculate the length of each fully expanded SPF record,
491 because they can't be longer than 256 bytes. We have to split them
492 up into multiple records if they are.
493  
494 =cut
495  
496 sub _build__lengths_of_expansions {
497 my $self = shift;
498 my $expansions = $self->_expansions;
499 my $length_per_domain = {};
500 for my $domain ( keys %$expansions ) {
501 my $record_string = join(
502 ' ',
503 @{ $expansions->{$domain}{elements} }
504 );
505 $length_per_domain->{$domain} = length($record_string);
506 }
507 return $length_per_domain;
508 }
509  
510 =head1 PUBLIC METHODS
511  
512 =head2 write
513  
514 This is the only method you really need to call. This expands all your SPF
515 records and writes out the new and the backup files.
516  
517 Returns a scalar string of the data written to the file.
518  
519 =cut
520  
521 sub write {
522 my $self = shift;
523 my $lines = $self->_new_records_lines;
524 my $path = $self->_input_file->filepath;
525 my $name = $self->_input_file->filename;
526 io( $self->backup_file )->print( $self->_input_file->all );
527 io( $self->output_file )->print(@$lines);
528 return join( '', @$lines );
529 }
530  
531 =head2 new_spf_records
532  
533 In case you want to see how your records were expanded, this returns
534 the hashref of L<Net::DNS::RR> objects used to create the new records.
535  
536 =cut
537  
538 sub new_spf_records {
539 my $self = shift;
540 my $lengths = $self->_lengths_of_expansions;
541 my $expansions = $self->_expansions;
542  
543 my %new_spf_records = ();
544  
545 for my $domain ( keys %$lengths ) {
546 my $new_records = [];
547  
548 # We need to make sure the SPF record is less than 256 chars,
549 # including the spf version and trailing ~all.
550 if ( $lengths->{$domain} > $self->maximum_record_length ) {
551 $new_records = $self->_new_records_from_partition(
552 $domain,
553 $expansions->{$domain}{elements},
554 );
555 } else {
556 $new_records = $self->_new_records_from_arrayref(
557 $domain,
558 $expansions->{$domain}{elements},
559 );
560 }
561 $new_spf_records{$domain} = $new_records;
562 }
563 return \%new_spf_records;
564 }
565  
566 =head1 PRIVATE METHODS
567  
568 =head2 _normalize_component
569  
570 Each component of an SPF record has a prefix, like include:, mx:, etc.
571 Here we chop off the prefix before performing the lookup on the value.
572  
573 =cut
574  
575 sub _normalize_component {
576 my ( $self, $component ) = @_;
577 my $return = $component;
578 $return =~ s/^.+?://g;
579 return $return;
580 }
581  
582 =head2 _perform_expansion
583  
584 Expand a single SPF record component. This returns either undef or the
585 full SPF record string from L<Net::DNS::RR::TXT>->txtdata.
586  
587 =cut
588  
589 sub _perform_expansion {
590 my ( $self, $component ) = @_;
591 $component = $self->_normalize_component($component);
592 my $packet = $self->_resolver->search( $component, 'TXT', 'IN' );
593 return unless ($packet) && $packet->isa('Net::DNS::Packet');
594 my ($answer) = $packet->answer;
595 return unless ($answer) && $answer->isa('Net::DNS::RR::TXT');
596 my $data = $answer->txtdata;
597 return $data;
598 }
599  
600 =head2 _expand_spf_component
601  
602 Recursively call _perform_expansion for each component of the SPF record.
603 This returns an array consisting of the component, e.g., include:salesforce.com,
604 and an arrayref consisting of its full expansion, e.g.,
605  
606 [
607 "ip4:216.239.32.0/19",
608 "ip4:64.233.160.0/19",
609 ...
610 "ip6:2c0f:fb50:4000::/36"
611 ]
612  
613 =cut
614  
615 sub _expand_spf_component {
616 my ( $self, $component, $expansions ) = @_;
617  
618 $expansions ||= [];
619  
620 return unless $component;
621  
622 my @component_splits = split( ' ', $component );
623 my $splits = @component_splits;
624 if ( $splits > 1 ) {
625 for my $component (@component_splits) {
626 $self->_expand_spf_component( $component, $expansions );
627 }
628 } else {
629 if (( any { $component =~ $_ } @{ $self->to_ignore } )) {
630 return $component;
631 } elsif (( any { $component =~ $_ } @{ $self->to_copy } )) {
632 push @{$expansions}, $component;
633 } elsif (( any { $component =~ $_ } @{ $self->to_expand } )) {
634 my $new_component = $self->_perform_expansion($component);
635 $self->_expand_spf_component( $new_component, $expansions );
636 } else {
637 return $component;
638 }
639 }
640 return ( $component, $expansions );
641 }
642  
643 =head2 _expand
644  
645 Create the _expansions hashref from which we generate new SPF records.
646  
647 =cut
648  
649 sub _expand {
650 my $self = shift;
651 my %spf_hash = ();
652 my %keys_to_delete = ();
653 for my $spf_record ( @{ $self->_spf_records } ) {
654 my @spf_components = split( ' ', $spf_record->txtdata );
655 for my $spf_component (@spf_components) {
656 my $component_name = $self->_normalize_component($spf_component);
657 # We want to make sure that we do not look up spf records that are
658 # defined in this zonefile. So that we could run this tool on a
659 # previously expanded zonefile if we want to. That sort of defeats
660 # the point of the tool, but you may edit the previously expanded zonefile,
661 # adding a new include: or mx, appending it to the other _spfX includes.
662 # We just take the component and its existing expansions and stick them
663 # into the component's parent as a key and value, and then we remove that
664 # component as a separate key from our hash.
665 if ( any { $component_name eq $_->name } @{ $self->_spf_records } ) {
666 my ($zonefile_record)
667 = grep { $component_name eq $_->name }
668 @{ $self->_spf_records };
669 my ( $comp, $expansions )
670 = $self->_expand_spf_component(
671 $zonefile_record->txtdata );
672 $spf_hash{ $spf_record->name }{$spf_component} = $expansions;
673 $keys_to_delete{$component_name} = 1;
674 # If the include or what have you is not defined in the zonefile,
675 # proceed as normal.
676 } else {
677 my ( $comp, $expansions )
678 = $self->_expand_spf_component($spf_component);
679 $spf_hash{ $spf_record->name }{$spf_component} = $expansions;
680 }
681 }
682 my $expansion_elements = $self->_extract_expansion_elements(
683 $spf_hash{ $spf_record->name } );
684 $spf_hash{ $spf_record->name }{elements} = $expansion_elements;
685 }
686 delete @spf_hash{ keys %keys_to_delete };
687 return \%spf_hash;
688 }
689  
690 =head2 _extract_expansion_elements
691  
692 Filter ignored elements from component expansions.
693  
694 =cut
695  
696 sub _extract_expansion_elements {
697 my ( $self, $expansions ) = @_;
698 my @elements = ();
699 my @leading = ();
700 my @trailing = ();
701 KEY: for my $key ( keys %$expansions ) {
702 if ( any { $key =~ $_ } @{ $self->to_ignore } ) {
703 next KEY;
704 }
705 if ( ref( $expansions->{$key} ) eq 'ARRAY' ) {
706 for my $expansion ( @{ $expansions->{$key} } ) {
707 push @elements, $expansion;
708 }
709 }
710 }
711 # We sort these so we can be sure of the order in tests.
712 my @return = uniq sort ( @leading, @elements, @trailing );
713 return \@return;
714 }
715  
716 =head2 _new_records_from_arrayref
717  
718 The full expansion of a given SPF record is contained in an arrayref,
719 and if the length of the resulting new SPF record would be less than the
720 maximum_record_length, we can use this method to make new
721 L<Net::DNS::RR> objects that will later be stringified for the new
722 SPF record.
723  
724 =cut
725  
726 sub _new_records_from_arrayref {
727 my ( $self, $domain, $expansions ) = @_;
728  
729  
730 my @new_records = ();
731 for my $type ( 'TXT', 'SPF' ) {
732 push @new_records,
733 new Net::DNS::RR(
734 type => $type,
735 name => $domain,
736 class => $self->_record_class,
737 ttl => $self->ttl,
738 txtdata => join( ' ', @$expansions ),
739 );
740 }
741 return \@new_records;
742 }
743  
744 =head2 _new_records_from_partition
745  
746 The full expansion of a given SPF record is contained in an arrayref,
747 and if the length of the resulting new SPF record would be greater than the
748 maximum_record_length, we have to jump through some hoops to properly split
749 it into new SPF records. Because there will be more than one, and each needs
750 to be less than the maximum_record_length. We do our partitioning here, and
751 then call _new_records_from_arrayref on each of the resulting partitions.
752  
753 =cut
754  
755 sub _new_records_from_partition {
756 my ( $self, $domain, $elements, $partitions_only ) = @_;
757 my $record_string = join( ' ', @$elements );
758 my $record_length = length($record_string);
759 my $max_length = $self->maximum_record_length;
760 my $offset = 0;
761 my $result = index( $record_string, ' ', $offset );
762 my @space_indices = ();
763  
764 while ( $result != -1 ) {
765 push @space_indices, $result if $result;
766 $offset = $result + 1;
767 $result = index( $record_string, ' ', $offset );
768 }
769  
770 my $number_of_partitions = int( $record_length / $max_length )
771 + ( ( $record_length % $max_length ) ? 1 : 0 );
772  
773 my @partitions = ();
774 my $partition_offset = 0;
775  
776 for my $part ( 1 .. $number_of_partitions ) {
777  
778 # We want the first space_index that is
779 # 1. less than the max_length times the number of parts, and
780 # 2. subtracting the partition_offset from it is less than
781 # max_length.
782 my $split_point = first {
783 ( $_ < ( $max_length * $part ) )
784 && ( ( $_ - $partition_offset ) < $max_length )
785 } reverse @space_indices;
786  
787 my $partition_length = $split_point - $partition_offset;
788  
789 # Go to the end of the string if we are dealing with
790 # the last partition. Otherwise, the last element
791 # gets chopped off, because it is after the last space_index!
792 my $length
793 = ( $part == $number_of_partitions ) ? undef : $partition_length;
794 my $substring;
795 if ( $part == $number_of_partitions ) {
796 # Go to the end.
797 $substring = substr( $record_string, $partition_offset );
798 } else {
799 # Take a specific length.
800 $substring = substr( $record_string, $partition_offset,
801 $partition_length );
802 }
803  
804 push @partitions, [ split( ' ', $substring ) ];
805 $partition_offset = $split_point;
806 }
807 return \@partitions if $partitions_only;
808  
809 my @return = ();
810  
811 for my $partition (@partitions) {
812 my $result = $self->_new_records_from_arrayref( $domain, $partition );
813 push @return, $result;
814 }
815 return \@return;
816 }
817  
818 =head2 _get_single_record_string
819  
820 Stringify the L<Net::DNS::RR::TXT> records when they will fit into
821 a single SPF record.
822  
823 =cut
824  
825 sub _get_single_record_string {
826 my ( $self, $domain, $record_set ) = @_;
827 my $origin = $self->origin;
828  
829 my @record_strings = ();
830  
831 my @sorted_record_set = map { $_ }
832 # We sort first by the string, and then by the type,
833 # so that TXT goes first, before SPF.
834 sort { $b->type cmp $a->type }
835 sort { $a->string cmp $b->string }
836 @$record_set;
837  
838 for my $record (@sorted_record_set) {
839 $record->name($domain);
840 $record->txtdata( 'v=spf1 ' . $record->txtdata . ' ~all' );
841 my $string = $self->_normalize_record_name( $record->string ) . "\n";
842 $string =~ s/\t/ /g;
843 push @record_strings, $string;
844 }
845 return \@record_strings;
846 }
847  
848 =head2 _normalize_record_name
849  
850 L<Net::DNS> uses fully qualified record names, so that new SPF records
851 will be named *.domain.com, and domain.com, instead of * and @. I prefer
852 the symbols. This code replaces the fully qualified record names with symbols.
853  
854 =cut
855  
856 sub _normalize_record_name {
857 my ( $self, $record ) = @_;
858  
859 $record =~ /(.+?)\s/;
860 my $original_name = $1;
861 my $origin = $self->origin;
862  
863 my $name;
864  
865 if ( $original_name =~ /^$origin(.?)$/ ) {
866 $name = '@';
867 } elsif ( $original_name =~ /^\.$/ ) {
868 $name = '@';
869 } elsif ( $original_name =~ /^\*/ ) {
870 $name = '*';
871 } else {
872 $name = $original_name;
873 }
874 $record =~ s/\Q$original_name\E/$name/g;
875 return $record;
876 }
877  
878 =head2 _get_multiple_record_strings
879  
880 Whereas a single new SPF record needs to be concatenated from
881 the stringified L<Net::DNS::RR::TXT>s, and have the trailing
882 ~all added, multiple new SPF records do not need that. They need to be given
883 special _spf names that will then be included in "master" SPF records, and
884 they don't need the trailing ~all.
885  
886 =cut
887  
888 sub _get_multiple_record_strings {
889 my ( $self, $values, $start_index ) = @_;
890 my $origin = $self->origin;
891  
892 my @record_strings = ();
893  
894 my @containing_records = ();
895  
896 for my $type ( 'TXT', 'SPF' ) {
897 my $i = $start_index // 1;
898 for my $value (@$values) {
899 push @containing_records,
900 new Net::DNS::RR(
901 type => $type,
902 name => "_spf$i.$origin",
903 class => $self->_record_class,
904 ttl => $self->ttl,
905 txtdata => 'v=spf1 ' . $value,
906 );
907 $i++;
908 }
909 }
910  
911 @record_strings = map { my $string = $self->_normalize_record_name( $_->string ) . "\n"; $string =~ s/\t/ /g; $string; }
912 # We sort first by the string, and then by the type,
913 # so that TXT goes first, before SPF.
914 sort { $b->type cmp $a->type }
915 sort { $a->string cmp $b->string }
916 @containing_records;
917  
918 return \@record_strings;
919 }
920  
921 =head2 _get_master_record_strings
922  
923 Create our "master" SPF records that include the split _spf records created
924 in _get_multiple_record_strings, e.g.,
925  
926 * 600 IN TXT "v=spf1 include:_spf1.test_zone.com include:_spf2.test_zone.com ~all"
927  
928 =cut
929  
930 sub _get_master_record_strings {
931 my ( $self, $values, $domains ) = @_;
932  
933 (my $origin = $self->origin) =~ s/\.$//g;
934 my @record_strings = ();
935  
936 my @containing_records = ();
937 my $additional_records = [];
938  
939 my $master_records = [ map {"include:_spf$_.$origin"} ( 1 .. scalar(@$values)) ];
940 my $master_record = join(' ', @$master_records);
941  
942 # If our master record will be too long, split it into a set of nested includes
943 if (length($master_record) > $self->maximum_record_length) {
944  
945 my $new_master_record_partitions = $self->_new_records_from_partition(
946 "master",
947 $master_records,
948 1, # Just return raw partitions
949 );
950  
951 for my $type ( 'TXT', 'SPF' ) {
952 for my $domain (@$domains) {
953  
954 push @containing_records, new Net::DNS::RR(
955 type => $type,
956 name => $domain,
957 class => $self->_record_class,
958 ttl => $self->ttl,
959 txtdata => 'v=spf1 ' . (join(
960 ' ',
961 ( map {"include:_spf$_.$origin"} ( (scalar(@$values) + 1 ) .. (scalar(@$values) + scalar(@$new_master_record_partitions) ) ) )
962 )) . ' ~all',
963 );
964 }
965 }
966 # Create the new _spfN.domain.tld records that we are including.
967 $additional_records = $self->_get_multiple_record_strings([map {join('', @$_)} @$new_master_record_partitions], scalar(@$values) + 1);
968  
969 # Otherwise, proceed as normal, and just use one master record with all the original _spfN.domain.tld records we already have.
970 } else {
971  
972 for my $type ( 'TXT', 'SPF' ) {
973 for my $domain (@$domains) {
974  
975 push @containing_records,
976 new Net::DNS::RR(
977 type => $type,
978 name => $domain,
979 class => $self->_record_class,
980 ttl => $self->ttl,
981 txtdata => 'v=spf1 ' . (join(
982 ' ',
983 ( map {"include:_spf$_.$origin"} ( 1 .. scalar(@$values) ) )
984 )) . ' ~all',
985 );
986 }
987 }
988  
989 }
990  
991 @record_strings = map { my $string = $self->_normalize_record_name( $_->string ) . "\n"; $string =~ s/\t/ /g; $string; }
992 # We sort first by the string, and then by the type,
993 # so that TXT goes first, before SPF.
994 sort { $b->type cmp $a->type }
995 sort { $a->string cmp $b->string }
996 @containing_records;
997  
998 # Be sure to add the additional records if we have them.
999 my @result = (@record_strings,@$additional_records);
1000  
1001 return \@result;
1002 }
1003  
1004 =head2 _new_records_lines
1005  
1006 Assemble the new DNS zonefile from the lines of the original,
1007 comment out the old SPF records, add in the new lines, and append the
1008 end of the original.
1009  
1010 =cut
1011  
1012 sub _new_records_lines {
1013 my $self = shift;
1014 my %new_records = %{ $self->new_spf_records || {} };
1015 my @record_strings = ();
1016  
1017 # Make a list of the unique records in case we need it.
1018 my @autosplit = ();
1019 for my $domain ( keys %new_records ) {
1020 for my $record_set ( @{ $new_records{$domain} } ) {
1021 if ( ref($record_set) eq 'ARRAY' ) {
1022 for my $record (@$record_set) {
1023 push @autosplit, $record->txtdata;
1024 }
1025 } else {
1026 push @autosplit, $record_set->txtdata;
1027 }
1028 }
1029 }
1030 @autosplit = uniq @autosplit;
1031  
1032 # If there are any autosplit SPF records, we just do that right away.
1033 # This test is kind of nasty.
1034 my $make_autosplit_records = grep {
1035 defined( ${ $new_records{$_} }[0] )
1036 && ref( ${ $new_records{$_} }[0] ) eq 'ARRAY'
1037 } sort keys %new_records;
1038 if ($make_autosplit_records) {
1039 my $master_record_strings
1040 = $self->_get_master_record_strings( \@autosplit,
1041 [ keys %new_records ] );
1042 my $record_strings
1043 = $self->_get_multiple_record_strings( \@autosplit );
1044 push @record_strings, @$master_record_strings;
1045 push @record_strings, @$record_strings;
1046 } else {
1047 for my $domain ( sort keys %new_records ) {
1048 my $record_string = $self->_get_single_record_string(
1049 $domain,
1050 $new_records{$domain},
1051 );
1052 push @record_strings, @$record_string;
1053 }
1054 }
1055 my @original_lines = $self->_input_file->slurp;
1056 my @new_lines = ();
1057 my @spf_indices;
1058 my $i = 0;
1059 LINE: for my $line (@original_lines) {
1060 if ( $line =~ /^[^;].+?v=spf1/ ) {
1061 push @spf_indices, $i;
1062 $line = ";" . $line;
1063 }
1064 push @new_lines, $line;
1065 $i++;
1066 }
1067 my @first_segment = @new_lines[ 0 .. $spf_indices[-1] ];
1068 my @last_segment = @new_lines[ $spf_indices[-1] + 1 .. $#new_lines ];
1069 my @final_lines = ( @first_segment, @record_strings, @last_segment );
1070  
1071 return \@final_lines;
1072 }
1073  
1074 __PACKAGE__->meta->make_immutable;
1075 __PACKAGE__->new_with_options->run unless caller;
1076  
1077 1;
1078  
1079 __END__
1080  
1081 =head1 AUTHOR
1082  
1083 Amiri Barksdale E<lt>amiri@campusexplorer.comE<gt>
1084  
1085 =head2 CONTRIBUTORS
1086  
1087 Neil Bowers E<lt>neil@bowers.comE<gt>
1088  
1089 Chris Weyl E<lt>cweyl@campusexplorer.comE<gt>
1090  
1091 =head1 COPYRIGHT
1092  
1093 Copyright (c) 2015 Campus Explorer, Inc.
1094  
1095 =head1 LICENSE
1096  
1097 This library is free software; you can redistribute it and/or modify
1098 it under the same terms as Perl itself.
1099  
1100 =head1 SEE ALSO
1101  
1102 L<Net::DNS>
1103  
1104 L<Net::DNS::RR::TXT>
1105  
1106 L<MooseX::Getopt>
1107  
1108 =cut