-
Notifications
You must be signed in to change notification settings - Fork 1
/
addon_bulk-dns-add.cgi
executable file
·1730 lines (1458 loc) · 51.6 KB
/
addon_bulk-dns-add.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-add:Bulk DNS Generate (zonemaker):bulkcoffee160-scaled.jpg
#ACLS:create-dns
# _|_| _| _|
# _| _| _| _|_| _|_|_| _|_|_|_| _| _|_| _|_| _|_|_| _|_|_| _|_|
# _|_|_|_| _| _|_| _|_| _| _|_| _|_|_|_| _| _| _| _| _|
# _| _| _| _| _|_| _| _| _| _| _| _| _| _|
# _| _| _| _| _|_|_| _|_| _| _|_|_| _|_|_| _| _| _|
############################################################################################
#
# This script enables bulk addition 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/cpaddons',
'/home/dklann/perl5/lib/perl5',
'/home/dklann/perl5/lib/perl5/x86_64-linux',
'/home/dklann/perl5/lib/perl5/i686-linux',
'/usr/local/cpanel/whostmgr/docroot/cgi',
'/usr/local/cpanel';
}
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 MWT_CPANEL => 0; # oh this is painful
use constant BASE_URL => q{http://localhost:2086} . ( $ENV{'cp_security_token'} || '' ) . q{/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( $@ );
# 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 Generate (zonemaker)',
-script => join( "", @javaScript ),
-style => { -type => 'text/css', -code => diff_css() },
);
Whostmgr::HTMLInterface::defheader( '', '', '/cgi/addon_bulk-dns-add.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( 'create-dns' )) {
my $ua = LWP::UserAgent->new;
print
$w->h1( 'Bulk DNS Generator (formerly known as zonemaker)' ), "\n",
$w->p( 'Use this form to generate a set of entries to add to 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 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 );
# prepend placeholders for adding a new domain
unshift( @forwardDomains, ( '' ));
unshift( @inaddrDomains, ( '' ));
} else {
@forwardDomains = ( '' );
@inaddrDomains = ( '' );
}
print
$w->start_form(
-name => 'bulk_add',
-method => 'POST',
-action => ( $ENV{'cp_security_token'} || '' ) . '/cgi/addon_bulk-dns-add.cgi',
), "\n";
print
$w->start_div({ -id => 'outer' }),
"\n";
# see if they want to add a TTL, default is to NOT include them in the new records
print
$w->checkbox(
-id => 'do_ttl',
-name => 'do_ttl',
-checked => 0,
-label => 'Add TTL for this block of addresses?',
-onClick => 'toggleVisibility(this, "ttl");toggleVisibility(this, "reverse-ttl");',
), "\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,
-onChange => 'showAddNew(this, "forward_domain_textfield")',
),
),
$w->td({ -id => 'info_existing_forward_domain' }, ' ' ),
),
), "\n";
# hide this <div> at first (style="display: none")
# the javascript function showAddNew() makes this visible and invisible (note that this is currently NOT implemented)
print
$w->div({ -id => 'forward_domain_textfield', -style => 'display: none' },
$w->table ({ -border => '0', -id => 't2' },
$w->Tr({ -align => 'left' },
$w->th({ -align => 'right' }, 'New Domain: ' ),
$w->td(
$w->textfield(
-id => 'forward_domain',
-name => 'forward_domain',
-size => '32',
-maxlength => '56',
-onChange => 'validateHostName(this, "info_forward_domain", true)'
),
),
$w->td({ -id => 'info_forward_domain' }, ' ' ),
),
), "\n"
);
# hide this <div> at first (style="display: none")
# the javascript function toggleVisibility() makes this visible and invisible
print
$w->div( { -id => 'ttl', -style => 'display: none' },
$w->table ({ -border => '0', id => 'ttl1' },
$w->Tr({ -align => 'left' },
$w->th({ -align => 'right' }, 'Enter a TTL for this address block: ' ),
$w->td(
$w->textfield(
-id => 'ttlData',
-name => 'ttlData',
-size => 5,
-maxlength => 5,
-onChange => 'validateNumericRange(this, "info_ttlData", 300, 86400, true)',
),
),
$w->td({ -id => 'info_ttlData' }, ' ' ),
),
),
), "\n";
### in-addr.arpa (reverse) domains
print
$w->br(),
$w->checkbox(
-id => 'do_reverse_domain',
-name => 'do_reverse_domain',
-checked => 0,
-label => 'Add reverse domain records',
-onClick => 'toggleVisibility(this, "reverse_domain"); toggleVisibility(this, "ipv4network");',
);
# hide this <div> at first (style="display: none")
# the javascript function toggleVisibility() 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",
# this option is currently disabled and hidden, reserved for future use
$w->div({ -id => 'reverse_domain_textfield', -style => 'display: none' },
$w->table ({ -border => '0', -id => 't4' },
$w->Tr({ -align => 'left' },
$w->th({ -align => 'right' }, 'New Reverse Domain: ' ),
$w->td(
$w->textfield(
-id => 'reverse_domain',
-name => 'reverse_domain',
-size => '32',
-maxlength => '56',
-onChange => 'validateReverseZone(this, "info_reverse_domain", true)'
),
),
$w->td({ -id => 'info_reverse_domain' }, ' ' ),
),
),
), "\n",
# the visibility of this div is controlled by the checkbox (above) "do_ttl'
$w->div( { -id => 'reverse-ttl', -style => 'display: none' },
$w->table ({ -border => '0', id => 'reverse-ttl1' },
$w->Tr({ -align => 'left' },
$w->th({ -align => 'right' },
'Enter a TTL for this reverse address block: ' .
"<br />\n" .
'(leave blank to use the forward TTL) '
),
$w->td(
$w->textfield(
-id => 'reverse_ttlData',
-name => 'reverse_ttlData',
-size => 5,
-maxlength => 5,
-onChange => 'validateNumericRange(this, "info_reverse_ttlData", 300, 86400, true)',
),
),
$w->td({ -id => 'info_reverse_ttlData' }, ' ' ),
),
),
"\n",
),
);
# the base (CIDR /24) address
# this block disappears when the user chooses to include a reverse zone
print
$w->div( { -id => 'ipv4network', -style => 'display: block' },
$w->table ( { -border => '0' },
$w->Tr({ -align => 'left' },
$w->th({ -align => 'right' }, 'Base Address (first three octets): ' ),
$w->td(
$w->textfield(
-id => 'ipv4network',
-name => 'ipv4network',
-size => 11,
-maxlength => 11,
-onChange => 'validateBaseAddress(this, "info_ipv4network", true)',
),
),
$w->td({ -id => 'info_ipv4network' }, ' ' ),
), "\n",
), "\n",
);
# fourth octet starting point
print
$w->start_table ({ -border => '0' } ),
$w->Tr({ -align => 'left' },
$w->th({ -align => 'right' }, 'Fourth octet start: ' ),
$w->td(
$w->textfield(
-id => 'ipv4start',
-name => 'ipv4start',
-size => 3,
-maxlength => 3,
-onchange => 'validateNumericRange(this, "info_ipv4start", 0, 255, true)',
),
),
$w->td({ -id => 'info_ipv4start' }, ' ' ),
), "\n";
# fourth octet ending point
print
$w->Tr({ -align => 'left' },
$w->th({ -align => 'right' }, 'Fourth octet end: ' ),
$w->td(
$w->textfield(
-id => 'ipv4end',
-name => 'ipv4end',
-size => 3,
-maxlength => 3,
-onchange => 'validateNumericRange(this, "info_ipv4end", (parseInt(document.forms[0].elements["ipv4start"].value) + 1), 255, true)',
),
),
$w->td({ -id => 'info_ipv4end' }, ' ' ),
), "\n";
# base hostname
print
$w->Tr({ -align => 'left' },
$w->th({ -align => 'right' }, 'Base hostname: ' ),
$w->td(
$w->textfield(
-id => 'hostname_base',
-name => 'hostname_base',
-size => 32,
-maxlength => 64,
-onchange => 'validateHostName(this, "info_hostname_base", true)',
),
),
$w->td({ -id => 'info_hostname_base' }, ' ' ),
), "\n";
# hostname number - this number gets incremented for as many records as they
# chose in the fourth octet range
# the maximum limit of 999 is arbitrary, but it really cannot be greater than 255, can it?
print
$w->Tr({ -align => 'left' },
$w->th({ -align => 'right' }, 'Starting point for hostname increment: ' ),
$w->td(
$w->textfield(
-id => 'hostname_offset',
-name => 'hostname_offset',
-size => 3,
-maxlength => 3,
-onchange => 'validateNumericRange(this, "info_hostname_offset", 0, 999, true)',
),
),
$w->td({ -id => 'info_hostname_offset' }, ' ' ),
), "\n";
print
$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"
);
}
}
# 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( 'create-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 $ipv4network = $w->param( 'ipv4network' );
my $ipv4start = $w->param( 'ipv4start' );
my $ipv4end = $w->param( 'ipv4end' );
my $hostname_base = $w->param( 'hostname_base' );
my $hostname_offset = $w->param( 'hostname_offset' );
my $ttlData = $w->param( 'ttlData' );
my $reverse_ttlData = $w->param( 'reverse_ttlData' ) || $w->param( 'ttlData' );
my $comment = $w->param( 'comment' );
my $verbose = $w->param( 'verbose' );
my $forward_domain = undef;
my $reverse_domain = undef;
my @bind = ();
my $addrCount = $ipv4start;
my $hostCount = $hostname_offset;
my %params = $w->Vars();
my $formatString = undef;
my @comment = ();
my @forward_zones = ();
my @reverse_zones = ();
my $ua = LWP::UserAgent->new;
$forward_domain = $existing_forward_domain;
if ( $do_reverse_domain ) {
$reverse_domain = $existing_reverse_domain;
$ipv4network = networkAddr( $reverse_domain );
}
# make the list of IP addresses and hostnames
# save the full IP address, the domain, and the numbered hostname
# use an array of hashes rather than a big hash so we can preserve the order of entries
for ( $addrCount = $ipv4start; $addrCount <= $ipv4end; $addrCount++ ) {
$bind[$addrCount]->{ipv4address} = sprintf( '%s.%d', $ipv4network, $addrCount );
$bind[$addrCount]->{resource} = sprintf( '%s-%d', $hostname_base, $hostCount );
if ( $do_reverse_domain ) {
$bind[$addrCount]->{forwardDomain} = $forward_domain;
}
$hostCount++;
}
if ( DEBUG || $verbose ) {
print
$w->div({ -id => 'debugzonerecords' },
$w->p( 'DEBUG (phase ', $w->param( 'phase' ), '): @bind is:' ), "\n",
$w->pre( Dumper( @bind )), "\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" ));
# we have to construct the format string differently if there
# is a TTL defined. See also the stuff in sub addOrReplace()
if ( $ttlData ) {
$formatString = '%-' . length( $hostname_base . '-xxx.' ) . "s\t%-5d\tIN\t%s\t%s\n";
} else {
$formatString = '%-' . length( $hostname_base . '-xxx.' ) . "s\tIN\t%s\t%s\n";
}
# build an array of strings to be searched for in the zone files.
foreach my $record ( @bind ) {
next unless ( $record->{ipv4address} );
push( @forward_zones,
(
$ttlData ?
sprintf( $formatString,
$record->{resource},
( $ttlData > 0 ? $ttlData : '' ),
'A',
$record->{ipv4address}
)
:
sprintf( $formatString,
$record->{resource},
'A',
$record->{ipv4address}
)
)
);
}
# do the same for the in-addr.arpa zones.
if ( $do_reverse_domain ) {
push ( @reverse_zones, ( wrap( '; ', '; ', grep( !/^;$/, @comment )), "\n" ));
if ( $reverse_ttlData ) {
$formatString = "%-3d\t%-5d\tIN\t%s\t%s.$forward_domain.\n";
} else {
$formatString = "%-3d\tIN\t%s\t%s.$forward_domain.\n";
}
for ( my $r = 0; $r <= $#bind; $r++ ) {
my $record = $bind[$r];
next unless ( $record->{ipv4address} );
push( @reverse_zones,
(
$reverse_ttlData ?
sprintf( $formatString,
$r,
( $reverse_ttlData > 0 ? $reverse_ttlData : '' ),
'PTR',
$record->{resource}
)
:
sprintf( $formatString,
$r,
'PTR',
$record->{resource}
)
)
);
}
}
print
$w->start_div({ -id => 'zonerecords' , -style => 'display: block'} ), "\n",
$w->start_form(
-name => 'review_changes',
-method => 'POST',
-action => ( $ENV{'cp_security_token'} || '' ) . '/cgi/addon_bulk-dns-add.cgi',
), "\n";
print
$w->p( 'Forward zone data:' ),
$w->textarea(
{
-id => 'forward_zone_records',
-name => 'forward_zone_records',
-rows => $#forward_zones + 1,
-columns => 80,
-default => join( '', @forward_zones ),
},
), "\n";
if ( $do_reverse_domain ) {
print
$w->p( 'Reverse zone data:' ),
$w->textarea(
{
-id => 'reverse_zone_records',
-name => 'reverse_zone_records',
-rows => $#reverse_zones + 1,
-columns => 80,
-default => join( '', @reverse_zones ),
},
), "\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 => '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( 'create-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 => ( $ENV{'cp_security_token'} || '' ) . '/cgi/addon_bulk-dns-add.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( 'create-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 ));
# Will not reach this if there was an error.
$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";
}
# We do not set $pushChanges here because we will have already set it above,
# and we will die() appropriately if something goes wrong here.
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";
}
}
# do not push changes if this is the MWT cPanel server
if ( $pushChanges && ! MWT_CPANEL ) {
die( "Error pushing changes to cluster servers ($!). Stopped" )
unless ( pushChanges( $w, ( $forward_domain, $reverse_domain )));
print
$w->p(
'Update of ',
$forward_domain,
$reverse_domain ? " and $reverse_domain " : ' ',
'completed successfully',
), "\n";
}
} 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;
# see http://docs.cpanel.net/twiki/bin/view/SoftwareDevelopmentKit/ApiAuthentication#Access%20hash%20authentication
# this is SO cheating, but it makes the script able to run on multiple cPanel servers without modification.
my $authHash = `cat /root/.accesshash`;
chomp( $authHash );
$authHash =~ s/^/WHM root:/;
$authHash =~ s/\n//g;
# 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};