1 | # dns/trunk/DNSDB.pm
|
---|
2 | # Abstraction functions for DNS administration
|
---|
3 | ##
|
---|
4 | # $Id: DNSDB.pm 307 2012-04-17 22:09:44Z kdeugau $
|
---|
5 | # Copyright 2008-2011 Kris Deugau <kdeugau@deepnet.cx>
|
---|
6 | #
|
---|
7 | # This program is free software: you can redistribute it and/or modify
|
---|
8 | # it under the terms of the GNU General Public License as published by
|
---|
9 | # the Free Software Foundation, either version 3 of the License, or
|
---|
10 | # (at your option) any later version.
|
---|
11 | #
|
---|
12 | # This program is distributed in the hope that it will be useful,
|
---|
13 | # but WITHOUT ANY WARRANTY; without even the implied warranty of
|
---|
14 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
---|
15 | # GNU General Public License for more details.
|
---|
16 | #
|
---|
17 | # You should have received a copy of the GNU General Public License
|
---|
18 | # along with this program. If not, see <http://www.gnu.org/licenses/>.
|
---|
19 | ##
|
---|
20 |
|
---|
21 | package DNSDB;
|
---|
22 |
|
---|
23 | use strict;
|
---|
24 | use warnings;
|
---|
25 | use Exporter;
|
---|
26 | use DBI;
|
---|
27 | use Net::DNS;
|
---|
28 | use Crypt::PasswdMD5;
|
---|
29 | use Net::SMTP;
|
---|
30 | use NetAddr::IP qw(:lower);
|
---|
31 | use POSIX;
|
---|
32 | use vars qw($VERSION @ISA @EXPORT @EXPORT_OK %EXPORT_TAGS);
|
---|
33 |
|
---|
34 | $VERSION = 0.1; ##VERSION##
|
---|
35 | @ISA = qw(Exporter);
|
---|
36 | @EXPORT_OK = qw(
|
---|
37 | &initGlobals &login &initActionLog
|
---|
38 | &initPermissions &getPermissions &changePermissions &comparePermissions
|
---|
39 | &changeGroup
|
---|
40 | &loadConfig &connectDB &finish
|
---|
41 | &addDomain &delZone &domainName &revName &domainID &revID &addRDNS
|
---|
42 | &getZoneCount &getZoneList
|
---|
43 | &addGroup &delGroup &getChildren &groupName
|
---|
44 | &addUser &updateUser &delUser &userFullName &userStatus &getUserData
|
---|
45 | &getSOA &updateSOA &getRecLine &getDomRecs &getRecCount
|
---|
46 | &addRec &updateRec &delRec
|
---|
47 | &getTypelist
|
---|
48 | &parentID
|
---|
49 | &isParent
|
---|
50 | &zoneStatus &importAXFR
|
---|
51 | &export
|
---|
52 | &mailNotify
|
---|
53 | %typemap %reverse_typemap %config
|
---|
54 | %permissions @permtypes $permlist
|
---|
55 | );
|
---|
56 |
|
---|
57 | @EXPORT = (); # Export nothing by default.
|
---|
58 | %EXPORT_TAGS = ( ALL => [qw(
|
---|
59 | &initGlobals &login &initActionLog
|
---|
60 | &initPermissions &getPermissions &changePermissions &comparePermissions
|
---|
61 | &changeGroup
|
---|
62 | &loadConfig &connectDB &finish
|
---|
63 | &addDomain &delZone &domainName &revName &domainID &revID &addRDNS
|
---|
64 | &getZoneCount &getZoneList
|
---|
65 | &addGroup &delGroup &getChildren &groupName
|
---|
66 | &addUser &updateUser &delUser &userFullName &userStatus &getUserData
|
---|
67 | &getSOA &updateSOA &getRecLine &getDomRecs &getRecCount
|
---|
68 | &addRec &updateRec &delRec
|
---|
69 | &getTypelist
|
---|
70 | &parentID
|
---|
71 | &isParent
|
---|
72 | &zoneStatus &importAXFR
|
---|
73 | &export
|
---|
74 | &mailNotify
|
---|
75 | %typemap %reverse_typemap %config
|
---|
76 | %permissions @permtypes $permlist
|
---|
77 | )]
|
---|
78 | );
|
---|
79 |
|
---|
80 | our $group = 1;
|
---|
81 | our $errstr = '';
|
---|
82 | our $resultstr = '';
|
---|
83 |
|
---|
84 | # Halfway sane defaults for SOA, TTL, etc.
|
---|
85 | # serial defaults to 0 for convenience.
|
---|
86 | # value will be either YYYYMMDDNN for BIND/etc, or auto-internal for tinydns
|
---|
87 | our %def = qw (
|
---|
88 | contact hostmaster.DOMAIN
|
---|
89 | prins ns1.myserver.com
|
---|
90 | serial 0
|
---|
91 | soattl 86400
|
---|
92 | refresh 10800
|
---|
93 | retry 3600
|
---|
94 | expire 604800
|
---|
95 | minttl 10800
|
---|
96 | ttl 10800
|
---|
97 | );
|
---|
98 |
|
---|
99 | # Arguably defined wholly in the db, but little reason to change without supporting code changes
|
---|
100 | our @permtypes = qw (
|
---|
101 | group_edit group_create group_delete
|
---|
102 | user_edit user_create user_delete
|
---|
103 | domain_edit domain_create domain_delete
|
---|
104 | record_edit record_create record_delete
|
---|
105 | self_edit admin
|
---|
106 | );
|
---|
107 | our $permlist = join(',',@permtypes);
|
---|
108 |
|
---|
109 | # DNS record type map and reverse map.
|
---|
110 | # loaded from the database, from http://www.iana.org/assignments/dns-parameters
|
---|
111 | our %typemap;
|
---|
112 | our %reverse_typemap;
|
---|
113 |
|
---|
114 | our %permissions;
|
---|
115 |
|
---|
116 | # Prepopulate a basic config. Note some of these *will* cause errors if left unset.
|
---|
117 | # note: add appropriate stanzas in loadConfig to parse these
|
---|
118 | our %config = (
|
---|
119 | # Database connection info
|
---|
120 | dbname => 'dnsdb',
|
---|
121 | dbuser => 'dnsdb',
|
---|
122 | dbpass => 'secret',
|
---|
123 | dbhost => '',
|
---|
124 |
|
---|
125 | # Email notice settings
|
---|
126 | mailhost => 'smtp.example.com',
|
---|
127 | mailnotify => 'dnsdb@example.com', # to
|
---|
128 | mailsender => 'dnsdb@example.com', # from
|
---|
129 | mailname => 'DNS Administration',
|
---|
130 | orgname => 'Example Corp',
|
---|
131 | domain => 'example.com',
|
---|
132 |
|
---|
133 | # Template directory
|
---|
134 | templatedir => 'templates/',
|
---|
135 | # fmeh. this is a real web path, not a logical internal one. hm..
|
---|
136 | # cssdir => 'templates/',
|
---|
137 | sessiondir => 'session/',
|
---|
138 |
|
---|
139 | # Session params
|
---|
140 | timeout => '3600', # 1 hour default
|
---|
141 |
|
---|
142 | # Other miscellanea
|
---|
143 | log_failures => 1, # log all evarthing by default
|
---|
144 | perpage => 15,
|
---|
145 | );
|
---|
146 |
|
---|
147 | ## (Semi)private variables
|
---|
148 |
|
---|
149 | # Hash of functions for validating record types. Filled in initGlobals() since
|
---|
150 | # it relies on visibility flags from the rectypes table in the DB
|
---|
151 | my %validators;
|
---|
152 |
|
---|
153 | # Username, full name, ID - mainly for logging
|
---|
154 | my %userdata;
|
---|
155 |
|
---|
156 | # Entity-relationship reference hashes.
|
---|
157 | my %par_tbl = (
|
---|
158 | group => 'groups',
|
---|
159 | user => 'users',
|
---|
160 | defrec => 'default_records',
|
---|
161 | defrevrec => 'default_rev_records',
|
---|
162 | domain => 'domains',
|
---|
163 | revzone => 'revzones',
|
---|
164 | record => 'records'
|
---|
165 | );
|
---|
166 | my %id_col = (
|
---|
167 | group => 'group_id',
|
---|
168 | user => 'user_id',
|
---|
169 | defrec => 'record_id',
|
---|
170 | defrevrec => 'record_id',
|
---|
171 | domain => 'domain_id',
|
---|
172 | revzone => 'rdns_id',
|
---|
173 | record => 'record_id'
|
---|
174 | );
|
---|
175 | my %par_col = (
|
---|
176 | group => 'parent_group_id',
|
---|
177 | user => 'group_id',
|
---|
178 | defrec => 'group_id',
|
---|
179 | defrevrec => 'group_id',
|
---|
180 | domain => 'group_id',
|
---|
181 | revzone => 'group_id',
|
---|
182 | record => 'domain_id'
|
---|
183 | );
|
---|
184 | my %par_type = (
|
---|
185 | group => 'group',
|
---|
186 | user => 'group',
|
---|
187 | defrec => 'group',
|
---|
188 | defrevrec => 'group',
|
---|
189 | domain => 'group',
|
---|
190 | revzone => 'group',
|
---|
191 | record => 'domain'
|
---|
192 | );
|
---|
193 |
|
---|
194 | ##
|
---|
195 | ## utility functions
|
---|
196 | ##
|
---|
197 |
|
---|
198 | ## DNSDB::_rectable()
|
---|
199 | # Takes default+rdns flags, returns appropriate table name
|
---|
200 | sub _rectable {
|
---|
201 | my $def = shift;
|
---|
202 | my $rev = shift;
|
---|
203 |
|
---|
204 | return 'records' if $def ne 'y';
|
---|
205 | return 'default_records' if $rev ne 'y';
|
---|
206 | return 'default_rev_records';
|
---|
207 | } # end _rectable()
|
---|
208 |
|
---|
209 | ## DNSDB::_recparent()
|
---|
210 | # Takes default+rdns flags, returns appropriate parent-id column name
|
---|
211 | sub _recparent {
|
---|
212 | my $def = shift;
|
---|
213 | my $rev = shift;
|
---|
214 |
|
---|
215 | return 'group_id' if $def eq 'y';
|
---|
216 | return 'rdns_id' if $rev eq 'y';
|
---|
217 | return 'domain_id';
|
---|
218 | } # end _recparent()
|
---|
219 |
|
---|
220 | ## DNSDB::_ipparent()
|
---|
221 | # Check an IP to be added in a reverse zone to see if it's really in the requested parent.
|
---|
222 | # Takes a database handle, default and reverse flags, IP (fragment) to check, parent zone ID,
|
---|
223 | # and a reference to a NetAddr::IP object (also used to pass back a fully-reconstructed IP for
|
---|
224 | # database insertion)
|
---|
225 | sub _ipparent {
|
---|
226 | my $dbh = shift;
|
---|
227 | my $defrec = shift;
|
---|
228 | my $revrec = shift;
|
---|
229 | my $val = shift;
|
---|
230 | my $id = shift;
|
---|
231 | my $addr = shift;
|
---|
232 |
|
---|
233 | return if $revrec ne 'y'; # this sub not useful in forward zones
|
---|
234 |
|
---|
235 | $$addr = NetAddr::IP->new($$val); #necessary?
|
---|
236 |
|
---|
237 | # subsub to split, reverse, and overlay an IP fragment on a netblock
|
---|
238 | sub __rev_overlay {
|
---|
239 | my $splitme = shift; # ':' or '.', m'lud?
|
---|
240 | my $parnet = shift;
|
---|
241 | my $val = shift;
|
---|
242 | my $addr = shift;
|
---|
243 |
|
---|
244 | my $joinme = $splitme;
|
---|
245 | $splitme = '\.' if $splitme eq '.';
|
---|
246 | my @working = reverse(split($splitme, $parnet->addr));
|
---|
247 | my @parts = reverse(split($splitme, $$val));
|
---|
248 | for (my $i = 0; $i <= $#parts; $i++) {
|
---|
249 | $working[$i] = $parts[$i];
|
---|
250 | }
|
---|
251 | my $checkme = NetAddr::IP->new(join($joinme, reverse(@working))) or return 0;
|
---|
252 | return 0 unless $checkme->within($parnet);
|
---|
253 | $$addr = $checkme; # force "correct" IP to be recorded.
|
---|
254 | return 1;
|
---|
255 | }
|
---|
256 |
|
---|
257 | my ($parstr) = $dbh->selectrow_array("SELECT revnet FROM revzones WHERE rdns_id = ?", undef, ($id));
|
---|
258 | my $parnet = NetAddr::IP->new($parstr);
|
---|
259 |
|
---|
260 | # Fail early on v6-in-v4 or v4-in-v6. We're not accepting these ATM.
|
---|
261 | return 0 if $parnet->addr =~ /\./ && $$val =~ /:/;
|
---|
262 | return 0 if $parnet->addr =~ /:/ && $$val =~ /\./;
|
---|
263 |
|
---|
264 | if ($$addr && $$val =~ /^[\da-fA-F][\da-fA-F:]+[\da-fA-F]$/) {
|
---|
265 | # the only case where NetAddr::IP's acceptance of legitimate IPs is "correct" is for a proper IPv6 address.
|
---|
266 | # the rest we have to restructure before fiddling. *sigh*
|
---|
267 | return 1 if $$addr->within($parnet);
|
---|
268 | } else {
|
---|
269 | # We don't have a complete IP in $$val (yet)
|
---|
270 | if ($parnet->addr =~ /:/) {
|
---|
271 | $$val =~ s/^:+//; # gotta strip'em all...
|
---|
272 | return __rev_overlay(':', $parnet, $val, $addr);
|
---|
273 | }
|
---|
274 | if ($parnet->addr =~ /\./) {
|
---|
275 | $$val =~ s/^\.+//;
|
---|
276 | return __rev_overlay('.', $parnet, $val, $addr);
|
---|
277 | }
|
---|
278 | # should be impossible to get here...
|
---|
279 | }
|
---|
280 | # ... and here.
|
---|
281 | # can't do nuttin' in forward zones
|
---|
282 | } # end _ipparent()
|
---|
283 |
|
---|
284 | ## DNSDB::_hostparent()
|
---|
285 | # A little different than _ipparent above; this tries to *find* the parent zone of a hostname
|
---|
286 | # Takes a database handle and hostname.
|
---|
287 | # Returns the domain ID of the parent domain if one was found.
|
---|
288 | sub _hostparent {
|
---|
289 | my $dbh = shift;
|
---|
290 | my $hname = shift;
|
---|
291 |
|
---|
292 | my @hostbits = split /\./, $hname;
|
---|
293 | my $sth = $dbh->prepare("SELECT count(*),domain_id FROM domains WHERE domain = ? GROUP BY domain_id");
|
---|
294 | foreach (@hostbits) {
|
---|
295 | $sth->execute($hname);
|
---|
296 | my ($found, $parid) = $sth->fetchrow_array;
|
---|
297 | if ($found) {
|
---|
298 | return $parid;
|
---|
299 | }
|
---|
300 | $hname =~ s/^$_\.//;
|
---|
301 | }
|
---|
302 | } # end _hostparent()
|
---|
303 |
|
---|
304 | ## DNSDB::_log()
|
---|
305 | # Log an action
|
---|
306 | # Takes a database handle and log entry hash containing at least:
|
---|
307 | # group_id, log entry
|
---|
308 | # and optionally one or more of:
|
---|
309 | # domain_id, rdns_id
|
---|
310 | # The %userdata hash provides the user ID, username, and fullname
|
---|
311 | sub _log {
|
---|
312 | my $dbh = shift;
|
---|
313 |
|
---|
314 | my %args = @_;
|
---|
315 |
|
---|
316 | $args{rdns_id} = 0 if !$args{rdns_id};
|
---|
317 | $args{domain_id} = 0 if !$args{domain_id};
|
---|
318 |
|
---|
319 | ##fixme: farm out the actual logging to different subs for file, syslog, internal, etc based on config
|
---|
320 | # if ($config{log_channel} eq 'sql') {
|
---|
321 | $dbh->do("INSERT INTO log (domain_id,rdns_id,group_id,entry,user_id,email,name) VALUES (?,?,?,?,?,?,?)",
|
---|
322 | undef,
|
---|
323 | ($args{domain_id}, $args{rdns_id}, $args{group_id}, $args{entry},
|
---|
324 | $userdata{userid}, $userdata{username}, $userdata{fullname}) );
|
---|
325 | # } elsif ($config{log_channel} eq 'file') {
|
---|
326 | # } elsif ($config{log_channel} eq 'syslog') {
|
---|
327 | # }
|
---|
328 | } # end _log
|
---|
329 |
|
---|
330 |
|
---|
331 | ##
|
---|
332 | ## Record validation subs.
|
---|
333 | ##
|
---|
334 |
|
---|
335 | ## All of these subs take substantially the same arguments:
|
---|
336 | # a database handle
|
---|
337 | # a hash containing at least the following keys:
|
---|
338 | # - defrec (default/live flag)
|
---|
339 | # - revrec (forward/reverse flag)
|
---|
340 | # - id (parent entity ID)
|
---|
341 | # - host (hostname)
|
---|
342 | # - rectype
|
---|
343 | # - val (IP, hostname [CNAME/MX/SRV] or text)
|
---|
344 | # - addr (NetAddr::IP object from val. May be undef.)
|
---|
345 | # MX and SRV record validation also expect distance, and SRV records expect weight and port as well.
|
---|
346 | # host, rectype, and addr should be references as these may be modified in validation
|
---|
347 |
|
---|
348 | # A record
|
---|
349 | sub _validate_1 {
|
---|
350 | my $dbh = shift;
|
---|
351 |
|
---|
352 | my %args = @_;
|
---|
353 |
|
---|
354 | return ('FAIL', 'Reverse zones cannot contain A records') if $args{revrec} eq 'y';
|
---|
355 |
|
---|
356 | # Coerce all hostnames to end in ".DOMAIN" for group/default records,
|
---|
357 | # or the intended parent domain for live records.
|
---|
358 | my $pname = ($args{defrec} eq 'y' ? 'DOMAIN' : domainName($dbh,$args{id}));
|
---|
359 | ${$args{host}} =~ s/\.*$/\.$pname/ if ${$args{host}} !~ /$pname$/;
|
---|
360 |
|
---|
361 | # Check IP is well-formed, and that it's a v4 address
|
---|
362 | # Fail on "compact" IPv4 variants, because they are not consistent and predictable.
|
---|
363 | return ('FAIL',"$typemap{${$args{rectype}}} record must be a valid IPv4 address")
|
---|
364 | unless ${$args{val}} =~ /^\d+\.\d+\.\d+\.\d+$/;
|
---|
365 | return ('FAIL',"$typemap{${$args{rectype}}} record must be a valid IPv4 address")
|
---|
366 | unless $args{addr} && !$args{addr}->{isv6};
|
---|
367 | # coerce IP/value to normalized form for storage
|
---|
368 | ${$args{val}} = $args{addr}->addr;
|
---|
369 |
|
---|
370 | return ('OK','OK');
|
---|
371 | } # done A record
|
---|
372 |
|
---|
373 | # NS record
|
---|
374 | sub _validate_2 {
|
---|
375 | my $dbh = shift;
|
---|
376 |
|
---|
377 | my %args = @_;
|
---|
378 |
|
---|
379 | # Coerce the hostname to "DOMAIN" for forward default records, "ZONE" for reverse default records,
|
---|
380 | # or the intended parent zone for live records.
|
---|
381 | ##fixme: allow for delegating <subdomain>.DOMAIN?
|
---|
382 | if ($args{revrec} eq 'y') {
|
---|
383 | my $pname = ($args{defrec} eq 'y' ? 'ZONE' : revName($dbh,$args{id}));
|
---|
384 | ${$args{host}} = $pname if ${$args{host}} ne $pname;
|
---|
385 | } else {
|
---|
386 | my $pname = ($args{defrec} eq 'y' ? 'DOMAIN' : domainName($dbh,$args{id}));
|
---|
387 | ${$args{host}} = $pname if ${$args{host}} ne $pname;
|
---|
388 | }
|
---|
389 |
|
---|
390 | # Let this lie for now. Needs more magic.
|
---|
391 | # # Check IP is well-formed, and that it's a v4 address
|
---|
392 | # return ('FAIL',"A record must be a valid IPv4 address")
|
---|
393 | # unless $addr && !$addr->{isv6};
|
---|
394 | # # coerce IP/value to normalized form for storage
|
---|
395 | # $$val = $addr->addr;
|
---|
396 |
|
---|
397 | return ('OK','OK');
|
---|
398 | } # done NS record
|
---|
399 |
|
---|
400 | # CNAME record
|
---|
401 | sub _validate_5 {
|
---|
402 | my $dbh = shift;
|
---|
403 |
|
---|
404 | my %args = @_;
|
---|
405 |
|
---|
406 | # Not really true, but these are only useful for delegating smaller-than-/24 IP blocks.
|
---|
407 | # This is fundamentally a messy operation and should really just be taken care of by the
|
---|
408 | # export process, not manual maintenance of the necessary records.
|
---|
409 | return ('FAIL', 'Reverse zones cannot contain CNAME records') if $args{revrec} eq 'y';
|
---|
410 |
|
---|
411 | # Coerce all hostnames to end in ".DOMAIN" for group/default records,
|
---|
412 | # or the intended parent domain for live records.
|
---|
413 | my $pname = ($args{defrec} eq 'y' ? 'DOMAIN' : domainName($dbh,$args{id}));
|
---|
414 | ${$args{host}} =~ s/\.*$/\.$pname/ if ${$args{host}} !~ /$pname$/;
|
---|
415 |
|
---|
416 | return ('OK','OK');
|
---|
417 | } # done CNAME record
|
---|
418 |
|
---|
419 | # SOA record
|
---|
420 | sub _validate_6 {
|
---|
421 | # Smart monkeys won't stick their fingers in here; we have
|
---|
422 | # separate dedicated routines to deal with SOA records.
|
---|
423 | return ('OK','OK');
|
---|
424 | } # done SOA record
|
---|
425 |
|
---|
426 | # PTR record
|
---|
427 | sub _validate_12 {
|
---|
428 | my $dbh = shift;
|
---|
429 |
|
---|
430 | my %args = @_;
|
---|
431 |
|
---|
432 | if ($args{revrec} eq 'y') {
|
---|
433 | if ($args{defrec} eq 'n') {
|
---|
434 | return ('FAIL', "IP or IP fragment ${$args{val}} is not within ".revName($dbh, $args{id}))
|
---|
435 | unless _ipparent($dbh, $args{defrec}, $args{revrec}, $args{val}, $args{id}, \$args{addr});
|
---|
436 | ${$args{val}} = $args{addr}->addr;
|
---|
437 | } else {
|
---|
438 | if (${$args{val}} =~ /\./) {
|
---|
439 | # looks like a v4 or fragment
|
---|
440 | if (${$args{val}} =~ /^\d+\.\d+\.\d+\.\d+$/) {
|
---|
441 | # woo! a complete IP! validate it and normalize, or fail.
|
---|
442 | $args{addr} = NetAddr::IP->new(${$args{val}})
|
---|
443 | or return ('FAIL', "IP/value looks like IPv4 but isn't valid");
|
---|
444 | ${$args{val}} = $args{addr}->addr;
|
---|
445 | } else {
|
---|
446 | ${$args{val}} =~ s/^\.*/ZONE./ unless ${$args{val}} =~ /^ZONE/;
|
---|
447 | }
|
---|
448 | } elsif (${$args{val}} =~ /[a-f:]/) {
|
---|
449 | # looks like a v6 or fragment
|
---|
450 | ${$args{val}} =~ s/^:*/ZONE::/ if !$args{addr} && ${$args{val}} !~ /^ZONE/;
|
---|
451 | if ($args{addr}) {
|
---|
452 | if ($args{addr}->addr =~ /^0/) {
|
---|
453 | ${$args{val}} =~ s/^:*/ZONE::/ unless ${$args{val}} =~ /^ZONE/;
|
---|
454 | } else {
|
---|
455 | ${$args{val}} = $args{addr}->addr;
|
---|
456 | }
|
---|
457 | }
|
---|
458 | } else {
|
---|
459 | # bare number (probably). These could be v4 or v6, so we'll
|
---|
460 | # expand on these on creation of a reverse zone.
|
---|
461 | ${$args{val}} = "ZONE,${$args{val}}" unless ${$args{val}} =~ /^ZONE/;
|
---|
462 | }
|
---|
463 | ${$args{host}} =~ s/\.*$/\.$config{domain}/ if ${$args{host}} !~ /(?:$config{domain}|ADMINDOMAIN)$/;
|
---|
464 | }
|
---|
465 |
|
---|
466 | # Multiple PTR records do NOT generally do what most people believe they do,
|
---|
467 | # and tend to fail in the most awkward way possible. Check and warn.
|
---|
468 | # We use $val instead of $addr->addr since we may be in a defrec, and may have eg "ZONE::42" or "ZONE.12"
|
---|
469 |
|
---|
470 | my @checkvals = (${$args{val}});
|
---|
471 | if (${$args{val}} =~ /,/) {
|
---|
472 | # push . and :: variants into checkvals if val has ,
|
---|
473 | my $tmp;
|
---|
474 | ($tmp = ${$args{val}}) =~ s/,/./;
|
---|
475 | push @checkvals, $tmp;
|
---|
476 | ($tmp = ${$args{val}}) =~ s/,/::/;
|
---|
477 | push @checkvals, $tmp;
|
---|
478 | }
|
---|
479 | my $pcsth = $dbh->prepare("SELECT count(*) FROM "._rectable($args{defrec},$args{revrec})." WHERE val = ?");
|
---|
480 | foreach my $checkme (@checkvals) {
|
---|
481 | if ($args{update}) {
|
---|
482 | # Record update. There should usually be an existing PTR (the record being updated)
|
---|
483 | my @ptrs = @{ $dbh->selectcol_arrayref("SELECT record_id FROM "._rectable($args{defrec},$args{revrec}).
|
---|
484 | " WHERE val = ?", undef, ($checkme)) };
|
---|
485 | return ('WARN', "PTR record for $checkme already exists; adding another will probably not do what you want")
|
---|
486 | if @ptrs && (!grep /^$args{update}$/, @ptrs);
|
---|
487 | } else {
|
---|
488 | # New record. Always warn if a PTR exists
|
---|
489 | my ($ptrcount) = $dbh->selectrow_array("SELECT count(*) FROM "._rectable($args{defrec},$args{revrec}).
|
---|
490 | " WHERE val = ?", undef, ($checkme));
|
---|
491 | return ('WARN', "PTR record for $checkme already exists; adding another will probably not do what you want")
|
---|
492 | if $ptrcount;
|
---|
493 | }
|
---|
494 | }
|
---|
495 |
|
---|
496 | } else {
|
---|
497 | # Not absolutely true but only useful if you hack things up for sub-/24 v4 reverse delegations
|
---|
498 | # Simpler to just create the reverse zone and grant access for the customer to edit it, and create direct
|
---|
499 | # PTR records on export
|
---|
500 | return ('FAIL',"Forward zones cannot contain PTR records");
|
---|
501 | }
|
---|
502 |
|
---|
503 | return ('OK','OK');
|
---|
504 | } # done PTR record
|
---|
505 |
|
---|
506 | # MX record
|
---|
507 | sub _validate_15 {
|
---|
508 | my $dbh = shift;
|
---|
509 |
|
---|
510 | my %args = @_;
|
---|
511 |
|
---|
512 | # Not absolutely true but WTF use is an MX record for a reverse zone?
|
---|
513 | return ('FAIL', 'Reverse zones cannot contain MX records') if $args{revrec} eq 'y';
|
---|
514 |
|
---|
515 | return ('FAIL', "Distance is required for MX records") unless defined(${$args{dist}});
|
---|
516 | ${$args{dist}} =~ s/\s*//g;
|
---|
517 | return ('FAIL',"Distance is required, and must be numeric") unless ${$args{dist}} =~ /^\d+$/;
|
---|
518 |
|
---|
519 | ${$args{fields}} = "distance,";
|
---|
520 | push @{$args{vallist}}, ${$args{dist}};
|
---|
521 |
|
---|
522 | # Coerce all hostnames to end in ".DOMAIN" for group/default records,
|
---|
523 | # or the intended parent domain for live records.
|
---|
524 | my $pname = ($args{defrec} eq 'y' ? 'DOMAIN' : domainName($dbh,$args{id}));
|
---|
525 | ${$args{host}} =~ s/\.*$/\.$pname/ if ${$args{host}} !~ /$pname$/;
|
---|
526 |
|
---|
527 | # hmm.. this might work. except possibly for something pointing to "deadbeef.ca". <g>
|
---|
528 | # if ($type == $reverse_typemap{NS} || $type == $reverse_typemap{MX} || $type == $reverse_typemap{SRV}) {
|
---|
529 | # if ($val =~ /^\s*[\da-f:.]+\s*$/) {
|
---|
530 | # return ('FAIL',"$val is not a valid IP address") if !$addr;
|
---|
531 | # }
|
---|
532 | # }
|
---|
533 |
|
---|
534 | return ('OK','OK');
|
---|
535 | } # done MX record
|
---|
536 |
|
---|
537 | # TXT record
|
---|
538 | sub _validate_16 {
|
---|
539 | # Could arguably put a WARN return here on very long (>512) records
|
---|
540 | return ('OK','OK');
|
---|
541 | } # done TXT record
|
---|
542 |
|
---|
543 | # RP record
|
---|
544 | sub _validate_17 {
|
---|
545 | # Probably have to validate these some day
|
---|
546 | return ('OK','OK');
|
---|
547 | } # done RP record
|
---|
548 |
|
---|
549 | # AAAA record
|
---|
550 | sub _validate_28 {
|
---|
551 | my $dbh = shift;
|
---|
552 |
|
---|
553 | my %args = @_;
|
---|
554 |
|
---|
555 | return ('FAIL', 'Reverse zones cannot contain AAAA records') if $args{revrec} eq 'y';
|
---|
556 |
|
---|
557 | # Coerce all hostnames to end in ".DOMAIN" for group/default records,
|
---|
558 | # or the intended parent domain for live records.
|
---|
559 | my $pname = ($args{defrec} eq 'y' ? 'DOMAIN' : domainName($dbh,$args{id}));
|
---|
560 | ${$args{host}} =~ s/\.*$/\.$pname/ if ${$args{host}} !~ /$pname$/;
|
---|
561 |
|
---|
562 | # Check IP is well-formed, and that it's a v6 address
|
---|
563 | return ('FAIL',"$typemap{${$args{rectype}}} record must be a valid IPv6 address")
|
---|
564 | unless $args{addr} && $args{addr}->{isv6};
|
---|
565 | # coerce IP/value to normalized form for storage
|
---|
566 | ${$args{val}} = $args{addr}->addr;
|
---|
567 |
|
---|
568 | return ('OK','OK');
|
---|
569 | } # done AAAA record
|
---|
570 |
|
---|
571 | # SRV record
|
---|
572 | sub _validate_33 {
|
---|
573 | my $dbh = shift;
|
---|
574 |
|
---|
575 | my %args = @_;
|
---|
576 |
|
---|
577 | # Not absolutely true but WTF use is an SRV record for a reverse zone?
|
---|
578 | return ('FAIL', 'Reverse zones cannot contain SRV records') if $args{revrec} eq 'y';
|
---|
579 |
|
---|
580 | return ('FAIL', "Distance is required for SRV records") unless defined(${$args{dist}});
|
---|
581 | ${$args{dist}} =~ s/\s*//g;
|
---|
582 | return ('FAIL',"Distance is required, and must be numeric") unless ${$args{dist}} =~ /^\d+$/;
|
---|
583 |
|
---|
584 | return ('FAIL',"SRV records must begin with _service._protocol [${$args{host}}]")
|
---|
585 | unless ${$args{host}} =~ /^_[A-Za-z]+\._[A-Za-z]+\.[a-zA-Z0-9-]+/;
|
---|
586 | return ('FAIL',"Port and weight are required for SRV records")
|
---|
587 | unless defined(${$args{weight}}) && defined(${$args{port}});
|
---|
588 | ${$args{weight}} =~ s/\s*//g;
|
---|
589 | ${$args{port}} =~ s/\s*//g;
|
---|
590 |
|
---|
591 | return ('FAIL',"Port and weight are required, and must be numeric")
|
---|
592 | unless ${$args{weight}} =~ /^\d+$/ && ${$args{port}} =~ /^\d+$/;
|
---|
593 |
|
---|
594 | ${$args{fields}} = "distance,weight,port,";
|
---|
595 | push @{$args{vallist}}, (${$args{dist}}, ${$args{weight}}, ${$args{port}});
|
---|
596 |
|
---|
597 | # Coerce all hostnames to end in ".DOMAIN" for group/default records,
|
---|
598 | # or the intended parent domain for live records.
|
---|
599 | my $pname = ($args{defrec} eq 'y' ? 'DOMAIN' : domainName($dbh,$args{id}));
|
---|
600 | ${$args{host}} =~ s/\.*$/\.$pname/ if ${$args{host}} !~ /$pname$/;
|
---|
601 |
|
---|
602 | return ('OK','OK');
|
---|
603 | } # done SRV record
|
---|
604 |
|
---|
605 | # Now the custom types
|
---|
606 |
|
---|
607 | # A+PTR record. With a very little bit of magic we can also use this sub to validate AAAA+PTR. Whee!
|
---|
608 | sub _validate_65280 {
|
---|
609 | my $dbh = shift;
|
---|
610 |
|
---|
611 | my %args = @_;
|
---|
612 |
|
---|
613 | my $code = 'OK';
|
---|
614 | my $msg = 'OK';
|
---|
615 |
|
---|
616 | if ($args{defrec} eq 'n') {
|
---|
617 | # live record; revrec determines whether we validate the PTR or A component first.
|
---|
618 |
|
---|
619 | if ($args{revrec} eq 'y') {
|
---|
620 | ($code,$msg) = _validate_12($dbh, %args);
|
---|
621 | return ($code,$msg) if $code eq 'FAIL';
|
---|
622 |
|
---|
623 | # Check if the reqested domain exists. If not, coerce the type down to PTR and warn.
|
---|
624 | if (!(${$args{domid}} = _hostparent($dbh, ${$args{host}}))) {
|
---|
625 | my $addmsg = "Record ".($args{update} ? 'updated' : 'added').
|
---|
626 | " as PTR instead of $typemap{${$args{rectype}}}; domain not found for ${$args{host}}";
|
---|
627 | $msg .= "\n$addmsg" if $code eq 'WARN';
|
---|
628 | $msg = $addmsg if $code eq 'OK';
|
---|
629 | ${$args{rectype}} = $reverse_typemap{PTR};
|
---|
630 | return ('WARN', $msg);
|
---|
631 | }
|
---|
632 |
|
---|
633 | # Add domain ID to field list and values
|
---|
634 | ${$args{fields}} .= "domain_id,";
|
---|
635 | push @{$args{vallist}}, ${$args{domid}};
|
---|
636 |
|
---|
637 | } else {
|
---|
638 | ($code,$msg) = _validate_1($dbh, %args) if ${$args{rectype}} == 65280;
|
---|
639 | ($code,$msg) = _validate_28($dbh, %args) if ${$args{rectype}} == 65281;
|
---|
640 | return ($code,$msg) if $code eq 'FAIL';
|
---|
641 |
|
---|
642 | # Check if the requested reverse zone exists - note, an IP fragment won't
|
---|
643 | # work here since we don't *know* which parent to put it in.
|
---|
644 | # ${$args{val}} has been validated as a valid IP by now, in one of the above calls.
|
---|
645 | my ($revid) = $dbh->selectrow_array("SELECT rdns_id FROM revzones WHERE revnet >> ?".
|
---|
646 | " ORDER BY masklen(revnet) DESC", undef, (${$args{val}}));
|
---|
647 | if (!$revid) {
|
---|
648 | $msg = "Record ".($args{update} ? 'updated' : 'added')." as ".(${$args{rectype}} == 65280 ? 'A' : 'AAAA').
|
---|
649 | " instead of $typemap{${$args{rectype}}}; reverse zone not found for ${$args{val}}";
|
---|
650 | ${$args{rectype}} = (${$args{rectype}} == 65280 ? $reverse_typemap{A} : $reverse_typemap{AAAA});
|
---|
651 | return ('WARN', $msg);
|
---|
652 | }
|
---|
653 |
|
---|
654 | # Check for duplicate PTRs. Note we don't have to play games with $code and $msg, because
|
---|
655 | # by definition there can't be duplicate PTRs if the reverse zone isn't managed here.
|
---|
656 | if ($args{update}) {
|
---|
657 | # Record update. There should usually be an existing PTR (the record being updated)
|
---|
658 | my @ptrs = @{ $dbh->selectcol_arrayref("SELECT record_id FROM "._rectable($args{defrec},$args{revrec}).
|
---|
659 | " WHERE val = ?", undef, (${$args{val}})) };
|
---|
660 | if (@ptrs && (!grep /^$args{update}$/, @ptrs)) {
|
---|
661 | $msg = "PTR record for ${$args{val}} already exists; adding another will probably not do what you want";
|
---|
662 | $code = 'WARN';
|
---|
663 | }
|
---|
664 | } else {
|
---|
665 | # New record. Always warn if a PTR exists
|
---|
666 | my ($ptrcount) = $dbh->selectrow_array("SELECT count(*) FROM "._rectable($args{defrec},$args{revrec}).
|
---|
667 | " WHERE val = ?", undef, (${$args{val}}));
|
---|
668 | $msg = "PTR record for ${$args{val}} already exists; adding another will probably not do what you want"
|
---|
669 | if $ptrcount;
|
---|
670 | $code = 'WARN' if $ptrcount;
|
---|
671 | }
|
---|
672 |
|
---|
673 | # my ($ptrcount) = $dbh->selectrow_array("SELECT count(*) FROM "._rectable($args{defrec},$args{revrec}).
|
---|
674 | # " WHERE val = ?", undef, ${$args{val}});
|
---|
675 | # if ($ptrcount) {
|
---|
676 | # my $curid = $dbh->selectrow_array("SELECT record_id FROM "._rectable($args{defrec},$args{revrec}).
|
---|
677 | # " WHERE val = ?
|
---|
678 | # $msg = "PTR record for ${$args{val}} already exists; adding another will probably not do what you want";
|
---|
679 | # $code = 'WARN';
|
---|
680 | # }
|
---|
681 |
|
---|
682 | ${$args{fields}} .= "rdns_id,";
|
---|
683 | push @{$args{vallist}}, $revid;
|
---|
684 | }
|
---|
685 |
|
---|
686 | } else { # defrec eq 'y'
|
---|
687 | if ($args{revrec} eq 'y') {
|
---|
688 | ($code,$msg) = _validate_12($dbh, %args);
|
---|
689 | return ($code,$msg) if $code eq 'FAIL';
|
---|
690 | if (${$args{rectype}} == 65280) {
|
---|
691 | return ('FAIL',"A+PTR record must be a valid IPv4 address or fragment")
|
---|
692 | if ${$args{val}} =~ /:/;
|
---|
693 | ${$args{val}} =~ s/^ZONE,/ZONE./; # Clean up after uncertain IP-fragment-type from _validate_12
|
---|
694 | } elsif (${$args{rectype}} == 65281) {
|
---|
695 | return ('FAIL',"AAAA+PTR record must be a valid IPv6 address or fragment")
|
---|
696 | if ${$args{val}} =~ /\./;
|
---|
697 | ${$args{val}} =~ s/^ZONE,/ZONE::/; # Clean up after uncertain IP-fragment-type from _validate_12
|
---|
698 | }
|
---|
699 | } else {
|
---|
700 | # This is easy. I also can't see a real use-case for A/AAAA+PTR in *all* forward
|
---|
701 | # domains, since you wouldn't be able to substitute both domain and reverse zone
|
---|
702 | # sanely, and you'd end up with guaranteed over-replicated PTR records that would
|
---|
703 | # confuse the hell out of pretty much anything that uses them.
|
---|
704 | ##fixme: make this a config flag?
|
---|
705 | return ('FAIL', "$typemap{${$args{rectype}}} records not allowed in default domains");
|
---|
706 | }
|
---|
707 | }
|
---|
708 |
|
---|
709 | return ($code, $msg);
|
---|
710 | } # done A+PTR record
|
---|
711 |
|
---|
712 | # AAAA+PTR record
|
---|
713 | # A+PTR above has been magicked to handle AAAA+PTR as well.
|
---|
714 | sub _validate_65281 {
|
---|
715 | return _validate_65280(@_);
|
---|
716 | } # done AAAA+PTR record
|
---|
717 |
|
---|
718 | # PTR template record
|
---|
719 | sub _validate_65282 {
|
---|
720 | return ('OK','OK');
|
---|
721 | } # done PTR template record
|
---|
722 |
|
---|
723 | # A+PTR template record
|
---|
724 | sub _validate_65283 {
|
---|
725 | return ('OK','OK');
|
---|
726 | } # done AAAA+PTR template record
|
---|
727 |
|
---|
728 | # AAAA+PTR template record
|
---|
729 | sub _validate_65284 {
|
---|
730 | return ('OK','OK');
|
---|
731 | } # done AAAA+PTR template record
|
---|
732 |
|
---|
733 |
|
---|
734 | ##
|
---|
735 | ## Record data substitution subs
|
---|
736 | ##
|
---|
737 |
|
---|
738 | # Replace ZONE in hostname, or create (most of) the actual proper zone name
|
---|
739 | sub _ZONE {
|
---|
740 | my $zone = shift;
|
---|
741 | my $string = shift;
|
---|
742 | my $fr = shift || 'f'; # flag for forward/reverse order? nb: ignored for IP
|
---|
743 | my $sep = shift || '-'; # Separator character - unlikely we'll ever need more than . or -
|
---|
744 |
|
---|
745 | my $prefix;
|
---|
746 |
|
---|
747 | $string =~ s/,/./ if !$zone->{isv6};
|
---|
748 | $string =~ s/,/::/ if $zone->{isv6};
|
---|
749 |
|
---|
750 | # Subbing ZONE in the host. We need to properly ID the netblock range
|
---|
751 | # The subbed text should have "network IP with trailing zeros stripped" for
|
---|
752 | # blocks lined up on octet (for v4) or hex-quad (for v6) boundaries
|
---|
753 | # For blocks that do NOT line up on these boundaries, we take the most
|
---|
754 | # significant octet or 16-bit chunk of the "broadcast" IP and append it
|
---|
755 | # after a double-dash
|
---|
756 | # ie:
|
---|
757 | # 8.0.0.0/6 -> 8.0.0.0 -> 11.255.255.255; sub should be 8--11
|
---|
758 | # 10.0.0.0/12 -> 10.0.0.0 -> 10.0.0.0 -> 10.15.255.255; sub should be 10-0--15
|
---|
759 | # 192.168.4.0/22 -> 192.168.4.0 -> 192.168.7.255; sub should be 192-168-4--7
|
---|
760 | # 192.168.0.8/29 -> 192.168.0.8 -> 192.168.0.15; sub should be 192-168-0-8--15
|
---|
761 | # Similar for v6
|
---|
762 |
|
---|
763 | if (!$zone->{isv6}) { # IPv4
|
---|
764 |
|
---|
765 | $prefix = $zone->network->addr; # Just In Case someone managed to slip in
|
---|
766 | # a funky subnet that had host bits set.
|
---|
767 | my $bc = $zone->broadcast->addr;
|
---|
768 |
|
---|
769 | if ($zone->masklen > 24) {
|
---|
770 | $bc =~ s/^\d+\.\d+\.\d+\.//;
|
---|
771 | } elsif ($zone->masklen > 16) {
|
---|
772 | $prefix =~ s/\.0$//;
|
---|
773 | $bc =~ s/^\d+\.\d+\.//;
|
---|
774 | } elsif ($zone->masklen > 8) {
|
---|
775 | $bc =~ s/^\d+\.//;
|
---|
776 | $prefix =~ s/\.0\.0$//;
|
---|
777 | } else {
|
---|
778 | $prefix =~ s/\.0\.0\.0$//;
|
---|
779 | }
|
---|
780 | if ($zone->masklen % 8) {
|
---|
781 | $bc =~ s/(\.255)+$//;
|
---|
782 | $prefix .= "--$bc"; #"--".zone->masklen; # use range or mask length?
|
---|
783 | }
|
---|
784 | if ($fr eq 'f') {
|
---|
785 | $prefix =~ s/\.+/$sep/g;
|
---|
786 | } else {
|
---|
787 | $prefix = join($sep, reverse(split(/\./, $prefix)));
|
---|
788 | }
|
---|
789 |
|
---|
790 | } else { # IPv6
|
---|
791 |
|
---|
792 | if ($fr eq 'f') {
|
---|
793 |
|
---|
794 | $prefix = $zone->network->addr; # Just In Case someone managed to slip in
|
---|
795 | # a funky subnet that had host bits set.
|
---|
796 | my $bc = $zone->broadcast->addr;
|
---|
797 | if (($zone->masklen % 16) != 0) {
|
---|
798 | # Strip trailing :0 off $prefix, and :ffff off the broadcast IP
|
---|
799 | for (my $i=0; $i<(7-int($zone->masklen / 16)); $i++) {
|
---|
800 | $prefix =~ s/:0$//;
|
---|
801 | $bc =~ s/:ffff$//;
|
---|
802 | }
|
---|
803 | # Strip the leading 16-bit chunks off the front of the broadcast IP
|
---|
804 | $bc =~ s/^([a-f0-9]+:)+//;
|
---|
805 | # Append the remaining 16-bit chunk to the prefix after "--"
|
---|
806 | $prefix .= "--$bc";
|
---|
807 | } else {
|
---|
808 | # Strip off :0 from the end until we reach the netblock length.
|
---|
809 | for (my $i=0; $i<(8-$zone->masklen / 16); $i++) {
|
---|
810 | $prefix =~ s/:0$//;
|
---|
811 | }
|
---|
812 | }
|
---|
813 | # Actually deal with the separator
|
---|
814 | $prefix =~ s/:/$sep/g;
|
---|
815 |
|
---|
816 | } else { # $fr eq 'f'
|
---|
817 |
|
---|
818 | $prefix = $zone->network->full; # Just In Case someone managed to slip in
|
---|
819 | # a funky subnet that had host bits set.
|
---|
820 | my $bc = $zone->broadcast->full;
|
---|
821 | $prefix =~ s/://g; # clean these out since they're not spaced right for this case
|
---|
822 | $bc =~ s/://g;
|
---|
823 | # Strip trailing 0 off $prefix, and f off the broadcast IP, to match the mask length
|
---|
824 | for (my $i=0; $i<(31-int($zone->masklen / 4)); $i++) {
|
---|
825 | $prefix =~ s/0$//;
|
---|
826 | $bc =~ s/f$//;
|
---|
827 | }
|
---|
828 | # Split and reverse the order of the nibbles in the network/broadcast IPs
|
---|
829 | my @nbits = reverse split //, $prefix;
|
---|
830 | my @bbits = reverse split //, $bc;
|
---|
831 | # Handle the sub-nibble case. Eww. I feel dirty supporting this...
|
---|
832 | $nbits[0] = "$nbits[0]-$bbits[0]" if ($zone->masklen % 4) != 0;
|
---|
833 | # Glue it back together
|
---|
834 | $prefix = join($sep, @nbits);
|
---|
835 |
|
---|
836 | } # $fr ne 'f'
|
---|
837 |
|
---|
838 | } # $zone->{isv6}
|
---|
839 |
|
---|
840 | # Do the substitution, finally
|
---|
841 | $string =~ s/ZONE/$prefix/;
|
---|
842 | $string =~ s/--/-/ if $sep ne '-'; # - as separator needs extra help for sub-octet v4 netblocks
|
---|
843 | return $string;
|
---|
844 | } # done _ZONE()
|
---|
845 |
|
---|
846 | # Not quite a substitution sub, but placed here as it's basically the inverse of above;
|
---|
847 | # given the .arpa zone name, return the CIDR netblock the zone is for.
|
---|
848 | # Supports v4 non-octet/non-classful netblocks as per the method outlined in the Grasshopper Book (2nd Ed p217-218)
|
---|
849 | # Does NOT support non-quad v6 netblocks via the same scheme; it shouldn't ever be necessary.
|
---|
850 | # Takes a nominal .arpa zone name, returns a success code and NetAddr::IP, or a fail code and message
|
---|
851 | sub _zone2cidr {
|
---|
852 | my $zone = shift;
|
---|
853 |
|
---|
854 | my $cidr;
|
---|
855 | my $tmpcidr;
|
---|
856 | my $warnmsg = '';
|
---|
857 |
|
---|
858 | if ($zone =~ /\.in-addr\.arpa\.?$/) {
|
---|
859 | # v4 revzone, formal zone name type
|
---|
860 | my $tmpzone = $zone;
|
---|
861 | $tmpzone =~ s/\.in-addr\.arpa\.?//;
|
---|
862 | return ('FAIL', "Non-numerics in apparent IPv4 reverse zone name") if $tmpzone !~ /^(?:\d+-)?[\d\.]+$/;
|
---|
863 |
|
---|
864 | # Snag the octet pieces
|
---|
865 | my @octs = split /\./, $tmpzone;
|
---|
866 |
|
---|
867 | # Map result of a range manipulation to a mask length change. Cheaper than finding the 2-root of $octets[0]+1.
|
---|
868 | # Note we will not support /31 blocks, mostly due to issues telling "24-31" -> .24/29 apart from
|
---|
869 | # "24-31" -> .24/31", with a litte bit of "/31 is icky".
|
---|
870 | my %maskmap = ( 3 => 2, 7 => 3, 15 => 4, 31 => 5, 63 => 6, 127 => 7,
|
---|
871 | 30 => 2, 29 => 3, 28 => 4, 27 => 5, 26 => 6, 25 => 7
|
---|
872 | );
|
---|
873 |
|
---|
874 | # Handle "range" blocks, eg, 80-83.168.192.in-addr.arpa (192.168.80.0/22)
|
---|
875 | # Need to take the size of the range to offset the basic octet-based mask length,
|
---|
876 | # and make sure the first number in the range gets used as the network address for the block
|
---|
877 | # Alternate form: The second number is actually the real netmask, not the end of the range.
|
---|
878 | my $masklen = 0;
|
---|
879 | if ($octs[0] =~ /^((\d+)-(\d+))$/) { # take the range...
|
---|
880 | if (24 < $3 && $3 < 31) {
|
---|
881 | # we have a real netmask
|
---|
882 | $masklen = -$maskmap{$3};
|
---|
883 | } else {
|
---|
884 | # we have a range. NB: only real CIDR ranges are supported
|
---|
885 | $masklen -= $maskmap{-(eval $1)}; # find the mask base...
|
---|
886 | }
|
---|
887 | $octs[0] = $2; # set the base octet of the range...
|
---|
888 | }
|
---|
889 | @octs = reverse @octs; # We can reverse the octet pieces now that we've extracted and munged any ranges
|
---|
890 |
|
---|
891 | # arguably we should only allow sub-octet range/mask in-addr.arpa
|
---|
892 | # specifications in the least significant octet, but the code is
|
---|
893 | # simpler if we deal with sub-octet delegations at any level.
|
---|
894 |
|
---|
895 | # Now we find the "true" mask with the aid of the "base" calculated above
|
---|
896 | if ($#octs == 0) {
|
---|
897 | $masklen += 8;
|
---|
898 | $tmpcidr = "$octs[0].0.0.0/$masklen"; # really hope we don't see one of these very often.
|
---|
899 | } elsif ($#octs == 1) {
|
---|
900 | $masklen += 16;
|
---|
901 | $tmpcidr = "$octs[0].$octs[1].0.0/$masklen";
|
---|
902 | } elsif ($#octs == 2) {
|
---|
903 | $masklen += 24;
|
---|
904 | $tmpcidr = "$octs[0].$octs[1].$octs[2].0/$masklen";
|
---|
905 | } else {
|
---|
906 | $masklen += 32;
|
---|
907 | $tmpcidr = "$octs[0].$octs[1].$octs[2].$octs[3]/$masklen";
|
---|
908 | }
|
---|
909 |
|
---|
910 | } elsif ($zone =~ /\.ip6\.arpa$/) {
|
---|
911 | # v6 revzone, formal zone name type
|
---|
912 | my $tmpzone = $zone;
|
---|
913 | $tmpzone =~ s/\.ip6\.arpa\.?//;
|
---|
914 | ##fixme: if-n-when we decide we can support sub-nibble v6 zone names, we'll need to change this segment
|
---|
915 | return ('FAIL', "Non-hexadecimals in apparent IPv6 reverse zone name") if $tmpzone !~ /^[a-fA-F\d\.]+$/;
|
---|
916 | my @quads = reverse(split(/\./, $tmpzone));
|
---|
917 | $warnmsg .= "Apparent sub-/64 IPv6 reverse zone\n" if $#quads > 15;
|
---|
918 | my $nc;
|
---|
919 | foreach (@quads) {
|
---|
920 | $tmpcidr .= $_;
|
---|
921 | $tmpcidr .= ":" if ++$nc % 4 == 0;
|
---|
922 | }
|
---|
923 | my $nq = 1 if $nc % 4 != 0;
|
---|
924 | my $mask = $nc * 4; # need to do this here because we probably increment it below
|
---|
925 | while ($nc++ % 4 != 0) {
|
---|
926 | $tmpcidr .= "0";
|
---|
927 | }
|
---|
928 | $tmpcidr .= ($nq ? '::' : ':')."/$mask";
|
---|
929 | }
|
---|
930 |
|
---|
931 | # Just to be sure, use NetAddr::IP to validate. Saves a lot of nasty regex watching for valid octet values.
|
---|
932 | return ('FAIL', "Invalid zone $zone (apparent netblock $tmpcidr)")
|
---|
933 | unless $cidr = NetAddr::IP->new($tmpcidr);
|
---|
934 |
|
---|
935 | if ($warnmsg) {
|
---|
936 | $errstr = $warnmsg;
|
---|
937 | return ('WARN', $cidr);
|
---|
938 | }
|
---|
939 | return ('OK', $cidr);
|
---|
940 | } # done _zone2cidr()
|
---|
941 |
|
---|
942 |
|
---|
943 | ##
|
---|
944 | ## Initialization and cleanup subs
|
---|
945 | ##
|
---|
946 |
|
---|
947 |
|
---|
948 | ## DNSDB::loadConfig()
|
---|
949 | # Load the minimum required initial state (DB connect info) from a config file
|
---|
950 | # Load misc other bits while we're at it.
|
---|
951 | # Takes an optional basename and config path to look for
|
---|
952 | # Populates the %config and %def hashes
|
---|
953 | sub loadConfig {
|
---|
954 | my $basename = shift || ''; # this will work OK
|
---|
955 | ##fixme $basename isn't doing what I think I thought I was trying to do.
|
---|
956 |
|
---|
957 | my $deferr = ''; # place to put error from default config file in case we can't find either one
|
---|
958 |
|
---|
959 | my $configroot = "/etc/dnsdb"; ##CFG_LEAF##
|
---|
960 | $configroot = '' if $basename =~ m|^/|;
|
---|
961 | $basename .= ".conf" if $basename !~ /\.conf$/;
|
---|
962 | my $defconfig = "$configroot/dnsdb.conf";
|
---|
963 | my $siteconfig = "$configroot/$basename";
|
---|
964 |
|
---|
965 | # System defaults
|
---|
966 | __cfgload("$defconfig") or $deferr = $errstr;
|
---|
967 |
|
---|
968 | # Per-site-ish settings.
|
---|
969 | if ($basename ne '.conf') {
|
---|
970 | unless (__cfgload("$siteconfig")) {
|
---|
971 | $errstr = ($deferr ? "Error opening default config file $defconfig: $deferr\n" : '').
|
---|
972 | "Error opening site config file $siteconfig";
|
---|
973 | return;
|
---|
974 | }
|
---|
975 | }
|
---|
976 |
|
---|
977 | # Munge log_failures.
|
---|
978 | if ($config{log_failures} ne '1' && $config{log_failures} ne '0') {
|
---|
979 | # true/false, on/off, yes/no all valid.
|
---|
980 | if ($config{log_failures} =~ /^(?:true|false|on|off|yes|no)$/) {
|
---|
981 | if ($config{log_failures} =~ /(?:true|on|yes)/) {
|
---|
982 | $config{log_failures} = 1;
|
---|
983 | } else {
|
---|
984 | $config{log_failures} = 0;
|
---|
985 | }
|
---|
986 | } else {
|
---|
987 | $errstr = "Bad log_failures setting $config{log_failures}";
|
---|
988 | $config{log_failures} = 1;
|
---|
989 | # Bad setting shouldn't be fatal.
|
---|
990 | # return 2;
|
---|
991 | }
|
---|
992 | }
|
---|
993 |
|
---|
994 | # All good, clear the error and go home.
|
---|
995 | $errstr = '';
|
---|
996 | return 1;
|
---|
997 | } # end loadConfig()
|
---|
998 |
|
---|
999 |
|
---|
1000 | ## DNSDB::__cfgload()
|
---|
1001 | # Private sub to parse a config file and load it into %config
|
---|
1002 | # Takes a file handle on an open config file
|
---|
1003 | sub __cfgload {
|
---|
1004 | $errstr = '';
|
---|
1005 | my $cfgfile = shift;
|
---|
1006 |
|
---|
1007 | if (open CFG, "<$cfgfile") {
|
---|
1008 | while (<CFG>) {
|
---|
1009 | chomp;
|
---|
1010 | s/^\s*//;
|
---|
1011 | next if /^#/;
|
---|
1012 | next if /^$/;
|
---|
1013 | # hmm. more complex bits in this file might require [heading] headers, maybe?
|
---|
1014 | # $mode = $1 if /^\[(a-z)+]/;
|
---|
1015 | # DB connect info
|
---|
1016 | $config{dbname} = $1 if /^dbname\s*=\s*([a-z0-9_.-]+)/i;
|
---|
1017 | $config{dbuser} = $1 if /^dbuser\s*=\s*([a-z0-9_.-]+)/i;
|
---|
1018 | $config{dbpass} = $1 if /^dbpass\s*=\s*([a-z0-9_.-]+)/i;
|
---|
1019 | $config{dbhost} = $1 if /^dbhost\s*=\s*([a-z0-9_.-]+)/i;
|
---|
1020 | # SOA defaults
|
---|
1021 | $def{contact} = $1 if /^contact\s*=\s*([a-z0-9_.-]+)/i;
|
---|
1022 | $def{prins} = $1 if /^prins\s*=\s*([a-z0-9_.-]+)/i;
|
---|
1023 | $def{soattl} = $1 if /^soattl\s*=\s*(\d+)/i;
|
---|
1024 | $def{refresh} = $1 if /^refresh\s*=\s*(\d+)/i;
|
---|
1025 | $def{retry} = $1 if /^retry\s*=\s*(\d+)/i;
|
---|
1026 | $def{expire} = $1 if /^expire\s*=\s*(\d+)/i;
|
---|
1027 | $def{minttl} = $1 if /^minttl\s*=\s*(\d+)/i;
|
---|
1028 | $def{ttl} = $1 if /^ttl\s*=\s*(\d+)/i;
|
---|
1029 | # Mail settings
|
---|
1030 | $config{mailhost} = $1 if /^mailhost\s*=\s*([a-z0-9_.-]+)/i;
|
---|
1031 | $config{mailnotify} = $1 if /^mailnotify\s*=\s*([a-z0-9_.\@-]+)/i;
|
---|
1032 | $config{mailsender} = $1 if /^mailsender\s*=\s*([a-z0-9_.\@-]+)/i;
|
---|
1033 | $config{mailname} = $1 if /^mailname\s*=\s*([a-z0-9\s_.-]+)/i;
|
---|
1034 | $config{orgname} = $1 if /^orgname\s*=\s*([a-z0-9\s_.,'-]+)/i;
|
---|
1035 | $config{domain} = $1 if /^domain\s*=\s*([a-z0-9_.-]+)/i;
|
---|
1036 | # session - note this is fed directly to CGI::Session
|
---|
1037 | $config{timeout} = $1 if /^[tT][iI][mM][eE][oO][uU][tT]\s*=\s*(\d+[smhdwMy]?)/;
|
---|
1038 | $config{sessiondir} = $1 if m{^sessiondir\s*=\s*([a-z0-9/_.-]+)}i;
|
---|
1039 | # misc
|
---|
1040 | $config{log_failures} = $1 if /^log_failures\s*=\s*([a-z01]+)/i;
|
---|
1041 | $config{perpage} = $1 if /^perpage\s*=\s*(\d+)/i;
|
---|
1042 | }
|
---|
1043 | close CFG;
|
---|
1044 | } else {
|
---|
1045 | $errstr = $!;
|
---|
1046 | return;
|
---|
1047 | }
|
---|
1048 | return 1;
|
---|
1049 | } # end __cfgload()
|
---|
1050 |
|
---|
1051 |
|
---|
1052 | ## DNSDB::connectDB()
|
---|
1053 | # Creates connection to DNS database.
|
---|
1054 | # Requires the database name, username, and password.
|
---|
1055 | # Returns a handle to the db.
|
---|
1056 | # Set up for a PostgreSQL db; could be any transactional DBMS with the
|
---|
1057 | # right changes.
|
---|
1058 | sub connectDB {
|
---|
1059 | $errstr = '';
|
---|
1060 | my $dbname = shift;
|
---|
1061 | my $user = shift;
|
---|
1062 | my $pass = shift;
|
---|
1063 | my $dbh;
|
---|
1064 | my $DSN = "DBI:Pg:dbname=$dbname";
|
---|
1065 |
|
---|
1066 | my $host = shift;
|
---|
1067 | $DSN .= ";host=$host" if $host;
|
---|
1068 |
|
---|
1069 | # Note that we want to autocommit by default, and we will turn it off locally as necessary.
|
---|
1070 | # We may not want to print gobbledygook errors; YMMV. Have to ponder that further.
|
---|
1071 | $dbh = DBI->connect($DSN, $user, $pass, {
|
---|
1072 | AutoCommit => 1,
|
---|
1073 | PrintError => 0
|
---|
1074 | })
|
---|
1075 | or return (undef, $DBI::errstr) if(!$dbh);
|
---|
1076 |
|
---|
1077 | ##fixme: initialize the DB if we can't find the table (since, by definition, there's
|
---|
1078 | # nothing there if we can't select from it...)
|
---|
1079 | my $tblsth = $dbh->prepare("SELECT count(*) FROM pg_catalog.pg_class WHERE relkind='r' AND relname=?");
|
---|
1080 | my ($tblcount) = $dbh->selectrow_array($tblsth, undef, ('misc'));
|
---|
1081 | return (undef,$DBI::errstr) if $dbh->err;
|
---|
1082 |
|
---|
1083 | #if ($tblcount == 0) {
|
---|
1084 | # # create tables one at a time, checking for each.
|
---|
1085 | # return (undef, "check table misc missing");
|
---|
1086 | #}
|
---|
1087 |
|
---|
1088 |
|
---|
1089 | # Return here if we can't select.
|
---|
1090 | # This should retrieve the dbversion key.
|
---|
1091 | my $sth = $dbh->prepare("SELECT key,value FROM misc WHERE misc_id=1");
|
---|
1092 | $sth->execute();
|
---|
1093 | return (undef,$DBI::errstr) if ($sth->err);
|
---|
1094 |
|
---|
1095 | ##fixme: do stuff to the DB on version mismatch
|
---|
1096 | # x.y series should upgrade on $DNSDB::VERSION > misc(key=>version)
|
---|
1097 | # DB should be downward-compatible; column defaults should give sane (if possibly
|
---|
1098 | # useless-and-needs-help) values in columns an older software stack doesn't know about.
|
---|
1099 |
|
---|
1100 | # See if the select returned anything (or null data). This should
|
---|
1101 | # succeed if the select executed, but...
|
---|
1102 | $sth->fetchrow();
|
---|
1103 | return (undef,$DBI::errstr) if ($sth->err);
|
---|
1104 |
|
---|
1105 | $sth->finish;
|
---|
1106 |
|
---|
1107 | # If we get here, we should be OK.
|
---|
1108 | return ($dbh,"DB connection OK");
|
---|
1109 | } # end connectDB
|
---|
1110 |
|
---|
1111 |
|
---|
1112 | ## DNSDB::finish()
|
---|
1113 | # Cleans up after database handles and so on.
|
---|
1114 | # Requires a database handle
|
---|
1115 | sub finish {
|
---|
1116 | my $dbh = $_[0];
|
---|
1117 | $dbh->disconnect;
|
---|
1118 | } # end finish
|
---|
1119 |
|
---|
1120 |
|
---|
1121 | ## DNSDB::initGlobals()
|
---|
1122 | # Initialize global variables
|
---|
1123 | # NB: this does NOT include web-specific session variables!
|
---|
1124 | # Requires a database handle
|
---|
1125 | sub initGlobals {
|
---|
1126 | my $dbh = shift;
|
---|
1127 |
|
---|
1128 | # load record types from database
|
---|
1129 | my $sth = $dbh->prepare("SELECT val,name,stdflag FROM rectypes");
|
---|
1130 | $sth->execute;
|
---|
1131 | while (my ($recval,$recname,$stdflag) = $sth->fetchrow_array()) {
|
---|
1132 | $typemap{$recval} = $recname;
|
---|
1133 | $reverse_typemap{$recname} = $recval;
|
---|
1134 | # now we fill the record validation function hash
|
---|
1135 | if ($stdflag < 5) {
|
---|
1136 | my $fn = "_validate_$recval";
|
---|
1137 | $validators{$recval} = \&$fn;
|
---|
1138 | } else {
|
---|
1139 | my $fn = "sub { return ('FAIL','Type $recval ($recname) not supported'); }";
|
---|
1140 | $validators{$recval} = eval $fn;
|
---|
1141 | }
|
---|
1142 | }
|
---|
1143 | } # end initGlobals
|
---|
1144 |
|
---|
1145 |
|
---|
1146 | ## DNSDB::login()
|
---|
1147 | # Takes a database handle, username and password
|
---|
1148 | # Returns a userdata hash (UID, GID, username, fullname parts) if username exists
|
---|
1149 | # and password matches the one on file
|
---|
1150 | # Returns undef otherwise
|
---|
1151 | sub login {
|
---|
1152 | my $dbh = shift;
|
---|
1153 | my $user = shift;
|
---|
1154 | my $pass = shift;
|
---|
1155 |
|
---|
1156 | my $userinfo = $dbh->selectrow_hashref("SELECT user_id,group_id,password,firstname,lastname FROM users WHERE username=?",
|
---|
1157 | undef, ($user) );
|
---|
1158 | return if !$userinfo;
|
---|
1159 |
|
---|
1160 | if ($userinfo->{password} =~ m|^\$1\$([A-Za-z0-9/.]+)\$|) {
|
---|
1161 | # native passwords (crypt-md5)
|
---|
1162 | return if $userinfo->{password} ne unix_md5_crypt($pass,$1);
|
---|
1163 | } elsif ($userinfo->{password} =~ /^[0-9a-f]{32}$/) {
|
---|
1164 | # VegaDNS import (hex-coded MD5)
|
---|
1165 | return if $userinfo->{password} ne md5_hex($pass);
|
---|
1166 | } else {
|
---|
1167 | # plaintext (convenient now and then)
|
---|
1168 | return if $userinfo->{password} ne $pass;
|
---|
1169 | }
|
---|
1170 |
|
---|
1171 | return $userinfo;
|
---|
1172 | } # end login()
|
---|
1173 |
|
---|
1174 |
|
---|
1175 | ## DNSDB::initActionLog()
|
---|
1176 | # Set up action logging. Takes a database handle and user ID
|
---|
1177 | # Sets some internal globals and Does The Right Thing to set up a logging channel.
|
---|
1178 | # This sets up _log() to spew out log entries to the defined channel without worrying
|
---|
1179 | # about having to open a file or a syslog channel
|
---|
1180 | ##fixme Need to call _initActionLog_blah() for various logging channels, configured
|
---|
1181 | # via dnsdb.conf, in $config{log_channel} or something
|
---|
1182 | # See https://secure.deepnet.cx/trac/dnsadmin/ticket/21
|
---|
1183 | sub initActionLog {
|
---|
1184 | my $dbh = shift;
|
---|
1185 | my $uid = shift;
|
---|
1186 |
|
---|
1187 | return if !$uid;
|
---|
1188 |
|
---|
1189 | # snag user info for logging. there's got to be a way to not have to pass this back
|
---|
1190 | # and forth from a caller, but web usage means no persistence we can rely on from
|
---|
1191 | # the server side.
|
---|
1192 | my ($username,$fullname) = $dbh->selectrow_array("SELECT username, firstname || ' ' || lastname".
|
---|
1193 | " FROM users WHERE user_id=?", undef, ($uid));
|
---|
1194 | ##fixme: errors are unpossible!
|
---|
1195 |
|
---|
1196 | $userdata{username} = $username;
|
---|
1197 | $userdata{userid} = $uid;
|
---|
1198 | $userdata{fullname} = $fullname;
|
---|
1199 |
|
---|
1200 | # convert to real check once we have other logging channels
|
---|
1201 | # if ($config{log_channel} eq 'sql') {
|
---|
1202 | # Open Log, Sez Me!
|
---|
1203 | # }
|
---|
1204 |
|
---|
1205 | } # end initActionLog
|
---|
1206 |
|
---|
1207 |
|
---|
1208 | ## DNSDB::initPermissions()
|
---|
1209 | # Set up permissions global
|
---|
1210 | # Takes database handle and UID
|
---|
1211 | sub initPermissions {
|
---|
1212 | my $dbh = shift;
|
---|
1213 | my $uid = shift;
|
---|
1214 |
|
---|
1215 | # %permissions = $(getPermissions($dbh,'user',$uid));
|
---|
1216 | getPermissions($dbh, 'user', $uid, \%permissions);
|
---|
1217 |
|
---|
1218 | } # end initPermissions()
|
---|
1219 |
|
---|
1220 |
|
---|
1221 | ## DNSDB::getPermissions()
|
---|
1222 | # Get permissions from DB
|
---|
1223 | # Requires DB handle, group or user flag, ID, and hashref.
|
---|
1224 | sub getPermissions {
|
---|
1225 | my $dbh = shift;
|
---|
1226 | my $type = shift;
|
---|
1227 | my $id = shift;
|
---|
1228 | my $hash = shift;
|
---|
1229 |
|
---|
1230 | my $sql = qq(
|
---|
1231 | SELECT
|
---|
1232 | p.admin,p.self_edit,
|
---|
1233 | p.group_create,p.group_edit,p.group_delete,
|
---|
1234 | p.user_create,p.user_edit,p.user_delete,
|
---|
1235 | p.domain_create,p.domain_edit,p.domain_delete,
|
---|
1236 | p.record_create,p.record_edit,p.record_delete
|
---|
1237 | FROM permissions p
|
---|
1238 | );
|
---|
1239 | if ($type eq 'group') {
|
---|
1240 | $sql .= qq(
|
---|
1241 | JOIN groups g ON g.permission_id=p.permission_id
|
---|
1242 | WHERE g.group_id=?
|
---|
1243 | );
|
---|
1244 | } else {
|
---|
1245 | $sql .= qq(
|
---|
1246 | JOIN users u ON u.permission_id=p.permission_id
|
---|
1247 | WHERE u.user_id=?
|
---|
1248 | );
|
---|
1249 | }
|
---|
1250 |
|
---|
1251 | my $sth = $dbh->prepare($sql);
|
---|
1252 |
|
---|
1253 | $sth->execute($id) or die "argh: ".$sth->errstr;
|
---|
1254 |
|
---|
1255 | # my $permref = $sth->fetchrow_hashref;
|
---|
1256 | # return $permref;
|
---|
1257 | # $hash = $permref;
|
---|
1258 | # Eww. Need to learn how to forcibly drop a hashref onto an existing hash.
|
---|
1259 | ($hash->{admin},$hash->{self_edit},
|
---|
1260 | $hash->{group_create},$hash->{group_edit},$hash->{group_delete},
|
---|
1261 | $hash->{user_create},$hash->{user_edit},$hash->{user_delete},
|
---|
1262 | $hash->{domain_create},$hash->{domain_edit},$hash->{domain_delete},
|
---|
1263 | $hash->{record_create},$hash->{record_edit},$hash->{record_delete})
|
---|
1264 | = $sth->fetchrow_array;
|
---|
1265 |
|
---|
1266 | } # end getPermissions()
|
---|
1267 |
|
---|
1268 |
|
---|
1269 | ## DNSDB::changePermissions()
|
---|
1270 | # Update an ACL entry
|
---|
1271 | # Takes a db handle, type, owner-id, and hashref for the changed permissions.
|
---|
1272 | sub changePermissions {
|
---|
1273 | my $dbh = shift;
|
---|
1274 | my $type = shift;
|
---|
1275 | my $id = shift;
|
---|
1276 | my $newperms = shift;
|
---|
1277 | my $inherit = shift || 0;
|
---|
1278 |
|
---|
1279 | my $resultmsg = '';
|
---|
1280 |
|
---|
1281 | # see if we're switching from inherited to custom. for bonus points,
|
---|
1282 | # snag the permid and parent permid anyway, since we'll need the permid
|
---|
1283 | # to set/alter custom perms, and both if we're switching from custom to
|
---|
1284 | # inherited.
|
---|
1285 | my $sth = $dbh->prepare("SELECT (u.permission_id=g.permission_id) AS was_inherited,u.permission_id,g.permission_id,".
|
---|
1286 | ($type eq 'user' ? 'u.group_id,u.username' : 'u.parent_group_id,u.group_name').
|
---|
1287 | " FROM ".($type eq 'user' ? 'users' : 'groups')." u ".
|
---|
1288 | " JOIN groups g ON u.".($type eq 'user' ? '' : 'parent_')."group_id=g.group_id ".
|
---|
1289 | " WHERE u.".($type eq 'user' ? 'user' : 'group')."_id=?");
|
---|
1290 | $sth->execute($id);
|
---|
1291 |
|
---|
1292 | my ($wasinherited,$permid,$parpermid,$parid,$name) = $sth->fetchrow_array;
|
---|
1293 |
|
---|
1294 | # hack phtoui
|
---|
1295 | # group id 1 is "special" in that it's it's own parent (err... possibly.)
|
---|
1296 | # may make its parent id 0 which doesn't exist, and as a bonus is Perl-false.
|
---|
1297 | $wasinherited = 0 if ($type eq 'group' && $id == 1);
|
---|
1298 |
|
---|
1299 | local $dbh->{AutoCommit} = 0;
|
---|
1300 | local $dbh->{RaiseError} = 1;
|
---|
1301 |
|
---|
1302 | # Wrap all the SQL in a transaction
|
---|
1303 | eval {
|
---|
1304 | if ($inherit) {
|
---|
1305 |
|
---|
1306 | $dbh->do("UPDATE ".($type eq 'user' ? 'users' : 'groups')." SET inherit_perm='t',permission_id=? ".
|
---|
1307 | "WHERE ".($type eq 'user' ? 'user' : 'group')."_id=?", undef, ($parpermid, $id) );
|
---|
1308 | $dbh->do("DELETE FROM permissions WHERE permission_id=?", undef, ($permid) );
|
---|
1309 |
|
---|
1310 | } else {
|
---|
1311 |
|
---|
1312 | if ($wasinherited) { # munge new permission entry in if we're switching from inherited perms
|
---|
1313 | ##fixme: need to add semirecursive bit to properly munge inherited permission ID on subgroups and users
|
---|
1314 | # ... if'n'when we have groups with fully inherited permissions.
|
---|
1315 | # SQL is coo
|
---|
1316 | $dbh->do("INSERT INTO permissions ($permlist,".($type eq 'user' ? 'user' : 'group')."_id) ".
|
---|
1317 | "SELECT $permlist,? FROM permissions WHERE permission_id=?", undef, ($id,$permid) );
|
---|
1318 | ($permid) = $dbh->selectrow_array("SELECT permission_id FROM permissions ".
|
---|
1319 | "WHERE ".($type eq 'user' ? 'user' : 'group')."_id=?", undef, ($id) );
|
---|
1320 | $dbh->do("UPDATE ".($type eq 'user' ? 'users' : 'groups')." SET inherit_perm='f',permission_id=? ".
|
---|
1321 | "WHERE ".($type eq 'user' ? 'user' : 'group')."_id=?", undef, ($permid, $id) );
|
---|
1322 | }
|
---|
1323 |
|
---|
1324 | # and now set the permissions we were passed
|
---|
1325 | foreach (@permtypes) {
|
---|
1326 | if (defined ($newperms->{$_})) {
|
---|
1327 | $dbh->do("UPDATE permissions SET $_=? WHERE permission_id=?", undef, ($newperms->{$_},$permid) );
|
---|
1328 | }
|
---|
1329 | }
|
---|
1330 |
|
---|
1331 | } # (inherited->)? custom
|
---|
1332 |
|
---|
1333 | if ($type eq 'user') {
|
---|
1334 | $resultmsg = "Updated permissions for user $name";
|
---|
1335 | } else {
|
---|
1336 | $resultmsg = "Updated default permissions for group $name";
|
---|
1337 | }
|
---|
1338 | _log($dbh, (group_id => ($type eq 'user' ? $parid : $id), entry => $resultmsg));
|
---|
1339 | $dbh->commit;
|
---|
1340 | }; # end eval
|
---|
1341 | if ($@) {
|
---|
1342 | my $msg = $@;
|
---|
1343 | eval { $dbh->rollback; };
|
---|
1344 | return ('FAIL',"Error changing permissions: $msg");
|
---|
1345 | }
|
---|
1346 |
|
---|
1347 | return ('OK',$resultmsg);
|
---|
1348 | } # end changePermissions()
|
---|
1349 |
|
---|
1350 |
|
---|
1351 | ## DNSDB::comparePermissions()
|
---|
1352 | # Compare two permission hashes
|
---|
1353 | # Returns '>', '<', '=', '!'
|
---|
1354 | sub comparePermissions {
|
---|
1355 | my $p1 = shift;
|
---|
1356 | my $p2 = shift;
|
---|
1357 |
|
---|
1358 | my $retval = '='; # assume equality until proven otherwise
|
---|
1359 |
|
---|
1360 | no warnings "uninitialized";
|
---|
1361 |
|
---|
1362 | foreach (@permtypes) {
|
---|
1363 | next if $p1->{$_} == $p2->{$_}; # equal is good
|
---|
1364 | if ($p1->{$_} && !$p2->{$_}) {
|
---|
1365 | if ($retval eq '<') { # if we've already found an unequal pair where
|
---|
1366 | $retval = '!'; # $p2 has more access, and we now find a pair
|
---|
1367 | last; # where $p1 has more access, the overall access
|
---|
1368 | } # is neither greater or lesser, it's unequal.
|
---|
1369 | $retval = '>';
|
---|
1370 | }
|
---|
1371 | if (!$p1->{$_} && $p2->{$_}) {
|
---|
1372 | if ($retval eq '>') { # if we've already found an unequal pair where
|
---|
1373 | $retval = '!'; # $p1 has more access, and we now find a pair
|
---|
1374 | last; # where $p2 has more access, the overall access
|
---|
1375 | } # is neither greater or lesser, it's unequal.
|
---|
1376 | $retval = '<';
|
---|
1377 | }
|
---|
1378 | }
|
---|
1379 | return $retval;
|
---|
1380 | } # end comparePermissions()
|
---|
1381 |
|
---|
1382 |
|
---|
1383 | ## DNSDB::changeGroup()
|
---|
1384 | # Change group ID of an entity
|
---|
1385 | # Takes a database handle, entity type, entity ID, and new group ID
|
---|
1386 | sub changeGroup {
|
---|
1387 | my $dbh = shift;
|
---|
1388 | my $type = shift;
|
---|
1389 | my $id = shift;
|
---|
1390 | my $newgrp = shift;
|
---|
1391 |
|
---|
1392 | ##fixme: fail on not enough args
|
---|
1393 | #return ('FAIL', "Missing
|
---|
1394 |
|
---|
1395 | return ('FAIL', "Can't change the group of a $type")
|
---|
1396 | unless grep /^$type$/, ('domain','revzone','user','group'); # could be extended for defrecs?
|
---|
1397 |
|
---|
1398 | # Collect some names for logging and messages
|
---|
1399 | my $entname;
|
---|
1400 | if ($type eq 'domain') {
|
---|
1401 | $entname = domainName($dbh, $id);
|
---|
1402 | } elsif ($type eq 'revzone') {
|
---|
1403 | $entname = revName($dbh, $id);
|
---|
1404 | } elsif ($type eq 'user') {
|
---|
1405 | $entname = userFullName($dbh, $id, '%u');
|
---|
1406 | } elsif ($type eq 'group') {
|
---|
1407 | $entname = groupName($dbh, $id);
|
---|
1408 | }
|
---|
1409 |
|
---|
1410 | my ($oldgid) = $dbh->selectrow_array("SELECT group_id FROM $par_tbl{$type} WHERE $id_col{$type}=?",
|
---|
1411 | undef, ($id));
|
---|
1412 | my $oldgname = groupName($dbh, $oldgid);
|
---|
1413 | my $newgname = groupName($dbh, $newgrp);
|
---|
1414 |
|
---|
1415 | return ('FAIL', "Can't move things into a group that doesn't exist") if !$newgname;
|
---|
1416 |
|
---|
1417 | return ('WARN', "Nothing to do, new group is the same as the old group") if $oldgid == $newgrp;
|
---|
1418 |
|
---|
1419 | # Allow transactions, and raise an exception on errors so we can catch it later.
|
---|
1420 | # Use local to make sure these get "reset" properly on exiting this block
|
---|
1421 | local $dbh->{AutoCommit} = 0;
|
---|
1422 | local $dbh->{RaiseError} = 1;
|
---|
1423 |
|
---|
1424 | eval {
|
---|
1425 | $dbh->do("UPDATE $par_tbl{$type} SET group_id=? WHERE $id_col{$type}=?", undef, ($newgrp, $id));
|
---|
1426 | # Log the change in both the old and new groups
|
---|
1427 | _log($dbh, (group_id => $oldgid, entry => "Moved $type $entname from $oldgname to $newgname"));
|
---|
1428 | _log($dbh, (group_id => $newgrp, entry => "Moved $type $entname from $oldgname to $newgname"));
|
---|
1429 | $dbh->commit;
|
---|
1430 | };
|
---|
1431 | if ($@) {
|
---|
1432 | my $msg = $@;
|
---|
1433 | eval { $dbh->rollback; };
|
---|
1434 | if ($config{log_failures}) {
|
---|
1435 | _log($dbh, (group_id => $oldgid, entry => "Error moving $type $entname to $newgname: $msg"));
|
---|
1436 | $dbh->commit; # since we enabled transactions earlier
|
---|
1437 | }
|
---|
1438 | return ('FAIL',"Error moving $type $entname to $newgname: $msg");
|
---|
1439 | }
|
---|
1440 |
|
---|
1441 | return ('OK',"Moved $type $entname from $oldgname to $newgname");
|
---|
1442 | } # end changeGroup()
|
---|
1443 |
|
---|
1444 |
|
---|
1445 | ##
|
---|
1446 | ## Processing subs
|
---|
1447 | ##
|
---|
1448 |
|
---|
1449 | ## DNSDB::addDomain()
|
---|
1450 | # Add a domain
|
---|
1451 | # Takes a database handle, domain name, numeric group, boolean(ish) state (active/inactive),
|
---|
1452 | # and user info hash (for logging).
|
---|
1453 | # Returns a status code and message
|
---|
1454 | sub addDomain {
|
---|
1455 | $errstr = '';
|
---|
1456 | my $dbh = shift;
|
---|
1457 | return ('FAIL',"Need database handle") if !$dbh;
|
---|
1458 | my $domain = shift;
|
---|
1459 | return ('FAIL',"Domain must not be blank") if !$domain;
|
---|
1460 | my $group = shift;
|
---|
1461 | return ('FAIL',"Need group") if !defined($group);
|
---|
1462 | my $state = shift;
|
---|
1463 | return ('FAIL',"Need domain status") if !defined($state);
|
---|
1464 |
|
---|
1465 | my %userinfo = @_; # remaining bits.
|
---|
1466 | # user ID, username, user full name
|
---|
1467 |
|
---|
1468 | $state = 1 if $state =~ /^active$/;
|
---|
1469 | $state = 1 if $state =~ /^on$/;
|
---|
1470 | $state = 0 if $state =~ /^inactive$/;
|
---|
1471 | $state = 0 if $state =~ /^off$/;
|
---|
1472 |
|
---|
1473 | return ('FAIL',"Invalid domain status") if $state !~ /^\d+$/;
|
---|
1474 |
|
---|
1475 | return ('FAIL', "Invalid characters in domain") if $domain !~ /^[a-zA-Z0-9_.-]+$/;
|
---|
1476 |
|
---|
1477 | my $sth = $dbh->prepare("SELECT domain_id FROM domains WHERE domain=?");
|
---|
1478 | my $dom_id;
|
---|
1479 |
|
---|
1480 | # quick check to start to see if we've already got one
|
---|
1481 | $sth->execute($domain);
|
---|
1482 | ($dom_id) = $sth->fetchrow_array;
|
---|
1483 |
|
---|
1484 | return ('FAIL', "Domain already exists") if $dom_id;
|
---|
1485 |
|
---|
1486 | # Allow transactions, and raise an exception on errors so we can catch it later.
|
---|
1487 | # Use local to make sure these get "reset" properly on exiting this block
|
---|
1488 | local $dbh->{AutoCommit} = 0;
|
---|
1489 | local $dbh->{RaiseError} = 1;
|
---|
1490 |
|
---|
1491 | # Wrap all the SQL in a transaction
|
---|
1492 | eval {
|
---|
1493 | # insert the domain...
|
---|
1494 | $dbh->do("INSERT INTO domains (domain,group_id,status) VALUES (?,?,?)", undef, ($domain, $group, $state));
|
---|
1495 |
|
---|
1496 | # get the ID...
|
---|
1497 | ($dom_id) = $dbh->selectrow_array("SELECT domain_id FROM domains WHERE domain=?", undef, ($domain));
|
---|
1498 |
|
---|
1499 | _log($dbh, (domain_id => $dom_id, group_id => $group,
|
---|
1500 | entry => "Added ".($state ? 'active' : 'inactive')." domain $domain"));
|
---|
1501 |
|
---|
1502 | # ... and now we construct the standard records from the default set. NB: group should be variable.
|
---|
1503 | my $sth = $dbh->prepare("SELECT host,type,val,distance,weight,port,ttl FROM default_records WHERE group_id=?");
|
---|
1504 | my $sth_in = $dbh->prepare("INSERT INTO records (domain_id,host,type,val,distance,weight,port,ttl)".
|
---|
1505 | " VALUES ($dom_id,?,?,?,?,?,?,?)");
|
---|
1506 | $sth->execute($group);
|
---|
1507 | while (my ($host,$type,$val,$dist,$weight,$port,$ttl) = $sth->fetchrow_array()) {
|
---|
1508 | $host =~ s/DOMAIN/$domain/g;
|
---|
1509 | $val =~ s/DOMAIN/$domain/g;
|
---|
1510 | $sth_in->execute($host,$type,$val,$dist,$weight,$port,$ttl);
|
---|
1511 | if ($typemap{$type} eq 'SOA') {
|
---|
1512 | my @tmp1 = split /:/, $host;
|
---|
1513 | my @tmp2 = split /:/, $val;
|
---|
1514 | _log($dbh, (domain_id => $dom_id, group_id => $group,
|
---|
1515 | entry => "[new $domain] Added SOA record [contact $tmp1[0]] [master $tmp1[1]] ".
|
---|
1516 | "[refresh $tmp2[0]] [retry $tmp2[1]] [expire $tmp2[2]] [minttl $tmp2[3]], TTL $ttl"));
|
---|
1517 | } else {
|
---|
1518 | my $logentry = "[new $domain] Added record '$host $typemap{$type}";
|
---|
1519 | $logentry .= " [distance $dist]" if $typemap{$type} eq 'MX';
|
---|
1520 | $logentry .= " [priority $dist] [weight $weight] [port $port]" if $typemap{$type} eq 'SRV';
|
---|
1521 | _log($dbh, (domain_id => $dom_id, group_id => $group,
|
---|
1522 | entry => $logentry." $val', TTL $ttl"));
|
---|
1523 | }
|
---|
1524 | }
|
---|
1525 |
|
---|
1526 | # once we get here, we should have suceeded.
|
---|
1527 | $dbh->commit;
|
---|
1528 | }; # end eval
|
---|
1529 |
|
---|
1530 | if ($@) {
|
---|
1531 | my $msg = $@;
|
---|
1532 | eval { $dbh->rollback; };
|
---|
1533 | _log($dbh, (group_id => $group, entry => "Failed adding domain $domain ($msg)"))
|
---|
1534 | if $config{log_failures};
|
---|
1535 | $dbh->commit; # since we enabled transactions earlier
|
---|
1536 | return ('FAIL',$msg);
|
---|
1537 | } else {
|
---|
1538 | return ('OK',$dom_id);
|
---|
1539 | }
|
---|
1540 | } # end addDomain
|
---|
1541 |
|
---|
1542 |
|
---|
1543 | ## DNSDB::delZone()
|
---|
1544 | # Delete a forward or reverse zone.
|
---|
1545 | # Takes a database handle, zone ID, and forward/reverse flag.
|
---|
1546 | # for now, just delete the records, then the domain.
|
---|
1547 | # later we may want to archive it in some way instead (status code 2, for example?)
|
---|
1548 | sub delZone {
|
---|
1549 | my $dbh = shift;
|
---|
1550 | my $zoneid = shift;
|
---|
1551 | my $revrec = shift;
|
---|
1552 |
|
---|
1553 | # Allow transactions, and raise an exception on errors so we can catch it later.
|
---|
1554 | # Use local to make sure these get "reset" properly on exiting this block
|
---|
1555 | local $dbh->{AutoCommit} = 0;
|
---|
1556 | local $dbh->{RaiseError} = 1;
|
---|
1557 |
|
---|
1558 | my $msg = '';
|
---|
1559 | my $failmsg = '';
|
---|
1560 | my $zone = ($revrec eq 'n' ? domainName($dbh, $zoneid) : revName($dbh, $zoneid));
|
---|
1561 |
|
---|
1562 | # Set this up here since we may use if if $config{log_failures} is enabled
|
---|
1563 | my %loghash;
|
---|
1564 | $loghash{domain_id} = $zoneid if $revrec eq 'n';
|
---|
1565 | $loghash{rdns_id} = $zoneid if $revrec eq 'y';
|
---|
1566 | $loghash{group_id} = parentID($dbh,
|
---|
1567 | (id => $zoneid, type => ($revrec eq 'n' ? 'domain' : 'revzone'), revrec => $revrec) );
|
---|
1568 |
|
---|
1569 | # Wrap all the SQL in a transaction
|
---|
1570 | eval {
|
---|
1571 | # Disentangle custom record types before removing the
|
---|
1572 | # ones that are only in the zone to be deleted
|
---|
1573 | if ($revrec eq 'n') {
|
---|
1574 | my $sth = $dbh->prepare("UPDATE records SET type=?,domain_id=0 WHERE domain_id=? AND type=?");
|
---|
1575 | $failmsg = "Failure converting multizone types to single-zone";
|
---|
1576 | $sth->execute($reverse_typemap{PTR}, $zoneid, 65280);
|
---|
1577 | $sth->execute($reverse_typemap{PTR}, $zoneid, 65281);
|
---|
1578 | $sth->execute(65282, $zoneid, 65283);
|
---|
1579 | $sth->execute(65282, $zoneid, 65284);
|
---|
1580 | $failmsg = "Failure removing domain records";
|
---|
1581 | $dbh->do("DELETE FROM records WHERE domain_id=?", undef, ($zoneid));
|
---|
1582 | $failmsg = "Failure removing domain";
|
---|
1583 | $dbh->do("DELETE FROM domains WHERE domain_id=?", undef, ($zoneid));
|
---|
1584 | } else {
|
---|
1585 | my $sth = $dbh->prepare("UPDATE records SET type=?,rdns_id=0 WHERE rdns_id=? AND type=?");
|
---|
1586 | $failmsg = "Failure converting multizone types to single-zone";
|
---|
1587 | $sth->execute($reverse_typemap{A}, $zoneid, 65280);
|
---|
1588 | $sth->execute($reverse_typemap{AAAA}, $zoneid, 65281);
|
---|
1589 | # We don't have an "A template" or "AAAA template" type, although it might be useful for symmetry.
|
---|
1590 | # $sth->execute(65285?, $zoneid, 65283);
|
---|
1591 | # $sth->execute(65285?, $zoneid, 65284);
|
---|
1592 | $failmsg = "Failure removing reverse records";
|
---|
1593 | $dbh->do("DELETE FROM records WHERE rdns_id=?", undef, ($zoneid));
|
---|
1594 | $failmsg = "Failure removing reverse zone";
|
---|
1595 | $dbh->do("DELETE FROM revzones WHERE rdns_id=?", undef, ($zoneid));
|
---|
1596 | }
|
---|
1597 |
|
---|
1598 | $msg = "Deleted ".($revrec eq 'n' ? 'domain' : 'reverse zone')." $zone";
|
---|
1599 | $loghash{entry} = $msg;
|
---|
1600 | _log($dbh, %loghash);
|
---|
1601 |
|
---|
1602 | # once we get here, we should have suceeded.
|
---|
1603 | $dbh->commit;
|
---|
1604 | }; # end eval
|
---|
1605 |
|
---|
1606 | if ($@) {
|
---|
1607 | $msg = $@;
|
---|
1608 | eval { $dbh->rollback; };
|
---|
1609 | $loghash{entry} = "Error deleting $zone: $msg ($failmsg)";
|
---|
1610 | if ($config{log_failures}) {
|
---|
1611 | _log($dbh, %loghash);
|
---|
1612 | $dbh->commit; # since we enabled transactions earlier
|
---|
1613 | }
|
---|
1614 | return ('FAIL', $loghash{entry});
|
---|
1615 | } else {
|
---|
1616 | return ('OK', $msg);
|
---|
1617 | }
|
---|
1618 |
|
---|
1619 | } # end delZone()
|
---|
1620 |
|
---|
1621 |
|
---|
1622 | ## DNSDB::domainName()
|
---|
1623 | # Return the domain name based on a domain ID
|
---|
1624 | # Takes a database handle and the domain ID
|
---|
1625 | # Returns the domain name or undef on failure
|
---|
1626 | sub domainName {
|
---|
1627 | $errstr = '';
|
---|
1628 | my $dbh = shift;
|
---|
1629 | my $domid = shift;
|
---|
1630 | my ($domname) = $dbh->selectrow_array("SELECT domain FROM domains WHERE domain_id=?", undef, ($domid) );
|
---|
1631 | $errstr = $DBI::errstr if !$domname;
|
---|
1632 | return $domname if $domname;
|
---|
1633 | } # end domainName()
|
---|
1634 |
|
---|
1635 |
|
---|
1636 | ## DNSDB::revName()
|
---|
1637 | # Return the reverse zone name based on an rDNS ID
|
---|
1638 | # Takes a database handle and the rDNS ID
|
---|
1639 | # Returns the reverse zone name or undef on failure
|
---|
1640 | sub revName {
|
---|
1641 | $errstr = '';
|
---|
1642 | my $dbh = shift;
|
---|
1643 | my $revid = shift;
|
---|
1644 | my ($revname) = $dbh->selectrow_array("SELECT revnet FROM revzones WHERE rdns_id=?", undef, ($revid) );
|
---|
1645 | $errstr = $DBI::errstr if !$revname;
|
---|
1646 | return $revname if $revname;
|
---|
1647 | } # end revName()
|
---|
1648 |
|
---|
1649 |
|
---|
1650 | ## DNSDB::domainID()
|
---|
1651 | # Takes a database handle and domain name
|
---|
1652 | # Returns the domain ID number
|
---|
1653 | sub domainID {
|
---|
1654 | $errstr = '';
|
---|
1655 | my $dbh = shift;
|
---|
1656 | my $domain = shift;
|
---|
1657 | my ($domid) = $dbh->selectrow_array("SELECT domain_id FROM domains WHERE domain=?", undef, ($domain) );
|
---|
1658 | $errstr = $DBI::errstr if !$domid;
|
---|
1659 | return $domid if $domid;
|
---|
1660 | } # end domainID()
|
---|
1661 |
|
---|
1662 |
|
---|
1663 | ## DNSDB::revID()
|
---|
1664 | # Takes a database handle and reverse zone name
|
---|
1665 | # Returns the rDNS ID number
|
---|
1666 | sub revID {
|
---|
1667 | $errstr = '';
|
---|
1668 | my $dbh = shift;
|
---|
1669 | my $revzone = shift;
|
---|
1670 | my ($revid) = $dbh->selectrow_array("SELECT rdns_id FROM revzones WHERE revnet=?", undef, ($revzone) );
|
---|
1671 | $errstr = $DBI::errstr if !$revid;
|
---|
1672 | return $revid if $revid;
|
---|
1673 | } # end revID()
|
---|
1674 |
|
---|
1675 |
|
---|
1676 | ## DNSDB::addRDNS
|
---|
1677 | # Adds a reverse DNS zone
|
---|
1678 | # Takes a database handle, CIDR block, reverse DNS pattern, numeric group,
|
---|
1679 | # and boolean(ish) state (active/inactive)
|
---|
1680 | # Returns a status code and message
|
---|
1681 | sub addRDNS {
|
---|
1682 | my $dbh = shift;
|
---|
1683 | my $zone = NetAddr::IP->new(shift);
|
---|
1684 | return ('FAIL',"Zone name must be a valid CIDR netblock") unless ($zone && $zone->addr !~ /^0/);
|
---|
1685 | my $revpatt = shift; # construct a custom (A/AAAA+)? PTR template record
|
---|
1686 | my $group = shift;
|
---|
1687 | my $state = shift;
|
---|
1688 |
|
---|
1689 | $state = 1 if $state =~ /^active$/;
|
---|
1690 | $state = 1 if $state =~ /^on$/;
|
---|
1691 | $state = 0 if $state =~ /^inactive$/;
|
---|
1692 | $state = 0 if $state =~ /^off$/;
|
---|
1693 |
|
---|
1694 | return ('FAIL',"Invalid zone status") if $state !~ /^\d+$/;
|
---|
1695 |
|
---|
1696 | # quick check to start to see if we've already got one
|
---|
1697 | my ($rdns_id) = $dbh->selectrow_array("SELECT rdns_id FROM revzones WHERE revnet=?", undef, ("$zone"));
|
---|
1698 |
|
---|
1699 | return ('FAIL', "Zone already exists") if $rdns_id;
|
---|
1700 |
|
---|
1701 | # Allow transactions, and raise an exception on errors so we can catch it later.
|
---|
1702 | # Use local to make sure these get "reset" properly on exiting this block
|
---|
1703 | local $dbh->{AutoCommit} = 0;
|
---|
1704 | local $dbh->{RaiseError} = 1;
|
---|
1705 |
|
---|
1706 | my $warnstr = '';
|
---|
1707 | my $defttl = 3600; # 1 hour should be reasonable. And unless things have gone horribly
|
---|
1708 | # wrong, we should have a value to override this anyway.
|
---|
1709 |
|
---|
1710 | # Wrap all the SQL in a transaction
|
---|
1711 | eval {
|
---|
1712 | # insert the domain...
|
---|
1713 | $dbh->do("INSERT INTO revzones (revnet,group_id,status) VALUES (?,?,?)", undef, ($zone, $group, $state));
|
---|
1714 |
|
---|
1715 | # get the ID...
|
---|
1716 | ($rdns_id) = $dbh->selectrow_array("SELECT currval('revzones_rdns_id_seq')");
|
---|
1717 |
|
---|
1718 | _log($dbh, (rdns_id => $rdns_id, group_id => $group,
|
---|
1719 | entry => "Added ".($state ? 'active' : 'inactive')." reverse zone $zone"));
|
---|
1720 |
|
---|
1721 | # ... and now we construct the standard records from the default set. NB: group should be variable.
|
---|
1722 | my $sth = $dbh->prepare("SELECT host,type,val,ttl FROM default_rev_records WHERE group_id=?");
|
---|
1723 | my $sth_in = $dbh->prepare("INSERT INTO records (rdns_id,domain_id,host,type,val,ttl)".
|
---|
1724 | " VALUES ($rdns_id,?,?,?,?,?)");
|
---|
1725 | $sth->execute($group);
|
---|
1726 | while (my ($host,$type,$val,$ttl) = $sth->fetchrow_array()) {
|
---|
1727 | # Silently skip v4/v6 mismatches. This is not an error, this is expected.
|
---|
1728 | if ($zone->{isv6}) {
|
---|
1729 | next if ($type == 65280 || $type == 65283);
|
---|
1730 | } else {
|
---|
1731 | next if ($type == 65281 || $type == 65284);
|
---|
1732 | }
|
---|
1733 |
|
---|
1734 | $host =~ s/ADMINDOMAIN/$config{domain}/g;
|
---|
1735 |
|
---|
1736 | # Check to make sure the IP stubs will fit in the zone. Under most usage failures here should be rare.
|
---|
1737 | # On failure, tack a note on to a warning string and continue without adding this record.
|
---|
1738 | # While we're at it, we substitute $zone for ZONE in the value.
|
---|
1739 | if ($val eq 'ZONE') {
|
---|
1740 | next if $revpatt; # If we've got a pattern, we skip the default record version.
|
---|
1741 | ##fixme? do we care if we have multiple whole-zone templates?
|
---|
1742 | $val = $zone->network;
|
---|
1743 | } elsif ($val =~ /ZONE/) {
|
---|
1744 | my $tmpval = $val;
|
---|
1745 | $tmpval =~ s/ZONE//;
|
---|
1746 | # Bend the rules and allow single-trailing-number PTR or PTR template records to be inserted
|
---|
1747 | # as either v4 or v6. May make this an off-by-default config flag
|
---|
1748 | # Note that the origin records that may trigger this **SHOULD** already have ZONE,\d
|
---|
1749 | if ($type == 12 || $type == 65282) {
|
---|
1750 | $tmpval =~ s/[,.]/::/ if ($tmpval =~ /^[,.]\d+$/ && $zone->{isv6});
|
---|
1751 | $tmpval =~ s/[,:]+/./ if ($tmpval =~ /^(?:,|::)\d+$/ && !$zone->{isv6});
|
---|
1752 | }
|
---|
1753 | my $addr;
|
---|
1754 | if (_ipparent($dbh, 'n', 'y', \$tmpval, $rdns_id, \$addr)) {
|
---|
1755 | $val = $addr->addr;
|
---|
1756 | } else {
|
---|
1757 | $warnstr .= "\nDefault record '$val $typemap{$type} $host' doesn't fit in $zone, skipping";
|
---|
1758 | next;
|
---|
1759 | }
|
---|
1760 | }
|
---|
1761 |
|
---|
1762 | # Substitute $zone for ZONE in the hostname.
|
---|
1763 | $host = _ZONE($zone, $host);
|
---|
1764 |
|
---|
1765 | # Fill in the forward domain ID if we can find it, otherwise:
|
---|
1766 | # Coerce type down to PTR or PTR template if we can't
|
---|
1767 | my $domid = 0;
|
---|
1768 | if ($type >= 65280) {
|
---|
1769 | if (!($domid = _hostparent($dbh, $host))) {
|
---|
1770 | $warnstr .= "\nRecord added as PTR instead of $typemap{$type}; domain not found for $host";
|
---|
1771 | $type = $reverse_typemap{PTR};
|
---|
1772 | $domid = 0; # just to be explicit.
|
---|
1773 | }
|
---|
1774 | }
|
---|
1775 |
|
---|
1776 | $sth_in->execute($domid,$host,$type,$val,$ttl);
|
---|
1777 |
|
---|
1778 | if ($typemap{$type} eq 'SOA') {
|
---|
1779 | my @tmp1 = split /:/, $host;
|
---|
1780 | my @tmp2 = split /:/, $val;
|
---|
1781 | _log($dbh, (rdns_id => $rdns_id, group_id => $group,
|
---|
1782 | entry => "[new $zone] Added SOA record [contact $tmp1[0]] [master $tmp1[1]] ".
|
---|
1783 | "[refresh $tmp2[0]] [retry $tmp2[1]] [expire $tmp2[2]] [minttl $tmp2[3]], TTL $ttl"));
|
---|
1784 | $defttl = $tmp2[3];
|
---|
1785 | } else {
|
---|
1786 | my $logentry = "[new $zone] Added record '$host $typemap{$type}";
|
---|
1787 | _log($dbh, (rdns_id => $rdns_id, domain_id => $domid, group_id => $group,
|
---|
1788 | entry => $logentry." $val', TTL $ttl"));
|
---|
1789 | }
|
---|
1790 | }
|
---|
1791 |
|
---|
1792 | # Generate record based on provided pattern.
|
---|
1793 | if ($revpatt) {
|
---|
1794 | my $host;
|
---|
1795 | my $type = ($zone->{isv6} ? 65284 : 65283);
|
---|
1796 | my $val = $zone->network;
|
---|
1797 |
|
---|
1798 | # Substitute $zone for ZONE in the hostname.
|
---|
1799 | $host = _ZONE($zone, $revpatt);
|
---|
1800 |
|
---|
1801 | my $domid = 0;
|
---|
1802 | if (!($domid = _hostparent($dbh, $host))) {
|
---|
1803 | $warnstr .= "\nDefault pattern added as PTR template instead of $typemap{$type}; domain not found for $host";
|
---|
1804 | $type = 65282;
|
---|
1805 | $domid = 0; # just to be explicit.
|
---|
1806 | }
|
---|
1807 |
|
---|
1808 | $sth_in->execute($domid,$host,$type,$val,$defttl);
|
---|
1809 | my $logentry = "[new $zone] Added record '$host $typemap{$type}";
|
---|
1810 | _log($dbh, (rdns_id => $rdns_id, domain_id => $domid, group_id => $group,
|
---|
1811 | entry => $logentry." $val', TTL $defttl from pattern"));
|
---|
1812 | }
|
---|
1813 |
|
---|
1814 | # If there are warnings (presumably about default records skipped for cause) log them
|
---|
1815 | _log($dbh, (rdns_id => $rdns_id, group_id => $group, entry => "Warning(s) adding $zone:$warnstr"))
|
---|
1816 | if $warnstr;
|
---|
1817 |
|
---|
1818 | # once we get here, we should have suceeded.
|
---|
1819 | $dbh->commit;
|
---|
1820 | }; # end eval
|
---|
1821 |
|
---|
1822 | if ($@) {
|
---|
1823 | my $msg = $@;
|
---|
1824 | eval { $dbh->rollback; };
|
---|
1825 | _log($dbh, (group_id => $group, entry => "Failed adding reverse zone $zone ($msg)"))
|
---|
1826 | if $config{log_failures};
|
---|
1827 | $dbh->commit; # since we enabled transactions earlier
|
---|
1828 | return ('FAIL',$msg);
|
---|
1829 | } else {
|
---|
1830 | my $retcode = 'OK';
|
---|
1831 | if ($warnstr) {
|
---|
1832 | $resultstr = $warnstr;
|
---|
1833 | $retcode = 'WARN';
|
---|
1834 | }
|
---|
1835 | return ($retcode, $rdns_id);
|
---|
1836 | }
|
---|
1837 |
|
---|
1838 | } # end addRDNS()
|
---|
1839 |
|
---|
1840 |
|
---|
1841 | ## DNSDB::getZoneCount
|
---|
1842 | # Get count of zones in group or groups
|
---|
1843 | # Takes a database handle and hash containing:
|
---|
1844 | # - the "current" group
|
---|
1845 | # - an array of "acceptable" groups
|
---|
1846 | # - a flag for forward/reverse zones
|
---|
1847 | # - Optionally accept a "starts with" and/or "contains" filter argument
|
---|
1848 | # Returns an integer count of the resulting zone list.
|
---|
1849 | sub getZoneCount {
|
---|
1850 | my $dbh = shift;
|
---|
1851 |
|
---|
1852 | my %args = @_;
|
---|
1853 |
|
---|
1854 | my @filterargs;
|
---|
1855 | $args{startwith} = undef if $args{startwith} && $args{startwith} !~ /^(?:[a-z]|0-9)$/;
|
---|
1856 | push @filterargs, "^$args{startwith}" if $args{startwith};
|
---|
1857 | $args{filter} =~ s/\./\[\.\]/g if $args{filter}; # only match literal dots, usually in reverse zones
|
---|
1858 | push @filterargs, $args{filter} if $args{filter};
|
---|
1859 |
|
---|
1860 | my $sql;
|
---|
1861 | # Not as compact, and fix-me-twice if the common bits get wrong, but much easier to read
|
---|
1862 | if ($args{revrec} eq 'n') {
|
---|
1863 | $sql = "SELECT count(*) FROM domains".
|
---|
1864 | " WHERE group_id IN ($args{curgroup}".($args{childlist} ? ",$args{childlist}" : '').")".
|
---|
1865 | ($args{startwith} ? " AND domain ~* ?" : '').
|
---|
1866 | ($args{filter} ? " AND domain ~* ?" : '');
|
---|
1867 | } else {
|
---|
1868 | $sql = "SELECT count(*) FROM revzones".
|
---|
1869 | " WHERE group_id IN ($args{curgroup}".($args{childlist} ? ",$args{childlist}" : '').")".
|
---|
1870 | ($args{startwith} ? " AND CAST(revnet AS VARCHAR) ~* ?" : '').
|
---|
1871 | ($args{filter} ? " AND CAST(revnet AS VARCHAR) ~* ?" : '');
|
---|
1872 | }
|
---|
1873 | my ($count) = $dbh->selectrow_array($sql, undef, @filterargs);
|
---|
1874 | return $count;
|
---|
1875 | } # end getZoneCount()
|
---|
1876 |
|
---|
1877 |
|
---|
1878 | ## DNSDB::getZoneList()
|
---|
1879 | # Get a list of zones in the specified group(s)
|
---|
1880 | # Takes the same arguments as getZoneCount() above
|
---|
1881 | # Returns a reference to an array of hashrefs suitable for feeding to HTML::Template
|
---|
1882 | sub getZoneList {
|
---|
1883 | my $dbh = shift;
|
---|
1884 |
|
---|
1885 | my %args = @_;
|
---|
1886 |
|
---|
1887 | my @zonelist;
|
---|
1888 |
|
---|
1889 | $args{sortorder} = 'ASC' if !grep $args{sortorder}, ('ASC','DESC');
|
---|
1890 | $args{offset} = 0 if !$args{offset} || $args{offset} !~ /^(?:all|\d+)$/;
|
---|
1891 |
|
---|
1892 | my @filterargs;
|
---|
1893 | $args{startwith} = undef if $args{startwith} && $args{startwith} !~ /^(?:[a-z]|0-9)$/;
|
---|
1894 | push @filterargs, "^$args{startwith}" if $args{startwith};
|
---|
1895 | $args{filter} =~ s/\./\[\.\]/g if $args{filter}; # only match literal dots, usually in reverse zones
|
---|
1896 | push @filterargs, $args{filter} if $args{filter};
|
---|
1897 |
|
---|
1898 | my $sql;
|
---|
1899 | # Not as compact, and fix-me-twice if the common bits get wrong, but much easier to read
|
---|
1900 | if ($args{revrec} eq 'n') {
|
---|
1901 | $args{sortby} = 'domain' if !grep $args{sortby}, ('revnet','group','status');
|
---|
1902 | $sql = "SELECT domain_id,domain,status,groups.group_name AS group FROM domains".
|
---|
1903 | " INNER JOIN groups ON domains.group_id=groups.group_id".
|
---|
1904 | " WHERE domains.group_id IN ($args{curgroup}".($args{childlist} ? ",$args{childlist}" : '').")".
|
---|
1905 | ($args{startwith} ? " AND domain ~* ?" : '').
|
---|
1906 | ($args{filter} ? " AND domain ~* ?" : '');
|
---|
1907 | } else {
|
---|
1908 | ##fixme: arguably startwith here is irrelevant. depends on the UI though.
|
---|
1909 | $args{sortby} = 'revnet' if !grep $args{sortby}, ('domain','group','status');
|
---|
1910 | $sql = "SELECT rdns_id,revnet,status,groups.group_name AS group FROM revzones".
|
---|
1911 | " INNER JOIN groups ON revzones.group_id=groups.group_id".
|
---|
1912 | " WHERE revzones.group_id IN ($args{curgroup}".($args{childlist} ? ",$args{childlist}" : '').")".
|
---|
1913 | ($args{startwith} ? " AND CAST(revnet AS VARCHAR) ~* ?" : '').
|
---|
1914 | ($args{filter} ? " AND CAST(revnet AS VARCHAR) ~* ?" : '');
|
---|
1915 | }
|
---|
1916 | # A common tail.
|
---|
1917 | $sql .= " ORDER BY ".($args{sortby} eq 'group' ? 'groups.group_name' : $args{sortby})." $args{sortorder} ".
|
---|
1918 | ($args{offset} eq 'all' ? '' : " LIMIT $config{perpage}".
|
---|
1919 | " OFFSET ".$args{offset}*$config{perpage});
|
---|
1920 | my $sth = $dbh->prepare($sql);
|
---|
1921 | $sth->execute(@filterargs);
|
---|
1922 | my $rownum = 0;
|
---|
1923 |
|
---|
1924 | while (my @data = $sth->fetchrow_array) {
|
---|
1925 | my %row;
|
---|
1926 | $row{domainid} = $data[0];
|
---|
1927 | $row{domain} = $data[1];
|
---|
1928 | $row{status} = $data[2];
|
---|
1929 | $row{group} = $data[3];
|
---|
1930 | push @zonelist, \%row;
|
---|
1931 | }
|
---|
1932 |
|
---|
1933 | return \@zonelist;
|
---|
1934 | } # end getZoneList()
|
---|
1935 |
|
---|
1936 |
|
---|
1937 | ## DNSDB::addGroup()
|
---|
1938 | # Add a group
|
---|
1939 | # Takes a database handle, group name, parent group, hashref for permissions,
|
---|
1940 | # and optional template-vs-cloneme flag for the default records
|
---|
1941 | # Returns a status code and message
|
---|
1942 | sub addGroup {
|
---|
1943 | $errstr = '';
|
---|
1944 | my $dbh = shift;
|
---|
1945 | my $groupname = shift;
|
---|
1946 | my $pargroup = shift;
|
---|
1947 | my $permissions = shift;
|
---|
1948 |
|
---|
1949 | # 0 indicates "custom", hardcoded.
|
---|
1950 | # Any other value clones that group's default records, if it exists.
|
---|
1951 | my $inherit = shift || 0;
|
---|
1952 | ##fixme: need a flag to indicate clone records or <?> ?
|
---|
1953 |
|
---|
1954 | # Allow transactions, and raise an exception on errors so we can catch it later.
|
---|
1955 | # Use local to make sure these get "reset" properly on exiting this block
|
---|
1956 | local $dbh->{AutoCommit} = 0;
|
---|
1957 | local $dbh->{RaiseError} = 1;
|
---|
1958 |
|
---|
1959 | my ($group_id) = $dbh->selectrow_array("SELECT group_id FROM groups WHERE group_name=?", undef, ($groupname));
|
---|
1960 |
|
---|
1961 | return ('FAIL', "Group already exists") if $group_id;
|
---|
1962 |
|
---|
1963 | # Wrap all the SQL in a transaction
|
---|
1964 | eval {
|
---|
1965 | $dbh->do("INSERT INTO groups (parent_group_id,group_name) VALUES (?,?)", undef, ($pargroup, $groupname) );
|
---|
1966 |
|
---|
1967 | my ($groupid) = $dbh->selectrow_array("SELECT currval('groups_group_id_seq')");
|
---|
1968 |
|
---|
1969 | # We work through the whole set of permissions instead of specifying them so
|
---|
1970 | # that when we add a new permission, we don't have to change the code anywhere
|
---|
1971 | # that doesn't explicitly deal with that specific permission.
|
---|
1972 | my @permvals;
|
---|
1973 | foreach (@permtypes) {
|
---|
1974 | if (!defined ($permissions->{$_})) {
|
---|
1975 | push @permvals, 0;
|
---|
1976 | } else {
|
---|
1977 | push @permvals, $permissions->{$_};
|
---|
1978 | }
|
---|
1979 | }
|
---|
1980 | $dbh->do("INSERT INTO permissions (group_id,$permlist) values (?".',?'x($#permtypes+1).")",
|
---|
1981 | undef, ($groupid, @permvals) );
|
---|
1982 | my ($permid) = $dbh->selectrow_array("SELECT currval('permissions_permission_id_seq')");
|
---|
1983 | $dbh->do("UPDATE groups SET permission_id=$permid WHERE group_id=$groupid");
|
---|
1984 |
|
---|
1985 | # Default records
|
---|
1986 | my $sthf = $dbh->prepare("INSERT INTO default_records (group_id,host,type,val,distance,weight,port,ttl) ".
|
---|
1987 | "VALUES ($groupid,?,?,?,?,?,?,?)");
|
---|
1988 | my $sthr = $dbh->prepare("INSERT INTO default_rev_records (group_id,host,type,val,ttl) ".
|
---|
1989 | "VALUES ($groupid,?,?,?,?)");
|
---|
1990 | if ($inherit) {
|
---|
1991 | # Duplicate records from parent. Actually relying on inherited records feels
|
---|
1992 | # very fragile, and it would be problematic to roll over at a later time.
|
---|
1993 | my $sth2 = $dbh->prepare("SELECT host,type,val,distance,weight,port,ttl FROM default_records WHERE group_id=?");
|
---|
1994 | $sth2->execute($pargroup);
|
---|
1995 | while (my @clonedata = $sth2->fetchrow_array) {
|
---|
1996 | $sthf->execute(@clonedata);
|
---|
1997 | }
|
---|
1998 | # And now the reverse records
|
---|
1999 | $sth2 = $dbh->prepare("SELECT host,type,val,ttl FROM default_rev_records WHERE group_id=?");
|
---|
2000 | $sth2->execute($pargroup);
|
---|
2001 | while (my @clonedata = $sth2->fetchrow_array) {
|
---|
2002 | $sthr->execute(@clonedata);
|
---|
2003 | }
|
---|
2004 | } else {
|
---|
2005 | ##fixme: Hardcoding is Bad, mmmmkaaaay?
|
---|
2006 | # reasonable basic defaults for SOA, MX, NS, and minimal hosting
|
---|
2007 | # could load from a config file, but somewhere along the line we need hardcoded bits.
|
---|
2008 | $sthf->execute('ns1.example.com:hostmaster.example.com', 6, '10800:3600:604800:10800', 0, 0, 0, 86400);
|
---|
2009 | $sthf->execute('DOMAIN', 1, '192.168.4.2', 0, 0, 0, 7200);
|
---|
2010 | $sthf->execute('DOMAIN', 15, 'mx.example.com', 10, 0, 0, 7200);
|
---|
2011 | $sthf->execute('DOMAIN', 2, 'ns1.example.com', 0, 0, 0, 7200);
|
---|
2012 | $sthf->execute('DOMAIN', 2, 'ns2.example.com', 0, 0, 0, 7200);
|
---|
2013 | $sthf->execute('www.DOMAIN', 5, 'DOMAIN', 0, 0, 0, 7200);
|
---|
2014 | # reasonable basic defaults for generic reverse zone. Same as initial SQL tabledef.
|
---|
2015 | $sthr->execute('hostmaster.ADMINDOMAIN:ns1.ADMINDOMAIN', 6, '10800:3600:604800:10800', 86400);
|
---|
2016 | $sthr->execute('unused-%r.ADMINDOMAIN', 65283, 'ZONE', 3600);
|
---|
2017 | }
|
---|
2018 |
|
---|
2019 | _log($dbh, (group_id => $pargroup, entry => "Added group $groupname") );
|
---|
2020 |
|
---|
2021 | # once we get here, we should have suceeded.
|
---|
2022 | $dbh->commit;
|
---|
2023 | }; # end eval
|
---|
2024 |
|
---|
2025 | if ($@) {
|
---|
2026 | my $msg = $@;
|
---|
2027 | eval { $dbh->rollback; };
|
---|
2028 | if ($config{log_failures}) {
|
---|
2029 | _log($dbh, (group_id => $pargroup, entry => "Failed to add group $groupname: $msg") );
|
---|
2030 | $dbh->commit;
|
---|
2031 | }
|
---|
2032 | return ('FAIL',$msg);
|
---|
2033 | }
|
---|
2034 |
|
---|
2035 | return ('OK','OK');
|
---|
2036 | } # end addGroup()
|
---|
2037 |
|
---|
2038 |
|
---|
2039 | ## DNSDB::delGroup()
|
---|
2040 | # Delete a group.
|
---|
2041 | # Takes a group ID
|
---|
2042 | # Returns a status code and message
|
---|
2043 | sub delGroup {
|
---|
2044 | my $dbh = shift;
|
---|
2045 | my $groupid = shift;
|
---|
2046 |
|
---|
2047 | # Allow transactions, and raise an exception on errors so we can catch it later.
|
---|
2048 | # Use local to make sure these get "reset" properly on exiting this block
|
---|
2049 | local $dbh->{AutoCommit} = 0;
|
---|
2050 | local $dbh->{RaiseError} = 1;
|
---|
2051 |
|
---|
2052 | ##fixme: locate "knowable" error conditions and deal with them before the eval
|
---|
2053 | # ... or inside, whatever.
|
---|
2054 | # -> domains still exist in group
|
---|
2055 | # -> ...
|
---|
2056 | my $failmsg = '';
|
---|
2057 | my $resultmsg = '';
|
---|
2058 |
|
---|
2059 | # collect some pieces for logging and error messages
|
---|
2060 | my $groupname = groupName($dbh,$groupid);
|
---|
2061 | my $parid = parentID($dbh, (id => $groupid, type => 'group'));
|
---|
2062 |
|
---|
2063 | # Wrap all the SQL in a transaction
|
---|
2064 | eval {
|
---|
2065 | # Check for Things in the group
|
---|
2066 | $failmsg = "Can't remove group $groupname";
|
---|
2067 | my ($grpcnt) = $dbh->selectrow_array("SELECT count(*) FROM groups WHERE parent_group_id=?", undef, ($groupid));
|
---|
2068 | die "$grpcnt groups still in group\n" if $grpcnt;
|
---|
2069 | my ($domcnt) = $dbh->selectrow_array("SELECT count(*) FROM domains WHERE group_id=?", undef, ($groupid));
|
---|
2070 | die "$domcnt domains still in group\n" if $domcnt;
|
---|
2071 | my ($usercnt) = $dbh->selectrow_array("SELECT count(*) FROM users WHERE group_id=?", undef, ($groupid));
|
---|
2072 | die "$usercnt users still in group\n" if $usercnt;
|
---|
2073 |
|
---|
2074 | $failmsg = "Failed to delete default records for $groupname";
|
---|
2075 | $dbh->do("DELETE from default_records WHERE group_id=?", undef, ($groupid));
|
---|
2076 | $failmsg = "Failed to delete default reverse records for $groupname";
|
---|
2077 | $dbh->do("DELETE from default_rev_records WHERE group_id=?", undef, ($groupid));
|
---|
2078 | $failmsg = "Failed to remove group $groupname";
|
---|
2079 | $dbh->do("DELETE from groups WHERE group_id=?", undef, ($groupid));
|
---|
2080 |
|
---|
2081 | _log($dbh, (group_id => $parid, entry => "Deleted group $groupname"));
|
---|
2082 | $resultmsg = "Deleted group $groupname";
|
---|
2083 |
|
---|
2084 | # once we get here, we should have suceeded.
|
---|
2085 | $dbh->commit;
|
---|
2086 | }; # end eval
|
---|
2087 |
|
---|
2088 | if ($@) {
|
---|
2089 | my $msg = $@;
|
---|
2090 | eval { $dbh->rollback; };
|
---|
2091 | if ($config{log_failures}) {
|
---|
2092 | _log($dbh, (group_id => $parid, entry => "$failmsg: $msg"));
|
---|
2093 | $dbh->commit; # since we enabled transactions earlier
|
---|
2094 | }
|
---|
2095 | return ('FAIL',"$failmsg: $msg");
|
---|
2096 | }
|
---|
2097 |
|
---|
2098 | return ('OK',$resultmsg);
|
---|
2099 | } # end delGroup()
|
---|
2100 |
|
---|
2101 |
|
---|
2102 | ## DNSDB::getChildren()
|
---|
2103 | # Get a list of all groups whose parent^n is group <n>
|
---|
2104 | # Takes a database handle, group ID, reference to an array to put the group IDs in,
|
---|
2105 | # and an optional flag to return only immediate children or all children-of-children
|
---|
2106 | # default to returning all children
|
---|
2107 | # Calls itself
|
---|
2108 | sub getChildren {
|
---|
2109 | $errstr = '';
|
---|
2110 | my $dbh = shift;
|
---|
2111 | my $rootgroup = shift;
|
---|
2112 | my $groupdest = shift;
|
---|
2113 | my $immed = shift || 'all';
|
---|
2114 |
|
---|
2115 | # special break for default group; otherwise we get stuck.
|
---|
2116 | if ($rootgroup == 1) {
|
---|
2117 | # by definition, group 1 is the Root Of All Groups
|
---|
2118 | my $sth = $dbh->prepare("SELECT group_id FROM groups WHERE NOT (group_id=1)".
|
---|
2119 | ($immed ne 'all' ? " AND parent_group_id=1" : ''));
|
---|
2120 | $sth->execute;
|
---|
2121 | while (my @this = $sth->fetchrow_array) {
|
---|
2122 | push @$groupdest, @this;
|
---|
2123 | }
|
---|
2124 | } else {
|
---|
2125 | my $sth = $dbh->prepare("SELECT group_id FROM groups WHERE parent_group_id=?");
|
---|
2126 | $sth->execute($rootgroup);
|
---|
2127 | return if $sth->rows == 0;
|
---|
2128 | my @grouplist;
|
---|
2129 | while (my ($group) = $sth->fetchrow_array) {
|
---|
2130 | push @$groupdest, $group;
|
---|
2131 | getChildren($dbh,$group,$groupdest) if $immed eq 'all';
|
---|
2132 | }
|
---|
2133 | }
|
---|
2134 | } # end getChildren()
|
---|
2135 |
|
---|
2136 |
|
---|
2137 | ## DNSDB::groupName()
|
---|
2138 | # Return the group name based on a group ID
|
---|
2139 | # Takes a database handle and the group ID
|
---|
2140 | # Returns the group name or undef on failure
|
---|
2141 | sub groupName {
|
---|
2142 | $errstr = '';
|
---|
2143 | my $dbh = shift;
|
---|
2144 | my $groupid = shift;
|
---|
2145 | my $sth = $dbh->prepare("SELECT group_name FROM groups WHERE group_id=?");
|
---|
2146 | $sth->execute($groupid);
|
---|
2147 | my ($groupname) = $sth->fetchrow_array();
|
---|
2148 | $errstr = $DBI::errstr if !$groupname;
|
---|
2149 | return $groupname if $groupname;
|
---|
2150 | } # end groupName
|
---|
2151 |
|
---|
2152 |
|
---|
2153 | ## DNSDB::groupID()
|
---|
2154 | # Return the group ID based on the group name
|
---|
2155 | # Takes a database handle and the group name
|
---|
2156 | # Returns the group ID or undef on failure
|
---|
2157 | sub groupID {
|
---|
2158 | $errstr = '';
|
---|
2159 | my $dbh = shift;
|
---|
2160 | my $group = shift;
|
---|
2161 | my ($grpid) = $dbh->selectrow_array("SELECT group_id FROM groups WHERE group=?", undef, ($group) );
|
---|
2162 | $errstr = $DBI::errstr if !$grpid;
|
---|
2163 | return $grpid if $grpid;
|
---|
2164 | } # end groupID()
|
---|
2165 |
|
---|
2166 |
|
---|
2167 | ## DNSDB::addUser()
|
---|
2168 | # Add a user.
|
---|
2169 | # Takes a DB handle, username, group ID, password, state (active/inactive).
|
---|
2170 | # Optionally accepts:
|
---|
2171 | # user type (user/admin) - defaults to user
|
---|
2172 | # permissions string - defaults to inherit from group
|
---|
2173 | # three valid forms:
|
---|
2174 | # i - Inherit permissions
|
---|
2175 | # c:<user_id> - Clone permissions from <user_id>
|
---|
2176 | # C:<permission list> - Set these specific permissions
|
---|
2177 | # first name - defaults to username
|
---|
2178 | # last name - defaults to blank
|
---|
2179 | # phone - defaults to blank (could put other data within column def)
|
---|
2180 | # Returns (OK,<uid>) on success, (FAIL,<message>) on failure
|
---|
2181 | sub addUser {
|
---|
2182 | $errstr = '';
|
---|
2183 | my $dbh = shift;
|
---|
2184 | my $username = shift;
|
---|
2185 | my $group = shift;
|
---|
2186 | my $pass = shift;
|
---|
2187 | my $state = shift;
|
---|
2188 |
|
---|
2189 | return ('FAIL', "Missing one or more required entries") if !defined($state);
|
---|
2190 | return ('FAIL', "Username must not be blank") if !$username;
|
---|
2191 |
|
---|
2192 | my $type = shift || 'u'; # create limited users by default - fwiw, not sure yet how this will interact with ACLs
|
---|
2193 |
|
---|
2194 | my $permstring = shift || 'i'; # default is to inhert permissions from group
|
---|
2195 |
|
---|
2196 | my $fname = shift || $username;
|
---|
2197 | my $lname = shift || '';
|
---|
2198 | my $phone = shift || ''; # not going format-check
|
---|
2199 |
|
---|
2200 | my $sth = $dbh->prepare("SELECT user_id FROM users WHERE username=?");
|
---|
2201 | my $user_id;
|
---|
2202 |
|
---|
2203 | # quick check to start to see if we've already got one
|
---|
2204 | $sth->execute($username);
|
---|
2205 | ($user_id) = $sth->fetchrow_array;
|
---|
2206 |
|
---|
2207 | return ('FAIL', "User already exists") if $user_id;
|
---|
2208 |
|
---|
2209 | # Allow transactions, and raise an exception on errors so we can catch it later.
|
---|
2210 | # Use local to make sure these get "reset" properly on exiting this block
|
---|
2211 | local $dbh->{AutoCommit} = 0;
|
---|
2212 | local $dbh->{RaiseError} = 1;
|
---|
2213 |
|
---|
2214 | # Wrap all the SQL in a transaction
|
---|
2215 | eval {
|
---|
2216 | # insert the user... note we set inherited perms by default since
|
---|
2217 | # it's simple and cleans up some other bits of state
|
---|
2218 | my $sth = $dbh->prepare("INSERT INTO users ".
|
---|
2219 | "(group_id,username,password,firstname,lastname,phone,type,status,permission_id,inherit_perm) ".
|
---|
2220 | "VALUES (?,?,?,?,?,?,?,?,(SELECT permission_id FROM permissions WHERE group_id=?),'t')");
|
---|
2221 | $sth->execute($group,$username,unix_md5_crypt($pass),$fname,$lname,$phone,$type,$state,$group);
|
---|
2222 |
|
---|
2223 | # get the ID...
|
---|
2224 | ($user_id) = $dbh->selectrow_array("SELECT currval('users_user_id_seq')");
|
---|
2225 |
|
---|
2226 | # Permissions! Gotta set'em all!
|
---|
2227 | die "Invalid permission string $permstring"
|
---|
2228 | if $permstring !~ /^(?:
|
---|
2229 | i # inherit
|
---|
2230 | |c:\d+ # clone
|
---|
2231 | # custom. no, the leading , is not a typo
|
---|
2232 | |C:(?:,(?:group|user|domain|record|self)_(?:edit|create|delete))*
|
---|
2233 | )$/x;
|
---|
2234 | # bleh. I'd call another function to do my dirty work, but we're in the middle of a transaction already.
|
---|
2235 | if ($permstring ne 'i') {
|
---|
2236 | # for cloned or custom permissions, we have to create a new permissions entry.
|
---|
2237 | my $clonesrc = $group;
|
---|
2238 | if ($permstring =~ /^c:(\d+)/) { $clonesrc = $1; }
|
---|
2239 | $dbh->do("INSERT INTO permissions ($permlist,user_id) ".
|
---|
2240 | "SELECT $permlist,? FROM permissions WHERE permission_id=".
|
---|
2241 | "(SELECT permission_id FROM permissions WHERE ".($permstring =~ /^c:/ ? 'user' : 'group')."_id=?)",
|
---|
2242 | undef, ($user_id,$clonesrc) );
|
---|
2243 | $dbh->do("UPDATE users SET permission_id=".
|
---|
2244 | "(SELECT permission_id FROM permissions WHERE user_id=?) ".
|
---|
2245 | "WHERE user_id=?", undef, ($user_id, $user_id) );
|
---|
2246 | }
|
---|
2247 | if ($permstring =~ /^C:/) {
|
---|
2248 | # finally for custom permissions, we set the passed-in permissions (and unset
|
---|
2249 | # any that might have been brought in by the clone operation above)
|
---|
2250 | my ($permid) = $dbh->selectrow_array("SELECT permission_id FROM permissions WHERE user_id=?",
|
---|
2251 | undef, ($user_id) );
|
---|
2252 | foreach (@permtypes) {
|
---|
2253 | if ($permstring =~ /,$_/) {
|
---|
2254 | $dbh->do("UPDATE permissions SET $_='t' WHERE permission_id=?", undef, ($permid) );
|
---|
2255 | } else {
|
---|
2256 | $dbh->do("UPDATE permissions SET $_='f' WHERE permission_id=?", undef, ($permid) );
|
---|
2257 | }
|
---|
2258 | }
|
---|
2259 | }
|
---|
2260 |
|
---|
2261 | $dbh->do("UPDATE users SET inherit_perm='n' WHERE user_id=?", undef, ($user_id) );
|
---|
2262 |
|
---|
2263 | ##fixme: add another table to hold name/email for log table?
|
---|
2264 |
|
---|
2265 | _log($dbh, (group_id => $group, entry => "Added user $username ($fname $lname)"));
|
---|
2266 | # once we get here, we should have suceeded.
|
---|
2267 | $dbh->commit;
|
---|
2268 | }; # end eval
|
---|
2269 |
|
---|
2270 | if ($@) {
|
---|
2271 | my $msg = $@;
|
---|
2272 | eval { $dbh->rollback; };
|
---|
2273 | if ($config{log_failures}) {
|
---|
2274 | _log($dbh, (group_id => $group, entry => "Error adding user $username: $msg"));
|
---|
2275 | $dbh->commit; # since we enabled transactions earlier
|
---|
2276 | }
|
---|
2277 | return ('FAIL',"Error adding user $username: $msg");
|
---|
2278 | }
|
---|
2279 |
|
---|
2280 | return ('OK',"User $username ($fname $lname) added");
|
---|
2281 | } # end addUser
|
---|
2282 |
|
---|
2283 |
|
---|
2284 | ## DNSDB::checkUser()
|
---|
2285 | # Check user/pass combo on login
|
---|
2286 | sub checkUser {
|
---|
2287 | my $dbh = shift;
|
---|
2288 | my $user = shift;
|
---|
2289 | my $inpass = shift;
|
---|
2290 |
|
---|
2291 | my $sth = $dbh->prepare("SELECT user_id,group_id,password,firstname,lastname FROM users WHERE username=?");
|
---|
2292 | $sth->execute($user);
|
---|
2293 | my ($uid,$gid,$pass,$fname,$lname) = $sth->fetchrow_array;
|
---|
2294 | my $loginfailed = 1 if !defined($uid);
|
---|
2295 |
|
---|
2296 | if ($pass =~ m|^\$1\$([A-Za-z0-9/.]+)\$|) {
|
---|
2297 | $loginfailed = 1 if $pass ne unix_md5_crypt($inpass,$1);
|
---|
2298 | } else {
|
---|
2299 | $loginfailed = 1 if $pass ne $inpass;
|
---|
2300 | }
|
---|
2301 |
|
---|
2302 | # nnnngggg
|
---|
2303 | return ($uid, $gid);
|
---|
2304 | } # end checkUser
|
---|
2305 |
|
---|
2306 |
|
---|
2307 | ## DNSDB:: updateUser()
|
---|
2308 | # Update general data about user
|
---|
2309 | sub updateUser {
|
---|
2310 | my $dbh = shift;
|
---|
2311 |
|
---|
2312 | ##fixme: tweak calling convention so that we can update any given bit of data
|
---|
2313 | my $uid = shift;
|
---|
2314 | my $username = shift;
|
---|
2315 | my $group = shift;
|
---|
2316 | my $pass = shift;
|
---|
2317 | my $state = shift;
|
---|
2318 | my $type = shift || 'u';
|
---|
2319 | my $fname = shift || $username;
|
---|
2320 | my $lname = shift || '';
|
---|
2321 | my $phone = shift || ''; # not going format-check
|
---|
2322 |
|
---|
2323 | my $resultmsg = '';
|
---|
2324 |
|
---|
2325 | # Allow transactions, and raise an exception on errors so we can catch it later.
|
---|
2326 | # Use local to make sure these get "reset" properly on exiting this block
|
---|
2327 | local $dbh->{AutoCommit} = 0;
|
---|
2328 | local $dbh->{RaiseError} = 1;
|
---|
2329 |
|
---|
2330 | my $sth;
|
---|
2331 |
|
---|
2332 | # Password can be left blank; if so we assume there's one on file.
|
---|
2333 | # Actual blank passwords are bad, mm'kay?
|
---|
2334 | if (!$pass) {
|
---|
2335 | ($pass) = $dbh->selectrow_array("SELECT password FROM users WHERE user_id=?", undef, ($uid));
|
---|
2336 | } else {
|
---|
2337 | $pass = unix_md5_crypt($pass);
|
---|
2338 | }
|
---|
2339 |
|
---|
2340 | eval {
|
---|
2341 | $dbh->do("UPDATE users SET username=?, password=?, firstname=?, lastname=?, phone=?, type=?, status=?".
|
---|
2342 | " WHERE user_id=?", undef, ($username, $pass, $fname, $lname, $phone, $type, $state, $uid));
|
---|
2343 | $resultmsg = "Updated user info for $username ($fname $lname)";
|
---|
2344 | _log($dbh, group_id => $group, entry => $resultmsg);
|
---|
2345 | $dbh->commit;
|
---|
2346 | };
|
---|
2347 | if ($@) {
|
---|
2348 | my $msg = $@;
|
---|
2349 | eval { $dbh->rollback; };
|
---|
2350 | if ($config{log_failures}) {
|
---|
2351 | _log($dbh, (group_id => $group, entry => "Error updating user $username: $msg"));
|
---|
2352 | $dbh->commit; # since we enabled transactions earlier
|
---|
2353 | }
|
---|
2354 | return ('FAIL',"Error updating user $username: $msg");
|
---|
2355 | }
|
---|
2356 |
|
---|
2357 | return ('OK',$resultmsg);
|
---|
2358 | } # end updateUser()
|
---|
2359 |
|
---|
2360 |
|
---|
2361 | ## DNSDB::delUser()
|
---|
2362 | # Delete a user.
|
---|
2363 | # Takes a database handle and user ID
|
---|
2364 | # Returns a success/failure code and matching message
|
---|
2365 | sub delUser {
|
---|
2366 | my $dbh = shift;
|
---|
2367 | my $userid = shift;
|
---|
2368 |
|
---|
2369 | return ('FAIL',"Bad userid") if !defined($userid);
|
---|
2370 |
|
---|
2371 | my $userdata = getUserData($dbh, $userid);
|
---|
2372 |
|
---|
2373 | # Allow transactions, and raise an exception on errors so we can catch it later.
|
---|
2374 | # Use local to make sure these get "reset" properly on exiting this block
|
---|
2375 | local $dbh->{AutoCommit} = 0;
|
---|
2376 | local $dbh->{RaiseError} = 1;
|
---|
2377 |
|
---|
2378 | eval {
|
---|
2379 | $dbh->do("DELETE FROM users WHERE user_id=?", undef, ($userid));
|
---|
2380 | _log($dbh, (group_id => $userdata->{group_id},
|
---|
2381 | entry => "Deleted user ID $userid/".$userdata->{username}.
|
---|
2382 | " (".$userdata->{firstname}." ".$userdata->{lastname}.")") );
|
---|
2383 | $dbh->commit;
|
---|
2384 | };
|
---|
2385 | if ($@) {
|
---|
2386 | my $msg = $@;
|
---|
2387 | eval { $dbh->rollback; };
|
---|
2388 | if ($config{log_failures}) {
|
---|
2389 | _log($dbh, (group_id => $userdata->{group_id}, entry => "Error deleting user ID ".
|
---|
2390 | "$userid/".$userdata->{username}.": $msg") );
|
---|
2391 | $dbh->commit;
|
---|
2392 | }
|
---|
2393 | return ('FAIL',"Error deleting user $userid/".$userdata->{username}.": $msg");
|
---|
2394 | }
|
---|
2395 |
|
---|
2396 | return ('OK',"Deleted user ".$userdata->{username}." (".$userdata->{firstname}." ".$userdata->{lastname}.")");
|
---|
2397 | } # end delUser
|
---|
2398 |
|
---|
2399 |
|
---|
2400 | ## DNSDB::userFullName()
|
---|
2401 | # Return a pretty string!
|
---|
2402 | # Takes a user_id and optional printf-ish string to indicate which pieces where:
|
---|
2403 | # %u for the username
|
---|
2404 | # %f for the first name
|
---|
2405 | # %l for the last name
|
---|
2406 | # All other text in the passed string will be left as-is.
|
---|
2407 | ##fixme: need a "smart" option too, so that missing/null/blank first/last names don't give funky output
|
---|
2408 | sub userFullName {
|
---|
2409 | $errstr = '';
|
---|
2410 | my $dbh = shift;
|
---|
2411 | my $userid = shift;
|
---|
2412 | my $fullformat = shift || '%f %l (%u)';
|
---|
2413 | my $sth = $dbh->prepare("select username,firstname,lastname from users where user_id=?");
|
---|
2414 | $sth->execute($userid);
|
---|
2415 | my ($uname,$fname,$lname) = $sth->fetchrow_array();
|
---|
2416 | $errstr = $DBI::errstr if !$uname;
|
---|
2417 |
|
---|
2418 | $fullformat =~ s/\%u/$uname/g;
|
---|
2419 | $fullformat =~ s/\%f/$fname/g;
|
---|
2420 | $fullformat =~ s/\%l/$lname/g;
|
---|
2421 |
|
---|
2422 | return $fullformat;
|
---|
2423 | } # end userFullName
|
---|
2424 |
|
---|
2425 |
|
---|
2426 | ## DNSDB::userStatus()
|
---|
2427 | # Sets and/or returns a user's status
|
---|
2428 | # Takes a database handle, user ID and optionally a status argument
|
---|
2429 | # Returns undef on errors.
|
---|
2430 | sub userStatus {
|
---|
2431 | my $dbh = shift;
|
---|
2432 | my $id = shift;
|
---|
2433 | my $newstatus = shift || 'mu';
|
---|
2434 |
|
---|
2435 | return undef if $id !~ /^\d+$/;
|
---|
2436 |
|
---|
2437 | my $userdata = getUserData($dbh, $id);
|
---|
2438 |
|
---|
2439 | # Allow transactions, and raise an exception on errors so we can catch it later.
|
---|
2440 | # Use local to make sure these get "reset" properly on exiting this block
|
---|
2441 | local $dbh->{AutoCommit} = 0;
|
---|
2442 | local $dbh->{RaiseError} = 1;
|
---|
2443 |
|
---|
2444 | if ($newstatus ne 'mu') {
|
---|
2445 | # ooo, fun! let's see what we were passed for status
|
---|
2446 | eval {
|
---|
2447 | $newstatus = 0 if $newstatus eq 'useroff';
|
---|
2448 | $newstatus = 1 if $newstatus eq 'useron';
|
---|
2449 | $dbh->do("UPDATE users SET status=? WHERE user_id=?", undef, ($newstatus, $id));
|
---|
2450 |
|
---|
2451 | $resultstr = ($newstatus ? 'Enabled' : 'Disabled')." user ".$userdata->{username}.
|
---|
2452 | " (".$userdata->{firstname}." ".$userdata->{lastname}.")";
|
---|
2453 |
|
---|
2454 | my %loghash;
|
---|
2455 | $loghash{group_id} = parentID($dbh, (id => $id, type => 'user'));
|
---|
2456 | $loghash{entry} = $resultstr;
|
---|
2457 | _log($dbh, %loghash);
|
---|
2458 |
|
---|
2459 | $dbh->commit;
|
---|
2460 | };
|
---|
2461 | if ($@) {
|
---|
2462 | my $msg = $@;
|
---|
2463 | eval { $dbh->rollback; };
|
---|
2464 | $resultstr = '';
|
---|
2465 | $errstr = $msg;
|
---|
2466 | ##fixme: failure logging?
|
---|
2467 | return;
|
---|
2468 | }
|
---|
2469 | }
|
---|
2470 |
|
---|
2471 | my ($status) = $dbh->selectrow_array("SELECT status FROM users WHERE user_id=?", undef, ($id));
|
---|
2472 | return $status;
|
---|
2473 | } # end userStatus()
|
---|
2474 |
|
---|
2475 |
|
---|
2476 | ## DNSDB::getUserData()
|
---|
2477 | # Get misc user data for display
|
---|
2478 | sub getUserData {
|
---|
2479 | my $dbh = shift;
|
---|
2480 | my $uid = shift;
|
---|
2481 |
|
---|
2482 | my $sth = $dbh->prepare("SELECT group_id,username,firstname,lastname,phone,type,status,inherit_perm ".
|
---|
2483 | "FROM users WHERE user_id=?");
|
---|
2484 | $sth->execute($uid);
|
---|
2485 | return $sth->fetchrow_hashref();
|
---|
2486 |
|
---|
2487 | } # end getUserData()
|
---|
2488 |
|
---|
2489 |
|
---|
2490 | ## DNSDB::getSOA()
|
---|
2491 | # Return all suitable fields from an SOA record in separate elements of a hash
|
---|
2492 | # Takes a database handle, default/live flag, domain/reverse flag, and parent ID
|
---|
2493 | sub getSOA {
|
---|
2494 | $errstr = '';
|
---|
2495 | my $dbh = shift;
|
---|
2496 | my $def = shift;
|
---|
2497 | my $rev = shift;
|
---|
2498 | my $id = shift;
|
---|
2499 | my %ret;
|
---|
2500 |
|
---|
2501 | # (ab)use distance and weight columns to store SOA data? can't for default_rev_records...
|
---|
2502 | # - should really attach serial to the zone parent somewhere
|
---|
2503 |
|
---|
2504 | my $sql = "SELECT record_id,host,val,ttl from "._rectable($def,$rev).
|
---|
2505 | " WHERE "._recparent($def,$rev)." = ? AND type=$reverse_typemap{SOA}";
|
---|
2506 |
|
---|
2507 | my $sth = $dbh->prepare($sql);
|
---|
2508 | $sth->execute($id);
|
---|
2509 | ##fixme: stick a flag somewhere if the record doesn't exist. by the API, this is an impossible case, but...
|
---|
2510 |
|
---|
2511 | my ($recid,$host,$val,$ttl) = $sth->fetchrow_array() or return;
|
---|
2512 | my ($contact,$prins) = split /:/, $host;
|
---|
2513 | my ($refresh,$retry,$expire,$minttl) = split /:/, $val;
|
---|
2514 |
|
---|
2515 | $ret{recid} = $recid;
|
---|
2516 | $ret{ttl} = $ttl;
|
---|
2517 | # $ret{serial} = $serial; # ca't use distance for serial with default_rev_records
|
---|
2518 | $ret{prins} = $prins;
|
---|
2519 | $ret{contact} = $contact;
|
---|
2520 | $ret{refresh} = $refresh;
|
---|
2521 | $ret{retry} = $retry;
|
---|
2522 | $ret{expire} = $expire;
|
---|
2523 | $ret{minttl} = $minttl;
|
---|
2524 |
|
---|
2525 | return %ret;
|
---|
2526 | } # end getSOA()
|
---|
2527 |
|
---|
2528 |
|
---|
2529 | ## DNSDB::updateSOA()
|
---|
2530 | # Update the specified SOA record
|
---|
2531 | # Takes a database handle, default/live flag, forward/reverse flag, and SOA data hash
|
---|
2532 | # Returns a two-element list with a result code and message
|
---|
2533 | sub updateSOA {
|
---|
2534 | my $dbh = shift;
|
---|
2535 | my $defrec = shift;
|
---|
2536 | my $revrec = shift;
|
---|
2537 |
|
---|
2538 | my %soa = @_;
|
---|
2539 |
|
---|
2540 | my %oldsoa = getSOA($dbh, $defrec, $revrec, $soa{recid});
|
---|
2541 |
|
---|
2542 | # Allow transactions, and raise an exception on errors so we can catch it later.
|
---|
2543 | # Use local to make sure these get "reset" properly on exiting this block
|
---|
2544 | local $dbh->{AutoCommit} = 0;
|
---|
2545 | local $dbh->{RaiseError} = 1;
|
---|
2546 |
|
---|
2547 | my $msg;
|
---|
2548 |
|
---|
2549 | eval {
|
---|
2550 | ##fixme: data validation: make sure {recid} is really the SOA for {parent}
|
---|
2551 | my $sql = "UPDATE "._rectable($defrec, $revrec)." SET host=?, val=?, ttl=? WHERE record_id=? AND type=6";
|
---|
2552 | $dbh->do($sql, undef, ("$soa{contact}:$soa{prins}", "$soa{refresh}:$soa{retry}:$soa{expire}:$soa{minttl}",
|
---|
2553 | $soa{ttl}, $soa{recid}) );
|
---|
2554 |
|
---|
2555 | $msg = "Updated ".($defrec eq 'y' ? 'default ' : '')."SOA for ".
|
---|
2556 | ($defrec eq 'y' ? groupName($dbh, $soa{recid}) :
|
---|
2557 | ($revrec eq 'n' ? domainName($dbh, $soa{recid}) : revName($dbh, $soa{recid}) ) ).
|
---|
2558 | ": (ns $oldsoa{prins}, contact $oldsoa{contact}, refresh $oldsoa{refresh},".
|
---|
2559 | " retry $oldsoa{retry}, expire $oldsoa{expire}, minTTL $oldsoa{minttl}, TTL $oldsoa{ttl}) to ".
|
---|
2560 | "(ns $soa{prins}, contact $soa{contact}, refresh $soa{refresh},".
|
---|
2561 | " retry $soa{retry}, expire $soa{expire}, minTTL $soa{minttl}, TTL $soa{ttl})";
|
---|
2562 |
|
---|
2563 | # _log($dbh, (rdns_id => $rdns_id, user_id => $userinfo{id}, group_id => $group,
|
---|
2564 | # username => $userinfo{name}, entry => $msg) );
|
---|
2565 |
|
---|
2566 | $dbh->commit;
|
---|
2567 | };
|
---|
2568 | if ($@) {
|
---|
2569 | $msg = $@;
|
---|
2570 | eval { $dbh->rollback; };
|
---|
2571 | return ('FAIL',$msg);
|
---|
2572 | } else {
|
---|
2573 | return ('OK', $msg);
|
---|
2574 | }
|
---|
2575 | } # end updateSOA()
|
---|
2576 |
|
---|
2577 |
|
---|
2578 | ## DNSDB::getRecLine()
|
---|
2579 | # Return all data fields for a zone record in separate elements of a hash
|
---|
2580 | # Takes a database handle, default/live flag, forward/reverse flag, and record ID
|
---|
2581 | sub getRecLine {
|
---|
2582 | $errstr = '';
|
---|
2583 | my $dbh = shift;
|
---|
2584 | my $defrec = shift;
|
---|
2585 | my $revrec = shift;
|
---|
2586 | my $id = shift;
|
---|
2587 |
|
---|
2588 | my $sql = "SELECT record_id,host,type,val,ttl".($revrec eq 'n' ? ',distance,weight,port' : '').
|
---|
2589 | (($defrec eq 'y') ? ',group_id FROM ' : ',domain_id,rdns_id FROM ').
|
---|
2590 | _rectable($defrec,$revrec)." WHERE record_id=?";
|
---|
2591 | my $ret = $dbh->selectrow_hashref($sql, undef, ($id) );
|
---|
2592 |
|
---|
2593 | if ($dbh->err) {
|
---|
2594 | $errstr = $DBI::errstr;
|
---|
2595 | return undef;
|
---|
2596 | }
|
---|
2597 |
|
---|
2598 | if (!$ret) {
|
---|
2599 | $errstr = "No such record";
|
---|
2600 | return undef;
|
---|
2601 | }
|
---|
2602 |
|
---|
2603 | # explicitly set a parent id
|
---|
2604 | if ($defrec eq 'y') {
|
---|
2605 | $ret->{parid} = $ret->{group_id};
|
---|
2606 | } else {
|
---|
2607 | $ret->{parid} = (($revrec eq 'n') ? $ret->{domain_id} : $ret->{rdns_id});
|
---|
2608 | # and a secondary if we have a custom type that lives in both a forward and reverse zone
|
---|
2609 | $ret->{secid} = (($revrec eq 'y') ? $ret->{domain_id} : $ret->{rdns_id}) if $ret->{type} > 65279;
|
---|
2610 | }
|
---|
2611 |
|
---|
2612 | return $ret;
|
---|
2613 | }
|
---|
2614 |
|
---|
2615 |
|
---|
2616 | ##fixme: should use above (getRecLine()) to get lines for below?
|
---|
2617 | ## DNSDB::getDomRecs()
|
---|
2618 | # Return records for a domain
|
---|
2619 | # Takes a database handle, default/live flag, group/domain ID, start,
|
---|
2620 | # number of records, sort field, and sort order
|
---|
2621 | # Returns a reference to an array of hashes
|
---|
2622 | sub getDomRecs {
|
---|
2623 | $errstr = '';
|
---|
2624 | my $dbh = shift;
|
---|
2625 | my $def = shift;
|
---|
2626 | my $rev = shift;
|
---|
2627 | my $id = shift;
|
---|
2628 | my $nrecs = shift || 'all';
|
---|
2629 | my $nstart = shift || 0;
|
---|
2630 |
|
---|
2631 | ## for order, need to map input to column names
|
---|
2632 | my $order = shift || 'host';
|
---|
2633 | my $direction = shift || 'ASC';
|
---|
2634 |
|
---|
2635 | my $filter = shift || '';
|
---|
2636 |
|
---|
2637 | my $sql = "SELECT r.record_id,r.host,r.type,r.val,r.ttl";
|
---|
2638 | $sql .= ",r.distance,r.weight,r.port" if $rev eq 'n';
|
---|
2639 | $sql .= " FROM "._rectable($def,$rev)." r ";
|
---|
2640 | $sql .= "INNER JOIN rectypes t ON r.type=t.val "; # for sorting by type alphabetically
|
---|
2641 | $sql .= "WHERE "._recparent($def,$rev)." = ?";
|
---|
2642 | $sql .= " AND NOT r.type=$reverse_typemap{SOA}";
|
---|
2643 | $sql .= " AND host ~* ?" if $filter;
|
---|
2644 | # use alphaorder column for "correct" ordering of sort-by-type instead of DNS RR type number
|
---|
2645 | $sql .= " ORDER BY ".($order eq 'type' ? 't.alphaorder' : "r.$order")." $direction";
|
---|
2646 |
|
---|
2647 | my @bindvars = ($id);
|
---|
2648 | push @bindvars, $filter if $filter;
|
---|
2649 |
|
---|
2650 | # just to be ultraparanoid about SQL injection vectors
|
---|
2651 | if ($nstart ne 'all') {
|
---|
2652 | $sql .= " LIMIT ? OFFSET ?";
|
---|
2653 | push @bindvars, $nrecs;
|
---|
2654 | push @bindvars, ($nstart*$nrecs);
|
---|
2655 | }
|
---|
2656 | my $sth = $dbh->prepare($sql) or warn $dbh->errstr;
|
---|
2657 | $sth->execute(@bindvars) or warn "$sql: ".$sth->errstr;
|
---|
2658 |
|
---|
2659 | my @retbase;
|
---|
2660 | while (my $ref = $sth->fetchrow_hashref()) {
|
---|
2661 | push @retbase, $ref;
|
---|
2662 | }
|
---|
2663 |
|
---|
2664 | my $ret = \@retbase;
|
---|
2665 | return $ret;
|
---|
2666 | } # end getDomRecs()
|
---|
2667 |
|
---|
2668 |
|
---|
2669 | ## DNSDB::getRecCount()
|
---|
2670 | # Return count of non-SOA records in zone (or default records in a group)
|
---|
2671 | # Takes a database handle, default/live flag, reverse/forward flag, group/domain ID,
|
---|
2672 | # and optional filtering modifier
|
---|
2673 | # Returns the count
|
---|
2674 | sub getRecCount {
|
---|
2675 | my $dbh = shift;
|
---|
2676 | my $defrec = shift;
|
---|
2677 | my $revrec = shift;
|
---|
2678 | my $id = shift;
|
---|
2679 | my $filter = shift || '';
|
---|
2680 |
|
---|
2681 | # keep the nasties down, since we can't ?-sub this bit. :/
|
---|
2682 | # note this is chars allowed in DNS hostnames
|
---|
2683 | $filter =~ s/[^a-zA-Z0-9_.:-]//g;
|
---|
2684 |
|
---|
2685 | my @bindvars = ($id);
|
---|
2686 | push @bindvars, $filter if $filter;
|
---|
2687 | my $sql = "SELECT count(*) FROM ".
|
---|
2688 | _rectable($defrec,$revrec).
|
---|
2689 | " WHERE "._recparent($defrec,$revrec)."=? ".
|
---|
2690 | "AND NOT type=$reverse_typemap{SOA}".
|
---|
2691 | ($filter ? " AND host ~* ?" : '');
|
---|
2692 | my ($count) = $dbh->selectrow_array($sql, undef, (@bindvars) );
|
---|
2693 |
|
---|
2694 | return $count;
|
---|
2695 |
|
---|
2696 | } # end getRecCount()
|
---|
2697 |
|
---|
2698 |
|
---|
2699 | ## DNSDB::addRec()
|
---|
2700 | # Add a new record to a domain or a group's default records
|
---|
2701 | # Takes a database handle, default/live flag, group/domain ID,
|
---|
2702 | # host, type, value, and TTL
|
---|
2703 | # Some types require additional detail: "distance" for MX and SRV,
|
---|
2704 | # and weight/port for SRV
|
---|
2705 | # Returns a status code and detail message in case of error
|
---|
2706 | ##fixme: pass a hash with the record data, not a series of separate values
|
---|
2707 | sub addRec {
|
---|
2708 | $errstr = '';
|
---|
2709 | my $dbh = shift;
|
---|
2710 | my $defrec = shift;
|
---|
2711 | my $revrec = shift;
|
---|
2712 | my $id = shift; # parent (group_id for defrecs, rdns_id for reverse records,
|
---|
2713 | # domain_id for domain records)
|
---|
2714 |
|
---|
2715 | my $host = shift;
|
---|
2716 | my $rectype = shift; # reference so we can coerce it if "+"-types can't find both zones
|
---|
2717 | my $val = shift;
|
---|
2718 | my $ttl = shift;
|
---|
2719 |
|
---|
2720 | # prep for validation
|
---|
2721 | my $addr = NetAddr::IP->new($$val);
|
---|
2722 | $$host =~ s/\.+$//; # FQDNs ending in . are an internal detail, and really shouldn't be exposed in the UI.
|
---|
2723 |
|
---|
2724 | my $domid = 0;
|
---|
2725 | my $revid = 0;
|
---|
2726 |
|
---|
2727 | my $retcode = 'OK'; # assume everything will go OK
|
---|
2728 | my $retmsg = '';
|
---|
2729 |
|
---|
2730 | # do simple validation first
|
---|
2731 | return ('FAIL', "TTL must be numeric") unless $ttl =~ /^\d+$/;
|
---|
2732 |
|
---|
2733 | # Quick check on hostname parts. Note the regex is more forgiving than the error message;
|
---|
2734 | # domain names technically are case-insensitive, and we use printf-like % codes for a couple
|
---|
2735 | # of types. Other things may also be added to validate default records of several flavours.
|
---|
2736 | return ('FAIL', "Hostnames may not contain anything other than (0-9 a-z . _)")
|
---|
2737 | if $defrec eq 'n' && $$host !~ /^[0-9a-z_%.-]+$/i;
|
---|
2738 |
|
---|
2739 | # Collect these even if we're only doing a simple A record so we can call *any* validation sub
|
---|
2740 | my $dist = shift;
|
---|
2741 | my $weight = shift;
|
---|
2742 | my $port = shift;
|
---|
2743 |
|
---|
2744 | my $fields;
|
---|
2745 | my @vallist;
|
---|
2746 |
|
---|
2747 | # Call the validation sub for the type requested.
|
---|
2748 | ($retcode,$retmsg) = $validators{$$rectype}($dbh, (defrec => $defrec, revrec => $revrec, id => $id,
|
---|
2749 | host => $host, rectype => $rectype, val => $val, addr => $addr,
|
---|
2750 | dist => \$dist, port => \$port, weight => \$weight,
|
---|
2751 | fields => \$fields, vallist => \@vallist) );
|
---|
2752 |
|
---|
2753 | return ($retcode,$retmsg) if $retcode eq 'FAIL';
|
---|
2754 |
|
---|
2755 | # Set up database fields and bind parameters
|
---|
2756 | $fields .= "host,type,val,ttl,"._recparent($defrec,$revrec);
|
---|
2757 | push @vallist, ($$host,$$rectype,$$val,$ttl,$id);
|
---|
2758 | my $vallen = '?'.(',?'x$#vallist);
|
---|
2759 |
|
---|
2760 | # Put together the success log entry. We have to use this horrible kludge
|
---|
2761 | # because domain_id and rdns_id may or may not be present, and if they are,
|
---|
2762 | # they're not at a guaranteed consistent index in the array. wheee!
|
---|
2763 | my %logdata;
|
---|
2764 | my @ftmp = split /,/, $fields;
|
---|
2765 | for (my $i=0; $i <= $#vallist; $i++) {
|
---|
2766 | $logdata{domain_id} = $vallist[$i] if $ftmp[$i] eq 'domain_id';
|
---|
2767 | $logdata{rdns_id} = $vallist[$i] if $ftmp[$i] eq 'rdns_id';
|
---|
2768 | }
|
---|
2769 | $logdata{group_id} = $id if $defrec eq 'y';
|
---|
2770 | $logdata{group_id} = parentID($dbh,
|
---|
2771 | (id => $id, type => ($revrec eq 'n' ? 'domain' : 'revzone'), revrec => $revrec) )
|
---|
2772 | if $defrec eq 'n';
|
---|
2773 | $logdata{entry} = "Added ".($defrec eq 'y' ? 'default record' : 'record')." '$$host $typemap{$$rectype} $$val";
|
---|
2774 | $logdata{entry} .= " [distance $dist]" if $typemap{$$rectype} eq 'MX';
|
---|
2775 | $logdata{entry} .= " [priority $dist] [weight $weight] [port $port]"
|
---|
2776 | if $typemap{$$rectype} eq 'SRV';
|
---|
2777 | $logdata{entry} .= "', TTL $ttl";
|
---|
2778 |
|
---|
2779 | # Allow transactions, and raise an exception on errors so we can catch it later.
|
---|
2780 | # Use local to make sure these get "reset" properly on exiting this block
|
---|
2781 | local $dbh->{AutoCommit} = 0;
|
---|
2782 | local $dbh->{RaiseError} = 1;
|
---|
2783 |
|
---|
2784 | eval {
|
---|
2785 | $dbh->do("INSERT INTO "._rectable($defrec, $revrec)." ($fields) VALUES ($vallen)",
|
---|
2786 | undef, @vallist);
|
---|
2787 | _log($dbh, %logdata);
|
---|
2788 | $dbh->commit;
|
---|
2789 | };
|
---|
2790 | if ($@) {
|
---|
2791 | my $msg = $@;
|
---|
2792 | eval { $dbh->rollback; };
|
---|
2793 | if ($config{log_failures}) {
|
---|
2794 | $logdata{entry} = "Failed adding ".($defrec eq 'y' ? 'default ' : '').
|
---|
2795 | "record '$$host $typemap{$$rectype} $$val', TTL $ttl ($msg)";
|
---|
2796 | _log($dbh, %logdata);
|
---|
2797 | $dbh->commit;
|
---|
2798 | }
|
---|
2799 | return ('FAIL',$msg);
|
---|
2800 | }
|
---|
2801 |
|
---|
2802 | $resultstr = $logdata{entry};
|
---|
2803 | return ($retcode, $retmsg);
|
---|
2804 |
|
---|
2805 | } # end addRec()
|
---|
2806 |
|
---|
2807 |
|
---|
2808 | ## DNSDB::updateRec()
|
---|
2809 | # Update a record
|
---|
2810 | # Takes a database handle, default and reverse flags, record ID, immediate parent ID, and new record data.
|
---|
2811 | # Returns a status code and message
|
---|
2812 | sub updateRec {
|
---|
2813 | $errstr = '';
|
---|
2814 |
|
---|
2815 | my $dbh = shift;
|
---|
2816 | my $defrec = shift;
|
---|
2817 | my $revrec = shift;
|
---|
2818 | my $id = shift;
|
---|
2819 | my $parid = shift; # immediate parent entity that we're descending from to update the record
|
---|
2820 |
|
---|
2821 | # all records have these
|
---|
2822 | my $host = shift;
|
---|
2823 | my $hostbk = $$host; # Keep a backup copy of the original, so we can WARN if the update mangles the domain
|
---|
2824 | my $rectype = shift;
|
---|
2825 | my $val = shift;
|
---|
2826 | my $ttl = shift;
|
---|
2827 |
|
---|
2828 | # prep for validation
|
---|
2829 | my $addr = NetAddr::IP->new($$val);
|
---|
2830 | $$host =~ s/\.+$//; # FQDNs ending in . are an internal detail, and really shouldn't be exposed in the UI.
|
---|
2831 |
|
---|
2832 | my $domid = 0;
|
---|
2833 | my $revid = 0;
|
---|
2834 |
|
---|
2835 | my $retcode = 'OK'; # assume everything will go OK
|
---|
2836 | my $retmsg = '';
|
---|
2837 |
|
---|
2838 | # do simple validation first
|
---|
2839 | return ('FAIL', "TTL must be numeric") unless $ttl =~ /^\d+$/;
|
---|
2840 |
|
---|
2841 | # Quick check on hostname parts. Note the regex is more forgiving than the error message;
|
---|
2842 | # domain names technically are case-insensitive, and we use printf-like % codes for a couple
|
---|
2843 | # of types. Other things may also be added to validate default records of several flavours.
|
---|
2844 | return ('FAIL', "Hostnames may not contain anything other than (0-9 a-z - . _)")
|
---|
2845 | if $defrec eq 'n' && $$host !~ /^[0-9a-z_%.-]+$/i;
|
---|
2846 |
|
---|
2847 | # only MX and SRV will use these
|
---|
2848 | my $dist = shift || 0;
|
---|
2849 | my $weight = shift || 0;
|
---|
2850 | my $port = shift || 0;
|
---|
2851 |
|
---|
2852 | my $fields;
|
---|
2853 | my @vallist;
|
---|
2854 |
|
---|
2855 | # get old record data so we have the right parent ID
|
---|
2856 | # and for logging (eventually)
|
---|
2857 | my $oldrec = getRecLine($dbh, $defrec, $revrec, $id);
|
---|
2858 |
|
---|
2859 | # Call the validation sub for the type requested.
|
---|
2860 | # Note the ID to pass here is the *parent*, not the record
|
---|
2861 | ($retcode,$retmsg) = $validators{$$rectype}($dbh, (defrec => $defrec, revrec => $revrec,
|
---|
2862 | id => ($defrec eq 'y' ? $oldrec->{group_id} : ($revrec eq 'n' ? $oldrec->{domain_id} : $oldrec->{rdns_id})),
|
---|
2863 | host => $host, rectype => $rectype, val => $val, addr => $addr,
|
---|
2864 | dist => \$dist, port => \$port, weight => \$weight,
|
---|
2865 | fields => \$fields, vallist => \@vallist,
|
---|
2866 | update => $id) );
|
---|
2867 |
|
---|
2868 | return ($retcode,$retmsg) if $retcode eq 'FAIL';
|
---|
2869 |
|
---|
2870 | # Set up database fields and bind parameters. Note only the optional fields
|
---|
2871 | # (distance, weight, port, secondary parent ID) are added in the validation call above
|
---|
2872 | $fields .= "host,type,val,ttl,"._recparent($defrec,$revrec);
|
---|
2873 | push @vallist, ($$host,$$rectype,$$val,$ttl,
|
---|
2874 | ($defrec eq 'y' ? $oldrec->{group_id} : ($revrec eq 'n' ? $oldrec->{domain_id} : $oldrec->{rdns_id})) );
|
---|
2875 |
|
---|
2876 | # hack hack PTHUI
|
---|
2877 | # need to forcibly make sure we disassociate a record with a parent it's no longer related to.
|
---|
2878 | # eg, PTR records may not have a domain parent, or A/AAAA records may not have a revzone parent.
|
---|
2879 | # mainly needed for crossover types that got coerced down to "standard" types
|
---|
2880 | if ($defrec eq 'n') {
|
---|
2881 | if ($$rectype == $reverse_typemap{PTR}) {
|
---|
2882 | $fields .= ",domain_id";
|
---|
2883 | push @vallist, 0;
|
---|
2884 | }
|
---|
2885 | if ($$rectype == $reverse_typemap{A} || $$rectype == $reverse_typemap{AAAA}) {
|
---|
2886 | $fields .= ",rdns_id";
|
---|
2887 | push @vallist, 0;
|
---|
2888 | }
|
---|
2889 | }
|
---|
2890 |
|
---|
2891 | # Fiddle the field list into something suitable for updates
|
---|
2892 | $fields =~ s/,/=?,/g;
|
---|
2893 | $fields .= "=?";
|
---|
2894 |
|
---|
2895 | # Put together the success log entry. Horrible kludge from addRec() copied as-is since
|
---|
2896 | # we don't know whether the passed arguments or retrieved values for domain_id and rdns_id
|
---|
2897 | # will be maintained (due to "not-in-zone" validation changes)
|
---|
2898 | my %logdata;
|
---|
2899 | my @ftmp = split /,/, $fields;
|
---|
2900 | for (my $i=0; $i <= $#vallist; $i++) {
|
---|
2901 | $logdata{domain_id} = $vallist[$i] if $ftmp[$i] eq 'domain_id';
|
---|
2902 | $logdata{rdns_id} = $vallist[$i] if $ftmp[$i] eq 'rdns_id';
|
---|
2903 | }
|
---|
2904 | $logdata{group_id} = $parid if $defrec eq 'y';
|
---|
2905 | $logdata{group_id} = parentID($dbh,
|
---|
2906 | (id => $parid, type => ($revrec eq 'n' ? 'domain' : 'revzone'), revrec => $revrec) )
|
---|
2907 | if $defrec eq 'n';
|
---|
2908 | $logdata{entry} = "Updated ".($defrec eq 'y' ? 'default record' : 'record')." from\n".
|
---|
2909 | "'$oldrec->{host} $typemap{$oldrec->{type}} $oldrec->{val}";
|
---|
2910 | $logdata{entry} .= " [distance $oldrec->{distance}]" if $typemap{$oldrec->{type}} eq 'MX';
|
---|
2911 | $logdata{entry} .= " [priority $oldrec->{distance}] [weight $oldrec->{weight}] [port $oldrec->{port}]"
|
---|
2912 | if $typemap{$oldrec->{type}} eq 'SRV';
|
---|
2913 | $logdata{entry} .= "', TTL $oldrec->{ttl}\nto\n'$$host $typemap{$$rectype} $$val";
|
---|
2914 | $logdata{entry} .= " [distance $dist]" if $typemap{$$rectype} eq 'MX';
|
---|
2915 | $logdata{entry} .= " [priority $dist] [weight $weight] [port $port]" if $typemap{$$rectype} eq 'SRV';
|
---|
2916 | $logdata{entry} .= "', TTL $ttl";
|
---|
2917 |
|
---|
2918 | local $dbh->{AutoCommit} = 0;
|
---|
2919 | local $dbh->{RaiseError} = 1;
|
---|
2920 |
|
---|
2921 | eval {
|
---|
2922 | $dbh->do("UPDATE "._rectable($defrec,$revrec)." SET $fields WHERE record_id=?", undef, (@vallist, $id) );
|
---|
2923 | _log($dbh, %logdata);
|
---|
2924 | $dbh->commit;
|
---|
2925 | };
|
---|
2926 | if ($@) {
|
---|
2927 | my $msg = $@;
|
---|
2928 | eval { $dbh->rollback; };
|
---|
2929 | if ($config{log_failures}) {
|
---|
2930 | $logdata{entry} = "Failed updating ".($defrec eq 'y' ? 'default ' : '').
|
---|
2931 | "record '$oldrec->{host} $typemap{$oldrec->{type}} $oldrec->{val}', TTL $oldrec->{ttl} ($msg)";
|
---|
2932 | _log($dbh, %logdata);
|
---|
2933 | $dbh->commit;
|
---|
2934 | }
|
---|
2935 | return ('FAIL', $msg);
|
---|
2936 | }
|
---|
2937 |
|
---|
2938 | $resultstr = $logdata{entry};
|
---|
2939 | return ($retcode, $retmsg);
|
---|
2940 | } # end updateRec()
|
---|
2941 |
|
---|
2942 |
|
---|
2943 | ## DNSDB::delRec()
|
---|
2944 | # Delete a record.
|
---|
2945 | sub delRec {
|
---|
2946 | $errstr = '';
|
---|
2947 | my $dbh = shift;
|
---|
2948 | my $defrec = shift;
|
---|
2949 | my $revrec = shift;
|
---|
2950 | my $id = shift;
|
---|
2951 |
|
---|
2952 | my $oldrec = getRecLine($dbh, $defrec, $revrec, $id);
|
---|
2953 |
|
---|
2954 | # Allow transactions, and raise an exception on errors so we can catch it later.
|
---|
2955 | # Use local to make sure these get "reset" properly on exiting this block
|
---|
2956 | local $dbh->{AutoCommit} = 0;
|
---|
2957 | local $dbh->{RaiseError} = 1;
|
---|
2958 |
|
---|
2959 | # Put together the log entry
|
---|
2960 | my %logdata;
|
---|
2961 | $logdata{domain_id} = $oldrec->{domain_id};
|
---|
2962 | $logdata{rdns_id} = $oldrec->{rdns_id};
|
---|
2963 | $logdata{group_id} = $oldrec->{group_id} if $defrec eq 'y';
|
---|
2964 | $logdata{group_id} = parentID($dbh,
|
---|
2965 | (id => $oldrec->{domain_id}, type => ($revrec eq 'n' ? 'domain' : 'revzone'), revrec => $revrec) )
|
---|
2966 | if $defrec eq 'n';
|
---|
2967 | $logdata{entry} = "Deleted ".($defrec eq 'y' ? 'default record ' : 'record ').
|
---|
2968 | "'$oldrec->{host} $typemap{$oldrec->{type}} $oldrec->{val}";
|
---|
2969 | $logdata{entry} .= " [distance $oldrec->{distance}]" if $typemap{$oldrec->{type}} eq 'MX';
|
---|
2970 | $logdata{entry} .= " [priority $oldrec->{distance}] [weight $oldrec->{weight}] [port $oldrec->{port}]"
|
---|
2971 | if $typemap{$oldrec->{type}} eq 'SRV';
|
---|
2972 | $logdata{entry} .= "', TTL $oldrec->{ttl}\n";
|
---|
2973 |
|
---|
2974 | eval {
|
---|
2975 | my $sth = $dbh->do("DELETE FROM "._rectable($defrec,$revrec)." WHERE record_id=?", undef, ($id));
|
---|
2976 | _log($dbh, %logdata);
|
---|
2977 | $dbh->commit;
|
---|
2978 | };
|
---|
2979 | if ($@) {
|
---|
2980 | my $msg = $@;
|
---|
2981 | eval { $dbh->rollback; };
|
---|
2982 | if ($config{log_failures}) {
|
---|
2983 | $logdata{entry} = "Error deleting ".($defrec eq 'y' ? 'default record' : 'record').
|
---|
2984 | " '$oldrec->{host} $typemap{$oldrec->{type}} $oldrec->{val}', TTL $oldrec->{ttl} ($msg)";
|
---|
2985 | _log($dbh, %logdata);
|
---|
2986 | $dbh->commit;
|
---|
2987 | }
|
---|
2988 | return ('FAIL', $msg);
|
---|
2989 | }
|
---|
2990 |
|
---|
2991 | return ('OK',$logdata{entry});
|
---|
2992 | } # end delRec()
|
---|
2993 |
|
---|
2994 |
|
---|
2995 | ## DNSDB::getTypelist()
|
---|
2996 | # Get a list of record types for various UI dropdowns
|
---|
2997 | # Takes database handle, forward/reverse/lookup flag, and optional "tag as selected" indicator (defaults to A)
|
---|
2998 | # Returns an arrayref to list of hashrefs perfect for HTML::Template
|
---|
2999 | sub getTypelist {
|
---|
3000 | my $dbh = shift;
|
---|
3001 | my $recgroup = shift;
|
---|
3002 | my $type = shift || $reverse_typemap{A};
|
---|
3003 |
|
---|
3004 | # also accepting $webvar{revrec}!
|
---|
3005 | $recgroup = 'f' if $recgroup eq 'n';
|
---|
3006 | $recgroup = 'r' if $recgroup eq 'y';
|
---|
3007 |
|
---|
3008 | my $sql = "SELECT val,name FROM rectypes WHERE ";
|
---|
3009 | if ($recgroup eq 'r') {
|
---|
3010 | # reverse zone types
|
---|
3011 | $sql .= "stdflag=2 OR stdflag=3";
|
---|
3012 | } elsif ($recgroup eq 'l') {
|
---|
3013 | # DNS lookup types. Note we avoid our custom types >= 65280, since those are entirely internal.
|
---|
3014 | $sql .= "(stdflag=1 OR stdflag=2 OR stdflag=3) AND val < 65280";
|
---|
3015 | } else {
|
---|
3016 | # default; forward zone types. technically $type eq 'f' but not worth the error message.
|
---|
3017 | $sql .= "stdflag=1 OR stdflag=2";
|
---|
3018 | }
|
---|
3019 | $sql .= " ORDER BY listorder";
|
---|
3020 |
|
---|
3021 | my $sth = $dbh->prepare($sql);
|
---|
3022 | $sth->execute;
|
---|
3023 | my @typelist;
|
---|
3024 | while (my ($rval,$rname) = $sth->fetchrow_array()) {
|
---|
3025 | my %row = ( recval => $rval, recname => $rname );
|
---|
3026 | $row{tselect} = 1 if $rval == $type;
|
---|
3027 | push @typelist, \%row;
|
---|
3028 | }
|
---|
3029 |
|
---|
3030 | # Add SOA on lookups since it's not listed in other dropdowns.
|
---|
3031 | if ($recgroup eq 'l') {
|
---|
3032 | my %row = ( recval => $reverse_typemap{SOA}, recname => 'SOA' );
|
---|
3033 | $row{tselect} = 1 if $reverse_typemap{SOA} == $type;
|
---|
3034 | push @typelist, \%row;
|
---|
3035 | }
|
---|
3036 |
|
---|
3037 | return \@typelist;
|
---|
3038 | } # end getTypelist()
|
---|
3039 |
|
---|
3040 |
|
---|
3041 | ## DNSDB::parentID()
|
---|
3042 | # Get ID of entity that is nearest parent to requested id
|
---|
3043 | # Takes a database handle and a hash of entity ID, entity type, optional parent type flag
|
---|
3044 | # (domain/reverse zone or group), and optional default/live and forward/reverse flags
|
---|
3045 | # Returns the ID or undef on failure
|
---|
3046 | sub parentID {
|
---|
3047 | my $dbh = shift;
|
---|
3048 |
|
---|
3049 | my %args = @_;
|
---|
3050 |
|
---|
3051 | # clean up the parent-type. Set it to group if not set; coerce revzone to domain for simpler logic
|
---|
3052 | $args{partype} = 'group' if !$args{partype};
|
---|
3053 | $args{partype} = 'domain' if $args{partype} eq 'revzone';
|
---|
3054 |
|
---|
3055 | # clean up defrec and revrec. default to live record, forward zone
|
---|
3056 | $args{defrec} = 'n' if !$args{defrec};
|
---|
3057 | $args{revrec} = 'n' if !$args{revrec};
|
---|
3058 |
|
---|
3059 | if ($par_type{$args{partype}} eq 'domain') {
|
---|
3060 | # only live records can have a domain/zone parent
|
---|
3061 | return unless ($args{type} eq 'record' && $args{defrec} eq 'n');
|
---|
3062 | my $result = $dbh->selectrow_hashref("SELECT ".($args{revrec} eq 'n' ? 'domain_id' : 'rdns_id').
|
---|
3063 | " FROM records WHERE record_id = ?",
|
---|
3064 | undef, ($args{id}) ) or return;
|
---|
3065 | return $result;
|
---|
3066 | } else {
|
---|
3067 | # snag some arguments that will either fall through or be overwritten to save some code duplication
|
---|
3068 | my $tmpid = $args{id};
|
---|
3069 | my $type = $args{type};
|
---|
3070 | if ($type eq 'record' && $args{defrec} eq 'n') {
|
---|
3071 | # Live records go through the records table first.
|
---|
3072 | ($tmpid) = $dbh->selectrow_array("SELECT ".($args{revrec} eq 'n' ? 'domain_id' : 'rdns_id').
|
---|
3073 | " FROM records WHERE record_id = ?",
|
---|
3074 | undef, ($args{id}) ) or return;
|
---|
3075 | $type = ($args{revrec} eq 'n' ? 'domain' : 'revzone');
|
---|
3076 | }
|
---|
3077 | my ($result) = $dbh->selectrow_array("SELECT $par_col{$type} FROM $par_tbl{$type} WHERE $id_col{$type} = ?",
|
---|
3078 | undef, ($tmpid) );
|
---|
3079 | return $result;
|
---|
3080 | }
|
---|
3081 | # should be impossible to get here with even remotely sane arguments
|
---|
3082 | return;
|
---|
3083 | } # end parentID()
|
---|
3084 |
|
---|
3085 |
|
---|
3086 | ## DNSDB::isParent()
|
---|
3087 | # Returns true if $id1 is a parent of $id2, false otherwise
|
---|
3088 | sub isParent {
|
---|
3089 | my $dbh = shift;
|
---|
3090 | my $id1 = shift;
|
---|
3091 | my $type1 = shift;
|
---|
3092 | my $id2 = shift;
|
---|
3093 | my $type2 = shift;
|
---|
3094 | ##todo: immediate, secondary, full (default)
|
---|
3095 |
|
---|
3096 | # Return false on invalid types
|
---|
3097 | return 0 if !grep /^$type1$/, ('record','defrec','defrevrec','user','domain','revzone','group');
|
---|
3098 | return 0 if !grep /^$type2$/, ('record','defrec','defrevrec','user','domain','revzone','group');
|
---|
3099 |
|
---|
3100 | # Return false on impossible relations
|
---|
3101 | return 0 if $type1 eq 'record'; # nothing may be a child of a record
|
---|
3102 | return 0 if $type1 eq 'defrec'; # nothing may be a child of a record
|
---|
3103 | return 0 if $type1 eq 'defrevrec'; # nothing may be a child of a record
|
---|
3104 | return 0 if $type1 eq 'user'; # nothing may be child of a user
|
---|
3105 | return 0 if $type1 eq 'domain' && $type2 ne 'record'; # domain may not be a parent of anything other than a record
|
---|
3106 | return 0 if $type1 eq 'revzone' && $type2 ne 'record';# reverse zone may not be a parent of anything other than a record
|
---|
3107 |
|
---|
3108 | # ennnhhhh.... if we're passed an id of 0, it will never be found. usual
|
---|
3109 | # case would be the UI creating a new <thing>, and so we don't have an ID for
|
---|
3110 | # <thing> to look up yet. in that case the UI should check the parent as well.
|
---|
3111 | return 0 if $id1 == 0; # nothing can have a parent id of 0
|
---|
3112 | return 1 if $id2 == 0; # anything could have a child id of 0 (or "unknown")
|
---|
3113 |
|
---|
3114 | # group 1 is the ultimate root parent
|
---|
3115 | return 1 if $type1 eq 'group' && $id1 == 1;
|
---|
3116 |
|
---|
3117 | # groups are always (a) parent of themselves
|
---|
3118 | return 1 if $type1 eq 'group' && $type2 eq 'group' && $id1 == $id2;
|
---|
3119 |
|
---|
3120 | my $id = $id2;
|
---|
3121 | my $type = $type2;
|
---|
3122 | my $foundparent = 0;
|
---|
3123 |
|
---|
3124 | # Records are the only entity with two possible parents. We need to split the parent checks on
|
---|
3125 | # domain/rdns.
|
---|
3126 | if ($type eq 'record') {
|
---|
3127 | my ($dom,$rdns) = $dbh->selectrow_array("SELECT domain_id,rdns_id FROM records WHERE record_id=?",
|
---|
3128 | undef, ($id));
|
---|
3129 | # check immediate parent against request
|
---|
3130 | return 1 if $type1 eq 'domain' && $id1 == $dom;
|
---|
3131 | return 1 if $type1 eq 'revzone' && $id1 == $rdns;
|
---|
3132 | # if request is group, check *both* parents. Only check if the parent is nonzero though.
|
---|
3133 | return 1 if $dom && isParent($dbh, $id1, $type1, $dom, 'domain');
|
---|
3134 | return 1 if $rdns && isParent($dbh, $id1, $type1, $rdns, 'revzone');
|
---|
3135 | # exit here since we've executed the loop below by proxy in the above recursive calls.
|
---|
3136 | return 0;
|
---|
3137 | }
|
---|
3138 |
|
---|
3139 | # almost the same loop as getParents() above
|
---|
3140 | my $limiter = 0;
|
---|
3141 | while (1) {
|
---|
3142 | my $sql = "SELECT $par_col{$type} FROM $par_tbl{$type} WHERE $id_col{$type} = ?";
|
---|
3143 | my $result = $dbh->selectrow_hashref($sql,
|
---|
3144 | undef, ($id) );
|
---|
3145 | if (!$result) {
|
---|
3146 | $limiter++;
|
---|
3147 | ##fixme: how often will this happen on a live site? fail at max limiter <n>?
|
---|
3148 | warn "no results looking for $sql with id $id (depth $limiter)\n";
|
---|
3149 | last;
|
---|
3150 | }
|
---|
3151 | if ($result && $result->{$par_col{$type}} == $id1) {
|
---|
3152 | $foundparent = 1;
|
---|
3153 | last;
|
---|
3154 | } else {
|
---|
3155 | ##fixme: do we care about trying to return a "no such record/domain/user/group" error?
|
---|
3156 | # should be impossible to create an inconsistent DB just with API calls.
|
---|
3157 | warn $dbh->errstr." $sql, $id" if $dbh->errstr;
|
---|
3158 | }
|
---|
3159 | # group 1 is its own parent. need this here more to break strange loops than for detecting a parent
|
---|
3160 | last if $result->{$par_col{$type}} == 1;
|
---|
3161 | $id = $result->{$par_col{$type}};
|
---|
3162 | $type = $par_type{$type};
|
---|
3163 | }
|
---|
3164 |
|
---|
3165 | return $foundparent;
|
---|
3166 | } # end isParent()
|
---|
3167 |
|
---|
3168 |
|
---|
3169 | ## DNSDB::zoneStatus()
|
---|
3170 | # Returns and optionally sets a zone's status
|
---|
3171 | # Takes a database handle, domain/revzone ID, forward/reverse flag, and optionally a status argument
|
---|
3172 | # Returns status, or undef on errors.
|
---|
3173 | sub zoneStatus {
|
---|
3174 | my $dbh = shift;
|
---|
3175 | my $id = shift;
|
---|
3176 | my $revrec = shift;
|
---|
3177 | my $newstatus = shift || 'mu';
|
---|
3178 |
|
---|
3179 | return undef if $id !~ /^\d+$/;
|
---|
3180 |
|
---|
3181 | # Allow transactions, and raise an exception on errors so we can catch it later.
|
---|
3182 | # Use local to make sure these get "reset" properly on exiting this block
|
---|
3183 | local $dbh->{AutoCommit} = 0;
|
---|
3184 | local $dbh->{RaiseError} = 1;
|
---|
3185 |
|
---|
3186 | if ($newstatus ne 'mu') {
|
---|
3187 | # ooo, fun! let's see what we were passed for status
|
---|
3188 | eval {
|
---|
3189 | $newstatus = 0 if $newstatus eq 'domoff';
|
---|
3190 | $newstatus = 1 if $newstatus eq 'domon';
|
---|
3191 | $dbh->do("UPDATE ".($revrec eq 'n' ? 'domains' : 'revzones')." SET status=? WHERE ".
|
---|
3192 | ($revrec eq 'n' ? 'domain_id' : 'rdns_id')."=?", undef, ($newstatus,$id) );
|
---|
3193 |
|
---|
3194 | ##fixme switch to more consise "Enabled <domain"/"Disabled <domain>" as with users?
|
---|
3195 | $resultstr = "Changed ".($revrec eq 'n' ? domainName($dbh, $id) : revName($dbh, $id)).
|
---|
3196 | " state to ".($newstatus ? 'active' : 'inactive');
|
---|
3197 |
|
---|
3198 | my %loghash;
|
---|
3199 | $loghash{domain_id} = $id if $revrec eq 'n';
|
---|
3200 | $loghash{rdns_id} = $id if $revrec eq 'y';
|
---|
3201 | $loghash{group_id} = parentID($dbh,
|
---|
3202 | (id => $id, type => ($revrec eq 'n' ? 'domain' : 'revzone'), revrec => $revrec) );
|
---|
3203 | $loghash{entry} = $resultstr;
|
---|
3204 | _log($dbh, %loghash);
|
---|
3205 |
|
---|
3206 | $dbh->commit;
|
---|
3207 | };
|
---|
3208 | if ($@) {
|
---|
3209 | my $msg = $@;
|
---|
3210 | eval { $dbh->rollback; };
|
---|
3211 | $resultstr = '';
|
---|
3212 | $errstr = $msg;
|
---|
3213 | return;
|
---|
3214 | }
|
---|
3215 | }
|
---|
3216 |
|
---|
3217 | my ($status) = $dbh->selectrow_array("SELECT status FROM ".
|
---|
3218 | ($revrec eq 'n' ? "domains WHERE domain_id=?" : "revzones WHERE rdns_id=?"),
|
---|
3219 | undef, ($id) );
|
---|
3220 | return $status;
|
---|
3221 | } # end zoneStatus()
|
---|
3222 |
|
---|
3223 |
|
---|
3224 | ## DNSDB::importAXFR
|
---|
3225 | # Import a domain via AXFR
|
---|
3226 | # Takes AXFR host, domain to transfer, group to put the domain in,
|
---|
3227 | # and optionally:
|
---|
3228 | # - active/inactive state flag (defaults to active)
|
---|
3229 | # - overwrite-SOA flag (defaults to off)
|
---|
3230 | # - overwrite-NS flag (defaults to off, doesn't affect subdomain NS records)
|
---|
3231 | # Returns a status code (OK, WARN, or FAIL) and message - message should be blank
|
---|
3232 | # if status is OK, but WARN includes conditions that are not fatal but should
|
---|
3233 | # really be reported.
|
---|
3234 | sub importAXFR {
|
---|
3235 | my $dbh = shift;
|
---|
3236 | my $ifrom_in = shift;
|
---|
3237 | my $zone = shift;
|
---|
3238 | my $group = shift;
|
---|
3239 | my $status = shift || 1;
|
---|
3240 | my $rwsoa = shift || 0;
|
---|
3241 | my $rwns = shift || 0;
|
---|
3242 | my $merge = shift || 0; # do we attempt to merge A/AAAA and PTR records whenever possible?
|
---|
3243 | # do we overload this with the fixme below?
|
---|
3244 | ##fixme: add mode to delete&replace, merge+overwrite, merge new?
|
---|
3245 |
|
---|
3246 | my $nrecs = 0;
|
---|
3247 | my $soaflag = 0;
|
---|
3248 | my $nsflag = 0;
|
---|
3249 | my $warnmsg = '';
|
---|
3250 | my $ifrom;
|
---|
3251 |
|
---|
3252 | my $rev = 'n';
|
---|
3253 | my $code = 'OK';
|
---|
3254 | my $msg = 'foobar?';
|
---|
3255 |
|
---|
3256 | # choke on possible bad setting in ifrom
|
---|
3257 | # IPv4 and v6, and valid hostnames!
|
---|
3258 | ($ifrom) = ($ifrom_in =~ /^([0-9a-f\:.]+|[0-9a-z_.-]+)$/i);
|
---|
3259 | return ('FAIL', "Bad AXFR source host $ifrom")
|
---|
3260 | unless ($ifrom) = ($ifrom_in =~ /^([0-9a-f\:.]+|[0-9a-z_.-]+)$/i);
|
---|
3261 |
|
---|
3262 | my $errmsg;
|
---|
3263 |
|
---|
3264 | my $zone_id;
|
---|
3265 | my $domain_id = 0;
|
---|
3266 | my $rdns_id = 0;
|
---|
3267 | my $cidr;
|
---|
3268 |
|
---|
3269 | # magic happens! detect if we're importing a domain or a reverse zone
|
---|
3270 | # while we're at it, figure out what the CIDR netblock is (if we got a .arpa)
|
---|
3271 | # or what the formal .arpa zone is (if we got a CIDR netblock)
|
---|
3272 | # Handles sub-octet v4 zones in the format specified in the Cricket Book, 2nd Ed, p217-218
|
---|
3273 |
|
---|
3274 | if ($zone =~ m{(?:\.arpa\.?|/\d+)$}) {
|
---|
3275 | # we seem to have a reverse zone
|
---|
3276 | $rev = 'y';
|
---|
3277 |
|
---|
3278 | if ($zone =~ /\.arpa\.?$/) {
|
---|
3279 | # we have a formal reverse zone. call _zone2cidr and get the CIDR block.
|
---|
3280 | ($code,$msg) = _zone2cidr($zone);
|
---|
3281 | return ($code, $msg) if $code eq 'FAIL';
|
---|
3282 | $cidr = $msg;
|
---|
3283 | } elsif ($zone =~ m|^[\d.]+/\d+$|) {
|
---|
3284 | # v4 revzone, CIDR netblock
|
---|
3285 | $cidr = NetAddr::IP->new($zone) or return ('FAIL',"$zone is not a valid CIDR block");
|
---|
3286 | $zone = _ZONE($cidr, 'ZONE.in-addr.arpa', 'r', '.');
|
---|
3287 | } elsif ($zone =~ m|^[a-fA-F\d:]+/\d+$|) {
|
---|
3288 | # v6 revzone, CIDR netblock
|
---|
3289 | $cidr = NetAddr::IP->new($zone) or return ('FAIL',"$zone is not a valid CIDR block");
|
---|
3290 | return ('FAIL', "$zone is not a nibble-aligned block") if $cidr->masklen % 4 != 0;
|
---|
3291 | $zone = _ZONE($cidr, 'ZONE.ip6.arpa', 'r', '.');
|
---|
3292 | } else {
|
---|
3293 | # there is. no. else!
|
---|
3294 | return ('FAIL', "Unknown zone name format");
|
---|
3295 | }
|
---|
3296 |
|
---|
3297 | # quick check to start to see if we've already got one
|
---|
3298 |
|
---|
3299 | ($zone_id) = $dbh->selectrow_array("SELECT rdns_id FROM revzones WHERE revnet=?",
|
---|
3300 | undef, ("$cidr"));
|
---|
3301 | $rdns_id = $zone_id;
|
---|
3302 | } else {
|
---|
3303 | # default to domain
|
---|
3304 | ($zone_id) = $dbh->selectrow_array("SELECT domain_id FROM domains WHERE domain=?",
|
---|
3305 | undef, ($zone));
|
---|
3306 | $domain_id = $zone_id;
|
---|
3307 | }
|
---|
3308 |
|
---|
3309 | return ('FAIL', ($rev eq 'n' ? 'Domain' : 'Reverse zone')." already exists") if $zone_id;
|
---|
3310 |
|
---|
3311 | # little local utility sub to swap $val and $host for revzone records.
|
---|
3312 | sub _revswap {
|
---|
3313 | my $rechost = shift;
|
---|
3314 | my $recdata = shift;
|
---|
3315 |
|
---|
3316 | if ($rechost =~ /\.in-addr\.arpa\.?$/) {
|
---|
3317 | $rechost =~ s/\.in-addr\.arpa\.?$//;
|
---|
3318 | $rechost = join '.', reverse split /\./, $rechost;
|
---|
3319 | } else {
|
---|
3320 | $rechost =~ s/\.ip6\.arpa\.?$//;
|
---|
3321 | my @nibs = reverse split /\./, $rechost;
|
---|
3322 | $rechost = '';
|
---|
3323 | my $nc;
|
---|
3324 | foreach (@nibs) {
|
---|
3325 | $rechost.= $_;
|
---|
3326 | $rechost .= ":" if ++$nc % 4 == 0 && $nc < 32;
|
---|
3327 | }
|
---|
3328 | $rechost .= ":" if $nc < 32 && $rechost !~ /\*$/; # close netblock records?
|
---|
3329 | ##fixme: there's a case that ends up with a partial entry here:
|
---|
3330 | # ip:add:re:ss::
|
---|
3331 | # can't reproduce after letting it sit overnight after discovery. :(
|
---|
3332 | #print "$rechost\n";
|
---|
3333 | # canonicalize with NetAddr::IP
|
---|
3334 | $rechost = NetAddr::IP->new($rechost)->addr unless $rechost =~ /\*$/;
|
---|
3335 | }
|
---|
3336 | return ($recdata,$rechost)
|
---|
3337 | }
|
---|
3338 |
|
---|
3339 |
|
---|
3340 | # Allow transactions, and raise an exception on errors so we can catch it later.
|
---|
3341 | # Use local to make sure these get "reset" properly on exiting this block
|
---|
3342 | local $dbh->{AutoCommit} = 0;
|
---|
3343 | local $dbh->{RaiseError} = 1;
|
---|
3344 |
|
---|
3345 | my $sth;
|
---|
3346 | eval {
|
---|
3347 |
|
---|
3348 | if ($rev eq 'n') {
|
---|
3349 |
|
---|
3350 | ##fixme: serial
|
---|
3351 | $dbh->do("INSERT INTO domains (domain,group_id,status) VALUES (?,?,?)", undef, ($zone,$group,$status) );
|
---|
3352 | # get domain id so we can do the records
|
---|
3353 | ($zone_id) = $dbh->selectrow_array("SELECT currval('domains_domain_id_seq')");
|
---|
3354 | $domain_id = $zone_id;
|
---|
3355 | _log($dbh, (group_id => $group, domain_id => $domain_id,
|
---|
3356 | entry => "[Added ".($status ? 'active' : 'inactive')." domain $zone via AXFR]") );
|
---|
3357 | } else {
|
---|
3358 | ##fixme: serial
|
---|
3359 | $dbh->do("INSERT INTO revzones (revnet,group_id,status) VALUES (?,?,?)", undef, ($cidr,$group,$status) );
|
---|
3360 | # get revzone id so we can do the records
|
---|
3361 | ($zone_id) = $dbh->selectrow_array("SELECT currval('revzones_rdns_id_seq')");
|
---|
3362 | $rdns_id = $zone_id;
|
---|
3363 | _log($dbh, (group_id => $group, rdns_id => $rdns_id,
|
---|
3364 | entry => "[Added ".($status ? 'active' : 'inactive')." reverse zone $cidr via AXFR]") );
|
---|
3365 | }
|
---|
3366 |
|
---|
3367 | ## bizarre DBI<->Net::DNS interaction bug:
|
---|
3368 | ## sometimes a zone will cause an immediate commit-and-exit (sort of) of the while()
|
---|
3369 | ## fixed, apparently I was doing *something* odd, but not certain what it was that
|
---|
3370 | ## caused a commit instead of barfing
|
---|
3371 |
|
---|
3372 | my $res = Net::DNS::Resolver->new;
|
---|
3373 | $res->nameservers($ifrom);
|
---|
3374 | $res->axfr_start($zone)
|
---|
3375 | or die "Couldn't begin AXFR\n";
|
---|
3376 |
|
---|
3377 | $sth = $dbh->prepare("INSERT INTO records (domain_id,rdns_id,host,type,val,distance,weight,port,ttl)".
|
---|
3378 | " VALUES (?,?,?,?,?,?,?,?,?)");
|
---|
3379 |
|
---|
3380 | # Stash info about sub-octet v4 revzones here so we don't have
|
---|
3381 | # to store the CNAMEs used to delegate a suboctet zone
|
---|
3382 | # $suboct{zone}{ns}[] -> array of nameservers
|
---|
3383 | # $suboct{zone}{cname}[] -> array of extant CNAMEs (Just In Case someone did something bizarre)
|
---|
3384 | ## commented pending actual use of this data. for now, we'll just
|
---|
3385 | ## auto-(re)create the CNAMEs in revzones on export
|
---|
3386 | # my %suboct;
|
---|
3387 |
|
---|
3388 | while (my $rr = $res->axfr_next()) {
|
---|
3389 |
|
---|
3390 | my $val;
|
---|
3391 | my $distance = 0;
|
---|
3392 | my $weight = 0;
|
---|
3393 | my $port = 0;
|
---|
3394 | my $logfrag = '';
|
---|
3395 |
|
---|
3396 | my $type = $rr->type;
|
---|
3397 | my $host = $rr->name;
|
---|
3398 | my $ttl = $rr->ttl;
|
---|
3399 |
|
---|
3400 | $soaflag = 1 if $type eq 'SOA';
|
---|
3401 | $nsflag = 1 if $type eq 'NS';
|
---|
3402 |
|
---|
3403 | # "Primary" types:
|
---|
3404 | # A, NS, CNAME, SOA, PTR(warn in forward), MX, TXT, AAAA, SRV, A6(ob), SPF
|
---|
3405 | # maybe KEY
|
---|
3406 |
|
---|
3407 | # BIND supports:
|
---|
3408 | # [standard]
|
---|
3409 | # A AAAA CNAME MX NS PTR SOA TXT
|
---|
3410 | # [variously experimental, obsolete, or obscure]
|
---|
3411 | # HINFO MB(ex) MD(ob) MF(ob) MG(ex) MINFO(ex) MR(ex) NULL WKS AFSDB(ex) ISDN(ex) RP(ex) RT(ex) X25(ex) PX
|
---|
3412 | # ... if one can ever find the right magic to format them correctly
|
---|
3413 |
|
---|
3414 | # Net::DNS supports:
|
---|
3415 | # RRSIG SIG NSAP NS NIMLOC NAPTR MX MR MINFO MG MB LOC ISDN IPSECKEY HINFO
|
---|
3416 | # EID DNAME CNAME CERT APL AFSDB AAAA A DS NXT NSEC3PARAM NSEC3 NSEC KEY
|
---|
3417 | # DNSKEY DLV X25 TXT TSIG TKEY SSHFP SRV SPF SOA RT RP PX PTR NULL APL::AplItem
|
---|
3418 |
|
---|
3419 | # nasty big ugly case-like thing here, since we have to do *some* different
|
---|
3420 | # processing depending on the record. le sigh.
|
---|
3421 |
|
---|
3422 | ##fixme: what record types other than TXT can/will have >255-byte payloads?
|
---|
3423 |
|
---|
3424 | if ($type eq 'A') {
|
---|
3425 | $val = $rr->address;
|
---|
3426 | } elsif ($type eq 'NS') {
|
---|
3427 | # hmm. should we warn here if subdomain NS'es are left alone?
|
---|
3428 | next if ($rwns && ($rr->name eq $zone));
|
---|
3429 | if ($rev eq 'y') {
|
---|
3430 | # revzones have records more or less reversed from forward zones.
|
---|
3431 | my ($tmpcode,$tmpmsg) = _zone2cidr($host);
|
---|
3432 | die "Error converting NS record: $tmpmsg" if $tmpcode eq 'FAIL'; # hmm. may not make sense...
|
---|
3433 | $val = "$tmpmsg";
|
---|
3434 | $host = $rr->nsdname;
|
---|
3435 | $logfrag = "Added record '$val $type $host', TTL $ttl";
|
---|
3436 | # Tag and preserve. For now this is commented for a no-op, but we have Ideas for
|
---|
3437 | # another custom storage type ("DELEGATE") that will use these subzone-delegation records
|
---|
3438 | #if ($val ne "$cidr") {
|
---|
3439 | # push @{$suboct{$val}{ns}}, $host;
|
---|
3440 | #}
|
---|
3441 | } else {
|
---|
3442 | $val = $rr->nsdname;
|
---|
3443 | }
|
---|
3444 | $nsflag = 1;
|
---|
3445 | } elsif ($type eq 'CNAME') {
|
---|
3446 | if ($rev eq 'y') {
|
---|
3447 | # hmm. do we even want to bother with storing these at this level? Sub-octet delegation
|
---|
3448 | # by CNAME is essentially a record-publication hack, and we want to just represent the
|
---|
3449 | # "true" logical intentions as far down the stack as we can from the UI.
|
---|
3450 | ($host,$val) = _revswap($host,$rr->cname);
|
---|
3451 | $logfrag = "Added record '$val $type $host', TTL $ttl";
|
---|
3452 | # Tag and preserve in case we want to commit them as-is later, but mostly we don't care.
|
---|
3453 | # Commented pending actually doing something with possibly new type DELEGATE
|
---|
3454 | #my $tmprev = $host;
|
---|
3455 | #$tmprev =~ s/^\d+\.//;
|
---|
3456 | #($code,$tmprev) = _zone2cidr($tmprev);
|
---|
3457 | #push @{$suboct{"$tmprev"}{cname}}, $val;
|
---|
3458 | # Silently skip CNAMEs in revzones.
|
---|
3459 | next;
|
---|
3460 | } else {
|
---|
3461 | $val = $rr->cname;
|
---|
3462 | }
|
---|
3463 | } elsif ($type eq 'SOA') {
|
---|
3464 | next if $rwsoa;
|
---|
3465 | $host = $rr->rname.":".$rr->mname;
|
---|
3466 | $val = $rr->refresh.":".$rr->retry.":".$rr->expire.":".$rr->minimum;
|
---|
3467 | $soaflag = 1;
|
---|
3468 | } elsif ($type eq 'PTR') {
|
---|
3469 | ($host,$val) = _revswap($host,$rr->ptrdname);
|
---|
3470 | $logfrag = "Added record '$val $type $host', TTL $ttl";
|
---|
3471 | # hmm. PTR records should not be in forward zones.
|
---|
3472 | } elsif ($type eq 'MX') {
|
---|
3473 | $val = $rr->exchange;
|
---|
3474 | $distance = $rr->preference;
|
---|
3475 | } elsif ($type eq 'TXT') {
|
---|
3476 | ##fixme: Net::DNS docs say this should be deprecated for rdatastr() or char_str_list(),
|
---|
3477 | ## but don't really seem enthusiastic about it.
|
---|
3478 | #print "should use rdatastr:\n\t".$rr->rdatastr."\n or char_str_list:\n\t".join(' ',$rr->char_str_list())."\n";
|
---|
3479 | # rdatastr returns a BIND-targetted logical string, including opening and closing quotes
|
---|
3480 | # char_str_list returns a list of the individual string fragments in the record
|
---|
3481 | # txtdata returns the more useful all-in-one form (since we want to push such protocol
|
---|
3482 | # details as far down the stack as we can)
|
---|
3483 | # NB: this may turn out to be more troublesome if we ever have need of >512-byte TXT records.
|
---|
3484 | if ($rev eq 'y') {
|
---|
3485 | ($host,$val) = _revswap($host,$rr->txtdata);
|
---|
3486 | $logfrag = "Added record '$val $type $host', TTL $ttl";
|
---|
3487 | } else {
|
---|
3488 | $val = $rr->txtdata;
|
---|
3489 | }
|
---|
3490 | } elsif ($type eq 'SPF') {
|
---|
3491 | ##fixme: and the same caveat here, since it is apparently a clone of ::TXT
|
---|
3492 | $val = $rr->txtdata;
|
---|
3493 | } elsif ($type eq 'AAAA') {
|
---|
3494 | $val = $rr->address;
|
---|
3495 | } elsif ($type eq 'SRV') {
|
---|
3496 | $val = $rr->target;
|
---|
3497 | $distance = $rr->priority;
|
---|
3498 | $weight = $rr->weight;
|
---|
3499 | $port = $rr->port;
|
---|
3500 | } elsif ($type eq 'KEY') {
|
---|
3501 | # we don't actually know what to do with these...
|
---|
3502 | $val = $rr->flags.":".$rr->protocol.":".$rr->algorithm.":".$rr->key.":".$rr->keytag.":".$rr->privatekeyname;
|
---|
3503 | } else {
|
---|
3504 | $val = $rr->rdatastr;
|
---|
3505 | # Finding a different record type is not fatal.... just problematic.
|
---|
3506 | # We may not be able to export it correctly.
|
---|
3507 | $warnmsg .= "Unusual record ".$rr->name." ($type) found\n";
|
---|
3508 | }
|
---|
3509 |
|
---|
3510 | my $logentry = "[AXFR ".($rev eq 'n' ? $zone : $cidr)."] ";
|
---|
3511 |
|
---|
3512 | if ($merge) {
|
---|
3513 | if ($rev eq 'n') {
|
---|
3514 | # importing a domain; we have A and AAAA records that could be merged with matching PTR records
|
---|
3515 | my $etype;
|
---|
3516 | my ($erdns,$erid,$ettl) = $dbh->selectrow_array("SELECT rdns_id,record_id,ttl FROM records ".
|
---|
3517 | "WHERE host=? AND val=? AND type=12",
|
---|
3518 | undef, ($host, $val) );
|
---|
3519 | if ($erid) {
|
---|
3520 | if ($type eq 'A') { # PTR -> A+PTR
|
---|
3521 | $etype = 65280;
|
---|
3522 | $logentry .= "Merged A record with existing PTR record '$host A+PTR $val', TTL $ettl";
|
---|
3523 | }
|
---|
3524 | if ($type eq 'AAAA') { # PTR -> AAAA+PTR
|
---|
3525 | $etype = 65281;
|
---|
3526 | $logentry .= "Merged AAAA record with existing PTR record '$host AAAA+PTR $val', TTL $ettl";
|
---|
3527 | }
|
---|
3528 | $ettl = ($ettl < $ttl ? $ettl : $ttl); # use lower TTL
|
---|
3529 | $dbh->do("UPDATE records SET domain_id=?,ttl=?,type=? WHERE record_id=?", undef,
|
---|
3530 | ($domain_id, $ettl, $etype, $erid));
|
---|
3531 | $nrecs++;
|
---|
3532 | _log($dbh, (group_id => $group, domain_id => $domain_id, rdns_id => $erdns, entry => $logentry) );
|
---|
3533 | next; # while axfr_next
|
---|
3534 | }
|
---|
3535 | } # $rev eq 'n'
|
---|
3536 | else {
|
---|
3537 | # importing a revzone, we have PTR records that could be merged with matching A/AAAA records
|
---|
3538 | my ($domid,$erid,$ettl,$etype) = $dbh->selectrow_array("SELECT domain_id,record_id,ttl,type FROM records ".
|
---|
3539 | "WHERE host=? AND val=? AND (type=1 OR type=28)",
|
---|
3540 | undef, ($host, $val) );
|
---|
3541 | if ($erid) {
|
---|
3542 | if ($etype == 1) { # A -> A+PTR
|
---|
3543 | $etype = 65280;
|
---|
3544 | $logentry .= "Merged PTR record with existing matching A record '$host A+PTR $val', TTL $ettl";
|
---|
3545 | }
|
---|
3546 | if ($etype == 28) { # AAAA -> AAAA+PTR
|
---|
3547 | $etype = 65281;
|
---|
3548 | $logentry .= "Merged PTR record with existing matching AAAA record '$host AAAA+PTR $val', TTL $ettl";
|
---|
3549 | }
|
---|
3550 | $ettl = ($ettl < $ttl ? $ettl : $ttl); # use lower TTL
|
---|
3551 | $dbh->do("UPDATE records SET rdns_id=?,ttl=?,type=? WHERE record_id=?", undef,
|
---|
3552 | ($rdns_id, $ettl, $etype, $erid));
|
---|
3553 | $nrecs++;
|
---|
3554 | _log($dbh, (group_id => $group, domain_id => $domid, rdns_id => $rdns_id, entry => $logentry) );
|
---|
3555 | next; # while axfr_next
|
---|
3556 | }
|
---|
3557 | } # $rev eq 'y'
|
---|
3558 | } # if $merge
|
---|
3559 |
|
---|
3560 | # Insert the new record
|
---|
3561 | $sth->execute($domain_id, $rdns_id, $host, $reverse_typemap{$type}, $val,
|
---|
3562 | $distance, $weight, $port, $ttl);
|
---|
3563 |
|
---|
3564 | $nrecs++;
|
---|
3565 |
|
---|
3566 | if ($type eq 'SOA') {
|
---|
3567 | # also !$rwsoa, but if that's set, it should be impossible to get here.
|
---|
3568 | my @tmp1 = split /:/, $host;
|
---|
3569 | my @tmp2 = split /:/, $val;
|
---|
3570 | $logentry .= "Added SOA record [contact $tmp1[0]] [master $tmp1[1]] ".
|
---|
3571 | "[refresh $tmp2[0]] [retry $tmp2[1]] [expire $tmp2[2]] [minttl $tmp2[3]], TTL $ttl";
|
---|
3572 | } elsif ($logfrag) {
|
---|
3573 | # special case for log entries we need to meddle with a little.
|
---|
3574 | $logentry .= $logfrag;
|
---|
3575 | } else {
|
---|
3576 | $logentry .= "Added record '$host $type";
|
---|
3577 | $logentry .= " [distance $distance]" if $type eq 'MX';
|
---|
3578 | $logentry .= " [priority $distance] [weight $weight] [port $port]" if $type eq 'SRV';
|
---|
3579 | $logentry .= " $val', TTL $ttl";
|
---|
3580 | }
|
---|
3581 | _log($dbh, (group_id => $group, domain_id => $domain_id, rdns_id => $rdns_id, entry => $logentry) );
|
---|
3582 |
|
---|
3583 | } # while axfr_next
|
---|
3584 |
|
---|
3585 | # Detect and handle delegated subzones
|
---|
3586 | # Placeholder for when we decide what to actually do with this, see previous comments in NS and CNAME handling.
|
---|
3587 | #foreach (keys %suboct) {
|
---|
3588 | # print "found ".($suboct{$_}{ns} ? @{$suboct{$_}{ns}} : '0')." NS records and ".
|
---|
3589 | # ($suboct{$_}{cname} ? @{$suboct{$_}{cname}} : '0')." CNAMEs for $_\n";
|
---|
3590 | #}
|
---|
3591 |
|
---|
3592 | # Overwrite SOA record
|
---|
3593 | if ($rwsoa) {
|
---|
3594 | $soaflag = 1;
|
---|
3595 | my $sthgetsoa = $dbh->prepare("SELECT host,val,ttl FROM default_records WHERE group_id=? AND type=?");
|
---|
3596 | my $sthputsoa = $dbh->prepare("INSERT INTO records (domain_id,host,type,val,ttl) VALUES (?,?,?,?,?)");
|
---|
3597 | $sthgetsoa->execute($group,$reverse_typemap{SOA});
|
---|
3598 | while (my ($host,$val,$ttl) = $sthgetsoa->fetchrow_array()) {
|
---|
3599 | $host =~ s/DOMAIN/$zone/g;
|
---|
3600 | $val =~ s/DOMAIN/$zone/g;
|
---|
3601 | $sthputsoa->execute($zone_id,$host,$reverse_typemap{SOA},$val,$ttl);
|
---|
3602 | }
|
---|
3603 | }
|
---|
3604 |
|
---|
3605 | # Overwrite NS records
|
---|
3606 | if ($rwns) {
|
---|
3607 | $nsflag = 1;
|
---|
3608 | my $sthgetns = $dbh->prepare("SELECT host,val,ttl FROM default_records WHERE group_id=? AND type=?");
|
---|
3609 | my $sthputns = $dbh->prepare("INSERT INTO records (domain_id,host,type,val,ttl) VALUES (?,?,?,?,?)");
|
---|
3610 | $sthgetns->execute($group,$reverse_typemap{NS});
|
---|
3611 | while (my ($host,$val,$ttl) = $sthgetns->fetchrow_array()) {
|
---|
3612 | $host =~ s/DOMAIN/$zone/g;
|
---|
3613 | $val =~ s/DOMAIN/$zone/g;
|
---|
3614 | $sthputns->execute($zone_id,$host,$reverse_typemap{NS},$val,$ttl);
|
---|
3615 | }
|
---|
3616 | }
|
---|
3617 |
|
---|
3618 | die "No records found; either $ifrom is not authoritative or doesn't allow transfers\n" if !$nrecs;
|
---|
3619 | die "Bad zone: No SOA record!\n" if !$soaflag;
|
---|
3620 | die "Bad zone: No NS records!\n" if !$nsflag;
|
---|
3621 |
|
---|
3622 | $dbh->commit;
|
---|
3623 |
|
---|
3624 | };
|
---|
3625 |
|
---|
3626 | if ($@) {
|
---|
3627 | my $msg = $@;
|
---|
3628 | eval { $dbh->rollback; };
|
---|
3629 | return ('FAIL',$msg." $warnmsg");
|
---|
3630 | } else {
|
---|
3631 | return ('WARN', $warnmsg) if $warnmsg;
|
---|
3632 | return ('OK',"Imported OK");
|
---|
3633 | }
|
---|
3634 |
|
---|
3635 | # it should be impossible to get here.
|
---|
3636 | return ('WARN',"OOOK!");
|
---|
3637 | } # end importAXFR()
|
---|
3638 |
|
---|
3639 |
|
---|
3640 | ## DNSDB::importBIND()
|
---|
3641 | sub importBIND {
|
---|
3642 | } # end importBIND()
|
---|
3643 |
|
---|
3644 |
|
---|
3645 | ## DNSDB::import_tinydns()
|
---|
3646 | sub import_tinydns {
|
---|
3647 | } # end import_tinydns()
|
---|
3648 |
|
---|
3649 |
|
---|
3650 | ## DNSDB::export()
|
---|
3651 | # Export the DNS database, or a part of it
|
---|
3652 | # Takes database handle, export type, optional arguments depending on type
|
---|
3653 | # Writes zone data to targets as appropriate for type
|
---|
3654 | sub export {
|
---|
3655 | my $dbh = shift;
|
---|
3656 | my $target = shift;
|
---|
3657 |
|
---|
3658 | if ($target eq 'tiny') {
|
---|
3659 | __export_tiny($dbh,@_);
|
---|
3660 | }
|
---|
3661 | # elsif ($target eq 'foo') {
|
---|
3662 | # __export_foo($dbh,@_);
|
---|
3663 | #}
|
---|
3664 | # etc
|
---|
3665 |
|
---|
3666 | } # end export()
|
---|
3667 |
|
---|
3668 |
|
---|
3669 | ## DNSDB::__export_tiny
|
---|
3670 | # Internal sub to implement tinyDNS (compatible) export
|
---|
3671 | # Takes database handle, filehandle to write export to, optional argument(s)
|
---|
3672 | # to determine which data gets exported
|
---|
3673 | sub __export_tiny {
|
---|
3674 | my $dbh = shift;
|
---|
3675 | my $datafile = shift;
|
---|
3676 |
|
---|
3677 | ##fixme: slurp up further options to specify particular zone(s) to export
|
---|
3678 |
|
---|
3679 | ## Convert a bare number into an octal-coded pair of octets.
|
---|
3680 | # Take optional arg to indicate a decimal or hex input. Defaults to hex.
|
---|
3681 | sub octalize {
|
---|
3682 | my $tmp = shift;
|
---|
3683 | my $srctype = shift || 'h'; # default assumes hex string
|
---|
3684 | $tmp = sprintf "%0.4x", hex($tmp) if $srctype eq 'h'; # 0-pad hex to 4 digits
|
---|
3685 | $tmp = sprintf "%0.4x", $tmp if $srctype eq 'd'; # 0-pad decimal to 4 hex digits
|
---|
3686 | my @o = ($tmp =~ /^(..)(..)$/); # split into octets
|
---|
3687 | return sprintf "\\%0.3o\\%0.3o", hex($o[0]), hex($o[1]);;
|
---|
3688 | }
|
---|
3689 |
|
---|
3690 | ##fixme: fail if $datafile isn't an open, writable file
|
---|
3691 |
|
---|
3692 | # easy case - export all evarything
|
---|
3693 | # not-so-easy case - export item(s) specified
|
---|
3694 | # todo: figure out what kind of list we use to export items
|
---|
3695 |
|
---|
3696 | my $domsth = $dbh->prepare("SELECT domain_id,domain,status FROM domains WHERE status=1");
|
---|
3697 | my $recsth = $dbh->prepare("SELECT host,type,val,distance,weight,port,ttl ".
|
---|
3698 | "FROM records WHERE domain_id=?");
|
---|
3699 | $domsth->execute();
|
---|
3700 | while (my ($domid,$dom,$domstat) = $domsth->fetchrow_array) {
|
---|
3701 | $recsth->execute($domid);
|
---|
3702 | while (my ($host,$type,$val,$dist,$weight,$port,$ttl) = $recsth->fetchrow_array) {
|
---|
3703 | ##fixme: need to store location in the db, and retrieve it here.
|
---|
3704 | # temporarily hardcoded to empty so we can include it further down.
|
---|
3705 | my $loc = '';
|
---|
3706 |
|
---|
3707 | ##fixme: record validity timestamp. tinydns supports fiddling with timestamps.
|
---|
3708 | # note $ttl must be set to 0 if we want to use tinydns's auto-expiring timestamps.
|
---|
3709 | # timestamps are TAI64
|
---|
3710 | # ~~ 2^62 + time()
|
---|
3711 | my $stamp = '';
|
---|
3712 |
|
---|
3713 | # raw packet in unknown format: first byte indicates length
|
---|
3714 | # of remaining data, allows up to 255 raw bytes
|
---|
3715 |
|
---|
3716 | ##fixme? append . to all host/val hostnames
|
---|
3717 | if ($typemap{$type} eq 'SOA') {
|
---|
3718 |
|
---|
3719 | # host contains pri-ns:responsible
|
---|
3720 | # val is abused to contain refresh:retry:expire:minttl
|
---|
3721 | ##fixme: "manual" serial vs tinydns-autoserial
|
---|
3722 | # let's be explicit about abusing $host and $val
|
---|
3723 | my ($email, $primary) = (split /:/, $host)[0,1];
|
---|
3724 | my ($refresh, $retry, $expire, $min_ttl) = (split /:/, $val)[0,1,2,3];
|
---|
3725 | print $datafile "Z$dom:$primary:$email"."::$refresh:$retry:$expire:$min_ttl:$ttl:$stamp:$loc\n";
|
---|
3726 |
|
---|
3727 | } elsif ($typemap{$type} eq 'A') {
|
---|
3728 |
|
---|
3729 | print $datafile "+$host:$val:$ttl:$stamp:$loc\n";
|
---|
3730 |
|
---|
3731 | } elsif ($typemap{$type} eq 'NS') {
|
---|
3732 |
|
---|
3733 | print $datafile "\&$host"."::$val:$ttl:$stamp:$loc\n";
|
---|
3734 |
|
---|
3735 | } elsif ($typemap{$type} eq 'AAAA') {
|
---|
3736 |
|
---|
3737 | print $datafile ":$host:28:";
|
---|
3738 | my $altgrp = 0;
|
---|
3739 | my @altconv;
|
---|
3740 | # Split in to up to 8 groups of hex digits (allows for IPv6 :: 0-collapsing)
|
---|
3741 | foreach (split /:/, $val) {
|
---|
3742 | if (/^$/) {
|
---|
3743 | # flag blank entry; this is a series of 0's of (currently) unknown length
|
---|
3744 | $altconv[$altgrp++] = 's';
|
---|
3745 | } else {
|
---|
3746 | # call sub to convert 1-4 hex digits to 2 string-rep octal bytes
|
---|
3747 | $altconv[$altgrp++] = octalize($_)
|
---|
3748 | }
|
---|
3749 | }
|
---|
3750 | foreach my $octet (@altconv) {
|
---|
3751 | # if not 's', output
|
---|
3752 | print $datafile $octet unless $octet =~ /^s$/;
|
---|
3753 | # if 's', output (9-array length)x literal '\000\000'
|
---|
3754 | print $datafile '\000\000'x(9-$altgrp) if $octet =~ /^s$/;
|
---|
3755 | }
|
---|
3756 | print $datafile ":$ttl:$stamp:$loc\n";
|
---|
3757 |
|
---|
3758 | } elsif ($typemap{$type} eq 'MX') {
|
---|
3759 |
|
---|
3760 | print $datafile "\@$host"."::$val:$dist:$ttl:$stamp:$loc\n";
|
---|
3761 |
|
---|
3762 | } elsif ($typemap{$type} eq 'TXT') {
|
---|
3763 |
|
---|
3764 | ##fixme: split v-e-r-y long TXT strings? will need to do so for BIND export, at least
|
---|
3765 | $val =~ s/:/\\072/g; # may need to replace other symbols
|
---|
3766 | print $datafile "'$host:$val:$ttl:$stamp:$loc\n";
|
---|
3767 |
|
---|
3768 | # by-hand TXT
|
---|
3769 | #:deepnet.cx:16:2v\075spf1\040a\040a\072bacon.deepnet.cx\040a\072home.deepnet.cx\040-all:3600
|
---|
3770 | #@ IN TXT "v=spf1 a a:bacon.deepnet.cx a:home.deepnet.cx -all"
|
---|
3771 | #'deepnet.cx:v=spf1 a a\072bacon.deepnet.cx a\072home.deepnet.cx -all:3600
|
---|
3772 |
|
---|
3773 | #txttest IN TXT "v=foo bar:bob kn;ob' \" !@#$%^&*()-=_+[]{}<>?"
|
---|
3774 | #:txttest.deepnet.cx:16:\054v\075foo\040bar\072bob\040kn\073ob\047\040\042\040\041\100\043\044\045\136\046\052\050\051-\075\137\053\133\135\173\175\074\076\077:3600
|
---|
3775 |
|
---|
3776 | # very long TXT record as brought in by axfr-get
|
---|
3777 | # note tinydns does not support >512-byte RR data, need axfr-dns (for TCP support) for that
|
---|
3778 | # also note, tinydns does not seem to support <512, >256-byte RRdata from axfr-get either. :/
|
---|
3779 | #:longtxt.deepnet.cx:16:
|
---|
3780 | #\170this is a very long txt record. it is really long. long. very long. really very long. this is a very long txt record.
|
---|
3781 | #\263 it is really long. long. very long. really very long. this is a very long txt record. it is really long. long. very long. really very long. this is a very long txt record.
|
---|
3782 | #\351 it is really long. long. very long. really very long.this is a very long txt record. it is really long. long. very long. really very long. this is a very long txt record. it is really long. long. very long. really very long.
|
---|
3783 | #:3600
|
---|
3784 |
|
---|
3785 | } elsif ($typemap{$type} eq 'CNAME') {
|
---|
3786 |
|
---|
3787 | print $datafile "C$host:$val:$ttl:$stamp:$loc\n";
|
---|
3788 |
|
---|
3789 | } elsif ($typemap{$type} eq 'SRV') {
|
---|
3790 |
|
---|
3791 | # data is two-byte values for priority, weight, port, in that order,
|
---|
3792 | # followed by length/string data
|
---|
3793 |
|
---|
3794 | print $datafile ":$host:33:".octalize($dist,'d').octalize($weight,'d').octalize($port,'d');
|
---|
3795 |
|
---|
3796 | $val .= '.' if $val !~ /\.$/;
|
---|
3797 | foreach (split /\./, $val) {
|
---|
3798 | printf $datafile "\\%0.3o%s", length($_), $_;
|
---|
3799 | }
|
---|
3800 | print $datafile "\\000:$ttl:$stamp:$loc\n";
|
---|
3801 |
|
---|
3802 | } elsif ($typemap{$type} eq 'RP') {
|
---|
3803 |
|
---|
3804 | # RP consists of two mostly free-form strings.
|
---|
3805 | # The first is supposed to be an email address with @ replaced by . (as with the SOA contact)
|
---|
3806 | # The second is the "hostname" of a TXT record with more info.
|
---|
3807 | print $datafile ":$host:17:";
|
---|
3808 | my ($who,$what) = split /\s/, $val;
|
---|
3809 | foreach (split /\./, $who) {
|
---|
3810 | printf $datafile "\\%0.3o%s", length($_), $_;
|
---|
3811 | }
|
---|
3812 | print $datafile '\000';
|
---|
3813 | foreach (split /\./, $what) {
|
---|
3814 | printf $datafile "\\%0.3o%s", length($_), $_;
|
---|
3815 | }
|
---|
3816 | print $datafile "\\000:$ttl:$stamp:$loc\n";
|
---|
3817 |
|
---|
3818 | } elsif ($typemap{$type} eq 'PTR') {
|
---|
3819 |
|
---|
3820 | # must handle both IPv4 and IPv6
|
---|
3821 | ##work
|
---|
3822 | # data should already be in suitable reverse order.
|
---|
3823 | print $datafile "^$host:$val:$ttl:$stamp:$loc\n";
|
---|
3824 |
|
---|
3825 | } else {
|
---|
3826 | # raw record. we don't know what's in here, so we ASS-U-ME the user has
|
---|
3827 | # put it in correctly, since either the user is messing directly with the
|
---|
3828 | # database, or the record was imported via AXFR
|
---|
3829 | # <split by char>
|
---|
3830 | # convert anything not a-zA-Z0-9.- to octal coding
|
---|
3831 |
|
---|
3832 | ##fixme: add flag to export "unknown" record types - note we'll probably end up
|
---|
3833 | # mangling them since they were written to the DB from Net::DNS::RR::<type>->rdatastr.
|
---|
3834 | #print $datafile ":$host:$type:$val:$ttl:$stamp:$loc\n";
|
---|
3835 |
|
---|
3836 | } # record type if-else
|
---|
3837 |
|
---|
3838 | } # while ($recsth)
|
---|
3839 | } # while ($domsth)
|
---|
3840 | } # end __export_tiny()
|
---|
3841 |
|
---|
3842 |
|
---|
3843 | ## DNSDB::mailNotify()
|
---|
3844 | # Sends notification mail to recipients regarding a DNSDB operation
|
---|
3845 | sub mailNotify {
|
---|
3846 | my $dbh = shift;
|
---|
3847 | my ($subj,$message) = @_;
|
---|
3848 |
|
---|
3849 | return if $config{mailhost} eq 'smtp.example.com'; # do nothing if still using default SMTP host.
|
---|
3850 |
|
---|
3851 | my $mailer = Net::SMTP->new($config{mailhost}, Hello => "dnsadmin.$config{domain}");
|
---|
3852 |
|
---|
3853 | my $mailsender = ($config{mailsender} ? $config{mailsender} : $config{mailnotify});
|
---|
3854 |
|
---|
3855 | $mailer->mail($mailsender);
|
---|
3856 | $mailer->to($config{mailnotify});
|
---|
3857 | $mailer->data("From: \"$config{mailname}\" <$mailsender>\n",
|
---|
3858 | "To: <$config{mailnotify}>\n",
|
---|
3859 | "Date: ".strftime("%a, %d %b %Y %H:%M:%S %z",localtime)."\n",
|
---|
3860 | "Subject: $subj\n",
|
---|
3861 | "X-Mailer: DNSAdmin Notify v".sprintf("%.1d",$DNSDB::VERSION)."\n",
|
---|
3862 | "Organization: $config{orgname}\n",
|
---|
3863 | "\n$message\n");
|
---|
3864 | $mailer->quit;
|
---|
3865 | }
|
---|
3866 |
|
---|
3867 | # shut Perl up
|
---|
3868 | 1;
|
---|