summaryrefslogtreecommitdiffstats
path: root/dns_wizard/Bind.pm
blob: e5b20ed3c3734461d2fe7132527e0662c9014607 (plain)
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
#!/usr/bin/perl -w
#
# version 0.4
# Copyright (C) 2004 Mandrakesoft
# Author: Antoine Ginies <aginies _ateuh _ mandrakesoft.com>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2, or (at your option)
# any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.

package MDK::Wizard::Bind;
use lib qw(/usr/lib/libDrakX);

use strict;
use services;
use common;
use MDK::Wizard::Varspaceval;
use MDK::Wizard::Wizcommon;


#unless ($> == 0) {
#  die "You are not root Exiting\n";
#}

my $wiz = new MDK::Wizard::Wizcommon;


my $SERIAL = `date +%d%m20%y`;
my $HOSTNAME = $wiz->{net}->network_get("HOSTNAME");
my $interface = 'eth0';
my $IPSERVER = $wiz->{net}->itf_get("IPADDR");
if (!$IPSERVER) {
  ($IPSERVER) = `/sbin/ip addr show dev $interface` =~ /^\s*inet\s+(\d+\.\d+\.\d+\.\d+)/m;
}
#my $DOMAINNAME = $wiz->{net}->network_get("DOMAINNAME");
my $DOMAINNAME = chomp_(`dnsdomainname`);

my $WDIR = "/tmp/dnstest";
my $NAMED_DIR = "/var/named";
my $DNSKEY = "";
my $SHORTHOSTNAME = chomp_(`hostname -s`);
my $TEXTINFO = "dns Wizard";
my $REP_SAVE = "/tmp/bck";
my $ZONE_DIR = $NAMED_DIR . "/zone";
my $DATE = `date +%d-%m-20%y`;
my $ft = "/var/named/master_srv";


my $o = { 
	 name => 'DNS Configuration Wizard',
	 var => {
		 IPOFFORWARDER => '',
		 ADDSEARCH => '',
		 DOMAINNAME => $DOMAINNAME,
		 SHORTHOSTNAME => $SHORTHOSTNAME,
		 IPMASTER => '',
		 CLIENTNAME => '',
		 CLIENTIP => '',
		},
	 needed_rpm => [ 'bind' ],
	 defaultimage => "/usr/share/wizards/dns_wizard/images/DNS.png",
	 init => sub {
	   if ($SHORTHOSTNAME =~ /localhost/) {
	     return 0, N("You need to readjust your hostname.")
	   }
	   if (member($DOMAINNAME, qw(localdomain (none)))) {
	     return 0, N("You need to readjust your domainname. For a DNS server you need a correct domainname, not equal to localdomain or none. Launch drakconnect to adjust it.")
	   }
	   1
	 },
	};

my %level = (
	     1 => N("Master DNS server"),
	     2 => N("Slave DNS server"),
	     3 => N("Add host in DNS"),
	     4 => N("Remove host in DNS"),
	     );

my @list_hosts;

sub list_hosts {
  my $iprev = get_spe_ip('iprev', $IPSERVER);
  my $db = "$ZONE_DIR/db.$iprev.hosts";
  #my $ipnor = get_spe_ip('iprev', $IPSERVER);
#  push @list_hosts, "";
  foreach (cat_($db)) {
    my ($h) = /\d{1,3}\tIN\tPTR\t(.*)/;
    !$h or push @list_hosts,$h;
  }
  @list_hosts;
}

$o->{pages} = {
	       welcome => {
			   name => N("DNS Master configuration wizard") . "\n\n" . N("DNS (Domain Name Server) is the service that maps an IP address of a machine with an internet host name.") . "\n\n" . N("This wizard will help you configuring the DNS services of your server. This configuration will provide a local DNS service for local computers names, with non-local requests forwarded to an outside DNS."),
			   no_back => 1,
			   pre => sub {
			     $o->{var}{wiz_level} ||= 1;
			   },
			   post => sub {
			     -f $ft or return 'error_notmaster';
			     if ($o->{var}{wiz_level} == 2) {
			       return 'slave' }
			     elsif ($o->{var}{wiz_level} == 3) {
			       return 'addhost' }
			     elsif ($o->{var}{wiz_level} == 4) {
			       return 'removehost' }
			   },
			   data => [
				    { label => N("What do you want to do:"), val => \$o->{var}{wiz_level}, list => [ keys %level ], format => sub { $level{$_[0]} } },
				   ],
			   next => 'ipforward',
			  },
	       addhost => {
			   name => N("Client identification:") . "\n\n" . N("Your client on the network will be identified by name, as in clientname.company.net. Every machine on the network must have a (unique) IP address, in the usual dotted syntax.") . "\n\n" . N("(you don't need to type the domain after the name)") . "\n\n" . N("Note that the given IP address and client name should be unique in the network."),
			   data => [
				    { label => N("Name of the machine:"), val => \$o->{var}{CLIENTNAME} },
				    { label => N("IP address of the machine:"), val => \$o->{var}{CLIENTIP} },
				   ],
			   post => \&check_iph,
			   next => 'summaryadd',
			  },
	       removehost => {
			      name => N("Remove host:") . "\n\n" . N("Remove a host in existing dns configuration.") . "\n\n" . N("Choose the host you want to remove in the following list."),
			      data => [
				       { label => N("Computer Name:"), val => \$o->{var}{CLIENTNAME}, fixed_list => \@list_hosts },
				      ],
			      post => \&list_hosts,
			      next => 'summaryremove',
			     },
	       slave => {
			 name => N("Slave DNS server") . "\n\n" . N("A slave name server will take some of the burden away from your primary name server, and will also function as a backup server, in case your master server is unreachable."),
			 data => [
				  { label => N("IP Address of the master DNS server:"), val => \$o->{var}{IPMASTER} },
				 ],
			 post => \&check_ipm,
			 next => 'summaryslave',
			},

	       ipforward => {
			     name => N("IP of your forwarder") . "\n\n" . N("Forwarding occurs on only those queries for which the server is not authoritative and  does not have the answer in its cache.") . "\n\n" . N("If you need it and know your IP forwarder enter IP address of it, if you dont know leave it blank"),
			     data => [
				      { label => N("External DNS:"), val => \$o->{var}{IPOFFORWARDER} },
				     ],
			     post => \&check_ipf,
			     next => 'addsearch',
			    },
	       addsearch => {
			     name => N("Add search domain") . "\n\n" . N("Search list for host-name lookup.  The search list is normally determined from the local domain name; by default, it contains only the local domain name. This may be changed by listing the desired domain search path following the search keyword") . "\n\n" . N("Domainname of this server is automatically added, and you dont need to add it here."),

			     data => [
				      { label => N("Default domain name to search:"), val => \$o->{var}{ADDSEARCH} },
				     ],
			     next => 'summary',
			    },
	       error_ipf => {
			     name => N("This is not a valid IP address for your forwarder... press next to continue"),
			     ignore => 1,
			     next => 'ipforward',
			    },
	       error_ipm => {
			     name => N("This is not a valid Master DNS IP address... press next to continue"),
			     ignore => 1,
			     next => 'slave',
			    },
	       error_iph => {
			     name => N("This is not a valid IP address... press next to continue"),
			     ignore => 1,
			     next => 'addhost',
			    },
	       dhcp_warning => {
				name => N("Warning") . "\n\n" . N("You are in dhcp, server may not work with your configuration."),
				ignore => 1,
				next => 'client_id'
			       },
	       error_add => {
			     name => N("Error.") . "\n\n" . N("It seems that host is already in your DNS configuration... press next to continue"),
			     ignore => 1,
			     next => 'addhost',
			    },
	       error_remove => {
				name => N("Error:") . "\n\n" . N("It seems that this is not present in your DNS configuration... press next to continue"),
				ignore => 1,
				next => 'removehost',
			       },
	       error_nosrv => {
			       name => N("It seems that no DNS server has been set through wizard. Please run DNS wizard: Master DNS server."),
			       next => 0,
			       end => 1,
			      },
	       error_notmaster => {
				   name => N("It seems that your are not a master DNS server, but just a slave one. So I can't add/remove host."),
				   next => 0,
				   end => 1,
				  },
	       summaryslave => {
				name => N("Ok Now building your DNS slave configuration") . "\n\n" . N("with this configuration:"),
				data => [
					 { label => N("IP Address of the master DNS server:"), fixed_val => \$o->{var}{IPMASTER} },
					],
				post => \&do_it_slave,
				next => 'end',
			       },
	       summaryadd => {
			      name => N("Client with this identification will be added to your DNS"),
			      data => [
				       { label => N("Computer name:"), fixed_val => \$o->{var}{CLIENTNAME} },
				       { label => N("Computer IP address:"), fixed_val => \$o->{var}{CLIENTIP} },
				      ],
			      post => \&do_it_add,
			      next => 'endadd',
			     },
	       summaryremove => {
				 name => N("Client with this identification will be removed from your DNS"),
				 data => [
					  { label => N("Computer name:"), val => \$o->{var}{CLIENTNAME}, fixed_list => \@list_hosts },
					 ],
				 post => \&do_it_remove,
				 next => 'endremove',
				},
	       summary => {
			   name => N("The DNS server is about to be configured with the following configuration"),
			   data => [
				    { label => N("Server Hostname:"), fixed_val => \$o->{var}{SHORTHOSTNAME} },
				    { label => N("Domainname:"), fixed_val => \$o->{var}{DOMAINNAME} },
				    { label => N("External DNS:"), fixed_val => \$o->{var}{IPOFFORWARDER} },
				    { label => N("Default domain name to search:"), fixed_val => \$o->{var}{ADDSEARCH} },
				   ],
			   post => \&do_it_master,
			   next => 'end',
			  },
	       endadd => {
			  name => N("Congratulations"),
			  data => [ { label => N("The wizard successfully add host in your DNS.") } ],
			  post => sub {
			    $o->{var}{CLIENTNAME} = '';
			    $o->{var}{CLIENTIP} = '';
			  },
			  no_back => 1,
			  next => 'addhost',
			 },
	       endremove => {
			     name => N("Congratulations"),
			     data => [ { label => N("The wizard successfully removed the host from your DNS.") } ],
			     no_back => 1,
			     end => 1,
			     next => 0,
			 },
	       end => {
		       name => N("Congratulations"),
		       data => [ { label => N("The wizard successfully configured the DNS service of your server.") } ],
		       no_back => 1,
		       end => 1,
		       next => 0,
		      },
	       error_end => {
			     name => N("Failed"),
			     data => [ { label => N("Relaunch drakwizard, and try to change some parameters.") } ],
			     no_back => 1,
			     end => 1,
			     next => 0,
			    },
	      };

sub test_srv {
  my $dir = "/var/named/zone";
  -d $dir or return 'error_nosrv';
}

sub interface_to_ip {
  my ($interface) = @_;
  my ($ip) = `/sbin/ip addr show dev $interface` =~ /^\s*inet\s+(\d+\.\d+\.\d+\.\d+)/m;
  $ip;
}

sub crea_wdir {
  if (-e $WDIR) { system("rm -rf $WDIR") }
  mkdir_p($WDIR);
}

sub resolv_ip {
  my ($ip) = @_;
  gethostbyaddr(Socket::inet_aton($ip), Socket::AF_INET());
}

sub resolv_name {
  my ($name) = @_;
  join(".", unpack "C4", (gethostbyname $name)[4]);
}


sub get_spe_ip {
  # waiting iprev, ipnorm or ipend
  my ($att, $ip) = @_;
  my @o = split(/\./, $ip);
  if ($att =~ /iprev/) {
    my $iprev = $o[2] . "." . $o[1] . "." . $o[0];
    return $iprev;
  } elsif ($att =~ /ipnor/) {
    my $ipnor = $o[0] . "." . $o[1] . "." . $o[2];
    return $ipnor;
  } elsif ($att =~ /ipend/) {
    my $ipend = $o[3];
    return $ipend;
  }
}

sub crea_db_local {
    output($WDIR . "/db.localhost", <<EOF);
\$TTL 3D
\@       IN      SOA     $HOSTNAME. root.$HOSTNAME. (
         $SERIAL  ; Serial
	 8H  ; Refresh
	 2H  ; Retry
	 4W  ; Expire
	 1D) ; Minimum TTL
         NS      $HOSTNAME.
1        IN PTR   localhost.
EOF
}
# end of db.local


# create named.conf file
sub crea_named_common {
    output($WDIR . "/named.conf", <<EOF);
key mykey {
    algorithm hmac-md5;
    secret "$DNSKEY";
};

controls {
    inet 127.0.0.1 port 953
    allow { 127.0.0.1; } keys { mykey; };
};

options {
    directory "$NAMED_DIR";
    pid-file "$NAMED_DIR/named.pid";
    version "Wizard drake";
    allow-query { any; };
    allow-transfer { any; };
EOF

    !$o->{var}{IPOFFORWARDER} or append_to_file($WDIR . "/named.conf", "\tforwarders { $o->{var}{IPOFFORWARDER}; };\n");
    append_to_file($WDIR . "/named.conf", <<EOF);
};

zone "localhost" {
    type master;
    file "zone/db.localhost";
};

zone "0.0.127.in-addr.arpa" {
    type master;
    file "zone/db.127.0.0.1";
};

zone "." {
    type hint;
    file "zone/root.hints";
};

EOF
}
# end named.conf

sub crea_named_master {
  my ($ip, $d) = @_;
  my $iprev = get_spe_ip('iprev', $ip);
  append_to_file($WDIR . "/named.conf", <<EOF);
zone "$iprev.in-addr.arpa" {
    type master;
    file "zone/db.$iprev.hosts";
    forwarders { };
};

zone "$d" {
    type master;
    file "zone/db.$d.hosts";
    forwarders { };
};
EOF
}

sub crea_named_slave {
  my ($ip, $d, $IPM) = @_;
  my $iprev = get_spe_ip('iprev', $ip);
  append_to_file($WDIR . "/named.conf", <<EOF);
zone "$iprev.in-addr.arpa" {
    type slave;
    masters { $IPM; };
    file "bak.db.$iprev.hosts";
};

zone "$d" {
    type slave;
    masters { $IPM; };
    file "bak.db.$d.hosts";
};
EOF
}

# create hints
sub crea_hints {
    output($WDIR . "/root.hints", <<EOF);
; <<>> DiG 8.1 <<>> \@A.ROOT-SERVERS.NET.
; (1 server found)
;; res options: init recurs defnam dnsrch
;; got answer:
;; ->>HEADER<<- opcode: QUERY, status: NOERROR, id: 10
;; flags: qr aa rd; QUERY: 1, ANSWER: 13, AUTHORITY: 0, ADDITIONAL: 13
;; QUERY SECTION:
;;      ., type = NS, class = IN

;; ANSWER SECTION:
.                       6D IN NS        G.ROOT-SERVERS.NET.
.                       6D IN NS        J.ROOT-SERVERS.NET.
.                       6D IN NS        K.ROOT-SERVERS.NET.
.                       6D IN NS        L.ROOT-SERVERS.NET.
.                       6D IN NS        M.ROOT-SERVERS.NET.
.                       6D IN NS        A.ROOT-SERVERS.NET.
.                       6D IN NS        H.ROOT-SERVERS.NET.
.                       6D IN NS        B.ROOT-SERVERS.NET.
.                       6D IN NS        C.ROOT-SERVERS.NET.
.                       6D IN NS        D.ROOT-SERVERS.NET.
.                       6D IN NS        E.ROOT-SERVERS.NET.
.                       6D IN NS        I.ROOT-SERVERS.NET.
.                       6D IN NS        F.ROOT-SERVERS.NET.

;; ADDITIONAL SECTION:
G.ROOT-SERVERS.NET.     5w6d16h IN A    192.112.36.4
J.ROOT-SERVERS.NET.     5w6d16h IN A    198.41.0.10
K.ROOT-SERVERS.NET.     5w6d16h IN A    193.0.14.129
L.ROOT-SERVERS.NET.     5w6d16h IN A    198.32.64.12
M.ROOT-SERVERS.NET.     5w6d16h IN A    202.12.27.33
A.ROOT-SERVERS.NET.     5w6d16h IN A    198.41.0.4
H.ROOT-SERVERS.NET.     5w6d16h IN A    128.63.2.53
B.ROOT-SERVERS.NET.     5w6d16h IN A    128.9.0.107
C.ROOT-SERVERS.NET.     5w6d16h IN A    192.33.4.12
D.ROOT-SERVERS.NET.     5w6d16h IN A    128.8.10.90
E.ROOT-SERVERS.NET.     5w6d16h IN A    192.203.230.10
I.ROOT-SERVERS.NET.     5w6d16h IN A    192.36.148.17
F.ROOT-SERVERS.NET.     5w6d16h IN A    192.5.5.241
;; Total query time: 215 msec
;; FROM: roke.uio.no to SERVER: A.ROOT-SERVERS.NET.  198.41.0.4
;; WHEN: Sun Feb 15 01:22:51 1998
;; MSG SIZE  sent: 17  rcvd: 436
EOF
}
# end roots.hints

# create ipreverse
sub crea_iprev {
  my ($ip, $d) = @_;
  my $iprev = get_spe_ip('iprev', $ip);
  my $ipend = get_spe_ip('ipend', $ip);
  output($WDIR . "/db." . $iprev . ".hosts", <<EOF);
\$TTL 3D
@       IN      SOA     $SHORTHOSTNAME.$d.        $SHORTHOSTNAME.$d. (
		$SERIAL ; serial
                10800   ; Refresh
                3600    ; Retry
                604800  ; Expire
                86400) ; Minimum TTL
                NS      $SHORTHOSTNAME.$d.
$ipend       IN      PTR     $SHORTHOSTNAME.$d.
; use tab to retrieve data in drakwizard bind
; 34      IN      PTR     xp2400.guibland.com.
EOF

}
# end create iprev

# create  ipnormal
sub crea_ipnorm {
  my ($ip, $d) = @_;
  output($WDIR . "/db.$d.hosts", <<EOF);
\$TTL 3D
@       IN      SOA     $SHORTHOSTNAME.$d. root.$SHORTHOSTNAME.$d. (
               $SERIAL       ; Serial
               8H   ; Refresh
               2H   ; Retry
               4W  ; Expire
               1D)  ; Minimum TTL
               TXT     $TEXTINFO
               IN      NS      $SHORTHOSTNAME.$d.
localhost              A       127.0.0.1
dnsmaster                   IN      CNAME   $SHORTHOSTNAME.$d.
$SHORTHOSTNAME.$d.        IN      A      $ip
; use tab to retrieve data in drakwizard bind
; xp2400.guibland.com.        IN      A      10.0.1.34
EOF
}
# end of ipnorm


# create 127.0.
sub crea_127 {
  my $d = $DOMAINNAME;
  output($WDIR . "/db.127.0.0.1", <<EOF);
\$TTL 3D
\@               IN      SOA     $d. root.$d. (
                $SERIAL ; Serial
                28800   ; Refresh
                7200    ; Retry
                604800  ; Expire
                86400)  ; Minimum TTL
                NS      $HOSTNAME.
localhost      IN       A     127.0.0.1
EOF
}
# end create 127

# create rndc.conf
sub crea_rndc {
  output($WDIR . "/rndc.conf", <<EOF);
/*
* Copyright (C) 2000, 2001  Internet Software Consortium.
*
* Permission to use, copy, modify, and distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND INTERNET SOFTWARE CONSORTIUM
* DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL
* INTERNET SOFTWARE CONSORTIUM BE LIABLE FOR ANY SPECIAL, DIRECT,
* INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING
* FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
* NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION
* WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
/* Id: dns_cluster.pm,v 1.18 2003/04/10 16:01:47 aginies Exp */
/*
* Sample rndc configuration file.
*/

options {
    default-server  localhost;
    default-key     "mykey";
};

server localhost {
    key     "mykey";
};

key "mykey" {
    algorithm       hmac-md5;
    secret "$DNSKEY";
};
EOF
}
# end of create rndc

# save old config files

sub save_old_config {
  if (-d $ZONE_DIR) {
    print " - Backup of current configuration in " . $REP_SAVE . "\n";
  }
  if (-d "$REP_SAVE/dns") { rm_rf("$REP_SAVE/dns") }
  mkdir_p($REP_SAVE . '/dns');
  cp_af($_, "$REP_SAVE/dns/$_" . '-' . $DATE . '.sauv') foreach glob_($ZONE_DIR . "/*");
  if (-e "/etc/named.conf") {
    cp_af("/etc/named.conf", "$REP_SAVE/dns/named.conf-$DATE");
  }
}
# end save old config

sub generate_rndc {
  mkdir_p($WDIR);
  system("rndc-confgen -a -c $WDIR/rndc.key");
  my ($key) = cat_("$WDIR/rndc.key") =~ /secret "(\S*)";/;
  $key;
}


# reinit resolv.conf
sub set_resolv {
    output($WDIR . "/resolv.conf", <<EOF);
domain $DOMAINNAME
search $DOMAINNAME
nameserver $IPSERVER
EOF

    !$o->{var}{IPMASTER} or return append_to_file($WDIR . "/resolv.conf", "nameserver $o->{var}{IPMASTER}\n");
    !$o->{var}{ADDSEARCH} or return append_to_file($WDIR . "/resolv.conf", "search $o->{var}{ADDSEARCH}\n");
    !$o->{var}{IPOFFORWARDER} or return append_to_file($WDIR . "/resolv.conf", "nameserver $o->{var}{IPOFFORWARDER}\n");
}
# end set resolv.conf

# set /etc/hosts
sub set_hosts {
  my ($ip, $h) = @_;
  if (!any { /$ip\s* $h/ } cat_($WDIR . "/hosts")) {
    append_to_file($WDIR . "/hosts", <<EOF);
$ip        $h
EOF
  }
}
# end set hosts

# check config of dns
sub check_config {
  system('named-checkconf', $WDIR . '/named.conf');
}
# end check config

# copy file correct place
sub copy_good {
  mkdir_p($ZONE_DIR);
  cp_af($WDIR . '/named.conf', '/etc/named.conf');
  cp_af($WDIR . '/rndc.conf', '/etc/rndc.conf');
  cp_af($WDIR . '/hosts', '/etc/hosts');
  cp_af($WDIR . '/resolv.conf', '/etc/resolv.conf');
  cp_af($WDIR . '/root.hints', $ZONE_DIR . '/');
  cp_af(glob($WDIR . '/db*'), $ZONE_DIR . '/');
}
# end copy goodplace

my $ip_regexp = qr/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/;
sub check_ipm {
    my $ip = $o->{var}{IPMASTER};
    $ip or return 'slave';
    my @fields = $ip =~ $ip_regexp or return 'error_ipm';
    every { 0 <= $_ && $_ <= 255 } @fields or return 'error_ipm';
}

sub check_ipf {
    my $ip = $o->{var}{IPOFFORWARDER};
    $ip or return 'addsearch';
    my @fields = $ip =~ $ip_regexp or return 'error_ipf';
    every { 0 <= $_ && $_ <= 255 } @fields or return 'error_ipf';
}


sub check_iph {
  my $ip = $o->{var}{CLIENTIP};
  my @fields = $ip =~ $ip_regexp or return 'error_iph';
  every { 0 <= $_ && $_ <= 255 } @fields or return 'error_iph';
}

sub do_it {
    $::testing and return;
    #my ($st) = @_;
    crea_wdir($WDIR);
    # create files
    crea_db_local();
    crea_127();
    crea_named_common();
    # set host configuration
    if (-f $WDIR . '/hosts')  { rm_rf($WDIR . '/hosts') }
    set_hosts('127.0.0.1', 'localhost.localdomain localhost');
    set_hosts($IPSERVER, $HOSTNAME);
}

sub end_it {
  crea_hints();
  crea_rndc();
  # set configuration files on server
  set_resolv();
  # check generated config file are good
  check_config();
  # create backup
  save_old_config();
  # copy in correct place
  copy_good();
  # start or restart the service
  if (services::is_service_running('named')) {
    services::restart('named')
    } else {
      services::start('named')
    }
}

sub do_it_master {
  return if $::testing;
  my $in = 'interactive'->vnew('su', 'dns');
  my $w = $in->wait_message(N("Master DNS server"), N("Configuring your system as Master DNS server ..."));
  system("touch $ft");
  do_it();
  crea_iprev($IPSERVER, $DOMAINNAME);
  crea_ipnorm($IPSERVER, $DOMAINNAME);
  crea_named_master($IPSERVER, $DOMAINNAME);
  end_it();
  undef $w;
  check_started('named');
}

sub do_it_slave {
  return if $::testing;
  my $in = 'interactive'->vnew('su', 'dns');
  my $w = $in->wait_message(N("Slave DNS server"), N("Configuring your system as Slave DNS server ..."));
  do_it();
  rm_rf(glob("$NAMED_DIR/bak*"));
  crea_named_slave($IPSERVER, $DOMAINNAME, $o->{var}{IPMASTER});
  end_it();
  undef $w;
  check_started('named');
}

sub get_shortname {
# sure someone can find a better method to do that
  my ($name) = @_;
  my @DT = split(/\./, $DOMAINNAME);
  my $NB = $#DT;
  if (any { /$DOMAINNAME$/x } $name) {
    my @shortname = split(/\./, $name);
    splice(@shortname, -$NB);
    my $shortn;
    foreach (@shortname) {
      $shortn or return $shortn = $_;
      !$shortn or return $shortn . "." . $_;
    }
  } else { return $name }
}

sub do_it_add {
  return if $::testing;
  test_srv();
  my $iprev = get_spe_ip('iprev', $IPSERVER);
  my $ipend = get_spe_ip('ipend', $o->{var}{CLIENTIP});
  my $SNAME = get_shortname($o->{var}{CLIENTNAME});
  if (any { /$ipend\tIN/ } cat_("$ZONE_DIR/db.$iprev.hosts")) {
    return 'error_add';
  } elsif (any { /$SNAME.$DOMAINNAME.$/ } cat_("$ZONE_DIR/db.$iprev.hosts")) {
    return 'error_add';
  } else {
    append_to_file("$ZONE_DIR/db.$DOMAINNAME.hosts",
		   "$SNAME.$DOMAINNAME.\tIN\tA\t$o->{var}{CLIENTIP}\n");
    append_to_file("$ZONE_DIR/db.$iprev.hosts",
		   "$ipend\tIN\tPTR\t$SNAME.$DOMAINNAME.\n");
  }
  system("service named reload");
}

sub do_it_remove {
  return if $::testing;
  test_srv();
  my $iprev = get_spe_ip('iprev', $IPSERVER);
  my $NAME = $o->{var}{CLIENTNAME};
  substInFile {
    s/^\b$NAME.\b.*//;
    s/^\s*$//;
  } "$ZONE_DIR/db.$DOMAINNAME.hosts";
  substInFile {
    s/^\d+\tIN\tPTR\t$NAME.*//;
    s/^\s*$//;
  } "$ZONE_DIR/db.$iprev.hosts";
  system("service named reload");
}


#34       IN      PTR     xp2400.guibland.com.
sub do_it_list {
  return if $::testing;
  my $iprev = get_spe_ip('iprev', $IPSERVER);
  my $db = "$ZONE_DIR/db.$iprev.hosts";
  #my $ipnor = get_spe_ip('ipnor', $IPSERVER);
  my @hosts; my @ip;
  foreach (cat_($db)) {
    my ($ipend, $h) = /(\d{1,3})\tIN\tPTR\t(.*)/;
    if (!$h) { push @hosts, $h; push @ip, $ipend }
  }
}


sub new {
    my ($class) = @_;
    bless {
            o   => $o,
       }, $class;
}

1;