-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathaddon_bulk-dns-del.cgi
executable file
·2068 lines (1768 loc) · 67.6 KB
/
addon_bulk-dns-del.cgi
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/perl
#WHMADDON:bulk-dns-del:Bulk DNS Removal (zone un-maker)
#ACLS:kill-dns
# _|_| _| _|
# _| _| _| _|_| _|_|_| _|_|_|_| _| _|_| _|_| _|_|_| _|_|_| _|_|
# _|_|_|_| _| _|_| _|_| _| _|_| _|_|_|_| _| _| _| _| _|
# _| _| _| _| _|_| _| _| _| _| _| _| _| _|
# _| _| _| _| _|_|_| _|_| _| _|_|_| _|_|_| _| _| _|
############################################################################################
#
# This script enables bulk removal of BIND zone records. See the perldoc for more details.
#
############################################################################################
# BEGIN is executed before anything else in the script
# this sets up the search path for library modules
BEGIN {
unshift @INC,
'/usr/local/cpanel',
'/usr/local/cpanel/whostmgr/docroot/cgi',
'/usr/local/cpanel/cpaddons',
'/home/dklann/perl5/lib/perl5';
}
use strict;
use warnings qw( all );
use Data::Dumper;
use CGI qw( :all );
use CGI::Carp qw( fatalsToBrowser );
use LWP::UserAgent;
use JSON::PP;
use Cpanel;
use Cpanel::PipeHandler ();
use Cpanel::HttpRequest ();
use Cpanel::StringFunc ();
use Cpanel::Config ();
use Whostmgr::HTMLInterface ();
use Whostmgr::ACLS ();
use Text::Wrap;
use Text::Diff::FormattedHTML;
use File::stat;
use Net::IP qw(:PROC);
use constant DEBUG => 1;
use constant BASE_URL => 'http://localhost:2086/json-api';
use constant NAMEDIR => '/var/named';
use constant DEFAULT_COMMENT => 'Comments for this block of addresses. This will be placed above the block of addresses.';
use constant SUFFIX => '.NEW';
sub main();
sub getFormData( $ );
sub getConfirmation( $ );
sub processFormData( $ );
sub commitChanges( $ );
sub authorizedRequest( $$$@ );
sub processJSONresponse( $$$ );
sub apiMessageDisplay ( $$$ );
sub newZoneFile ( $$$ );
sub addOrReplace( $$$$ );
sub networkAddr( $ );
sub incrementSerial ( $$ );
sub pushChanges( $@ );
sub select_css ();
# run it
main;
1;
# main process
sub main() {
my $w = CGI->new();
my @javaScript = <DATA>;
Whostmgr::ACLS::init_acls();
print
$w->header( -expires => '-1D' ),
$w->start_html(
-title => 'Bulk DNS Removal (zone un-maker)',
-script => [
join( "", @javaScript ),
qq{var forward = new OptionTransfer("forward_zone_records_from", "forward_zone_records_to");\n} .
qq{forward.setAutoSort(false);\n} .
qq{forward.setDelimiter("|");\n} .
qq{forward.setStaticOptionRegex("");\n}
],
-style => { -type => 'text/css', -code => diff_css() },
-style => { -type => 'text/css', -code => select_css() },
-onLoad => ( $w->param( 'phase' ) == 1 ? 'ot.init(document.forms[0])' : 'false' ),
-class => 'yui-skin-sam',
);
Whostmgr::HTMLInterface::defheader( '', '', '/cgi/addon_bulk-dns-del.cgi' );
print
$w->p( 'phase: ', $w->param( 'phase' ) || '0' ), "\n" if ( DEBUG );
# query the form parameters to see which phase we are in and what
# task to perform during this run
if ( $w->param( 'phase' ) == 3 ) {
commitChanges( $w );
} elsif ( $w->param( 'phase' ) == 2 ) {
processFormData( $w );
} elsif ( $w->param( 'phase' ) == 1 ) {
getConfirmation( $w );
} else {
getFormData( $w );
}
Whostmgr::HTMLInterface::sendfooter();
print
$w->end_html(), "\n";
}
# phase 0: gather initial zone and domain data
sub getFormData( $ ) {
my $w = shift;
# Ensure they have proper access before doing anything else. See
# http://docs.cpanel.net/twiki/bin/view/SoftwareDevelopmentKit/CreatingWhmPlugins#Access%20Control
# for details.
if ( DEBUG || Whostmgr::ACLS::checkacl( 'kill-dns' )) {
my $ua = LWP::UserAgent->new;
print
$w->h1( 'Bulk DNS Removal (zone un-maker)' ), "\n",
$w->p( 'Use this form to mark a set of records for removal from a DNS zone.' );
##################################################
### get initial pop-up menu data from cPanel ###
##################################################
# $domains is the JSON data structure returned from the query
# @domains is the array containing a sorted list of unique domains
# @forwardDomains contains "normal" domains, and
# @inaddrDomains contains "reverse" (in-addr.arpa) domains
my $domains = authorizedRequest( $w, $ua, 'listzones', ( 'api.version=1', 'searchtype=owner', ));
my @domains = ();
my @forwardDomains = ();
my @inaddrDomains = ();
if ( $domains ) {
# "map/reduce": map() gives an array of domain hashes,
# keys() gives an array of owners, sort(grep()) drops the
# in-addr.arpa zones, the last sort(grep()) gets a list of
# in-addr.arpa zones sorted by IP address in normal order
@domains = map( { $_->{domain} } @{$domains->{data}->{zone}} );
@domains = keys( %{{ map( { $_ => 1 } @domains ) }} );
@forwardDomains = sort( grep( !/(in-addr|ip6)\.arpa/, @domains ));
# this godawful sort does the Right Thing(tm)
@inaddrDomains = sort {
my @a = $a =~ /(\d+)\.(\d+)\.(\d+)\.(in-addr\.arpa|ip6\.arpa)/;
my @b = $b =~ /(\d+)\.(\d+)\.(\d+)\.(in-addr\.arpa|ip6\.arpa)/;
$a[2] <=> $b[2]
||
$a[1] <=> $b[1]
||
$a[0] <=> $b[0]
} grep( /(in-addr|ip6)\.arpa/, @domains );
} else {
print
$w->p( { -style => 'color:red;' },
'Could not retrieve domain list from cPanel.',
"\n");
}
print
$w->start_form(
-name => 'bulk_del',
-method => 'POST',
-action => '/cgi/addon_bulk-dns-del.cgi',
), "\n";
print
$w->start_div({ -id => 'outer' }),
"\n";
### forward domains
print
$w->table ({ -border => '0', id => 't1' },
$w->Tr({ -align => 'left' },
$w->th({ -align => 'right' }, 'Choose a forward domain: ' ),
$w->td(
$w->popup_menu(
-id => 'existing_forward_domain',
-name => 'existing_forward_domain',
-values => \@forwardDomains,
),
),
$w->td({ -id => 'info_existing_forward_domain' }, ' ' ),
),
), "\n";
### in-addr.arpa (reverse) domains
print
$w->checkbox(
-id => 'do_reverse_domain',
-name => 'do_reverse_domain',
-checked => 0,
-label => 'Remove reverse domain records',
-onClick => 'toggleVisibility(this, "reverse_domain"); toggleVisibility(this, "ipv4network");',
), "\n";
# hide this <div> at first (style="display: none")
# the javascript function showRemove() makes this visible and invisible
print
$w->div( { -id => 'reverse_domain', -style => 'display: none' },
$w->table ({ -border => '0', id => 't3' },
$w->Tr({ -align => 'left' },
$w->th({ -align => 'right' }, 'Choose a reverse domain (check to include): ' ),
$w->td(
$w->popup_menu(
-id => 'existing_reverse_domain',
-name => 'existing_reverse_domain',
-values => \@inaddrDomains,
),
),
$w->td({ -id => 'info_existing_reverse_domain' }, ' ' ),
),
)), "\n";
print
$w->start_table ({ -border => '0' } ),
$w->Tr({ -align => 'left' },
$w->th({ -align => 'right' }, 'Comments: ', $w->br(), '(comments will be wrapped and set off with ";")' ),
$w->td(
$w->textarea(
-id => 'comment',
-name => 'comment',
-default => DEFAULT_COMMENT,
-rows => 4,
-columns => 76,
-onFocus => 'if (this.value == this.defaultValue) {this.value = "";}',
-onBlur => 'if (this.value == "") {this.value="' . DEFAULT_COMMENT . '";}'
),
),
$w->td({ -id => 'info_comment' }, ' ' ),
), "\n";
print
$w->Tr({ -align => 'left' },
$w->td(
$w->checkbox(
-id => 'verbose',
-name => 'verbose',
-value => 'ON',
-label => 'Verbose processing (AKA "debugging")',
),
),
), "\n";
print
$w->Tr({ -align => 'left' },
$w->td(
$w->submit(
-name => 'submit',
-label => 'Show Records'
),
),
$w->td(
$w->button(
-name => 'Reset',
-value => 'Reset',
-label => 'Reset Form',
-onClick => 'this.form.reset()',
),
),
), "\n";
print
$w->hidden(
-name => 'phase',
-value => '1',
-default => '1',
), "\n";
print
$w->end_form(), "\n",
$w->end_table(), "\n",
$w->end_div({ id => 'outer' });
} else {
print
$w->br(),
$w->br(),
$w->div({ -align => 'center' },
$w->h1( 'Permission denied' ),
"\n"
), "\n";
}
}
# phase 1: generate zone file entries and permit user to edit them
sub getConfirmation( $ ) {
my $w = shift;
# Ensure they have proper access before doing anything else. See
# http://docs.cpanel.net/twiki/bin/view/SoftwareDevelopmentKit/CreatingWhmPlugins#Access%20Control
# for details.
if ( DEBUG || Whostmgr::ACLS::checkacl( 'kill-dns' )) {
# get all the parameters from the completed form
my $existing_forward_domain = $w->param( 'existing_forward_domain' );
my $existing_reverse_domain = $w->param( 'existing_reverse_domain' );
my $do_reverse_domain = $w->param( 'do_reverse_domain' );
my $comment = $w->param( 'comment' );
my $verbose = $w->param( 'verbose' );
my $forward_zone = undef;
my $reverse_zone = undef;
my $forward_domain = undef;
my $reverse_domain = undef;
my %params = $w->Vars();
my $formatString = undef;
my @comment = ();
my @forward_zones = ();
my @reverse_zones = ();
my $countDomainsA = 0;
my $countReverseA = 0;
my $countDomainsB = 0;
my $countReverseB = 0;
my $ua = LWP::UserAgent->new;
$forward_zone = authorizedRequest( $w, $ua, 'dumpzone', ( 'api.version=1', 'domain=' . $existing_forward_domain, ));
$forward_domain = $existing_forward_domain;
if ( $do_reverse_domain ) {
$reverse_zone = authorizedRequest( $w, $ua, 'dumpzone', ( 'api.version=1', 'domain=' . $existing_reverse_domain, ));
}
if ( DEBUG || $verbose ) {
print
$w->start_div( { -id => 'debugzonerecords' } ),
$w->p( 'DEBUG (phase ', $w->param( 'phase' ), '): COOKED $forward_zone for ', $existing_forward_domain, ' is:' ), "\n",
$w->start_pre(), "\n";
for my $record ( @{$forward_zone->{data}->{zone}->[0]->{record}} ) {
print
$record->{Line}, ' ',
$record->{type}, ' ',
$record->{ttl}, ' ',
( $record->{type} eq ':RAW' ? $record->{raw} : '' ), ' ',
( $record->{type} eq 'A' ? $record->{name} . ': ' . $record->{address} : '' ), ' ',
"\n";
}
if ( $do_reverse_domain ) {
print
$w->p( 'DEBUG (phase ', $w->param( 'phase' ), '): RAW $reverse_zone ', $existing_reverse_domain, ' is:' ), "\n";
for my $record ( @{$reverse_zone->{data}->{zone}->[0]->{record}} ) {
print
$record->{Line}, ' ',
$record->{type}, ' ',
$record->{ttl},
( $record->{type} eq ':RAW' ? $record->{raw} : '' ), ' ',
( $record->{type} eq 'PTR' ? $record->{name} . ': ' . $record->{ptrdname} : '' ), ' ',
"\n";
}
}
print
$w->end_pre(), "\n",
$w->end_div(), "\n";
}
# strip any hand-entered comment symbols, the default comment, and save the wrapped comment
my $default_comment = DEFAULT_COMMENT;
$comment =~ s/^$default_comment$//;
@comment = split( ' ', $comment );
push ( @forward_zones, ( wrap( '; ', '; ', grep( !/^;$/, @comment )), "\n" )) if ( @comment );
for my $record ( @{$forward_zone->{data}->{zone}->[0]->{record}} ) {
next if ( $record->{type} =~ /^(mx|ns|:raw|soa|\$ttl)$/i );
my $line = sprintf( "%-32s\t%-4s\t%52s",
$record->{name},
$record->{type},
( $record->{type} eq 'CNAME' ? $record->{cname} : $record->{address} )
);
push( @forward_zones, $line );
}
if ( $do_reverse_domain ) {
for my $record ( @{$reverse_zone->{data}->{zone}->[0]->{record}} ) {
next if ( $record->{type} =~ /^(mx|ns|:raw|soa|\$ttl)$/i );
my $line = sprintf( "%-32s\t%-4s\t%52s",
$record->{name},
$record->{type},
( $record->{type} eq 'CNAME' ? $record->{cname} : $record->{address} )
);
push( @reverse_zones, $line );
}
}
print
$w->start_div({ -id => 'zonerecords' , -style => 'display: block'} ), "\n",
$w->start_form(
-name => 'review_changes',
-method => 'POST',
-action => '/cgi/addon_bulk-dns-del.cgi',
), "\n";
print
$w->p( 'Forward zone data:' ),
$w->table( { -border => '0' }, "\n",
$w->Tr(
$w->td(
$w->scrolling_list(
{
-id => 'forward_zone_records_from',
-name => 'forward_zone_records_from',
-size => ( $#forward_zones > 51 ? 51 : $#forward_zones + 1 ),
-multiple => 'true',
-onDblClick => 'opt.transferRight()',
-values => [ map { $countDomainsA++ } @forward_zones ],
-labels => { map { $countDomainsB++ => $_ } @forward_zones }
},
)), "\n",
$w->td( { -valign => 'bottom', -align => 'center' },
$w->button( -name => 'right', -value => '>>', -onClick => 'opt.transferRight()' ), br, br, "\n",
$w->button( -name => 'right', -value => 'All >>', -onClick => 'opt.transferAllRight()' ), br, br, "\n",
$w->button( -name => 'left', -value => '<<', -onClick => 'opt.transferLeft()' ), br, br, "\n",
$w->button( -name => 'left', -value => 'All <<', -onClick => 'opt.transferAllLeft()' ), "\n"
), "\n",
$w->td(
$w->scrolling_list(
{
-id => 'forward_zone_records_to',
-name => 'forward_zone_records_to',
-size => ( $#forward_zones > 51 ? 51 : $#forward_zones + 1 ),
-multiple => 'true',
}), "\n"
)), "\n",
), "\n";
if ( $do_reverse_domain ) {
print
$w->p( 'Reverse zone data:' ),
$w->scrolling_list(
{
-id => 'reverse_zone_records_from',
-name => 'reverse_zone_records_from',
-size => $#reverse_zones + 1,
-multiple => 'true',
-values => [ map { $countReverseA++ } @reverse_zones ],
-labels => { map { $countReverseB++ => $_ } @reverse_zones }
},
), "\n",
$w->scrolling_list(
{
-id => 'reverse_zone_records_to',
-name => 'reverse_zone_records_to',
-size => $#reverse_zones + 1,
-multiple => 'true',
}), "\n";
}
print
$w->br(),
$w->script( { -type => 'text/javascript' },
q{createMovableOptions( "forward_zone_records_from", "forward_zone_records_to", 1024, 680, 'Available Records', 'Selected Records');},
q{// ADDING ACTIONS INTO YOUR PAGE},
q{// Finally, add calls to the object to move options back and forth, either},
q{// from links in your page or from double-clicking the options themselves.},
q{// See example page, and use the following methods:},
q{ot.transferRight();},
q{ot.transferAllRight();},
q{ot.transferLeft();},
q{ot.transferAllLeft();},
), "\n";
print
$w->script( { -type => 'text/javascript' },
q{createMovableOptions( "reverse_zone_records_from", "reverse_zone_records_to", 1024, 680, 'Available Records', 'Selected Records');},
), "\n" if ( $do_reverse_domain );
# save the parameters from the previous form for the next phase
foreach my $p ( sort( keys( %params ))) {
next if ( $p =~ /phase|submit/ );
print
$w->hidden(
-name => $p,
-default => $w->param( $p )
), "\n";
}
print
$w->submit(
-name => 'submit',
-label => 'Ready'
), "\n";
$w->param( -name => 'phase', -value => '2' );
print
$w->hidden(
-name => 'phase',
-default => '2',
-override => 1,
),
"\n";
print
$w->end_form(),
$w->end_div({-id => 'zonerecords' } ),
"\n";
print
$w->p(
'Click your browser\'s Back button if you need to make changes.'
), "\n";
} else {
print
$w->br(), $w->br(),
$w->div({ -align => 'center' },
$w->h1( 'Permission denied' ),
"\n"
);
}
}
# phase 2: process the inputs and generate new zone file(s)
sub processFormData( $ ) {
my $w = shift;
# Ensure they have proper access before doing anything else. See
# http://docs.cpanel.net/twiki/bin/view/SoftwareDevelopmentKit/CreatingWhmPlugins#Access%20Control
# for details.
if ( DEBUG || Whostmgr::ACLS::checkacl( 'kill-dns' )) {
# get all the parameters from the completed form
my $existing_forward_domain = $w->param( 'existing_forward_domain' );
my $existing_reverse_domain = $w->param( 'existing_reverse_domain' );
my $do_reverse_domain = $w->param( 'do_reverse_domain' );
my $verbose = $w->param( 'verbose' );
my $forward_zone_records = $w->param( 'forward_zone_records' );
my $reverse_zone_records = $w->param( 'reverse_zone_records' );
my $forward_domain = undef;
my $reverse_domain = undef;
my %params = $w->Vars();
my $response = undef;
my $ua = LWP::UserAgent->new;
$forward_domain = $existing_forward_domain;
if ( $do_reverse_domain ) {
$reverse_domain = $existing_reverse_domain;
}
if ( DEBUG || $verbose ) {
print
$w->div( { -id => 'debugzonerecords' },
$w->p( 'DEBUG (phase ', $w->param( 'phase' ), '): forward zone records for: ', $forward_domain ), "\n",
$w->pre( $forward_zone_records ), "\n",
);
if ( $do_reverse_domain ) {
print
$w->div( { -id => 'debugzonerecords' },
$w->p( 'DEBUG (phase ', $w->param( 'phase' ), '): reverse zone records for: ', $reverse_domain ), "\n",
$w->pre( $reverse_zone_records ), "\n",
);
}
}
# update the forward zone file
if ( -r NAMEDIR . '/' . $forward_domain . '.db' ) {
newZoneFile ( $w, $forward_domain, $forward_zone_records );
} else {
print
$w->p( 'Cannot read zone file ', $forward_domain, ' (', $!, ')' ), "\n";
}
if ( $do_reverse_domain ) {
# update the reverse zone file
if ( -r NAMEDIR . '/' . $reverse_domain . '.db' ) {
newZoneFile ( $w, $reverse_domain, $reverse_zone_records );
} else {
print
$w->p( 'Cannot read zone file ', $reverse_domain, ' (', $!, ')' ), "\n";
}
}
print
$w->p( 'Click the Commit button if the above changes are correct. Otherwise click Back and make necessary changes.' );
print
start_form(
-name => 'commit_changes',
-method => 'POST',
-action => '/cgi/addon_bulk-dns-del.cgi',
), "\n";
# save the parameters from the previous form for the next phase
foreach my $p ( sort( keys( %params ))) {
next if ( $p =~ /phase|submit/ );
print
$w->hidden(
-name => $p,
-default => $w->param( $p )
), "\n";
}
print
$w->br(),
$w->submit(
-name => 'submit',
-label => 'Commit'
), "\n";
$w->param( -name => 'phase', -value => '3' );
print
$w->hidden(
-name => 'phase',
-default => '3',
-override => 1,
),
"\n";
print
end_form(),
"\n";
} else {
print
$w->br(), $w->br(),
$w->div({ -align => 'center' },
$w->h1( 'Permission denied' ),
"\n"
);
}
}
# phase 3: commit the changes after reviewing the diffs
sub commitChanges( $ ) {
my $w = shift;
# Ensure they have proper access before doing anything else. See
# http://docs.cpanel.net/twiki/bin/view/SoftwareDevelopmentKit/CreatingWhmPlugins#Access%20Control
# for details.
if ( DEBUG || Whostmgr::ACLS::checkacl( 'kill-dns' )) {
# get all the parameters from the completed form
my $existing_forward_domain = $w->param( 'existing_forward_domain' );
my $existing_reverse_domain = $w->param( 'existing_reverse_domain' );
my $do_reverse_domain = $w->param( 'do_reverse_domain' );
my $verbose = $w->param( 'verbose' );
my $forward_domain = undef;
my $reverse_domain = undef;
my $pushChanges = undef;
$forward_domain = $existing_forward_domain;
if ( $do_reverse_domain ) {
$reverse_domain = $existing_reverse_domain;
}
my $forwardZoneFileName = NAMEDIR . '/' . $forward_domain . '.db';
my $reverseZoneFileName = NAMEDIR . '/' . $reverse_domain . '.db';
my $newForwardZoneFileName = NAMEDIR . '/' . $forward_domain . SUFFIX;
my $newReverseZoneFileName = NAMEDIR . '/' . $reverse_domain . SUFFIX;
if ( -r $newForwardZoneFileName ) {
if ( -w $forwardZoneFileName ) {
if ( DEBUG ) {
print
$w->p( 'DEBUG (phase ', $w->param( 'phase' ), '): Would rename( ',
$newForwardZoneFileName, ', ', $forwardZoneFileName, ')' ),
"\n";
$pushChanges = 1;
} else {
die( "Could not rename $newForwardZoneFileName to $forwardZoneFileName ($!). Stopped" )
unless ( rename( $newForwardZoneFileName, $forwardZoneFileName ));
$pushChanges = 1;
}
} else {
print
$w->p( { -style => 'color:red;' },
'Exception! ', $forwardZoneFileName, ' is not writable!'
), "\n";
}
} else {
print
$w->p( { -style => 'color:red;' },
'Exception! ', $newForwardZoneFileName, ' is not readable!'
), "\n";
}
if ( $do_reverse_domain ) {
if ( -r $newReverseZoneFileName ) {
if ( -w $reverseZoneFileName ) {
if ( DEBUG ) {
print
$w->p( 'DEBUG (phase ', $w->param( 'phase' ), '): Would rename( ',
$newReverseZoneFileName, ', ', $reverseZoneFileName, ')' ),
"\n";
} else {
die( "Could not rename $newReverseZoneFileName to $reverseZoneFileName ($!). Stopped" )
unless ( rename( $newReverseZoneFileName, $reverseZoneFileName ));
}
} else {
print
$w->p( { -style => 'color:red;' },
'Exception! ', $reverseZoneFileName, ' is not writable!'
), "\n";
}
} else {
print
$w->p( { -style => 'color:red;' },
'Exception! ', $newReverseZoneFileName, ' is not readable!'
), "\n";
}
}
if ( $pushChanges ) {
die( "Error pushing changes to cluster servers ($!). Stopped" )
unless ( pushChanges( $w, ( $forward_domain, $reverse_domain )));
}
} else {
print
$w->br(), $w->br(),
$w->div({ -align => 'center' },
$w->h1( 'Permission denied' ),
"\n"
);
}
}
# return a hash reference to response data from a request
sub authorizedRequest( $$$@ ) {
my $w = shift;
my $ua = shift;
my $action = shift;
my @args = @_;
my ( $request, $response ) = ( undef, undef );
my $URL = undef;
my $jsonRef = undef;
my $authHash = 'WHM root:653b9361f915790c31cd8072a53b0d836eb931e920ce32f21d6d3edd48d4347858d4b4fdd756c961a27cbbacdacc8ef20ff6401e8a80aeacddd29f6ee5674daa88d0db5781c623e42d15ed839d78309411b164677f6623ca006667c238b772b927c40e368aea3d814232ac157a0fdee9ec441b62a949ff9a4e3d5cd4d5050df29a916afdc709ae55386755bfaa6296b55988681e2a5c5124ede05807657b17b9478d89f83c392cc0ac226eba6453924e54c8b98cb977102f5c00efa55ae65a5b61fe4d3ce8bafc32455bc1c0864b9fddc3b7b7f9400d0a51afb3525e83f5e91ac37c4bab5cd26dcf643f0a4c23e51a2e26b2408f60a91e8456851b6807e651aea4430a606204758b4712916d2a63e7557e76447f886e1c0f5421e2983eb24701477027eef9d2d58249d70fcb82c47321ab297884e6b1157edb3d369725369868985f8cfa373176b15f5a2b625fd58eb45a0d9f0b21007b0e4077414b97a0aed1801a690a33146eb1236a6c9308e5ec8f037c9ffca61e05744812d2a58a6a9a7b837de8395b3196707aabca4c2c4a1d35045215018cc1b686ef0fcc96a968e9c43c8695c23ccddc01e65c27cdfc0ebb087a163da35c8378d2b3f0a29de0a5fc59eeed9ba8f39c2b8e8f459f3d1ecd0f0c';
# make a complete URL from the arguments passed in
$URL = BASE_URL . '/' . $action . '?' . join( '&', @args );
# print $w->pre( Dumper( $URL )), "\n" if ( DEBUG );
# see http://docs.cpanel.net/twiki/bin/view/SoftwareDevelopmentKit/ApiAuthentication
if ( $request = HTTP::Request->new( GET => $URL )) {
$request->header( Authorization => $authHash );
$response = $ua->request( $request );
}
if ( $response ) {
# print
# $w->p( '$response from $ua->request():' ),
# $w->pre( Dumper( $response )), "\n" if ( DEBUG ),;
$jsonRef = processJSONresponse( $w, $action, $response->{'_content'} );
# print $w->pre( Dumper( $jsonRef )), "\n" if ( DEBUG );
} else {
print
$w->p( 'ERROR: missing response from $ua->request()' ),
$w->pre( Dumper( $response )), "\n";
}
$jsonRef;
}
# parse the JSON response from the API call and
# normalize it to something we can deal with
sub processJSONresponse( $$$ ) {
my $w = shift;
my $action = shift;
my $response = shift;
my $jsonRef = undef;
if ( $response ) {
my $json = JSON::PP->new();
$jsonRef = $json->decode( $response );
if ( $jsonRef ) {
if ( $jsonRef->{metadata} ) {
if ( $w->param('verbose') || $jsonRef->{metadata}->{result} != 1 ) {
print $w->pre( Dumper( $jsonRef )), "\n";
}
} elsif ( $jsonRef->{result} ) {
if ( $jsonRef->{result}[0]->{status} ) {
$jsonRef->{metadata}->{result} = $jsonRef->{result}[0]->{status};
$jsonRef->{metadata}->{reason} = 'API Success';
$jsonRef->{metadata}->{statusmsg} = $jsonRef->{result}[0]->{statusmsg};
} else {
$jsonRef->{metadata}->{result} = $jsonRef->{result}[0]->{status};
$jsonRef->{metadata}->{reason} = 'API Error';
$jsonRef->{metadata}->{statusmsg} = $jsonRef->{result}[0]->{statusmsg};
}
} else {
print
$w->p( 'ERROR: unknown JSON structure in $response:' ), "\n",
$w->pre( Dumper( $jsonRef )), "\n";
}
} else {
print $w->p( 'ERROR: unable to decode JSON from ', $response ), "\n";
}
} else {
print $w->p( 'ERROR: received NULL response from adddns request' ), "\n";
}
$jsonRef;
}
# display a message based on cPanel API JSON data
sub apiMessageDisplay ( $$$ ) {
my $w = shift;
my $response = shift;
my $message = shift;
print
$w->h1( $message ), "\n";
if ( $response ) {
print
$w->p(
'Result: ', $response->{metadata}->{result},
$w->br(),
'Reason: ', $response->{metadata}->{reason},
$w->br(),
$w->pre( $response->{metadata}->{statusmsg}, "\n" ),
), "\n";
}
}
# update a zone file with a named based on the $domainName and new records in $zoneRecords
sub newZoneFile ( $$$ ) {
my $w = shift;
my $domainName = shift;
my $zoneRecords = shift;
my $zoneFileName = NAMEDIR . '/' . $domainName . '.db';
my $newZoneFileName = NAMEDIR . '/' . $domainName . SUFFIX;
my @zoneFileContents = ();
my @newZoneFileContents = ();
# the map statement in addOrReplace() is different for reverse zones
my $reverseZone = ( $domainName =~ /(in-addr|ip6)\.arpa/i );
# metadata for the existing file will be applied to the new file
my $sb = stat( $zoneFileName );
# place the new zone records into an array for further processing
my @newLines = split( /\n/, $zoneRecords );
open( ZF, $zoneFileName ) || die "Cannot open $zoneFileName for reading ($!). Stopped";
@zoneFileContents = <ZF>;
close( ZF );
chomp( @zoneFileContents );
# replace the records if they exist, else add them to the end of the existing records
@newZoneFileContents = addOrReplace ( $w, \@zoneFileContents, \@newLines, $reverseZone );
# set the serial number for the zone
if ( incrementSerial( $w, \@newZoneFileContents )) {
print
$w->h1( $zoneFileName ),
$w->p( 'Showing differences between old and new versions of the zone file.' ), "\n";
# use Text::Diff::FormattedHTML to display the old and the new zone file contents
# (chop lines at 80 characters just for display purposes)
print
diff_strings(
join( "\n", map( substr($_, 0, 79), @zoneFileContents )),
join( "\n", map( substr($_, 0, 79), @newZoneFileContents ))
);
if ( -f $newZoneFileName ) {
unlink( $newZoneFileName );
}
# save @newZoneFileContents to a file for processing in the next phase
open( NEW, ">$newZoneFileName" ) || die( "Cannot open $newZoneFileName for writing ($!). Stopped" );
print NEW join( "\n", @newZoneFileContents ), "\n" || die( "Could not write to $newZoneFileName ($!). Stopped" );
close( NEW );
die( "Cannot set ownership of new zone file $newZoneFileName ($!). Stopped" )
unless ( chown( $sb->uid, $sb->gid, $newZoneFileName ) == 1 );
die( "Cannot set permissions for new zone file $newZoneFileName ($!). Stopped" )
unless ( chmod( $sb->mode & 07777, $newZoneFileName ) == 1 );
} else {
print
$w->h1( { -style => 'color:red;' },
'Exception: Could not update serial number for zone file ', $zoneFileName, '!',
),
"\n";
}
}
# return an array containing the new contents of the zone file
sub addOrReplace( $$$$ ) {
my $w = shift;
my $oldContents = shift;
my $newLines = shift;
my $reverseZone = shift;
my @newContents = @$oldContents;
my $successExpr = qr/^1$/;
my $searchExpr = undef;
foreach my $line ( @$newLines ) {
my @result = ();
# this line format is established in the subrouting getConfirmation() with variable $formatString
# and make sure everything is in lower case
my ( $hostName, $class, $type, $resourceName ) = split( ' ', $line );
# $hostName = lc( $hostName );
# $class = lc( $class );
# $type = lc( $type );
# $resourceName = lc( $resourceName );
if ( $reverseZone ) {
# reverse zones: replace the resource name (the right-hand field)
# back references (items in parentheses):
# $1 - first word on the line (the hostname), what we search for
# $2 - spaces + TTL (empty if no TTL)
# $3 - TTL (empty if no TTL)
# $4 - class (IN)
# $5 - type (A, PTR, etc)
# $6 - fqdn (resource name), what we replace
# host TTL class type resource name
$searchExpr = qr/^($hostName)(\s+(\d+))*\s+($class)\s+(ptr)\s+(.*)\s*$/i;
@result = map( { s/$searchExpr/$1$2\t$4\t$5\t$resourceName/; } @newContents );
# the above map() call returns an array of success or undef
# for each element of @newContents depending on the result of
# the substitution (s///)
if ( ! grep( /$successExpr/, @result )) {
# add the new line to the end of the zone file contents if no match succeeded
push( @newContents, $line );
}
} else {
# forward zones: replace the hostname (the left-hand field)
# back references (items in parentheses):
# $1 - first char on the line
# $2 - first word on the line (the hostname), what we replace
# $3 - spaces + TTL (empty if no TTL)
# $4 - TTL (empty if no TTL)
# $5 - class (IN)
# $6 - type (A, PTR, etc)
# $7 - IP address (resource name), what we search for
# host TTL class type resource name
$searchExpr = qr/^(([^;\s])+)(\s+(\d+))*\s+($class)\s+(a)\s+($resourceName)\s*$/i;
@result = map( s/$searchExpr/$hostName$3\t$5\t$6\t$7/, @newContents );
# the above map() call returns an array of success or undef