1 | # dns/trunk/DNSDB.pm
|
---|
2 | # Abstraction functions for DNS administration
|
---|
3 | ##
|
---|
4 | # $Id: DNSDB.pm 652 2014-06-24 17:45:46Z kdeugau $
|
---|
5 | # Copyright 2008-2013 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 Digest::MD5 qw(md5_hex);
|
---|
30 | use Net::SMTP;
|
---|
31 | use NetAddr::IP 4.027 qw(:lower);
|
---|
32 | use POSIX;
|
---|
33 | use Fcntl qw(:flock);
|
---|
34 | use Time::TAI64 qw(:tai64);
|
---|
35 |
|
---|
36 | use vars qw($VERSION @ISA @EXPORT @EXPORT_OK %EXPORT_TAGS);
|
---|
37 |
|
---|
38 | $VERSION = "1.2.4"; ##VERSION##
|
---|
39 | @ISA = qw(Exporter);
|
---|
40 | @EXPORT_OK = qw(
|
---|
41 | &initGlobals &login &initActionLog
|
---|
42 | &getPermissions &changePermissions &comparePermissions
|
---|
43 | &changeGroup
|
---|
44 | &connectDB &finish
|
---|
45 | &addDomain &delZone &domainName &revName &domainID &revID &addRDNS
|
---|
46 | &getZoneCount &getZoneList &getZoneLocation
|
---|
47 | &addGroup &delGroup &getChildren &groupName
|
---|
48 | &getGroupCount &getGroupList
|
---|
49 | &addUser &updateUser &delUser &userFullName &userStatus &getUserData
|
---|
50 | &getUserCount &getUserList &getUserDropdown
|
---|
51 | &addLoc &updateLoc &delLoc &getLoc
|
---|
52 | &getLocCount &getLocList &getLocDropdown
|
---|
53 | &getSOA &updateSOA &getRecLine &getRecList &getRecCount
|
---|
54 | &addRec &updateRec &delRec
|
---|
55 | &getLogCount &getLogEntries
|
---|
56 | &getRevPattern
|
---|
57 | &getTypelist
|
---|
58 | &parentID
|
---|
59 | &isParent
|
---|
60 | &zoneStatus &getZonesByCIDR &importAXFR
|
---|
61 | &export
|
---|
62 | &mailNotify
|
---|
63 | %typemap %reverse_typemap
|
---|
64 | @permtypes $permlist %permchains
|
---|
65 | );
|
---|
66 |
|
---|
67 | @EXPORT = qw(%typemap %reverse_typemap @permtypes $permlist %permchains);
|
---|
68 | %EXPORT_TAGS = ( ALL => [qw(
|
---|
69 | &initGlobals &login &initActionLog
|
---|
70 | &getPermissions &changePermissions &comparePermissions
|
---|
71 | &changeGroup
|
---|
72 | &connectDB &finish
|
---|
73 | &addDomain &delZone &domainName &revName &domainID &revID &addRDNS
|
---|
74 | &getZoneCount &getZoneList &getZoneLocation
|
---|
75 | &addGroup &delGroup &getChildren &groupName
|
---|
76 | &getGroupCount &getGroupList
|
---|
77 | &addUser &updateUser &delUser &userFullName &userStatus &getUserData
|
---|
78 | &getUserCount &getUserList &getUserDropdown
|
---|
79 | &addLoc &updateLoc &delLoc &getLoc
|
---|
80 | &getLocCount &getLocList &getLocDropdown
|
---|
81 | &getSOA &updateSOA &getRecLine &getRecList &getRecCount
|
---|
82 | &addRec &updateRec &delRec
|
---|
83 | &getLogCount &getLogEntries
|
---|
84 | &getRevPattern
|
---|
85 | &getTypelist
|
---|
86 | &parentID
|
---|
87 | &isParent
|
---|
88 | &zoneStatus &getZonesByCIDR &importAXFR
|
---|
89 | &export
|
---|
90 | &mailNotify
|
---|
91 | %typemap %reverse_typemap
|
---|
92 | @permtypes $permlist %permchains
|
---|
93 | )]
|
---|
94 | );
|
---|
95 |
|
---|
96 | our $errstr = '';
|
---|
97 | our $resultstr = '';
|
---|
98 |
|
---|
99 | # Arguably defined wholly in the db, but little reason to change without supporting code changes
|
---|
100 | # group_view, user_view permissions? separate rDNS permission(s)?
|
---|
101 | our @permtypes = qw (
|
---|
102 | group_edit group_create group_delete
|
---|
103 | user_edit user_create user_delete
|
---|
104 | domain_edit domain_create domain_delete
|
---|
105 | record_edit record_create record_delete record_locchg
|
---|
106 | location_edit location_create location_delete location_view
|
---|
107 | self_edit admin
|
---|
108 | );
|
---|
109 | our $permlist = join(',',@permtypes);
|
---|
110 |
|
---|
111 | # Some permissions more or less require certain others.
|
---|
112 | our %permchains = (
|
---|
113 | user_edit => 'self_edit',
|
---|
114 | location_edit => 'location_view',
|
---|
115 | location_create => 'location_view',
|
---|
116 | location_delete => 'location_view',
|
---|
117 | record_locchg => 'location_view',
|
---|
118 | );
|
---|
119 |
|
---|
120 | # DNS record type map and reverse map.
|
---|
121 | # loaded from the database, from http://www.iana.org/assignments/dns-parameters
|
---|
122 | our %typemap;
|
---|
123 | our %reverse_typemap;
|
---|
124 |
|
---|
125 | ## (Semi)private variables
|
---|
126 |
|
---|
127 | # Hash of functions for validating record types. Filled in initGlobals() since
|
---|
128 | # it relies on visibility flags from the rectypes table in the DB
|
---|
129 | my %validators;
|
---|
130 |
|
---|
131 | # Entity-relationship reference hashes.
|
---|
132 | my %par_tbl = (
|
---|
133 | group => 'groups',
|
---|
134 | user => 'users',
|
---|
135 | defrec => 'default_records',
|
---|
136 | defrevrec => 'default_rev_records',
|
---|
137 | domain => 'domains',
|
---|
138 | revzone => 'revzones',
|
---|
139 | record => 'records'
|
---|
140 | );
|
---|
141 | my %id_col = (
|
---|
142 | group => 'group_id',
|
---|
143 | user => 'user_id',
|
---|
144 | defrec => 'record_id',
|
---|
145 | defrevrec => 'record_id',
|
---|
146 | domain => 'domain_id',
|
---|
147 | revzone => 'rdns_id',
|
---|
148 | record => 'record_id'
|
---|
149 | );
|
---|
150 | my %par_col = (
|
---|
151 | group => 'parent_group_id',
|
---|
152 | user => 'group_id',
|
---|
153 | defrec => 'group_id',
|
---|
154 | defrevrec => 'group_id',
|
---|
155 | domain => 'group_id',
|
---|
156 | revzone => 'group_id',
|
---|
157 | record => 'domain_id'
|
---|
158 | );
|
---|
159 | my %par_type = (
|
---|
160 | group => 'group',
|
---|
161 | user => 'group',
|
---|
162 | defrec => 'group',
|
---|
163 | defrevrec => 'group',
|
---|
164 | domain => 'group',
|
---|
165 | revzone => 'group',
|
---|
166 | record => 'domain'
|
---|
167 | );
|
---|
168 |
|
---|
169 | ##
|
---|
170 | ## Constructor and destructor
|
---|
171 | ##
|
---|
172 |
|
---|
173 | sub new {
|
---|
174 | my $this = shift;
|
---|
175 | my $class = ref($this) || $this;
|
---|
176 | my %args = @_;
|
---|
177 |
|
---|
178 | # Prepopulate a basic config. Note some of these *will* cause errors if left unset.
|
---|
179 | # note: add appropriate stanzas in __cfgload() to parse these
|
---|
180 | my %defconfig = (
|
---|
181 | # The only configuration options not loadable from a config file.
|
---|
182 | configfile => "/etc/dnsdb/dnsdb.conf", ##CFG_LEAF##
|
---|
183 |
|
---|
184 | # Database connection info
|
---|
185 | dbname => 'dnsdb',
|
---|
186 | dbuser => 'dnsdb',
|
---|
187 | dbpass => 'secret',
|
---|
188 | dbhost => '',
|
---|
189 |
|
---|
190 | # Email notice settings
|
---|
191 | mailhost => 'smtp.example.com',
|
---|
192 | mailnotify => 'dnsdb@example.com', # to
|
---|
193 | mailsender => 'dnsdb@example.com', # from
|
---|
194 | mailname => 'DNS Administration',
|
---|
195 | orgname => 'Example Corp',
|
---|
196 | domain => 'example.com',
|
---|
197 |
|
---|
198 | # Template directory
|
---|
199 | templatedir => 'templates/',
|
---|
200 | # fmeh. this is a real web path, not a logical internal one. hm..
|
---|
201 | # cssdir => 'templates/',
|
---|
202 | sessiondir => 'session/',
|
---|
203 | exportcache => 'cache/',
|
---|
204 | usecache => 1, # do we bother using the cache above?
|
---|
205 |
|
---|
206 | # Session params
|
---|
207 | timeout => '1h', # passed as-is to CGI::Session
|
---|
208 |
|
---|
209 | # Other miscellanea
|
---|
210 | log_failures => 1, # log all evarthing by default
|
---|
211 | perpage => 15,
|
---|
212 | maxfcgi => 10, # reasonable default?
|
---|
213 | force_refresh => 1,
|
---|
214 | lowercase => 0, # mangle as little as possible by default
|
---|
215 | # show IPs and CIDR blocks as-is for reverse zones. valid values are
|
---|
216 | # 'none' (default, show natural IP or CIDR)
|
---|
217 | # 'zone' (zone name, wherever used)
|
---|
218 | # 'record' (IP or CIDR values in reverse record lists)
|
---|
219 | # 'all' (all IP values in any reverse zone view)
|
---|
220 | showrev_arpa => 'none',
|
---|
221 | # Two options for template record expansion:
|
---|
222 | template_skip_0 => 0, # publish .0 by default
|
---|
223 | template_skip_255 => 0, # publish .255 by default
|
---|
224 | );
|
---|
225 |
|
---|
226 | # Config file parse calls.
|
---|
227 | # If we are passed a blank argument for $args{configfile},
|
---|
228 | # we should NOT parse the default config file - we will
|
---|
229 | # rely on hardcoded defaults OR caller-specified values.
|
---|
230 | # If we are passed a non-blank argument, parse that file.
|
---|
231 | # If no config file is specified, parse the default one.
|
---|
232 | my %siteconfig;
|
---|
233 | if (defined($args{configfile})) {
|
---|
234 | if ($args{configfile}) {
|
---|
235 | return if !__cfgload($args{configfile}, \%siteconfig);
|
---|
236 | }
|
---|
237 | } else {
|
---|
238 | return if !__cfgload($defconfig{configfile}, \%siteconfig);
|
---|
239 | }
|
---|
240 |
|
---|
241 | # Assemble the object. Apply configuration hashes in order of precedence.
|
---|
242 | my $self = {
|
---|
243 | # Hardcoded defaults
|
---|
244 | %defconfig,
|
---|
245 | # Default config file OR caller-specified one, loaded above
|
---|
246 | %siteconfig,
|
---|
247 | # Caller-specified arguments
|
---|
248 | %args
|
---|
249 | };
|
---|
250 | bless $self, $class;
|
---|
251 |
|
---|
252 | # Several settings are booleans. Handle multiple possible ways of setting them.
|
---|
253 | for my $boolopt ('log_failures', 'force_refresh', 'lowercase', 'usecache',
|
---|
254 | 'template_skip_0', 'template_skip_255') {
|
---|
255 | if ($self->{$boolopt} ne '1' && $self->{$boolopt} ne '0') {
|
---|
256 | # true/false, on/off, yes/no all valid.
|
---|
257 | if ($self->{$boolopt} =~ /^(?:true|false|t|f|on|off|yes|no)$/) {
|
---|
258 | if ($self->{$boolopt} =~ /(?:true|t|on|yes)/) {
|
---|
259 | $self->{$boolopt} = 1;
|
---|
260 | } else {
|
---|
261 | $self->{$boolopt} = 0;
|
---|
262 | }
|
---|
263 | } else {
|
---|
264 | warn "Bad $boolopt setting $self->{$boolopt}, using default\n";
|
---|
265 | $self->{$boolopt} = $defconfig{$boolopt};
|
---|
266 | }
|
---|
267 | }
|
---|
268 | }
|
---|
269 |
|
---|
270 | # Enum-ish option(s)
|
---|
271 | if (!grep /$self->{showrev_arpa}/, ('none','zone','record','all')) {
|
---|
272 | warn "Bad showrev_arpa setting $self->{showrev_arpa}, using default\n";
|
---|
273 | $self->{showrev_arpa} = 'none';
|
---|
274 | }
|
---|
275 |
|
---|
276 | # Try to connect to the DB, and initialize a number of handy globals.
|
---|
277 | $self->{dbh} = connectDB($self->{dbname}, $self->{dbuser}, $self->{dbpass}, $self->{dbhost}) or return;
|
---|
278 | $self->initGlobals();
|
---|
279 |
|
---|
280 | return $self;
|
---|
281 | }
|
---|
282 |
|
---|
283 | sub DESTROY {
|
---|
284 | my $self = shift;
|
---|
285 | $self->{dbh}->disconnect if $self->{dbh};
|
---|
286 | }
|
---|
287 |
|
---|
288 | sub errstr { $DNSDB::errstr; }
|
---|
289 |
|
---|
290 | ##
|
---|
291 | ## utility functions
|
---|
292 | ##
|
---|
293 |
|
---|
294 | ## DNSDB::_rectable()
|
---|
295 | # Takes default+rdns flags, returns appropriate table name
|
---|
296 | sub _rectable {
|
---|
297 | my $def = shift;
|
---|
298 | my $rev = shift;
|
---|
299 |
|
---|
300 | return 'records' if $def ne 'y';
|
---|
301 | return 'default_records' if $rev ne 'y';
|
---|
302 | return 'default_rev_records';
|
---|
303 | } # end _rectable()
|
---|
304 |
|
---|
305 | ## DNSDB::_recparent()
|
---|
306 | # Takes default+rdns flags, returns appropriate parent-id column name
|
---|
307 | sub _recparent {
|
---|
308 | my $def = shift;
|
---|
309 | my $rev = shift;
|
---|
310 |
|
---|
311 | return 'group_id' if $def eq 'y';
|
---|
312 | return 'rdns_id' if $rev eq 'y';
|
---|
313 | return 'domain_id';
|
---|
314 | } # end _recparent()
|
---|
315 |
|
---|
316 | ## DNSDB::_ipparent()
|
---|
317 | # Check an IP to be added in a reverse zone to see if it's really in the requested parent.
|
---|
318 | # Takes default and reverse flags, IP (fragment) to check, parent zone ID,
|
---|
319 | # and a reference to a NetAddr::IP object (also used to pass back a fully-reconstructed IP for
|
---|
320 | # database insertion)
|
---|
321 | sub _ipparent {
|
---|
322 | my $self = shift;
|
---|
323 | my $dbh = $self->{dbh};
|
---|
324 | my $defrec = shift;
|
---|
325 | my $revrec = shift;
|
---|
326 | my $val = shift;
|
---|
327 | my $id = shift;
|
---|
328 | my $addr = shift;
|
---|
329 |
|
---|
330 | return if $revrec ne 'y'; # this sub not useful in forward zones
|
---|
331 |
|
---|
332 | $$addr = NetAddr::IP->new($$val); #necessary?
|
---|
333 |
|
---|
334 | # subsub to split, reverse, and overlay an IP fragment on a netblock
|
---|
335 | sub __rev_overlay {
|
---|
336 | my $splitme = shift; # ':' or '.', m'lud?
|
---|
337 | my $parnet = shift;
|
---|
338 | my $val = shift;
|
---|
339 | my $addr = shift;
|
---|
340 |
|
---|
341 | my $joinme = $splitme;
|
---|
342 | $splitme = '\.' if $splitme eq '.';
|
---|
343 | my @working = reverse(split($splitme, $parnet->addr));
|
---|
344 | my @parts = reverse(split($splitme, $$val));
|
---|
345 | for (my $i = 0; $i <= $#parts; $i++) {
|
---|
346 | $working[$i] = $parts[$i];
|
---|
347 | }
|
---|
348 | my $checkme = NetAddr::IP->new(join($joinme, reverse(@working))) or return 0;
|
---|
349 | return 0 unless $checkme->within($parnet);
|
---|
350 | $$addr = $checkme; # force "correct" IP to be recorded.
|
---|
351 | return 1;
|
---|
352 | }
|
---|
353 |
|
---|
354 | my ($parstr) = $dbh->selectrow_array("SELECT revnet FROM revzones WHERE rdns_id = ?", undef, ($id));
|
---|
355 | my $parnet = NetAddr::IP->new($parstr);
|
---|
356 |
|
---|
357 | # Fail early on v6-in-v4 or v4-in-v6. We're not accepting these ATM.
|
---|
358 | return 0 if $parnet->addr =~ /\./ && $$val =~ /:/;
|
---|
359 | return 0 if $parnet->addr =~ /:/ && $$val =~ /\./;
|
---|
360 |
|
---|
361 | if ($$addr && ($$val =~ /^[\da-fA-F][\da-fA-F:]+[\da-fA-F]$/ || $$val =~ m|/\d+$|)) {
|
---|
362 | # the only case where NetAddr::IP's acceptance of legitimate IPs is "correct" is for a proper IPv6 address,
|
---|
363 | # or a netblock (only expected on templates)
|
---|
364 | # the rest we have to restructure before fiddling. *sigh*
|
---|
365 | return 1 if $$addr->within($parnet);
|
---|
366 | } else {
|
---|
367 | # We don't have a complete IP in $$val (yet)... unless we have a netblock
|
---|
368 | if ($parnet->addr =~ /:/) {
|
---|
369 | $$val =~ s/^:+//; # gotta strip'em all...
|
---|
370 | return __rev_overlay(':', $parnet, $val, $addr);
|
---|
371 | }
|
---|
372 | if ($parnet->addr =~ /\./) {
|
---|
373 | $$val =~ s/^\.+//;
|
---|
374 | return __rev_overlay('.', $parnet, $val, $addr);
|
---|
375 | }
|
---|
376 | # should be impossible to get here...
|
---|
377 | }
|
---|
378 | # ... and here.
|
---|
379 | # can't do nuttin' in forward zones
|
---|
380 | } # end _ipparent()
|
---|
381 |
|
---|
382 | ## DNSDB::_maybeip()
|
---|
383 | # Wrapper for quick "does this look like an IP address?" regex, so we don't make dumb copy-paste mistakes
|
---|
384 | sub _maybeip {
|
---|
385 | my $izzit = shift; # reference
|
---|
386 | return 1 if $$izzit =~ m,^(?:[\d\./]+|[0-9a-fA-F:/]+)$,;
|
---|
387 | }
|
---|
388 |
|
---|
389 | ## DNSDB::_inrev()
|
---|
390 | # Check if a given "hostname" is within a given reverse zone
|
---|
391 | # Takes a reference to the "hostname" and the reverse zone CIDR as a NetAddr::IP
|
---|
392 | # Returns true/false. Sets $errstr on errors.
|
---|
393 | sub _inrev {
|
---|
394 | my $self = shift;
|
---|
395 | my $dbh = $self->{dbh};
|
---|
396 | # References, since we might munge them
|
---|
397 | my $fq = shift;
|
---|
398 | my $zone = shift;
|
---|
399 |
|
---|
400 | # set default error
|
---|
401 | $errstr = "$$fq not within $zone";
|
---|
402 |
|
---|
403 | # Unlike forward zones, we will not coerce the data into the reverse zone - an A record
|
---|
404 | # in a reverse zone is already silly enough without appending a mess of 1.2.3.in-addr.arpa
|
---|
405 | # (or worse, 1.2.3.4.5.6.7.8.ip6.arpa) on the end of the nominal "hostname".
|
---|
406 | # We're also going to allow the "hostname" to be stored as .arpa or IP, because of
|
---|
407 | # non-IP FQDNs in .arpa
|
---|
408 | if ($$fq =~ /\.arpa$/) {
|
---|
409 | # "FQDN" could be any syntactically legitimate string, but it must be within the formal
|
---|
410 | # .arpa zone. Note we're not validating these for correct reverse-IP values.
|
---|
411 | # yes, we really need the v6 branch on the end here.
|
---|
412 | $zone = _ZONE($zone, 'ZONE', 'r', '.').($zone->{isv6} ? '.ip6.arpa' : '.in-addr.arpa');
|
---|
413 | return unless $$fq =~ /$zone$/;
|
---|
414 | } else {
|
---|
415 | # in most cases we should be getting a real IP as the "FQDN" to test
|
---|
416 | my $addr = new NetAddr::IP $$fq if _maybeip($fq);
|
---|
417 |
|
---|
418 | # "FQDN" should be a valid IP address. Normalize formatting if so.
|
---|
419 | if (!$addr) {
|
---|
420 | $errstr = "$$fq is not a valid IP address";
|
---|
421 | return;
|
---|
422 | }
|
---|
423 | return if !$zone->contains($addr);
|
---|
424 | ($$fq = $addr) =~ s{/(?:32|128)$}{};
|
---|
425 | }
|
---|
426 | return 1;
|
---|
427 | } # end _inrev()
|
---|
428 |
|
---|
429 | ## DNSDB::_hostparent()
|
---|
430 | # A little different than _ipparent above; this tries to *find* the parent zone of a hostname
|
---|
431 | # Takes a hostname.
|
---|
432 | # Returns the domain ID of the parent domain if one was found.
|
---|
433 | sub _hostparent {
|
---|
434 | my $self = shift;
|
---|
435 | my $dbh = $self->{dbh};
|
---|
436 | my $hname = shift;
|
---|
437 |
|
---|
438 | $hname =~ s/^\*\.//; # this should be impossible to find in the domains table.
|
---|
439 | my @hostbits = split /\./, $hname;
|
---|
440 | my $sth = $dbh->prepare("SELECT count(*),domain_id FROM domains WHERE lower(domain) = lower(?) GROUP BY domain_id");
|
---|
441 | foreach (@hostbits) {
|
---|
442 | $sth->execute($hname);
|
---|
443 | my ($found, $parid) = $sth->fetchrow_array;
|
---|
444 | if ($found) {
|
---|
445 | return $parid;
|
---|
446 | }
|
---|
447 | $hname =~ s/^$_\.//;
|
---|
448 | }
|
---|
449 | } # end _hostparent()
|
---|
450 |
|
---|
451 | ## DNSDB::_log()
|
---|
452 | # Log an action
|
---|
453 | # Takes a log entry hash containing at least:
|
---|
454 | # group_id, log entry
|
---|
455 | # and optionally one or more of:
|
---|
456 | # domain_id, rdns_id
|
---|
457 | # The %userdata hash provides the user ID, username, and fullname
|
---|
458 | sub _log {
|
---|
459 | my $self = shift;
|
---|
460 | my $dbh = $self->{dbh};
|
---|
461 |
|
---|
462 | my %args = @_;
|
---|
463 |
|
---|
464 | $args{rdns_id} = 0 if !$args{rdns_id};
|
---|
465 | $args{domain_id} = 0 if !$args{domain_id};
|
---|
466 |
|
---|
467 | ##fixme: farm out the actual logging to different subs for file, syslog, internal, etc based on config
|
---|
468 | # if ($self->{log_channel} eq 'sql') {
|
---|
469 | $dbh->do("INSERT INTO log (domain_id,rdns_id,group_id,entry,user_id,email,name) VALUES (?,?,?,?,?,?,?)",
|
---|
470 | undef,
|
---|
471 | ($args{domain_id}, $args{rdns_id}, $args{group_id}, $args{entry},
|
---|
472 | $self->{loguserid}, $self->{logusername}, $self->{logfullname}) );
|
---|
473 | # } elsif ($self->{log_channel} eq 'file') {
|
---|
474 | # } elsif ($self->{log_channel} eq 'syslog') {
|
---|
475 | # }
|
---|
476 | } # end _log
|
---|
477 |
|
---|
478 |
|
---|
479 | ##
|
---|
480 | ## Record validation subs.
|
---|
481 | ##
|
---|
482 |
|
---|
483 | ## All of these subs take substantially the same arguments:
|
---|
484 | # a hash containing at least the following keys:
|
---|
485 | # - defrec (default/live flag)
|
---|
486 | # - revrec (forward/reverse flag)
|
---|
487 | # - id (parent entity ID)
|
---|
488 | # - host (hostname)
|
---|
489 | # - rectype
|
---|
490 | # - val (IP, hostname [CNAME/MX/SRV] or text)
|
---|
491 | # - addr (NetAddr::IP object from val. May be undef.)
|
---|
492 | # MX and SRV record validation also expect distance, and SRV records expect weight and port as well.
|
---|
493 | # host, rectype, and addr should be references as these may be modified in validation
|
---|
494 |
|
---|
495 | # A record
|
---|
496 | sub _validate_1 {
|
---|
497 | my $self = shift;
|
---|
498 | my $dbh = $self->{dbh};
|
---|
499 |
|
---|
500 | my %args = @_;
|
---|
501 |
|
---|
502 | # only for strict type restrictions
|
---|
503 | # return ('FAIL', 'Reverse zones cannot contain A records') if $args{revrec} eq 'y';
|
---|
504 |
|
---|
505 | if ($args{revrec} eq 'y') {
|
---|
506 | # Get the revzone, so we can see if ${$args{val}} is in that zone
|
---|
507 | my $revzone = new NetAddr::IP $self->revName($args{id}, 'y');
|
---|
508 |
|
---|
509 | return ('FAIL', $errstr) if !$self->_inrev($args{val}, $revzone);
|
---|
510 |
|
---|
511 | # ${$args{val}} is either a valid IP or a string ending with the .arpa zone name;
|
---|
512 | # now check if it's a well-formed FQDN
|
---|
513 | return ('FAIL', $errstr) if ! _check_hostname_form(${$args{val}}, ${$args{rectype}}, $args{defrec}, $args{revrec}) &&
|
---|
514 | ${$args{val}} =~ /\.arpa$/;
|
---|
515 |
|
---|
516 | # Check IP is well-formed, and that it's a v4 address
|
---|
517 | # Fail on "compact" IPv4 variants, because they are not consistent and predictable.
|
---|
518 | return ('FAIL',"A record must be a valid IPv4 address")
|
---|
519 | unless ${$args{host}} =~ /^\d+\.\d+\.\d+\.\d+$/;
|
---|
520 | $args{addr} = new NetAddr::IP ${$args{host}};
|
---|
521 | return ('FAIL',"A record must be a valid IPv4 address")
|
---|
522 | unless $args{addr} && !$args{addr}->{isv6};
|
---|
523 | # coerce IP/value to normalized form for storage
|
---|
524 | ${$args{host}} = $args{addr}->addr;
|
---|
525 |
|
---|
526 | # I'm just going to ignore the utterly barmy idea of an A record in the *default*
|
---|
527 | # records for a reverse zone; it's bad enough to find one in funky legacy data.
|
---|
528 |
|
---|
529 | } else {
|
---|
530 | # revrec ne 'y'
|
---|
531 |
|
---|
532 | # Coerce all hostnames to end in ".DOMAIN" for group/default records,
|
---|
533 | # or the intended parent domain for live records.
|
---|
534 | my $pname = ($args{defrec} eq 'y' ? 'DOMAIN' : $self->domainName($args{id}));
|
---|
535 | ${$args{host}} =~ s/\.*$/\.$pname/ if (${$args{host}} ne '@' && ${$args{host}} !~ /$pname$/);
|
---|
536 |
|
---|
537 | # Check if it's a proper formal .arpa name for an IP, and renormalize it to the IP
|
---|
538 | # value if so. Done mainly for symmetry with PTR/A+PTR, and saves a conversion on export.
|
---|
539 | if (${$args{val}} =~ /\.arpa$/) {
|
---|
540 | my ($code,$tmp) = _zone2cidr(${$args{val}});
|
---|
541 | if ($code ne 'FAIL') {
|
---|
542 | ${$args{val}} = $tmp->addr;
|
---|
543 | $args{addr} = $tmp;
|
---|
544 | }
|
---|
545 | }
|
---|
546 | # Check IP is well-formed, and that it's a v4 address
|
---|
547 | # Fail on "compact" IPv4 variants, because they are not consistent and predictable.
|
---|
548 | return ('FAIL',"A record must be a valid IPv4 address")
|
---|
549 | unless ${$args{val}} =~ /^\d+\.\d+\.\d+\.\d+$/;
|
---|
550 | $args{addr} = new NetAddr::IP ${$args{val}};
|
---|
551 | return ('FAIL',"A record must be a valid IPv4 address")
|
---|
552 | unless $args{addr} && !$args{addr}->{isv6};
|
---|
553 | # coerce IP/value to normalized form for storage
|
---|
554 | ${$args{val}} = $args{addr}->addr;
|
---|
555 | }
|
---|
556 |
|
---|
557 | return ('OK','OK');
|
---|
558 | } # done A record
|
---|
559 |
|
---|
560 | # NS record
|
---|
561 | sub _validate_2 {
|
---|
562 | my $self = shift;
|
---|
563 | my $dbh = $self->{dbh};
|
---|
564 |
|
---|
565 | my %args = @_;
|
---|
566 |
|
---|
567 | # NS target check - IP addresses not allowed. Must be a more or less well-formed hostname.
|
---|
568 | if ($args{revrec} eq 'y') {
|
---|
569 | return ('FAIL', "NS records cannot point directly to an IP address")
|
---|
570 | if ${$args{host}} =~ /^(?:[\d.]+|[0-9a-fA-F:]+)$/;
|
---|
571 | ##enhance: Look up the passed value to see if it exists. Ooo, fancy.
|
---|
572 | return ('FAIL', $errstr) if ! _check_hostname_form(${$args{host}}, ${$args{rectype}}, $args{defrec}, $args{revrec});
|
---|
573 | } else {
|
---|
574 | return ('FAIL', "NS records cannot point directly to an IP address")
|
---|
575 | if ${$args{val}} =~ /^(?:[\d.]+|[0-9a-fA-F:]+)$/;
|
---|
576 | ##enhance: Look up the passed value to see if it exists. Ooo, fancy.
|
---|
577 | return ('FAIL', $errstr) if ! _check_hostname_form(${$args{val}}, ${$args{rectype}}, $args{defrec}, $args{revrec});
|
---|
578 | }
|
---|
579 |
|
---|
580 | # Check that the target of the record is within the parent.
|
---|
581 | if ($args{defrec} eq 'n') {
|
---|
582 | # Check if IP/address/zone/"subzone" is within the parent
|
---|
583 | if ($args{revrec} eq 'y') {
|
---|
584 | # Get the revzone, so we can see if ${$args{val}} is in that zone
|
---|
585 | my $revzone = new NetAddr::IP $self->revName($args{id}, 'y');
|
---|
586 |
|
---|
587 | # Note the NS record may or may not be for the zone itself, it may be a pointer for a subzone
|
---|
588 | return ('FAIL', $errstr) if !$self->_inrev($args{val}, $revzone);
|
---|
589 |
|
---|
590 | # ${$args{val}} is either a valid IP or a string ending with the .arpa zone name;
|
---|
591 | # now check if it's a well-formed FQDN
|
---|
592 | ##enhance or ##fixme
|
---|
593 | # convert well-formed .arpa names to IP addresses to match old "strict" validation design
|
---|
594 | return ('FAIL', $errstr) if ! _check_hostname_form(${$args{val}}, ${$args{rectype}}, $args{defrec}, $args{revrec}) &&
|
---|
595 | ${$args{val}} =~ /\.arpa$/;
|
---|
596 | } else {
|
---|
597 | # Forcibly append the domain name if the hostname being added does not end with the current domain name
|
---|
598 | my $pname = $self->domainName($args{id});
|
---|
599 | ${$args{host}} =~ s/\.*$/\.$pname/ if ${$args{host}} !~ /$pname$/;
|
---|
600 | }
|
---|
601 | } else {
|
---|
602 | # Default reverse NS records should always refer to the implied parent.
|
---|
603 | if ($args{revrec} eq 'y') {
|
---|
604 | ${$args{val}} = 'ZONE';
|
---|
605 | } else {
|
---|
606 | ${$args{host}} = 'DOMAIN';
|
---|
607 | }
|
---|
608 | }
|
---|
609 |
|
---|
610 | return ('OK','OK');
|
---|
611 | } # done NS record
|
---|
612 |
|
---|
613 | # CNAME record
|
---|
614 | sub _validate_5 {
|
---|
615 | my $self = shift;
|
---|
616 | my $dbh = $self->{dbh};
|
---|
617 |
|
---|
618 | my %args = @_;
|
---|
619 |
|
---|
620 | # CNAMEs in reverse zones shouldn't be handled manually, they should be generated on
|
---|
621 | # export by use of the "delegation" type. For the masochistic, and those importing
|
---|
622 | # legacy data from $deity-knows-where, we'll support them.
|
---|
623 |
|
---|
624 | if ($args{revrec} eq 'y') {
|
---|
625 | # CNAME target check - IP addresses not allowed. Must be a more or less well-formed hostname.
|
---|
626 | return ('FAIL', "CNAME records cannot point directly to an IP address")
|
---|
627 | if ${$args{host}} =~ /^(?:[\d.]+|[0-9a-fA-F:]+)$/;
|
---|
628 |
|
---|
629 | if ($args{defrec} eq 'n') {
|
---|
630 | # Get the revzone, so we can see if ${$args{val}} is in that zone
|
---|
631 | my $revzone = new NetAddr::IP $self->revName($args{id}, 'y');
|
---|
632 | return ('FAIL', $errstr) if !$self->_inrev($args{val}, $revzone);
|
---|
633 | # CNAMEs can not be used for parent nodes; just leaf nodes with no other record types
|
---|
634 | # note that this WILL probably miss some edge cases.
|
---|
635 | if (${$args{val}} =~ /^[\d.\/]+$/) {
|
---|
636 | # convert IP "hostname" to .arpa
|
---|
637 | my $tmphn = _ZONE(NetAddr::IP->new(${$args{val}}), 'ZONE', 'r', '.');
|
---|
638 | my $tmpz = _ZONE($revzone, 'ZONE', 'r', '.');
|
---|
639 | return ('FAIL', "The bare zone may not be a CNAME") if $tmphn eq $tmpz;
|
---|
640 | }
|
---|
641 | }
|
---|
642 |
|
---|
643 | ##enhance or ##fixme
|
---|
644 | # convert well-formed .arpa names to IP addresses to match old "strict" validation design
|
---|
645 | return ('FAIL', $errstr) if ! _check_hostname_form(${$args{val}}, ${$args{rectype}}, $args{defrec}, $args{revrec}) &&
|
---|
646 | ${$args{val}} =~ /\.arpa$/;
|
---|
647 |
|
---|
648 | ##enhance: Look up the passed value to see if it exists. Ooo, fancy.
|
---|
649 | return ('FAIL', $errstr) if ! _check_hostname_form(${$args{host}}, ${$args{rectype}}, $args{defrec}, $args{revrec});
|
---|
650 | } else {
|
---|
651 | # CNAME target check - IP addresses not allowed. Must be a more or less well-formed hostname.
|
---|
652 | return ('FAIL', "CNAME records cannot point directly to an IP address")
|
---|
653 | if ${$args{val}} =~ /^(?:[\d.]+|[0-9a-fA-F:]+)$/;
|
---|
654 |
|
---|
655 | # Forcibly append the domain name if the hostname being added does not end with the current domain name
|
---|
656 | my $pname = ($args{defrec} eq 'y' ? 'DOMAIN' : $self->domainName($args{id}));
|
---|
657 | ${$args{host}} =~ s/\.*$/\.$pname/ if ${$args{host}} !~ /$pname$/;
|
---|
658 |
|
---|
659 | # CNAMEs can not be used for parent nodes; just leaf nodes with no other record types
|
---|
660 | # Enforce this for the zone name
|
---|
661 | return ('FAIL', "The bare zone name may not be a CNAME") if ${$args{host}} eq $pname;
|
---|
662 |
|
---|
663 | ##enhance: Look up the passed value to see if it exists. Ooo, fancy.
|
---|
664 | return ('FAIL', $errstr) if ! _check_hostname_form(${$args{val}}, ${$args{rectype}}, $args{defrec}, $args{revrec});
|
---|
665 | }
|
---|
666 |
|
---|
667 | return ('OK','OK');
|
---|
668 | } # done CNAME record
|
---|
669 |
|
---|
670 | # SOA record
|
---|
671 | sub _validate_6 {
|
---|
672 | # Smart monkeys won't stick their fingers in here; we have
|
---|
673 | # separate dedicated routines to deal with SOA records.
|
---|
674 | return ('OK','OK');
|
---|
675 | } # done SOA record
|
---|
676 |
|
---|
677 | # PTR record
|
---|
678 | sub _validate_12 {
|
---|
679 | my $self = shift;
|
---|
680 | my $dbh = $self->{dbh};
|
---|
681 |
|
---|
682 | my %args = @_;
|
---|
683 | my $warnflag = '';
|
---|
684 |
|
---|
685 | if ($args{defrec} eq 'y') {
|
---|
686 | if ($args{revrec} eq 'y') {
|
---|
687 | if (${$args{val}} =~ /^[\d.]+$/) {
|
---|
688 | # v4 or bare number
|
---|
689 | if (${$args{val}} =~ /^\d+\.\d+\.\d+\.\d+$/) {
|
---|
690 | # probable full IP. pointless but harmless. validate/normalize.
|
---|
691 | my $tmp = NetAddr::IP->new(${$args{val}})->addr
|
---|
692 | or return ('FAIL', "${$args{val}} is not a valid IP address");
|
---|
693 | ${$args{val}} = $tmp;
|
---|
694 | $warnflag = "${$args{val}} will only be added to a small number of zones\n";
|
---|
695 | } elsif (${$args{val}} =~ /^\d+$/) {
|
---|
696 | # bare number. This can be expanded to either a v4 or v6 zone
|
---|
697 | ${$args{val}} =~ s/^\.*/ZONE./ unless ${$args{val}} =~ /^ZONE/;
|
---|
698 | } else {
|
---|
699 | # $deity-only-knows what kind of gibberish we've been given. Only usable as a formal .arpa name.
|
---|
700 | # Append ARPAZONE to be replaced with the formal .arpa zone name when converted to a live record.
|
---|
701 | ${$args{val}} =~ s/\.*$/.ARPAZONE/ unless ${$args{val}} =~ /ARPAZONE$/;
|
---|
702 | }
|
---|
703 | } elsif (${$args{val}} =~ /^[a-fA-F0-9:]+$/) {
|
---|
704 | # v6 or fragment; pray it's not complete gibberish
|
---|
705 | ${$args{val}} =~ s/^:*/ZONE::/ unless ${$args{val}} =~ /^ZONE/;
|
---|
706 | } else {
|
---|
707 | # $deity-only-knows what kind of gibberish we've been given. Only usable as a formal .arpa name.
|
---|
708 | # Append ARPAZONE to be replaced with the formal .arpa zone name when converted to a live record.
|
---|
709 | ${$args{val}} .= ".ARPAZONE" unless ${$args{val}} =~ /ARPAZONE$/;
|
---|
710 | }
|
---|
711 | } else {
|
---|
712 | return ('FAIL', "PTR records are not supported in default record sets for forward zones (domains)");
|
---|
713 | }
|
---|
714 | } else {
|
---|
715 | if ($args{revrec} eq 'y') {
|
---|
716 | # Get the revzone, so we can see if ${$args{val}} is in that zone
|
---|
717 | my $revzone = new NetAddr::IP $self->revName($args{id}, 'y');
|
---|
718 |
|
---|
719 | return ('FAIL', $errstr) if !$self->_inrev($args{val}, $revzone);
|
---|
720 |
|
---|
721 | if (${$args{val}} =~ /\.arpa$/) {
|
---|
722 | # Check that it's well-formed
|
---|
723 | return ('FAIL', $errstr) if ! _check_hostname_form(${$args{val}}, ${$args{rectype}}, $args{defrec}, $args{revrec});
|
---|
724 |
|
---|
725 | # Check if it's a proper formal .arpa name for an IP, and renormalize it to the IP
|
---|
726 | # value if so. I can't see why someone would voluntarily work with those instead of
|
---|
727 | # the natural IP values but what the hey.
|
---|
728 | my ($code,$tmp) = _zone2cidr(${$args{val}});
|
---|
729 | ${$args{val}} = $tmp->addr if $code ne 'FAIL';
|
---|
730 | } else {
|
---|
731 | # not a formal .arpa name, so it should be an IP value. Validate...
|
---|
732 | return ('FAIL', "${$args{val}} is not a valid IP value")
|
---|
733 | unless ${$args{val}} =~ /^(?:\d+\.\d+\.\d+\.\d+|[a-fA-F0-9:]+)$/;
|
---|
734 | $args{addr} = NetAddr::IP->new(${$args{val}})
|
---|
735 | or return ('FAIL', "IP/value looks like an IP address but isn't valid");
|
---|
736 | # ... and normalize.
|
---|
737 | ${$args{val}} = $args{addr}->addr;
|
---|
738 | }
|
---|
739 | # Validate PTR target for form.
|
---|
740 | return ('FAIL', $errstr) if ! _check_hostname_form(${$args{host}}, ${$args{rectype}}, $args{defrec}, $args{revrec});
|
---|
741 | } else { # revrec ne 'y'
|
---|
742 | # Fetch the domain and append if the passed hostname isn't within it.
|
---|
743 | my $pname = ($args{defrec} eq 'y' ? 'DOMAIN' : $self->domainName($args{id}));
|
---|
744 | ${$args{host}} =~ s/\.*$/\.$pname/ if ${$args{host}} !~ /$pname$/;
|
---|
745 | # Validate hostname and target for form
|
---|
746 | return ('FAIL', $errstr) if ! _check_hostname_form(${$args{host}}, ${$args{rectype}}, $args{defrec}, $args{revrec});
|
---|
747 | return ('FAIL', $errstr) if ! _check_hostname_form(${$args{val}}, ${$args{rectype}}, $args{defrec}, $args{revrec});
|
---|
748 | }
|
---|
749 | }
|
---|
750 |
|
---|
751 | # Multiple PTR records do NOT generally do what most people believe they do,
|
---|
752 | # and tend to fail in the most awkward way possible. Check and warn.
|
---|
753 |
|
---|
754 | my $chkbase = ${$args{val}};;
|
---|
755 | my $hostcol = 'val'; # Reverse zone hostnames are stored "backwards"
|
---|
756 | if ($args{revrec} eq 'n') { # PTRs in forward zones should be rare.
|
---|
757 | $chkbase = ${$args{host}};
|
---|
758 | $hostcol = 'host';
|
---|
759 | }
|
---|
760 | my @checkvals = ($chkbase);
|
---|
761 | if ($chkbase =~ /,/) {
|
---|
762 | # push . and :: variants into checkvals if $chkbase has ,
|
---|
763 | my $tmp;
|
---|
764 | ($tmp = $chkbase) =~ s/,/./;
|
---|
765 | push @checkvals, $tmp;
|
---|
766 | ($tmp = $chkbase) =~ s/,/::/;
|
---|
767 | push @checkvals, $tmp;
|
---|
768 | }
|
---|
769 |
|
---|
770 | my $pcsth = $dbh->prepare("SELECT count(*) FROM "._rectable($args{defrec},$args{revrec})." WHERE $hostcol = ?");
|
---|
771 | foreach my $checkme (@checkvals) {
|
---|
772 | if ($args{update}) {
|
---|
773 | # $args{update} contains the ID of the record being updated. If the list of records that matches
|
---|
774 | # the new hostname specification doesn't include this, the change effectively adds a new PTR that's
|
---|
775 | # the same as one or more existing ones.
|
---|
776 | my @ptrs = @{ $dbh->selectcol_arrayref("SELECT record_id FROM "._rectable($args{defrec},$args{revrec}).
|
---|
777 | " WHERE val = ?", undef, ($checkme)) };
|
---|
778 | $warnflag .= "PTR record for $checkme already exists; adding another will probably not do what you want"
|
---|
779 | if @ptrs && (!grep /^$args{update}$/, @ptrs);
|
---|
780 | } else {
|
---|
781 | # New record. Always warn if a PTR exists
|
---|
782 | my ($ptrcount) = $dbh->selectrow_array("SELECT count(*) FROM "._rectable($args{defrec},$args{revrec}).
|
---|
783 | " WHERE $hostcol = ?", undef, ($checkme));
|
---|
784 | $warnflag .= "PTR record for $checkme already exists; adding another will probably not do what you want"
|
---|
785 | if $ptrcount;
|
---|
786 | }
|
---|
787 | }
|
---|
788 |
|
---|
789 | return ('WARN',$warnflag) if $warnflag;
|
---|
790 |
|
---|
791 | return ('OK','OK');
|
---|
792 | } # done PTR record
|
---|
793 |
|
---|
794 | # MX record
|
---|
795 | sub _validate_15 {
|
---|
796 | my $self = shift;
|
---|
797 | my $dbh = $self->{dbh};
|
---|
798 |
|
---|
799 | my %args = @_;
|
---|
800 |
|
---|
801 | # only for strict type restrictions
|
---|
802 | # return ('FAIL', 'Reverse zones cannot contain MX records') if $args{revrec} eq 'y';
|
---|
803 |
|
---|
804 | return ('FAIL', "Distance is required for MX records") unless defined(${$args{dist}});
|
---|
805 | ${$args{dist}} =~ s/\s*//g;
|
---|
806 | return ('FAIL',"Distance is required, and must be numeric") unless ${$args{dist}} =~ /^\d+$/;
|
---|
807 |
|
---|
808 | ${$args{fields}} = "distance,";
|
---|
809 | push @{$args{vallist}}, ${$args{dist}};
|
---|
810 |
|
---|
811 | if ($args{revrec} eq 'n') {
|
---|
812 | # MX target check - IP addresses not allowed. Must be a more or less well-formed hostname.
|
---|
813 | return ('FAIL', "MX records cannot point directly to an IP address")
|
---|
814 | if ${$args{val}} =~ /^(?:[\d.]+|[0-9a-fA-F:]+)$/;
|
---|
815 |
|
---|
816 | # Coerce all hostnames to end in ".DOMAIN" for group/default records,
|
---|
817 | # or the intended parent domain for live records.
|
---|
818 | my $pname = ($args{defrec} eq 'y' ? 'DOMAIN' : $self->domainName($args{id}));
|
---|
819 | ${$args{host}} =~ s/\.*$/\.$pname/ if ${$args{host}} !~ /$pname$/;
|
---|
820 | } else {
|
---|
821 | # MX target check - IP addresses not allowed. Must be a more or less well-formed hostname.
|
---|
822 | return ('FAIL', "MX records cannot point directly to an IP address")
|
---|
823 | if ${$args{host}} =~ /^(?:[\d.]+|[0-9a-fA-F:]+)$/;
|
---|
824 |
|
---|
825 | # MX records in reverse zones get stricter treatment. The UI bars adding them in
|
---|
826 | # reverse record sets, but we "need" to allow editing existing ones. And we'll allow
|
---|
827 | # editing them if some loon manually munges one into a default reverse record set.
|
---|
828 | if ($args{defrec} eq 'n') {
|
---|
829 | # Get the revzone, so we can see if ${$args{val}} is in that zone
|
---|
830 | my $revzone = new NetAddr::IP $self->revName($args{id}, 'y');
|
---|
831 | return ('FAIL', $errstr) if !$self->_inrev($args{val}, $revzone);
|
---|
832 | }
|
---|
833 |
|
---|
834 | ##enhance or ##fixme
|
---|
835 | # convert well-formed .arpa names to IP addresses to match old "strict" validation design
|
---|
836 | return ('FAIL', $errstr) if ! _check_hostname_form(${$args{val}}, ${$args{rectype}}, $args{defrec}, $args{revrec}) &&
|
---|
837 | ${$args{val}} =~ /\.arpa$/;
|
---|
838 |
|
---|
839 | ##enhance: Look up the passed value to see if it exists. Ooo, fancy.
|
---|
840 | return ('FAIL', $errstr) if ! _check_hostname_form(${$args{host}}, ${$args{rectype}}, $args{defrec}, $args{revrec});
|
---|
841 |
|
---|
842 | }
|
---|
843 |
|
---|
844 | return ('OK','OK');
|
---|
845 | } # done MX record
|
---|
846 |
|
---|
847 | # TXT record
|
---|
848 | sub _validate_16 {
|
---|
849 | my $self = shift;
|
---|
850 |
|
---|
851 | my %args = @_;
|
---|
852 |
|
---|
853 | if ($args{revrec} eq 'n') {
|
---|
854 | # Coerce all hostnames to end in ".DOMAIN" for group/default records,
|
---|
855 | # or the intended parent domain for live records.
|
---|
856 | my $pname = ($args{defrec} eq 'y' ? 'DOMAIN' : $self->domainName($args{id}));
|
---|
857 | ${$args{host}} =~ s/\.*$/\.$pname/ if ${$args{host}} !~ /$pname$/;
|
---|
858 | return ('FAIL', $errstr) if ! _check_hostname_form(${$args{host}}, ${$args{rectype}}, $args{defrec}, $args{revrec});
|
---|
859 | } else {
|
---|
860 | # We don't coerce reverse "hostnames" into the zone, mainly because we store most sane
|
---|
861 | # records as IP values, not .arpa names.
|
---|
862 | if ($args{defrec} eq 'n') {
|
---|
863 | # Get the revzone, so we can see if ${$args{val}} is in that zone
|
---|
864 | my $revzone = new NetAddr::IP $self->revName($args{id}, 'y');
|
---|
865 | return ('FAIL', $errstr) if !$self->_inrev($args{val}, $revzone);
|
---|
866 | }
|
---|
867 |
|
---|
868 | ##enhance or ##fixme
|
---|
869 | # convert well-formed .arpa names to IP addresses to match old "strict" validation design
|
---|
870 | return ('FAIL', $errstr) if ! _check_hostname_form(${$args{val}}, ${$args{rectype}}, $args{defrec}, $args{revrec}) &&
|
---|
871 | ${$args{val}} =~ /\.arpa$/;
|
---|
872 | }
|
---|
873 |
|
---|
874 | # Could arguably put a WARN return here on very long (>512) records
|
---|
875 | return ('OK','OK');
|
---|
876 | } # done TXT record
|
---|
877 |
|
---|
878 | # RP record
|
---|
879 | sub _validate_17 {
|
---|
880 | # Probably have to validate these separately some day. Call _validate_16() above since
|
---|
881 | # they're otherwise very similar
|
---|
882 | return _validate_16(@_);
|
---|
883 | } # done RP record
|
---|
884 |
|
---|
885 | # AAAA record
|
---|
886 | # Almost but not quite an exact duplicate of A record
|
---|
887 | sub _validate_28 {
|
---|
888 | my $self = shift;
|
---|
889 | my $dbh = $self->{dbh};
|
---|
890 |
|
---|
891 | my %args = @_;
|
---|
892 |
|
---|
893 | # only for strict type restrictions
|
---|
894 | # return ('FAIL', 'Reverse zones cannot contain AAAA records') if $args{revrec} eq 'y';
|
---|
895 |
|
---|
896 | if ($args{revrec} eq 'y') {
|
---|
897 | # Get the revzone, so we can see if ${$args{val}} is in that zone
|
---|
898 | my $revzone = new NetAddr::IP $self->revName($args{id}, 'y');
|
---|
899 |
|
---|
900 | return ('FAIL', $errstr) if !$self->_inrev($args{val}, $revzone);
|
---|
901 |
|
---|
902 | # ${$args{val}} is either a valid IP or a string ending with the .arpa zone name;
|
---|
903 | # now check if it's a well-formed FQDN
|
---|
904 | return ('FAIL', $errstr) if ! _check_hostname_form(${$args{val}}, ${$args{rectype}}, $args{defrec}, $args{revrec}) &&
|
---|
905 | ${$args{val}} =~ /\.arpa$/;
|
---|
906 |
|
---|
907 | # Check IP is well-formed, and that it's a v4 address
|
---|
908 | # Fail on "compact" IPv4 variants, because they are not consistent and predictable.
|
---|
909 | return ('FAIL',"AAAA record must be a valid IPv6 address")
|
---|
910 | unless ${$args{host}} =~ /^[a-fA-F0-9:]+$/;
|
---|
911 | $args{addr} = new NetAddr::IP ${$args{host}};
|
---|
912 | return ('FAIL',"AAAA record must be a valid IPv6 address")
|
---|
913 | unless $args{addr} && $args{addr}->{isv6};
|
---|
914 | # coerce IP/value to normalized form for storage
|
---|
915 | ${$args{host}} = $args{addr}->addr;
|
---|
916 |
|
---|
917 | # I'm just going to ignore the utterly barmy idea of an AAAA record in the *default*
|
---|
918 | # records for a reverse zone; it's bad enough to find one in funky legacy data.
|
---|
919 |
|
---|
920 | } else {
|
---|
921 | # revrec ne 'y'
|
---|
922 |
|
---|
923 | # Coerce all hostnames to end in ".DOMAIN" for group/default records,
|
---|
924 | # or the intended parent domain for live records.
|
---|
925 | my $pname = ($args{defrec} eq 'y' ? 'DOMAIN' : $self->domainName($args{id}));
|
---|
926 | ${$args{host}} =~ s/\.*$/\.$pname/ if (${$args{host}} ne '@' && ${$args{host}} !~ /$pname$/);
|
---|
927 |
|
---|
928 | # Check if it's a proper formal .arpa name for an IP, and renormalize it to the IP
|
---|
929 | # value if so. Done mainly for symmetry with PTR/AAAA+PTR, and saves a conversion on export.
|
---|
930 | if (${$args{val}} =~ /\.arpa$/) {
|
---|
931 | my ($code,$tmp) = _zone2cidr(${$args{val}});
|
---|
932 | if ($code ne 'FAIL') {
|
---|
933 | ${$args{val}} = $tmp->addr;
|
---|
934 | $args{addr} = $tmp;
|
---|
935 | }
|
---|
936 | }
|
---|
937 | # Check IP is well-formed, and that it's a v6 address
|
---|
938 | return ('FAIL',"AAAA record must be a valid IPv6 address")
|
---|
939 | unless ${$args{val}} =~ /^[a-fA-F0-9:]+$/;
|
---|
940 | $args{addr} = new NetAddr::IP ${$args{val}};
|
---|
941 | return ('FAIL',"AAAA record must be a valid IPv6 address")
|
---|
942 | unless $args{addr} && $args{addr}->{isv6};
|
---|
943 | # coerce IP/value to normalized form for storage
|
---|
944 | ${$args{val}} = $args{addr}->addr;
|
---|
945 | }
|
---|
946 |
|
---|
947 | return ('OK','OK');
|
---|
948 | } # done AAAA record
|
---|
949 |
|
---|
950 | # SRV record
|
---|
951 | sub _validate_33 {
|
---|
952 | my $self = shift;
|
---|
953 | my $dbh = $self->{dbh};
|
---|
954 |
|
---|
955 | my %args = @_;
|
---|
956 |
|
---|
957 | # Not absolutely true but WTF use is an SRV record for a reverse zone?
|
---|
958 | return ('FAIL', 'Reverse zones cannot contain SRV records') if $args{revrec} eq 'y';
|
---|
959 |
|
---|
960 | # Key additional record parts. Always required.
|
---|
961 | return ('FAIL',"Distance, port and weight are required for SRV records")
|
---|
962 | unless defined(${$args{weight}}) && defined(${$args{port}}) && defined(${$args{dist}});
|
---|
963 | ${$args{dist}} =~ s/\s*//g;
|
---|
964 | ${$args{weight}} =~ s/\s*//g;
|
---|
965 | ${$args{port}} =~ s/\s*//g;
|
---|
966 | return ('FAIL',"Distance, port and weight are required, and must be numeric")
|
---|
967 | unless ${$args{weight}} =~ /^\d+$/ && ${$args{port}} =~ /^\d+$/;
|
---|
968 |
|
---|
969 | ${$args{fields}} = "distance,weight,port,";
|
---|
970 | push @{$args{vallist}}, (${$args{dist}}, ${$args{weight}}, ${$args{port}});
|
---|
971 |
|
---|
972 | if ($args{revrec} eq 'n') {
|
---|
973 | # Coerce all hostnames to end in ".DOMAIN" for group/default records,
|
---|
974 | # or the intended parent domain for live records.
|
---|
975 | my $pname = ($args{defrec} eq 'y' ? 'DOMAIN' : $self->domainName($args{id}));
|
---|
976 | ${$args{host}} =~ s/\.*$/\.$pname/ if ${$args{host}} !~ /$pname$/;
|
---|
977 |
|
---|
978 | ##enhance: Rejig so that we can pass back a WARN red flag, instead of
|
---|
979 | # hard-failing, since it seems that purely from the DNS record perspective,
|
---|
980 | # SRV records without underscores are syntactically valid
|
---|
981 | # Not strictly true, but SRV records not following this convention won't be found.
|
---|
982 | return ('FAIL',"SRV records must begin with _service._protocol [${$args{host}}]")
|
---|
983 | unless ${$args{host}} =~ /^_[A-Za-z]+\._[A-Za-z]+\.[a-zA-Z0-9-]+/;
|
---|
984 |
|
---|
985 | # SRV target check - IP addresses not allowed. Must be a more or less well-formed hostname.
|
---|
986 | return ('FAIL', "SRV records cannot point directly to an IP address")
|
---|
987 | if ${$args{val}} =~ /^(?:[\d.]+|[0-9a-fA-F:]+)$/;
|
---|
988 | } else {
|
---|
989 | # hm. we can't do anything sane with IP values here; part of the record data is in
|
---|
990 | # fact encoded in the "hostname". enforce .arpa names? OTOH, SRV records in a reverse
|
---|
991 | # zone are pretty silly.
|
---|
992 |
|
---|
993 | ##enhance: Rejig so that we can pass back a WARN red flag, instead of
|
---|
994 | # hard-failing, since it seems that purely from the DNS record perspective,
|
---|
995 | # SRV records without underscores are syntactically valid
|
---|
996 | # Not strictly true, but SRV records not following this convention won't be found.
|
---|
997 | return ('FAIL',"SRV records must begin with _service._protocol [${$args{host}}]")
|
---|
998 | unless ${$args{val}} =~ /^_[A-Za-z]+\._[A-Za-z]+\.[a-zA-Z0-9-]+/;
|
---|
999 |
|
---|
1000 | # SRV target check - IP addresses not allowed. Must be a more or less well-formed hostname.
|
---|
1001 | return ('FAIL', "SRV records cannot point directly to an IP address")
|
---|
1002 | if ${$args{host}} =~ /^(?:[\d.]+|[0-9a-fA-F:]+)$/;
|
---|
1003 |
|
---|
1004 | # SRV records in reverse zones get stricter treatment. The UI bars adding them in
|
---|
1005 | # reverse record sets, but we "need" to allow editing existing ones. And we'll allow
|
---|
1006 | # editing them if some loon manually munges one into a default reverse record set.
|
---|
1007 | if ($args{defrec} eq 'n') {
|
---|
1008 | # Get the revzone, so we can see if ${$args{val}} is in that zone
|
---|
1009 | my $revzone = new NetAddr::IP $self->revName($args{id}, 'y');
|
---|
1010 | return ('FAIL', $errstr) if !$self->_inrev($args{val}, $revzone);
|
---|
1011 | }
|
---|
1012 |
|
---|
1013 | ##enhance or ##fixme
|
---|
1014 | # convert well-formed .arpa names to IP addresses to match old "strict" validation design
|
---|
1015 | return ('FAIL', $errstr) if ! _check_hostname_form(${$args{val}}, ${$args{rectype}}, $args{defrec}, $args{revrec}) &&
|
---|
1016 | ${$args{val}} =~ /\.arpa$/;
|
---|
1017 |
|
---|
1018 | ##enhance: Look up the passed value to see if it exists. Ooo, fancy.
|
---|
1019 | return ('FAIL', $errstr) if ! _check_hostname_form(${$args{host}}, ${$args{rectype}}, $args{defrec}, $args{revrec});
|
---|
1020 |
|
---|
1021 | }
|
---|
1022 |
|
---|
1023 | return ('OK','OK');
|
---|
1024 | } # done SRV record
|
---|
1025 |
|
---|
1026 | # Now the custom types
|
---|
1027 |
|
---|
1028 | # A+PTR record. With a very little bit of magic we can also use this sub to validate AAAA+PTR. Whee!
|
---|
1029 | sub _validate_65280 {
|
---|
1030 | my $self = shift;
|
---|
1031 | my $dbh = $self->{dbh};
|
---|
1032 |
|
---|
1033 | my %args = @_;
|
---|
1034 |
|
---|
1035 | my $code = 'OK';
|
---|
1036 | my $msg = 'OK';
|
---|
1037 |
|
---|
1038 | if ($args{defrec} eq 'n') {
|
---|
1039 | # live record; revrec determines whether we validate the PTR or A component first.
|
---|
1040 |
|
---|
1041 | # Fail early on non-IP gibberish in ${$args{val}}. Arguably .arpa names might be acceptable
|
---|
1042 | # but that gets stupid in forward zones, since these records are shared.
|
---|
1043 | return ('FAIL', "$typemap{${$args{rectype}}} record must be a valid IPv4 address")
|
---|
1044 | if ${$args{rectype}} == 65280 && ${$args{val}} !~ /^\d+\.\d+\.\d+\.\d+$/;
|
---|
1045 | return ('FAIL', "$typemap{${$args{rectype}}} record must be a valid IPv6 address")
|
---|
1046 | if ${$args{rectype}} == 65281 && ${$args{val}} !~ /^[a-fA-F0-9:]+$/;
|
---|
1047 | # If things are not OK, this should prevent Stupid in the error log.
|
---|
1048 | $args{addr} = new NetAddr::IP ${$args{val}}
|
---|
1049 | or return ('FAIL', "$typemap{${$args{rectype}}} record must be a valid IPv".
|
---|
1050 | (${$args{rectype}} == 65280 ? '4' : '6')." address");
|
---|
1051 | ${$args{val}} = $args{addr}->addr;
|
---|
1052 |
|
---|
1053 | if ($args{revrec} eq 'y') {
|
---|
1054 | ($code,$msg) = $self->_validate_12(%args);
|
---|
1055 | return ($code,$msg) if $code eq 'FAIL';
|
---|
1056 |
|
---|
1057 | # check A+PTR is really v4
|
---|
1058 | return ('FAIL',"$typemap{${$args{rectype}}} record must be a valid IPv4 address")
|
---|
1059 | if ${$args{rectype}} == 65280 && $args{addr}->{isv6};
|
---|
1060 | # check AAAA+PTR is really v6
|
---|
1061 | return ('FAIL',"$typemap{${$args{rectype}}} record must be a valid IPv6 address")
|
---|
1062 | if ${$args{rectype}} == 65281 && !$args{addr}->{isv6};
|
---|
1063 |
|
---|
1064 | # Check if the reqested domain exists. If not, coerce the type down to PTR and warn.
|
---|
1065 | if (!(${$args{domid}} = $self->_hostparent(${$args{host}}))) {
|
---|
1066 | my $addmsg = "Record ".($args{update} ? 'updated' : 'added').
|
---|
1067 | " as PTR instead of $typemap{${$args{rectype}}}; domain not found for ${$args{host}}";
|
---|
1068 | $msg .= "\n$addmsg" if $code eq 'WARN';
|
---|
1069 | $msg = $addmsg if $code eq 'OK';
|
---|
1070 | ${$args{rectype}} = $reverse_typemap{PTR};
|
---|
1071 | return ('WARN', $msg);
|
---|
1072 | }
|
---|
1073 |
|
---|
1074 | # Add domain ID to field list and values
|
---|
1075 | ${$args{fields}} .= "domain_id,";
|
---|
1076 | push @{$args{vallist}}, ${$args{domid}};
|
---|
1077 |
|
---|
1078 | } else {
|
---|
1079 | ($code,$msg) = $self->_validate_1(%args) if ${$args{rectype}} == 65280;
|
---|
1080 | ($code,$msg) = $self->_validate_28(%args) if ${$args{rectype}} == 65281;
|
---|
1081 | return ($code,$msg) if $code eq 'FAIL';
|
---|
1082 |
|
---|
1083 | # Check if the requested reverse zone exists - note, an IP fragment won't
|
---|
1084 | # work here since we don't *know* which parent to put it in.
|
---|
1085 | # ${$args{val}} has been validated as a valid IP by now, in one of the above calls.
|
---|
1086 | my ($revid) = $dbh->selectrow_array("SELECT rdns_id FROM revzones WHERE revnet >> ?".
|
---|
1087 | " ORDER BY masklen(revnet) DESC", undef, (${$args{val}}));
|
---|
1088 | if (!$revid) {
|
---|
1089 | $msg = "Record ".($args{update} ? 'updated' : 'added')." as ".(${$args{rectype}} == 65280 ? 'A' : 'AAAA').
|
---|
1090 | " instead of $typemap{${$args{rectype}}}; reverse zone not found for ${$args{val}}";
|
---|
1091 | ${$args{rectype}} = (${$args{rectype}} == 65280 ? $reverse_typemap{A} : $reverse_typemap{AAAA});
|
---|
1092 | return ('WARN', $msg);
|
---|
1093 | }
|
---|
1094 |
|
---|
1095 | # Check for duplicate PTRs. Note we don't have to play games with $code and $msg, because
|
---|
1096 | # by definition there can't be duplicate PTRs if the reverse zone isn't managed here.
|
---|
1097 | if ($args{update}) {
|
---|
1098 | # Record update. There should usually be an existing PTR (the record being updated)
|
---|
1099 | my @ptrs = @{ $dbh->selectcol_arrayref("SELECT record_id FROM "._rectable($args{defrec},$args{revrec}).
|
---|
1100 | " WHERE val = ?", undef, (${$args{val}})) };
|
---|
1101 | if (@ptrs && (!grep /^$args{update}$/, @ptrs)) {
|
---|
1102 | $msg = "PTR record for ${$args{val}} already exists; adding another will probably not do what you want";
|
---|
1103 | $code = 'WARN';
|
---|
1104 | }
|
---|
1105 | } else {
|
---|
1106 | # New record. Always warn if a PTR exists
|
---|
1107 | my ($ptrcount) = $dbh->selectrow_array("SELECT count(*) FROM "._rectable($args{defrec},$args{revrec}).
|
---|
1108 | " WHERE val = ?", undef, (${$args{val}}));
|
---|
1109 | $msg = "PTR record for ${$args{val}} already exists; adding another will probably not do what you want"
|
---|
1110 | if $ptrcount;
|
---|
1111 | $code = 'WARN' if $ptrcount;
|
---|
1112 | }
|
---|
1113 |
|
---|
1114 | # Add the reverse zone ID to the fieldlist
|
---|
1115 | ${$args{fields}} .= "rdns_id,";
|
---|
1116 | push @{$args{vallist}}, $revid;
|
---|
1117 | }
|
---|
1118 |
|
---|
1119 | } else { # defrec eq 'y'
|
---|
1120 |
|
---|
1121 | if ($args{revrec} eq 'y') {
|
---|
1122 | ($code,$msg) = $self->_validate_12(%args);
|
---|
1123 | return ($code,$msg) if $code eq 'FAIL';
|
---|
1124 | if (${$args{rectype}} == 65280) {
|
---|
1125 | return ('FAIL',"A+PTR record must be a valid IPv4 address or fragment")
|
---|
1126 | if ${$args{val}} =~ /:/;
|
---|
1127 | ${$args{val}} =~ s/^ZONE,/ZONE./; # Clean up after uncertain IP-fragment-type from _validate_12
|
---|
1128 | } elsif (${$args{rectype}} == 65281) {
|
---|
1129 | return ('FAIL',"AAAA+PTR record must be a valid IPv6 address or fragment")
|
---|
1130 | if ${$args{val}} =~ /\./;
|
---|
1131 | ${$args{val}} =~ s/^ZONE,/ZONE::/; # Clean up after uncertain IP-fragment-type from _validate_12
|
---|
1132 | }
|
---|
1133 | } else {
|
---|
1134 | # This is easy. I also can't see a real use-case for A/AAAA+PTR in *all* forward
|
---|
1135 | # domains, since you wouldn't be able to substitute both domain and reverse zone
|
---|
1136 | # sanely, and you'd end up with guaranteed over-replicated PTR records that would
|
---|
1137 | # confuse the hell out of pretty much anything that uses them.
|
---|
1138 | ##fixme: make this a config flag?
|
---|
1139 | return ('FAIL', "$typemap{${$args{rectype}}} records not allowed in default domains");
|
---|
1140 | }
|
---|
1141 | }
|
---|
1142 |
|
---|
1143 | return ($code, $msg);
|
---|
1144 | } # done A+PTR record
|
---|
1145 |
|
---|
1146 | # AAAA+PTR record
|
---|
1147 | # A+PTR above has been magicked to handle AAAA+PTR as well.
|
---|
1148 | sub _validate_65281 {
|
---|
1149 | return _validate_65280(@_);
|
---|
1150 | } # done AAAA+PTR record
|
---|
1151 |
|
---|
1152 | # PTR template record
|
---|
1153 | sub _validate_65282 {
|
---|
1154 | my $self = shift;
|
---|
1155 | my $dbh = $self->{dbh};
|
---|
1156 |
|
---|
1157 | my %args = @_;
|
---|
1158 |
|
---|
1159 | # we're *this* >.< close to being able to just call _validate_12... unfortunately we can't, quite.
|
---|
1160 | if ($args{revrec} eq 'y') {
|
---|
1161 | if ($args{defrec} eq 'n') {
|
---|
1162 | return ('FAIL', "Template block ${$args{val}} is not within ".$self->revName($args{id}))
|
---|
1163 | unless $self->_ipparent($args{defrec}, $args{revrec}, $args{val}, $args{id}, \$args{addr});
|
---|
1164 | ##fixme: warn if $args{val} is not /31 or larger block?
|
---|
1165 | ${$args{val}} = "$args{addr}";
|
---|
1166 | } else {
|
---|
1167 | if (${$args{val}} =~ /\./) {
|
---|
1168 | # looks like a v4 or fragment
|
---|
1169 | if (${$args{val}} =~ m|^\d+\.\d+\.\d+\.\d+(?:/\d+)?$|) {
|
---|
1170 | # woo! a complete IP! validate it and normalize, or fail.
|
---|
1171 | $args{addr} = NetAddr::IP->new(${$args{val}})
|
---|
1172 | or return ('FAIL', "IP/value looks like IPv4 but isn't valid");
|
---|
1173 | ${$args{val}} = "$args{addr}";
|
---|
1174 | } else {
|
---|
1175 | ${$args{val}} =~ s/^\.*/ZONE./ unless ${$args{val}} =~ /^ZONE/;
|
---|
1176 | }
|
---|
1177 | } elsif (${$args{val}} =~ /[a-f:]/) {
|
---|
1178 | # looks like a v6 or fragment
|
---|
1179 | ${$args{val}} =~ s/^:*/ZONE::/ if !$args{addr} && ${$args{val}} !~ /^ZONE/;
|
---|
1180 | if ($args{addr}) {
|
---|
1181 | if ($args{addr}->addr =~ /^0/) {
|
---|
1182 | ${$args{val}} =~ s/^:*/ZONE::/ unless ${$args{val}} =~ /^ZONE/;
|
---|
1183 | } else {
|
---|
1184 | ${$args{val}} = "$args{addr}";
|
---|
1185 | }
|
---|
1186 | }
|
---|
1187 | } else {
|
---|
1188 | # bare number (probably). These could be v4 or v6, so we'll
|
---|
1189 | # expand on these on creation of a reverse zone.
|
---|
1190 | ${$args{val}} = "ZONE,${$args{val}}" unless ${$args{val}} =~ /^ZONE/;
|
---|
1191 | }
|
---|
1192 | }
|
---|
1193 | ##fixme: validate %-patterns?
|
---|
1194 |
|
---|
1195 | # Unlike single PTR records, there is absolutely no way to sanely support multiple
|
---|
1196 | # PTR templates for the same block, since they expect to expand to all the individual
|
---|
1197 | # IPs on export. Nested templates should be supported though.
|
---|
1198 |
|
---|
1199 | my @checkvals = (${$args{val}});
|
---|
1200 | if (${$args{val}} =~ /,/) {
|
---|
1201 | # push . and :: variants into checkvals if val has ,
|
---|
1202 | my $tmp;
|
---|
1203 | ($tmp = ${$args{val}}) =~ s/,/./;
|
---|
1204 | push @checkvals, $tmp;
|
---|
1205 | ($tmp = ${$args{val}}) =~ s/,/::/;
|
---|
1206 | push @checkvals, $tmp;
|
---|
1207 | }
|
---|
1208 | ##fixme: this feels wrong still - need to restrict template pseudorecords to One Of Each
|
---|
1209 | # Per Netblock such that they don't conflict on export
|
---|
1210 | my $typeck;
|
---|
1211 | # type 65282 -> ptr template -> look for any of 65282, 65283, 65284
|
---|
1212 | $typeck = 'type=65283 OR type=65284' if ${$args{rectype}} == 65282;
|
---|
1213 | # type 65283 -> a+ptr template -> v4 -> look for 65282 or 65283
|
---|
1214 | $typeck = 'type=65283' if ${$args{rectype}} == 65282;
|
---|
1215 | # type 65284 -> aaaa+ptr template -> v6 -> look for 65282 or 65284
|
---|
1216 | $typeck = 'type=65284' if ${$args{rectype}} == 65282;
|
---|
1217 | my $pcsth = $dbh->prepare("SELECT count(*) FROM "._rectable($args{defrec},$args{revrec})." WHERE val = ? ".
|
---|
1218 | "AND (type=65282 OR $typeck)");
|
---|
1219 | foreach my $checkme (@checkvals) {
|
---|
1220 | $pcsth->execute($checkme);
|
---|
1221 | my ($rc) = $pcsth->fetchrow_array;
|
---|
1222 | return ('FAIL', "Only one template pseudorecord may exist for a given IP block") if $rc > 1;
|
---|
1223 | }
|
---|
1224 |
|
---|
1225 | } else {
|
---|
1226 | return ('FAIL', "Forward zones cannot contain PTR records");
|
---|
1227 | }
|
---|
1228 |
|
---|
1229 | return ('OK','OK');
|
---|
1230 | } # done PTR template record
|
---|
1231 |
|
---|
1232 | # A+PTR template record
|
---|
1233 | sub _validate_65283 {
|
---|
1234 | my $self = shift;
|
---|
1235 | my $dbh = $self->{dbh};
|
---|
1236 |
|
---|
1237 | my %args = @_;
|
---|
1238 |
|
---|
1239 | my ($code,$msg) = ('OK','OK');
|
---|
1240 |
|
---|
1241 | ##fixme: need to fiddle things since A+PTR templates are acceptable in live
|
---|
1242 | # forward zones but not default records
|
---|
1243 | if ($args{defrec} eq 'n') {
|
---|
1244 | if ($args{revrec} eq 'n') {
|
---|
1245 | ($code,$msg) = $self->_validate_1(%args) if ${$args{rectype}} == 65280;
|
---|
1246 | ($code,$msg) = $self->_validate_28(%args) if ${$args{rectype}} == 65281;
|
---|
1247 | return ($code,$msg) if $code eq 'FAIL';
|
---|
1248 |
|
---|
1249 | # Check if the requested reverse zone exists - note, an IP fragment won't
|
---|
1250 | # work here since we don't *know* which parent to put it in.
|
---|
1251 | # ${$args{val}} has been validated as a valid IP by now, in one of the above calls.
|
---|
1252 | my ($revid) = $dbh->selectrow_array("SELECT rdns_id FROM revzones WHERE revnet >> ?".
|
---|
1253 | " ORDER BY masklen(revnet) DESC", undef, (${$args{val}}));
|
---|
1254 | # Fail if no match; we can't coerce a PTR-template type down to not include the PTR bit currently.
|
---|
1255 | if (!$revid) {
|
---|
1256 | $msg = "Can't ".($args{update} ? 'update' : 'add')." ${$args{host}}/${$args{val}} as ".
|
---|
1257 | "$typemap{${$args{rectype}}}: reverse zone not found for ${$args{val}}";
|
---|
1258 | ##fixme: add A template, AAAA template types?
|
---|
1259 | # ${$args{rectype}} = (${$args{rectype}} == 65280 ? $reverse_typemap{A} : $reverse_typemap{AAAA});
|
---|
1260 | return ('FAIL', $msg);
|
---|
1261 | }
|
---|
1262 |
|
---|
1263 | # Add reverse zone ID to field list and values
|
---|
1264 | ${$args{fields}} .= "rdns_id,";
|
---|
1265 | push @{$args{vallist}}, $revid;
|
---|
1266 |
|
---|
1267 | } else {
|
---|
1268 | return ('FAIL', "IP or IP fragment ${$args{val}} is not within ".$self->revName($args{id}))
|
---|
1269 | unless $self->_ipparent($args{defrec}, $args{revrec}, $args{val}, $args{id}, \$args{addr});
|
---|
1270 | ${$args{val}} = "$args{addr}";
|
---|
1271 |
|
---|
1272 | if (!(${$args{domid}} = $self->_hostparent(${$args{host}}))) {
|
---|
1273 | my $addmsg = "Record ".($args{update} ? 'updated' : 'added').
|
---|
1274 | " as PTR template instead of $typemap{${$args{rectype}}}; domain not found for ${$args{host}}";
|
---|
1275 | $msg .= "\n$addmsg" if $code eq 'WARN';
|
---|
1276 | $msg = $addmsg if $code eq 'OK';
|
---|
1277 | ${$args{rectype}} = 65282;
|
---|
1278 | return ('WARN', $msg);
|
---|
1279 | }
|
---|
1280 |
|
---|
1281 | # Add domain ID to field list and values
|
---|
1282 | ${$args{fields}} .= "domain_id,";
|
---|
1283 | push @{$args{vallist}}, ${$args{domid}};
|
---|
1284 | }
|
---|
1285 |
|
---|
1286 | } else {
|
---|
1287 | my ($code,$msg) = $self->_validate_65282(%args);
|
---|
1288 | return ($code, $msg) if $code eq 'FAIL';
|
---|
1289 | # get domain, check against ${$args{name}}
|
---|
1290 | }
|
---|
1291 |
|
---|
1292 | return ('OK','OK');
|
---|
1293 | } # done A+PTR template record
|
---|
1294 |
|
---|
1295 | # AAAA+PTR template record
|
---|
1296 | # Not sure this can be handled sanely due to the size of IPv6 address space
|
---|
1297 | sub _validate_65284 {
|
---|
1298 | return ('OK','OK');
|
---|
1299 | } # done AAAA+PTR template record
|
---|
1300 |
|
---|
1301 | # Delegation record
|
---|
1302 | # This is essentially a specialized clone of the NS record, primarily useful
|
---|
1303 | # for delegating IPv4 sub-/24 reverse blocks
|
---|
1304 | sub _validate_65285 {
|
---|
1305 | my $self = shift;
|
---|
1306 | my $dbh = $self->{dbh};
|
---|
1307 |
|
---|
1308 | my %args = @_;
|
---|
1309 |
|
---|
1310 | # Almost, but not quite, identical to NS record validation.
|
---|
1311 |
|
---|
1312 | # Check that the target of the record is within the parent.
|
---|
1313 | # Yes, host<->val are mixed up here; can't see a way to avoid it. :(
|
---|
1314 | if ($args{defrec} eq 'n') {
|
---|
1315 | # Check if IP/address/zone/"subzone" is within the parent
|
---|
1316 | if ($args{revrec} eq 'y') {
|
---|
1317 | my $tmpip = NetAddr::IP->new(${$args{val}});
|
---|
1318 | my $pname = $self->revName($args{id});
|
---|
1319 | return ('FAIL',"${$args{val}} not within $pname")
|
---|
1320 | unless $self->_ipparent($args{defrec}, $args{revrec}, $args{val}, $args{id}, \$tmpip);
|
---|
1321 | # Normalize
|
---|
1322 | ${$args{val}} = "$tmpip";
|
---|
1323 | } else {
|
---|
1324 | my $pname = $self->domainName($args{id});
|
---|
1325 | ${$args{host}} =~ s/\.*$/\.$pname/ if ${$args{host}} !~ /$pname$/;
|
---|
1326 | }
|
---|
1327 | } else {
|
---|
1328 | return ('FAIL',"Delegation records are not permitted in default record sets");
|
---|
1329 | }
|
---|
1330 | return ('OK','OK');
|
---|
1331 | }
|
---|
1332 |
|
---|
1333 | # Subs not specific to a particular record type
|
---|
1334 |
|
---|
1335 | # Convert $$host and/or $$val to lowercase as appropriate.
|
---|
1336 | # Should only be called if $self->{lowercase} is true.
|
---|
1337 | # $rectype is also a reference for caller convenience
|
---|
1338 | sub _caseclean {
|
---|
1339 | my ($rectype, $host, $val, $defrec, $revrec) = @_;
|
---|
1340 |
|
---|
1341 | # Can't case-squash default records, due to DOMAIN, ZONE, and ADMINDOMAIN templating
|
---|
1342 | return if $defrec eq 'y';
|
---|
1343 |
|
---|
1344 | if ($typemap{$$rectype} eq 'TXT' || $typemap{$$rectype} eq 'SPF') {
|
---|
1345 | # TXT records should preserve user entry in the string.
|
---|
1346 | # SPF records are a duplicate of TXT with a new record type value (99)
|
---|
1347 | $$host = lc($$host) if $revrec eq 'n'; # only lowercase $$host on live forward TXT; preserve TXT content
|
---|
1348 | $$val = lc($$val) if $revrec eq 'y'; # only lowercase $$val on live reverse TXT; preserve TXT content
|
---|
1349 | } else {
|
---|
1350 | # Non-TXT, live records, are fully case-insensitive
|
---|
1351 | $$host = lc($$host);
|
---|
1352 | $$val = lc($$val);
|
---|
1353 | } # $typemap{$$rectype} else
|
---|
1354 |
|
---|
1355 | } # _caseclean()
|
---|
1356 |
|
---|
1357 |
|
---|
1358 | ##
|
---|
1359 | ## Record data substitution subs
|
---|
1360 | ##
|
---|
1361 |
|
---|
1362 | # Replace ZONE in hostname, or create (most of) the actual proper zone name
|
---|
1363 | sub _ZONE {
|
---|
1364 | my $zone = shift;
|
---|
1365 | my $string = shift;
|
---|
1366 | my $fr = shift || 'f'; # flag for forward/reverse order? nb: ignored for IP
|
---|
1367 | my $sep = shift || '-'; # Separator character - unlikely we'll ever need more than . or -
|
---|
1368 |
|
---|
1369 | my $prefix;
|
---|
1370 |
|
---|
1371 | $string =~ s/,/./ if !$zone->{isv6};
|
---|
1372 | $string =~ s/,/::/ if $zone->{isv6};
|
---|
1373 |
|
---|
1374 | # Subbing ZONE in the host. We need to properly ID the netblock range
|
---|
1375 | # The subbed text should have "network IP with trailing zeros stripped" for
|
---|
1376 | # blocks lined up on octet (for v4) or hex-quad (for v6) boundaries
|
---|
1377 | # For blocks that do NOT line up on these boundaries, we take the most
|
---|
1378 | # significant octet or 16-bit chunk of the "broadcast" IP and append it
|
---|
1379 | # after a double-dash
|
---|
1380 | # ie:
|
---|
1381 | # 8.0.0.0/6 -> 8.0.0.0 -> 11.255.255.255; sub should be 8--11
|
---|
1382 | # 10.0.0.0/12 -> 10.0.0.0 -> 10.0.0.0 -> 10.15.255.255; sub should be 10-0--15
|
---|
1383 | # 192.168.4.0/22 -> 192.168.4.0 -> 192.168.7.255; sub should be 192-168-4--7
|
---|
1384 | # 192.168.0.8/29 -> 192.168.0.8 -> 192.168.0.15; sub should be 192-168-0-8--15
|
---|
1385 | # Similar for v6
|
---|
1386 |
|
---|
1387 | if (!$zone->{isv6}) { # IPv4
|
---|
1388 |
|
---|
1389 | $prefix = $zone->network->addr; # Just In Case someone managed to slip in
|
---|
1390 | # a funky subnet that had host bits set.
|
---|
1391 | my $bc = $zone->broadcast->addr;
|
---|
1392 |
|
---|
1393 | if ($zone->masklen > 24) {
|
---|
1394 | $bc =~ s/^\d+\.\d+\.\d+\.//;
|
---|
1395 | } elsif ($zone->masklen > 16) {
|
---|
1396 | $prefix =~ s/\.0$//;
|
---|
1397 | $bc =~ s/^\d+\.\d+\.//;
|
---|
1398 | } elsif ($zone->masklen > 8) {
|
---|
1399 | $bc =~ s/^\d+\.//;
|
---|
1400 | $prefix =~ s/\.0\.0$//;
|
---|
1401 | } else {
|
---|
1402 | $prefix =~ s/\.0\.0\.0$//;
|
---|
1403 | }
|
---|
1404 | if ($zone->masklen % 8) {
|
---|
1405 | $bc =~ s/(\.255)+$//;
|
---|
1406 | $prefix .= "--$bc"; #"--".zone->masklen; # use range or mask length?
|
---|
1407 | }
|
---|
1408 | if ($fr eq 'f') {
|
---|
1409 | $prefix =~ s/\.+/$sep/g;
|
---|
1410 | } else {
|
---|
1411 | $prefix = join($sep, reverse(split(/\./, $prefix)));
|
---|
1412 | }
|
---|
1413 |
|
---|
1414 | } else { # IPv6
|
---|
1415 |
|
---|
1416 | if ($fr eq 'f') {
|
---|
1417 |
|
---|
1418 | $prefix = $zone->network->addr; # Just In Case someone managed to slip in
|
---|
1419 | # a funky subnet that had host bits set.
|
---|
1420 | my $bc = $zone->broadcast->addr;
|
---|
1421 | if (($zone->masklen % 16) != 0) {
|
---|
1422 | # Strip trailing :0 off $prefix, and :ffff off the broadcast IP
|
---|
1423 | for (my $i=0; $i<(7-int($zone->masklen / 16)); $i++) {
|
---|
1424 | $prefix =~ s/:0$//;
|
---|
1425 | $bc =~ s/:ffff$//;
|
---|
1426 | }
|
---|
1427 | # Strip the leading 16-bit chunks off the front of the broadcast IP
|
---|
1428 | $bc =~ s/^([a-f0-9]+:)+//;
|
---|
1429 | # Append the remaining 16-bit chunk to the prefix after "--"
|
---|
1430 | $prefix .= "--$bc";
|
---|
1431 | } else {
|
---|
1432 | # Strip off :0 from the end until we reach the netblock length.
|
---|
1433 | for (my $i=0; $i<(8-$zone->masklen / 16); $i++) {
|
---|
1434 | $prefix =~ s/:0$//;
|
---|
1435 | }
|
---|
1436 | }
|
---|
1437 | # Actually deal with the separator
|
---|
1438 | $prefix =~ s/:/$sep/g;
|
---|
1439 |
|
---|
1440 | } else { # $fr eq 'f'
|
---|
1441 |
|
---|
1442 | $prefix = $zone->network->full; # Just In Case someone managed to slip in
|
---|
1443 | # a funky subnet that had host bits set.
|
---|
1444 | my $bc = $zone->broadcast->full;
|
---|
1445 | $prefix =~ s/://g; # clean these out since they're not spaced right for this case
|
---|
1446 | $bc =~ s/://g;
|
---|
1447 | # Strip trailing 0 off $prefix, and f off the broadcast IP, to match the mask length
|
---|
1448 | for (my $i=0; $i<(31-int($zone->masklen / 4)); $i++) {
|
---|
1449 | $prefix =~ s/0$//;
|
---|
1450 | $bc =~ s/f$//;
|
---|
1451 | }
|
---|
1452 | # Split and reverse the order of the nibbles in the network/broadcast IPs
|
---|
1453 | # trim another 0 for nibble-aligned blocks first, but only if we really have a block, not an IP
|
---|
1454 | $prefix =~ s/0$// if $zone->masklen % 4 == 0 && $zone->masklen != 128;
|
---|
1455 | my @nbits = reverse split //, $prefix;
|
---|
1456 | my @bbits = reverse split //, $bc;
|
---|
1457 | # Handle the sub-nibble case. Eww. I feel dirty supporting this...
|
---|
1458 | $nbits[0] = "$nbits[0]-$bbits[0]" if ($zone->masklen % 4) != 0;
|
---|
1459 | # Glue it back together
|
---|
1460 | $prefix = join($sep, @nbits);
|
---|
1461 |
|
---|
1462 | } # $fr ne 'f'
|
---|
1463 |
|
---|
1464 | } # $zone->{isv6}
|
---|
1465 |
|
---|
1466 | # Do the substitution, finally
|
---|
1467 | $string =~ s/ZONE/$prefix/;
|
---|
1468 | $string =~ s/--/-/ if $sep ne '-'; # - as separator needs extra help for sub-octet v4 netblocks
|
---|
1469 | return $string;
|
---|
1470 | } # done _ZONE()
|
---|
1471 |
|
---|
1472 | # Not quite a substitution sub, but placed here as it's basically the inverse of above;
|
---|
1473 | # given the .arpa zone name, return the CIDR netblock the zone is for.
|
---|
1474 | # Supports v4 non-octet/non-classful netblocks as per the method outlined in the Grasshopper Book (2nd Ed p217-218)
|
---|
1475 | # Does NOT support non-quad v6 netblocks via the same scheme; it shouldn't ever be necessary.
|
---|
1476 | # Takes a nominal .arpa zone name, returns a success code and NetAddr::IP, or a fail code and message
|
---|
1477 | sub _zone2cidr {
|
---|
1478 | my $zone = shift;
|
---|
1479 |
|
---|
1480 | my $cidr;
|
---|
1481 | my $tmpcidr;
|
---|
1482 | my $warnmsg = '';
|
---|
1483 |
|
---|
1484 | if ($zone =~ /\.in-addr\.arpa\.?$/) {
|
---|
1485 | # v4 revzone, formal zone name type
|
---|
1486 | my $tmpzone = $zone;
|
---|
1487 | return ('FAIL', "Non-numerics in apparent IPv4 reverse zone name [$tmpzone]")
|
---|
1488 | if $tmpzone !~ m{^(?:\d+[/-])?[\d\.]+\.in-addr\.arpa\.?$};
|
---|
1489 | $tmpzone =~ s/\.in-addr\.arpa\.?//;
|
---|
1490 |
|
---|
1491 | # Snag the octet pieces
|
---|
1492 | my @octs = split /\./, $tmpzone;
|
---|
1493 |
|
---|
1494 | # Map result of a range manipulation to a mask length change. Cheaper than finding the 2-root of $octets[0]+1.
|
---|
1495 | # Note we will not support /31 blocks, mostly due to issues telling "24-31" -> .24/29 apart from
|
---|
1496 | # "24-31" -> .24/31", with a litte bit of "/31 is icky".
|
---|
1497 | my %maskmap = ( 3 => 2, 7 => 3, 15 => 4, 31 => 5, 63 => 6, 127 => 7,
|
---|
1498 | 30 => 2, 29 => 3, 28 => 4, 27 => 5, 26 => 6, 25 => 7
|
---|
1499 | );
|
---|
1500 |
|
---|
1501 | # Handle "range" blocks, eg, 80-83.168.192.in-addr.arpa (192.168.80.0/22)
|
---|
1502 | # Need to take the size of the range to offset the basic octet-based mask length,
|
---|
1503 | # and make sure the first number in the range gets used as the network address for the block
|
---|
1504 | # Alternate form: The second number is actually the real netmask, not the end of the range.
|
---|
1505 | my $masklen = 0;
|
---|
1506 | if ($octs[0] =~ m{^((\d+)[/-](\d+))$}) { # take the range...
|
---|
1507 | if (24 < $3 && $3 < 31) {
|
---|
1508 | # we have a real netmask
|
---|
1509 | $masklen = -$maskmap{$3};
|
---|
1510 | } else {
|
---|
1511 | # we have a range. NB: only real CIDR ranges are supported
|
---|
1512 | $masklen -= $maskmap{-(eval $1)}; # find the mask base...
|
---|
1513 | }
|
---|
1514 | $octs[0] = $2; # set the base octet of the range...
|
---|
1515 | }
|
---|
1516 | @octs = reverse @octs; # We can reverse the octet pieces now that we've extracted and munged any ranges
|
---|
1517 |
|
---|
1518 | # arguably we should only allow sub-octet range/mask in-addr.arpa
|
---|
1519 | # specifications in the least significant octet, but the code is
|
---|
1520 | # simpler if we deal with sub-octet delegations at any level.
|
---|
1521 |
|
---|
1522 | # Now we find the "true" mask with the aid of the "base" calculated above
|
---|
1523 | if ($#octs == 0) {
|
---|
1524 | $masklen += 8;
|
---|
1525 | $tmpcidr = "$octs[0].0.0.0/$masklen"; # really hope we don't see one of these very often.
|
---|
1526 | } elsif ($#octs == 1) {
|
---|
1527 | $masklen += 16;
|
---|
1528 | $tmpcidr = "$octs[0].$octs[1].0.0/$masklen";
|
---|
1529 | } elsif ($#octs == 2) {
|
---|
1530 | $masklen += 24;
|
---|
1531 | $tmpcidr = "$octs[0].$octs[1].$octs[2].0/$masklen";
|
---|
1532 | } else {
|
---|
1533 | $masklen += 32;
|
---|
1534 | $tmpcidr = "$octs[0].$octs[1].$octs[2].$octs[3]/$masklen";
|
---|
1535 | }
|
---|
1536 |
|
---|
1537 | } elsif ($zone =~ /\.ip6\.arpa\.?$/) {
|
---|
1538 | # v6 revzone, formal zone name type
|
---|
1539 | my $tmpzone = $zone;
|
---|
1540 | ##fixme: if-n-when we decide we can support sub-nibble v6 zone names, we'll need to change this segment
|
---|
1541 | return ('FAIL', "Non-hexadecimals in apparent IPv6 reverse zone name [$tmpzone]")
|
---|
1542 | if $tmpzone !~ /^[a-fA-F\d\.]+\.ip6\.arpa\.?$/;
|
---|
1543 | $tmpzone =~ s/\.ip6\.arpa\.?//;
|
---|
1544 | my @quads = reverse(split(/\./, $tmpzone));
|
---|
1545 | $warnmsg .= "Apparent sub-/64 IPv6 reverse zone\n" if $#quads > 15;
|
---|
1546 | my $nc;
|
---|
1547 | foreach (@quads) {
|
---|
1548 | $tmpcidr .= $_;
|
---|
1549 | $tmpcidr .= ":" if ++$nc % 4 == 0 && $nc < $#quads;
|
---|
1550 | }
|
---|
1551 | my $nq = 1 if $nc % 4 != 0;
|
---|
1552 | my $mask = $nc * 4; # need to do this here because we probably increment it below
|
---|
1553 | while ($nc++ % 4 != 0) {
|
---|
1554 | $tmpcidr .= "0";
|
---|
1555 | }
|
---|
1556 | # polish it off with trailing ::/mask if this is a CIDR block instead of an IP
|
---|
1557 | $tmpcidr .= "::/$mask" if $mask != 128;
|
---|
1558 | }
|
---|
1559 |
|
---|
1560 | # Just to be sure, use NetAddr::IP to validate. Saves a lot of nasty regex watching for valid octet values.
|
---|
1561 | return ('FAIL', "Invalid zone $zone (apparent netblock $tmpcidr)")
|
---|
1562 | unless $cidr = NetAddr::IP->new($tmpcidr);
|
---|
1563 |
|
---|
1564 | if ($warnmsg) {
|
---|
1565 | $errstr = $warnmsg;
|
---|
1566 | return ('WARN', $cidr);
|
---|
1567 | }
|
---|
1568 | return ('OK', $cidr);
|
---|
1569 | ##fixme: use wantarray() to decide what to return?
|
---|
1570 | } # done _zone2cidr()
|
---|
1571 |
|
---|
1572 | # Record template %-parameter expansion, IPv4. Note that IPv6 doesn't
|
---|
1573 | # really have a sane way to handle this type of expansion at the moment
|
---|
1574 | # due to the size of the address space.
|
---|
1575 | # Takes a reference to a template string to be expanded, and an IP to use in the replacement.
|
---|
1576 | sub _template4_expand {
|
---|
1577 | my $tmpl = shift;
|
---|
1578 | my $ip = shift;
|
---|
1579 |
|
---|
1580 | my @ipparts = split /\./, $ip;
|
---|
1581 | my @iphex;
|
---|
1582 | my @ippad;
|
---|
1583 | for (@ipparts) {
|
---|
1584 | push @iphex, sprintf("%x", $_);
|
---|
1585 | push @ippad, sprintf("%0.3u", $_);
|
---|
1586 | }
|
---|
1587 |
|
---|
1588 | # IP substitutions in template records:
|
---|
1589 | #major patterns:
|
---|
1590 | #dashed IP, forward and reverse
|
---|
1591 | #underscoreed IP, forward and reverse
|
---|
1592 | #dotted IP, forward and reverse (even if forward is... dumb)
|
---|
1593 | # -> %r for reverse, %i for forward, leading -, _, or . to indicate separator, defaults to -
|
---|
1594 | # %r or %-r => %4d-%3d-%2d-%1d
|
---|
1595 | # %_r => %4d_%3d_%2d_%1d
|
---|
1596 | # %.r => %4d.%3d.%2d.%1d
|
---|
1597 | # %i or %-i => %1d-%2d-%3d-%4d
|
---|
1598 | # %_i => %1d_%2d_%3d_%4d
|
---|
1599 | # %.i => %1d.%2d.%3d.%4d
|
---|
1600 | $$tmpl =~ s/\%r/\%4d-\%3d-\%2d-\%1d/g;
|
---|
1601 | $$tmpl =~ s/\%([-._])r/\%4d$1\%3d$1\%2d$1\%1d/g;
|
---|
1602 | $$tmpl =~ s/\%i/\%1d-\%2d-\%3d-\%4d/g;
|
---|
1603 | $$tmpl =~ s/\%([-._])i/\%1d$1\%2d$1\%3d$1\%4d/g;
|
---|
1604 |
|
---|
1605 | #hex-coded IP
|
---|
1606 | # %h
|
---|
1607 | $$tmpl =~ s/\%h/$iphex[0]$iphex[1]$iphex[2]$iphex[3]/g;
|
---|
1608 |
|
---|
1609 | #IP as decimal-coded 32-bit value
|
---|
1610 | # %d
|
---|
1611 | my $iptmp = $ipparts[0]*256*256*256 + $ipparts[1]*256*256 + $ipparts[2]*256 + $ipparts[3];
|
---|
1612 | $$tmpl =~ s/\%d/$iptmp/g;
|
---|
1613 |
|
---|
1614 | #minor patterns (per-octet)
|
---|
1615 | # %[1234][dh0]
|
---|
1616 | #octet
|
---|
1617 | #hex-coded octet
|
---|
1618 | #0-padded octet
|
---|
1619 | $$tmpl =~ s/\%([1234])d/$ipparts[$1-1]/g;
|
---|
1620 | $$tmpl =~ s/\%([1234])h/$iphex[$1-1]/g;
|
---|
1621 | $$tmpl =~ s/\%([1234])0/$ippad[$1-1]/g;
|
---|
1622 | } # _template4_expand()
|
---|
1623 |
|
---|
1624 | # Broad syntactic check on the hostname. Checks for valid characters, correctly-expandable template patterns.
|
---|
1625 | # Takes the hostname, type, and live/default and forward/reverse flags
|
---|
1626 | # Returns true/false, sets errstr on failures
|
---|
1627 | sub _check_hostname_form {
|
---|
1628 | my ($hname,$rectype,$defrec,$revrec) = @_;
|
---|
1629 |
|
---|
1630 | if ($hname =~ /\%/ && ($rectype == 65282 || $rectype == 65283) ) {
|
---|
1631 | my $tmphost = $hname;
|
---|
1632 | # we don't actually need to test with the real IP passed; that saves a bit of fiddling.
|
---|
1633 | _template4_expand(\$tmphost, '10.10.10.10');
|
---|
1634 | if ($tmphost =~ /\%/) {
|
---|
1635 | $errstr = "Invalid template $hname";
|
---|
1636 | return;
|
---|
1637 | }
|
---|
1638 | } elsif ($rectype == $reverse_typemap{CNAME}) {
|
---|
1639 | # Allow / in reverse CNAME hostnames for sub-/24 delegation
|
---|
1640 | if (lc($hname) !~ m|^[0-9a-z_./-]+$|) {
|
---|
1641 | # error message is deliberately restrictive; special cases are SPECIAL and not for general use
|
---|
1642 | $errstr = "Hostnames may not contain anything other than (0-9 a-z . _)";
|
---|
1643 | return;
|
---|
1644 | }
|
---|
1645 | } elsif ($revrec eq 'y') {
|
---|
1646 | # Reverse zones don't support @ in hostnames
|
---|
1647 | if (lc($hname) !~ /^(?:\*\.)?[0-9a-z_.-]+$/) {
|
---|
1648 | # error message is deliberately restrictive; special cases are SPECIAL and not for general use
|
---|
1649 | $errstr = "Hostnames may not contain anything other than (0-9 a-z . _)";
|
---|
1650 | return;
|
---|
1651 | }
|
---|
1652 | } else {
|
---|
1653 | if (lc($hname) !~ /^(?:\*\.)?(?:[0-9a-z_.-]+|@)$/) {
|
---|
1654 | # Don't mention @, because it would be far too wordy to explain the nuance of @
|
---|
1655 | $errstr = "Hostnames may not contain anything other than (0-9 a-z . _)";
|
---|
1656 | return;
|
---|
1657 | }
|
---|
1658 | }
|
---|
1659 | return 1;
|
---|
1660 | } # _check_hostname_form()
|
---|
1661 |
|
---|
1662 |
|
---|
1663 | ##
|
---|
1664 | ## Initialization and cleanup subs
|
---|
1665 | ##
|
---|
1666 |
|
---|
1667 | ## DNSDB::__cfgload()
|
---|
1668 | # Private sub to parse a config file and load it into %config
|
---|
1669 | # Takes a filename and a hashref to put the parsed entries in
|
---|
1670 | sub __cfgload {
|
---|
1671 | $errstr = '';
|
---|
1672 | my $cfgfile = shift;
|
---|
1673 | my $cfg = shift;
|
---|
1674 |
|
---|
1675 | if (open CFG, "<$cfgfile") {
|
---|
1676 | while (<CFG>) {
|
---|
1677 | chomp;
|
---|
1678 | s/^\s*//;
|
---|
1679 | next if /^#/;
|
---|
1680 | next if /^$/;
|
---|
1681 | # hmm. more complex bits in this file might require [heading] headers, maybe?
|
---|
1682 | # $mode = $1 if /^\[(a-z)+]/;
|
---|
1683 | # DB connect info
|
---|
1684 | $cfg->{dbname} = $1 if /^dbname\s*=\s*([a-z0-9_.-]+)/i;
|
---|
1685 | $cfg->{dbuser} = $1 if /^dbuser\s*=\s*([a-z0-9_.-]+)/i;
|
---|
1686 | $cfg->{dbpass} = $1 if /^dbpass\s*=\s*([a-z0-9_.-]+)/i;
|
---|
1687 | $cfg->{dbhost} = $1 if /^dbhost\s*=\s*([a-z0-9_.-]+)/i;
|
---|
1688 | # Mail settings
|
---|
1689 | $cfg->{mailhost} = $1 if /^mailhost\s*=\s*([a-z0-9_.-]+)/i;
|
---|
1690 | $cfg->{mailnotify} = $1 if /^mailnotify\s*=\s*([a-z0-9_.\@-]+)/i;
|
---|
1691 | $cfg->{mailsender} = $1 if /^mailsender\s*=\s*([a-z0-9_.\@-]+)/i;
|
---|
1692 | $cfg->{mailname} = $1 if /^mailname\s*=\s*([a-z0-9\s_.-]+)/i;
|
---|
1693 | $cfg->{orgname} = $1 if /^orgname\s*=\s*([a-z0-9\s_.,'-]+)/i;
|
---|
1694 | $cfg->{domain} = $1 if /^domain\s*=\s*([a-z0-9_.-]+)/i;
|
---|
1695 | # session - note this is fed directly to CGI::Session
|
---|
1696 | $cfg->{timeout} = $1 if /^[tT][iI][mM][eE][oO][uU][tT]\s*=\s*(\d+[smhdwMy]?)/;
|
---|
1697 | $cfg->{sessiondir} = $1 if m{^sessiondir\s*=\s*([a-z0-9/_.-]+)}i;
|
---|
1698 | # misc
|
---|
1699 | $cfg->{log_failures} = $1 if /^log_failures\s*=\s*([a-z01]+)/i;
|
---|
1700 | $cfg->{perpage} = $1 if /^perpage\s*=\s*(\d+)/i;
|
---|
1701 | $cfg->{exportcache} = $1 if m{^exportcache\s*=\s*([a-z0-9/_.-]+)}i;
|
---|
1702 | $cfg->{usecache} = $1 if m{^usecache\s*=\s*([a-z01]+)}i;
|
---|
1703 | $cfg->{force_refresh} = $1 if /^force_refresh\s*=\s*([a-z01]+)/i;
|
---|
1704 | $cfg->{lowercase} = $1 if /^lowercase\s*=\s*([a-z01]+)/i;
|
---|
1705 | $cfg->{showrev_arpa} = $1 if /^showrev_arpa\s*=\s*([a-z]+)/i;
|
---|
1706 | $cfg->{template_skip_0} = $1 if /^template_skip_0\s*=\s*([a-z01]+)/i;
|
---|
1707 | $cfg->{template_skip_255} = $1 if /^template_skip_255\s*=\s*([a-z01]+)/i;
|
---|
1708 | # not supported in dns.cgi yet
|
---|
1709 | # $cfg->{templatedir} = $1 if m{^templatedir\s*=\s*([a-z0-9/_.-]+)}i;
|
---|
1710 | # $cfg->{templateoverride} = $1 if m{^templateoverride\s*=\s*([a-z0-9/_.-]+)}i;
|
---|
1711 | # RPC options
|
---|
1712 | $cfg->{rpcmode} = $1 if /^rpc_mode\s*=\s*(socket|HTTP|XMLRPC)\s*$/i;
|
---|
1713 | $cfg->{maxfcgi} = $1 if /^max_fcgi_requests\s*=\s*(\d+)\s*$/i;
|
---|
1714 | if (my ($tmp) = /^rpc_iplist\s*=\s*(.+)/i) {
|
---|
1715 | my @ips = split /[,\s]+/, $tmp;
|
---|
1716 | my $rpcsys = shift @ips;
|
---|
1717 | push @{$cfg->{rpcacl}{$rpcsys}}, @ips;
|
---|
1718 | }
|
---|
1719 | }
|
---|
1720 | close CFG;
|
---|
1721 | } else {
|
---|
1722 | $errstr = "Couldn't load configuration file $cfgfile: $!";
|
---|
1723 | return;
|
---|
1724 | }
|
---|
1725 | return 1;
|
---|
1726 | } # end __cfgload()
|
---|
1727 |
|
---|
1728 |
|
---|
1729 | ## DNSDB::connectDB()
|
---|
1730 | # Creates connection to DNS database.
|
---|
1731 | # Requires the database name, username, and password.
|
---|
1732 | # Returns a handle to the db or undef on failure.
|
---|
1733 | # Set up for a PostgreSQL db; could be any transactional DBMS with the
|
---|
1734 | # right changes.
|
---|
1735 | # Called by new(); not intended to be called publicly.
|
---|
1736 | sub connectDB {
|
---|
1737 | $errstr = '';
|
---|
1738 | my $dbname = shift;
|
---|
1739 | my $user = shift;
|
---|
1740 | my $pass = shift;
|
---|
1741 | my $dbh;
|
---|
1742 | my $DSN = "DBI:Pg:dbname=$dbname";
|
---|
1743 |
|
---|
1744 | my $host = shift;
|
---|
1745 | $DSN .= ";host=$host" if $host;
|
---|
1746 |
|
---|
1747 | # Note that we want to autocommit by default, and we will turn it off locally as necessary.
|
---|
1748 | # We may not want to print gobbledygook errors; YMMV. Have to ponder that further.
|
---|
1749 | $dbh = DBI->connect($DSN, $user, $pass, {
|
---|
1750 | AutoCommit => 1,
|
---|
1751 | PrintError => 0
|
---|
1752 | });
|
---|
1753 | if (!$dbh) {
|
---|
1754 | $errstr = $DBI::errstr;
|
---|
1755 | return;
|
---|
1756 | }
|
---|
1757 | #) if(!$dbh);
|
---|
1758 |
|
---|
1759 | local $dbh->{RaiseError} = 1;
|
---|
1760 |
|
---|
1761 | eval {
|
---|
1762 | ##fixme: initialize the DB if we can't find the table (since, by definition, there's
|
---|
1763 | # nothing there if we can't select from it...)
|
---|
1764 | my $tblsth = $dbh->prepare("SELECT count(*) FROM pg_catalog.pg_class WHERE relkind='r' AND relname=?");
|
---|
1765 | my ($tblcount) = $dbh->selectrow_array($tblsth, undef, ('misc'));
|
---|
1766 | # return (undef,$DBI::errstr) if $dbh->err;
|
---|
1767 |
|
---|
1768 | #if ($tblcount == 0) {
|
---|
1769 | # # create tables one at a time, checking for each.
|
---|
1770 | # return (undef, "check table misc missing");
|
---|
1771 | #}
|
---|
1772 |
|
---|
1773 | # Return here if we can't select.
|
---|
1774 | # This should retrieve the dbversion key.
|
---|
1775 | my $sth = $dbh->prepare("SELECT key,value FROM misc WHERE misc_id=1");
|
---|
1776 | $sth->execute();
|
---|
1777 | # return (undef,$DBI::errstr) if ($sth->err);
|
---|
1778 |
|
---|
1779 | ##fixme: do stuff to the DB on version mismatch
|
---|
1780 | # x.y series should upgrade on $DNSDB::VERSION > misc(key=>version)
|
---|
1781 | # DB should be downward-compatible; column defaults should give sane (if possibly
|
---|
1782 | # useless-and-needs-help) values in columns an older software stack doesn't know about.
|
---|
1783 |
|
---|
1784 | # See if the select returned anything (or null data). This should
|
---|
1785 | # succeed if the select executed, but...
|
---|
1786 | $sth->fetchrow();
|
---|
1787 | # return (undef,$DBI::errstr) if ($sth->err);
|
---|
1788 |
|
---|
1789 | $sth->finish;
|
---|
1790 |
|
---|
1791 | }; # wrapped DB checks
|
---|
1792 | if ($@) {
|
---|
1793 | $errstr = $@;
|
---|
1794 | return;
|
---|
1795 | }
|
---|
1796 |
|
---|
1797 | # If we get here, we should be OK.
|
---|
1798 | return $dbh;
|
---|
1799 | } # end connectDB
|
---|
1800 |
|
---|
1801 |
|
---|
1802 | ## DNSDB::finish()
|
---|
1803 | # Cleans up after database handles and so on.
|
---|
1804 | # Requires a database handle
|
---|
1805 | sub finish {
|
---|
1806 | my $self = shift;
|
---|
1807 | $self->{dbh}->disconnect;
|
---|
1808 | } # end finish
|
---|
1809 |
|
---|
1810 |
|
---|
1811 | ## DNSDB::initGlobals()
|
---|
1812 | # Initialize global variables
|
---|
1813 | # NB: this does NOT include web-specific session variables!
|
---|
1814 | sub initGlobals {
|
---|
1815 | my $self = shift;
|
---|
1816 | my $dbh = $self->{dbh};
|
---|
1817 |
|
---|
1818 | # load record types from database
|
---|
1819 | my $sth = $dbh->prepare("SELECT val,name,stdflag FROM rectypes");
|
---|
1820 | $sth->execute;
|
---|
1821 | while (my ($recval,$recname,$stdflag) = $sth->fetchrow_array()) {
|
---|
1822 | $typemap{$recval} = $recname;
|
---|
1823 | $reverse_typemap{$recname} = $recval;
|
---|
1824 | # now we fill the record validation function hash
|
---|
1825 | if ($stdflag < 5) {
|
---|
1826 | my $fn = "_validate_$recval";
|
---|
1827 | $validators{$recval} = \&$fn;
|
---|
1828 | } else {
|
---|
1829 | my $fn = "sub { return ('FAIL','Type $recval ($recname) not supported'); }";
|
---|
1830 | $validators{$recval} = eval $fn;
|
---|
1831 | }
|
---|
1832 | }
|
---|
1833 | } # end initGlobals
|
---|
1834 |
|
---|
1835 |
|
---|
1836 | ## DNSDB::initRPC()
|
---|
1837 | # Takes a remote username and remote fullname.
|
---|
1838 | # Sets up the RPC logging-pseudouser if needed.
|
---|
1839 | # Sets the %userdata hash for logging.
|
---|
1840 | # Returns undef on failure
|
---|
1841 | sub initRPC {
|
---|
1842 | my $self = shift;
|
---|
1843 | my $dbh = $self->{dbh};
|
---|
1844 | my %args = @_;
|
---|
1845 |
|
---|
1846 | return if !$args{username};
|
---|
1847 | return if !$args{fullname};
|
---|
1848 |
|
---|
1849 | $args{username} = "$args{username}/$args{rpcsys}";
|
---|
1850 |
|
---|
1851 | my $tmpuser = $dbh->selectrow_hashref("SELECT username,user_id AS userid,group_id,firstname,lastname,status".
|
---|
1852 | " FROM users WHERE username=?", undef, ($args{username}) );
|
---|
1853 | if (!$tmpuser) {
|
---|
1854 | $dbh->do("INSERT INTO users (username,password,firstname,type) VALUES (?,'RPC',?,'R')", undef,
|
---|
1855 | ($args{username}, $args{fullname}) );
|
---|
1856 | $tmpuser = $dbh->selectrow_hashref("SELECT username,user_id AS userid,group_id,firstname,lastname,status".
|
---|
1857 | " FROM users WHERE username=?", undef, ($args{username}) );
|
---|
1858 | }
|
---|
1859 | $tmpuser->{lastname} = '' if !$tmpuser->{lastname};
|
---|
1860 | $self->{loguserid} = $tmpuser->{userid};
|
---|
1861 | $self->{logusername} = $tmpuser->{username};
|
---|
1862 | $self->{logfullname} = "$tmpuser->{firstname} $tmpuser->{lastname} ($args{rpcsys})";
|
---|
1863 | return 1 if $tmpuser;
|
---|
1864 | } # end initRPC()
|
---|
1865 |
|
---|
1866 |
|
---|
1867 | ## DNSDB::login()
|
---|
1868 | # Takes a database handle, username and password
|
---|
1869 | # Returns a userdata hash (UID, GID, username, fullname parts) if username exists,
|
---|
1870 | # password matches the one on file, and account is not disabled
|
---|
1871 | # Returns undef otherwise
|
---|
1872 | sub login {
|
---|
1873 | my $self = shift;
|
---|
1874 | my $dbh = $self->{dbh};
|
---|
1875 | my $user = shift;
|
---|
1876 | my $pass = shift;
|
---|
1877 |
|
---|
1878 | my $userinfo = $dbh->selectrow_hashref("SELECT user_id,group_id,password,firstname,lastname,status".
|
---|
1879 | " FROM users WHERE username=?",
|
---|
1880 | undef, ($user) );
|
---|
1881 | return if !$userinfo;
|
---|
1882 | return if !$userinfo->{status};
|
---|
1883 |
|
---|
1884 | if ($userinfo->{password} =~ m|^\$1\$([A-Za-z0-9/.]+)\$|) {
|
---|
1885 | # native passwords (crypt-md5)
|
---|
1886 | return if $userinfo->{password} ne unix_md5_crypt($pass,$1);
|
---|
1887 | } elsif ($userinfo->{password} =~ /^[0-9a-f]{32}$/) {
|
---|
1888 | # VegaDNS import (hex-coded MD5)
|
---|
1889 | return if $userinfo->{password} ne md5_hex($pass);
|
---|
1890 | } else {
|
---|
1891 | # plaintext (convenient now and then)
|
---|
1892 | return if $userinfo->{password} ne $pass;
|
---|
1893 | }
|
---|
1894 |
|
---|
1895 | return $userinfo;
|
---|
1896 | } # end login()
|
---|
1897 |
|
---|
1898 |
|
---|
1899 | ## DNSDB::initActionLog()
|
---|
1900 | # Set up action logging. Takes a database handle and user ID
|
---|
1901 | # Sets some internal globals and Does The Right Thing to set up a logging channel.
|
---|
1902 | # This sets up _log() to spew out log entries to the defined channel without worrying
|
---|
1903 | # about having to open a file or a syslog channel
|
---|
1904 | ##fixme Need to call _initActionLog_blah() for various logging channels, configured
|
---|
1905 | # via dnsdb.conf, in $self->{log_channel} or something
|
---|
1906 | # See https://secure.deepnet.cx/trac/dnsadmin/ticket/21
|
---|
1907 | sub initActionLog {
|
---|
1908 | my $self = shift;
|
---|
1909 | my $dbh = $self->{dbh};
|
---|
1910 | my $uid = shift;
|
---|
1911 |
|
---|
1912 | return if !$uid;
|
---|
1913 |
|
---|
1914 | # snag user info for logging. there's got to be a way to not have to pass this back
|
---|
1915 | # and forth from a caller, but web usage means no persistence we can rely on from
|
---|
1916 | # the server side.
|
---|
1917 | my ($username,$fullname) = $dbh->selectrow_array("SELECT username, firstname || ' ' || lastname".
|
---|
1918 | " FROM users WHERE user_id=?", undef, ($uid));
|
---|
1919 | ##fixme: errors are unpossible!
|
---|
1920 |
|
---|
1921 | $self->{logusername} = $username;
|
---|
1922 | $self->{loguserid} = $uid;
|
---|
1923 | $self->{logfullname} = $fullname;
|
---|
1924 |
|
---|
1925 | # convert to real check once we have other logging channels
|
---|
1926 | # if ($self->{log_channel} eq 'sql') {
|
---|
1927 | # Open Log, Sez Me!
|
---|
1928 | # }
|
---|
1929 |
|
---|
1930 | } # end initActionLog
|
---|
1931 |
|
---|
1932 |
|
---|
1933 | ## DNSDB::getPermissions()
|
---|
1934 | # Get permissions from DB
|
---|
1935 | # Requires DB handle, group or user flag, ID, and hashref.
|
---|
1936 | sub getPermissions {
|
---|
1937 | my $self = shift;
|
---|
1938 | my $dbh = $self->{dbh};
|
---|
1939 |
|
---|
1940 | my $type = shift;
|
---|
1941 | my $id = shift;
|
---|
1942 | my $hash = shift;
|
---|
1943 |
|
---|
1944 | my $sql = qq(
|
---|
1945 | SELECT
|
---|
1946 | p.admin,p.self_edit,
|
---|
1947 | p.group_create,p.group_edit,p.group_delete,
|
---|
1948 | p.user_create,p.user_edit,p.user_delete,
|
---|
1949 | p.domain_create,p.domain_edit,p.domain_delete,
|
---|
1950 | p.record_create,p.record_edit,p.record_delete,p.record_locchg,
|
---|
1951 | p.location_create,p.location_edit,p.location_delete,p.location_view
|
---|
1952 | FROM permissions p
|
---|
1953 | );
|
---|
1954 | if ($type eq 'group') {
|
---|
1955 | $sql .= qq(
|
---|
1956 | JOIN groups g ON g.permission_id=p.permission_id
|
---|
1957 | WHERE g.group_id=?
|
---|
1958 | );
|
---|
1959 | } else {
|
---|
1960 | $sql .= qq(
|
---|
1961 | JOIN users u ON u.permission_id=p.permission_id
|
---|
1962 | WHERE u.user_id=?
|
---|
1963 | );
|
---|
1964 | }
|
---|
1965 |
|
---|
1966 | my $sth = $dbh->prepare($sql);
|
---|
1967 |
|
---|
1968 | ##fixme? we don't trap other plain SELECT errors
|
---|
1969 | $sth->execute($id);
|
---|
1970 |
|
---|
1971 | # my $permref = $sth->fetchrow_hashref;
|
---|
1972 | # return $permref;
|
---|
1973 | # $hash = $permref;
|
---|
1974 | # Eww. Need to learn how to forcibly drop a hashref onto an existing hash.
|
---|
1975 | ($hash->{admin},$hash->{self_edit},
|
---|
1976 | $hash->{group_create},$hash->{group_edit},$hash->{group_delete},
|
---|
1977 | $hash->{user_create},$hash->{user_edit},$hash->{user_delete},
|
---|
1978 | $hash->{domain_create},$hash->{domain_edit},$hash->{domain_delete},
|
---|
1979 | $hash->{record_create},$hash->{record_edit},$hash->{record_delete},$hash->{record_locchg},
|
---|
1980 | $hash->{location_create},$hash->{location_edit},$hash->{location_delete},$hash->{location_view}
|
---|
1981 | ) = $sth->fetchrow_array;
|
---|
1982 |
|
---|
1983 | } # end getPermissions()
|
---|
1984 |
|
---|
1985 |
|
---|
1986 | ## DNSDB::changePermissions()
|
---|
1987 | # Update an ACL entry
|
---|
1988 | # Takes a db handle, type, owner-id, and hashref for the changed permissions.
|
---|
1989 | sub changePermissions {
|
---|
1990 | my $self = shift;
|
---|
1991 | my $dbh = $self->{dbh};
|
---|
1992 | my $type = shift;
|
---|
1993 | my $id = shift;
|
---|
1994 | my $newperms = shift;
|
---|
1995 | my $inherit = shift || 0;
|
---|
1996 |
|
---|
1997 | my $resultmsg = '';
|
---|
1998 |
|
---|
1999 | # see if we're switching from inherited to custom. for bonus points,
|
---|
2000 | # snag the permid and parent permid anyway, since we'll need the permid
|
---|
2001 | # to set/alter custom perms, and both if we're switching from custom to
|
---|
2002 | # inherited.
|
---|
2003 | my $sth = $dbh->prepare("SELECT (u.permission_id=g.permission_id) AS was_inherited,u.permission_id,g.permission_id,".
|
---|
2004 | ($type eq 'user' ? 'u.group_id,u.username' : 'u.parent_group_id,u.group_name').
|
---|
2005 | " FROM ".($type eq 'user' ? 'users' : 'groups')." u ".
|
---|
2006 | " JOIN groups g ON u.".($type eq 'user' ? '' : 'parent_')."group_id=g.group_id ".
|
---|
2007 | " WHERE u.".($type eq 'user' ? 'user' : 'group')."_id=?");
|
---|
2008 | $sth->execute($id);
|
---|
2009 |
|
---|
2010 | my ($wasinherited,$permid,$parpermid,$parid,$name) = $sth->fetchrow_array;
|
---|
2011 |
|
---|
2012 | # hack phtoui
|
---|
2013 | # group id 1 is "special" in that it's it's own parent (err... possibly.)
|
---|
2014 | # may make its parent id 0 which doesn't exist, and as a bonus is Perl-false.
|
---|
2015 | $wasinherited = 0 if ($type eq 'group' && $id == 1);
|
---|
2016 |
|
---|
2017 | local $dbh->{AutoCommit} = 0;
|
---|
2018 | local $dbh->{RaiseError} = 1;
|
---|
2019 |
|
---|
2020 | # Wrap all the SQL in a transaction
|
---|
2021 | eval {
|
---|
2022 | if ($inherit) {
|
---|
2023 |
|
---|
2024 | $dbh->do("UPDATE ".($type eq 'user' ? 'users' : 'groups')." SET inherit_perm='t',permission_id=? ".
|
---|
2025 | "WHERE ".($type eq 'user' ? 'user' : 'group')."_id=?", undef, ($parpermid, $id) );
|
---|
2026 | $dbh->do("DELETE FROM permissions WHERE permission_id=?", undef, ($permid) );
|
---|
2027 |
|
---|
2028 | } else {
|
---|
2029 |
|
---|
2030 | if ($wasinherited) { # munge new permission entry in if we're switching from inherited perms
|
---|
2031 | ##fixme: need to add semirecursive bit to properly munge inherited permission ID on subgroups and users
|
---|
2032 | # ... if'n'when we have groups with fully inherited permissions.
|
---|
2033 | # SQL is coo
|
---|
2034 | $dbh->do("INSERT INTO permissions ($permlist,".($type eq 'user' ? 'user' : 'group')."_id) ".
|
---|
2035 | "SELECT $permlist,? FROM permissions WHERE permission_id=?", undef, ($id,$permid) );
|
---|
2036 | ($permid) = $dbh->selectrow_array("SELECT permission_id FROM permissions ".
|
---|
2037 | "WHERE ".($type eq 'user' ? 'user' : 'group')."_id=?", undef, ($id) );
|
---|
2038 | $dbh->do("UPDATE ".($type eq 'user' ? 'users' : 'groups')." SET inherit_perm='f',permission_id=? ".
|
---|
2039 | "WHERE ".($type eq 'user' ? 'user' : 'group')."_id=?", undef, ($permid, $id) );
|
---|
2040 | }
|
---|
2041 |
|
---|
2042 | # and now set the permissions we were passed
|
---|
2043 | foreach (@permtypes) {
|
---|
2044 | if (defined ($newperms->{$_})) {
|
---|
2045 | $dbh->do("UPDATE permissions SET $_=? WHERE permission_id=?", undef, ($newperms->{$_},$permid) );
|
---|
2046 | }
|
---|
2047 | }
|
---|
2048 |
|
---|
2049 | } # (inherited->)? custom
|
---|
2050 |
|
---|
2051 | if ($type eq 'user') {
|
---|
2052 | $resultmsg = "Updated permissions for user $name";
|
---|
2053 | } else {
|
---|
2054 | $resultmsg = "Updated default permissions for group $name";
|
---|
2055 | }
|
---|
2056 | $self->_log(group_id => ($type eq 'user' ? $parid : $id), entry => $resultmsg);
|
---|
2057 | $dbh->commit;
|
---|
2058 | }; # end eval
|
---|
2059 | if ($@) {
|
---|
2060 | my $msg = $@;
|
---|
2061 | eval { $dbh->rollback; };
|
---|
2062 | return ('FAIL',"Error changing permissions: $msg");
|
---|
2063 | }
|
---|
2064 |
|
---|
2065 | return ('OK',$resultmsg);
|
---|
2066 | } # end changePermissions()
|
---|
2067 |
|
---|
2068 |
|
---|
2069 | ## DNSDB::comparePermissions()
|
---|
2070 | # Compare two permission hashes
|
---|
2071 | # Returns '>', '<', '=', '!'
|
---|
2072 | sub comparePermissions {
|
---|
2073 | my $self = shift;
|
---|
2074 | my $p1 = shift;
|
---|
2075 | my $p2 = shift;
|
---|
2076 |
|
---|
2077 | my $retval = '='; # assume equality until proven otherwise
|
---|
2078 |
|
---|
2079 | no warnings "uninitialized";
|
---|
2080 |
|
---|
2081 | foreach (@permtypes) {
|
---|
2082 | next if $p1->{$_} == $p2->{$_}; # equal is good
|
---|
2083 | if ($p1->{$_} && !$p2->{$_}) {
|
---|
2084 | if ($retval eq '<') { # if we've already found an unequal pair where
|
---|
2085 | $retval = '!'; # $p2 has more access, and we now find a pair
|
---|
2086 | last; # where $p1 has more access, the overall access
|
---|
2087 | } # is neither greater or lesser, it's unequal.
|
---|
2088 | $retval = '>';
|
---|
2089 | }
|
---|
2090 | if (!$p1->{$_} && $p2->{$_}) {
|
---|
2091 | if ($retval eq '>') { # if we've already found an unequal pair where
|
---|
2092 | $retval = '!'; # $p1 has more access, and we now find a pair
|
---|
2093 | last; # where $p2 has more access, the overall access
|
---|
2094 | } # is neither greater or lesser, it's unequal.
|
---|
2095 | $retval = '<';
|
---|
2096 | }
|
---|
2097 | }
|
---|
2098 | return $retval;
|
---|
2099 | } # end comparePermissions()
|
---|
2100 |
|
---|
2101 |
|
---|
2102 | ## DNSDB::changeGroup()
|
---|
2103 | # Change group ID of an entity
|
---|
2104 | # Takes a database handle, entity type, entity ID, and new group ID
|
---|
2105 | sub changeGroup {
|
---|
2106 | my $self = shift;
|
---|
2107 | my $dbh = $self->{dbh};
|
---|
2108 | my $type = shift;
|
---|
2109 | my $id = shift;
|
---|
2110 | my $newgrp = shift;
|
---|
2111 |
|
---|
2112 | ##fixme: fail on not enough args
|
---|
2113 | #return ('FAIL', "Missing
|
---|
2114 |
|
---|
2115 | return ('FAIL', "Can't change the group of a $type")
|
---|
2116 | unless grep /^$type$/, ('domain','revzone','user','group'); # could be extended for defrecs?
|
---|
2117 |
|
---|
2118 | # Collect some names for logging and messages
|
---|
2119 | my $entname;
|
---|
2120 | if ($type eq 'domain') {
|
---|
2121 | $entname = $self->domainName($id);
|
---|
2122 | } elsif ($type eq 'revzone') {
|
---|
2123 | $entname = $self->revName($id);
|
---|
2124 | } elsif ($type eq 'user') {
|
---|
2125 | $entname = $self->userFullName($id, '%u');
|
---|
2126 | } elsif ($type eq 'group') {
|
---|
2127 | $entname = $self->groupName($id);
|
---|
2128 | }
|
---|
2129 |
|
---|
2130 | my ($oldgid) = $dbh->selectrow_array("SELECT group_id FROM $par_tbl{$type} WHERE $id_col{$type}=?",
|
---|
2131 | undef, ($id));
|
---|
2132 | my $oldgname = $self->groupName($oldgid);
|
---|
2133 | my $newgname = $self->groupName($newgrp);
|
---|
2134 |
|
---|
2135 | return ('FAIL', "Can't move things into a group that doesn't exist") if !$newgname;
|
---|
2136 |
|
---|
2137 | return ('WARN', "Nothing to do, new group is the same as the old group") if $oldgid == $newgrp;
|
---|
2138 |
|
---|
2139 | # Allow transactions, and raise an exception on errors so we can catch it later.
|
---|
2140 | # Use local to make sure these get "reset" properly on exiting this block
|
---|
2141 | local $dbh->{AutoCommit} = 0;
|
---|
2142 | local $dbh->{RaiseError} = 1;
|
---|
2143 |
|
---|
2144 | eval {
|
---|
2145 | $dbh->do("UPDATE $par_tbl{$type} SET group_id=? WHERE $id_col{$type}=?", undef, ($newgrp, $id));
|
---|
2146 | # Log the change in both the old and new groups
|
---|
2147 | $self->_log(group_id => $oldgid, entry => "Moved $type $entname from $oldgname to $newgname");
|
---|
2148 | $self->_log(group_id => $newgrp, entry => "Moved $type $entname from $oldgname to $newgname");
|
---|
2149 | $dbh->commit;
|
---|
2150 | };
|
---|
2151 | if ($@) {
|
---|
2152 | my $msg = $@;
|
---|
2153 | eval { $dbh->rollback; };
|
---|
2154 | if ($self->{log_failures}) {
|
---|
2155 | $self->_log(group_id => $oldgid, entry => "Error moving $type $entname to $newgname: $msg");
|
---|
2156 | $dbh->commit; # since we enabled transactions earlier
|
---|
2157 | }
|
---|
2158 | return ('FAIL',"Error moving $type $entname to $newgname: $msg");
|
---|
2159 | }
|
---|
2160 |
|
---|
2161 | return ('OK',"Moved $type $entname from $oldgname to $newgname");
|
---|
2162 | } # end changeGroup()
|
---|
2163 |
|
---|
2164 |
|
---|
2165 | ##
|
---|
2166 | ## Processing subs
|
---|
2167 | ##
|
---|
2168 |
|
---|
2169 | ## DNSDB::addDomain()
|
---|
2170 | # Add a domain
|
---|
2171 | # Takes a database handle, domain name, numeric group, boolean(ish) state (active/inactive),
|
---|
2172 | # and user info hash (for logging).
|
---|
2173 | # Returns a status code and message
|
---|
2174 | sub addDomain {
|
---|
2175 | $errstr = '';
|
---|
2176 | my $self = shift;
|
---|
2177 | my $dbh = $self->{dbh};
|
---|
2178 | my $domain = shift;
|
---|
2179 | return ('FAIL',"Domain must not be blank\n") if !$domain;
|
---|
2180 | my $group = shift;
|
---|
2181 | return ('FAIL',"Group must be specified\n") if !defined($group);
|
---|
2182 | my $state = shift;
|
---|
2183 | return ('FAIL',"Domain status must be specified\n") if !defined($state);
|
---|
2184 | my $defloc = shift || '';
|
---|
2185 |
|
---|
2186 | $state = 1 if $state =~ /^active$/;
|
---|
2187 | $state = 1 if $state =~ /^on$/;
|
---|
2188 | $state = 0 if $state =~ /^inactive$/;
|
---|
2189 | $state = 0 if $state =~ /^off$/;
|
---|
2190 |
|
---|
2191 | return ('FAIL',"Invalid domain status") if $state !~ /^\d+$/;
|
---|
2192 |
|
---|
2193 | $domain = lc($domain) if $self->{lowercase};
|
---|
2194 |
|
---|
2195 | return ('FAIL', "Invalid characters in domain") if $domain !~ /^[a-zA-Z0-9_.-]+$/;
|
---|
2196 |
|
---|
2197 | my $sth = $dbh->prepare("SELECT domain_id FROM domains WHERE lower(domain) = lower(?)");
|
---|
2198 | my $dom_id;
|
---|
2199 |
|
---|
2200 | # quick check to start to see if we've already got one
|
---|
2201 | $sth->execute($domain);
|
---|
2202 | ($dom_id) = $sth->fetchrow_array;
|
---|
2203 |
|
---|
2204 | return ('FAIL', "Domain already exists") if $dom_id;
|
---|
2205 |
|
---|
2206 | # Allow transactions, and raise an exception on errors so we can catch it later.
|
---|
2207 | # Use local to make sure these get "reset" properly on exiting this block
|
---|
2208 | local $dbh->{AutoCommit} = 0;
|
---|
2209 | local $dbh->{RaiseError} = 1;
|
---|
2210 |
|
---|
2211 | # Wrap all the SQL in a transaction
|
---|
2212 | eval {
|
---|
2213 | # insert the domain...
|
---|
2214 | $dbh->do("INSERT INTO domains (domain,group_id,status,default_location) VALUES (?,?,?,?)", undef,
|
---|
2215 | ($domain, $group, $state, $defloc));
|
---|
2216 |
|
---|
2217 | # get the ID...
|
---|
2218 | ($dom_id) = $dbh->selectrow_array("SELECT domain_id FROM domains WHERE lower(domain) = lower(?)",
|
---|
2219 | undef, ($domain));
|
---|
2220 |
|
---|
2221 | $self->_log(domain_id => $dom_id, group_id => $group,
|
---|
2222 | entry => "Added ".($state ? 'active' : 'inactive')." domain $domain");
|
---|
2223 |
|
---|
2224 | # ... and now we construct the standard records from the default set. NB: group should be variable.
|
---|
2225 | my $sth = $dbh->prepare("SELECT host,type,val,distance,weight,port,ttl FROM default_records WHERE group_id=?");
|
---|
2226 | my $sth_in = $dbh->prepare("INSERT INTO records (domain_id,host,type,val,distance,weight,port,ttl,location)".
|
---|
2227 | " VALUES ($dom_id,?,?,?,?,?,?,?,?)");
|
---|
2228 | $sth->execute($group);
|
---|
2229 | while (my ($host, $type, $val, $dist, $weight, $port, $ttl) = $sth->fetchrow_array()) {
|
---|
2230 | $host =~ s/DOMAIN/$domain/g;
|
---|
2231 | $val =~ s/DOMAIN/$domain/g;
|
---|
2232 | _caseclean(\$type, \$host, \$val, 'n', 'n') if $self->{lowercase};
|
---|
2233 | $sth_in->execute($host, $type, $val, $dist, $weight, $port, $ttl, $defloc);
|
---|
2234 | if ($typemap{$type} eq 'SOA') {
|
---|
2235 | my @tmp1 = split /:/, $host;
|
---|
2236 | my @tmp2 = split /:/, $val;
|
---|
2237 | $self->_log(domain_id => $dom_id, group_id => $group,
|
---|
2238 | entry => "[new $domain] Added SOA record [contact $tmp1[0]] [master $tmp1[1]] ".
|
---|
2239 | "[refresh $tmp2[0]] [retry $tmp2[1]] [expire $tmp2[2]] [minttl $tmp2[3]], TTL $ttl");
|
---|
2240 | } else {
|
---|
2241 | my $logentry = "[new $domain] Added record '$host $typemap{$type}";
|
---|
2242 | $logentry .= " [distance $dist]" if $typemap{$type} eq 'MX';
|
---|
2243 | $logentry .= " [priority $dist] [weight $weight] [port $port]" if $typemap{$type} eq 'SRV';
|
---|
2244 | $self->_log(domain_id => $dom_id, group_id => $group,
|
---|
2245 | entry => $logentry." $val', TTL $ttl");
|
---|
2246 | }
|
---|
2247 | }
|
---|
2248 |
|
---|
2249 | # once we get here, we should have suceeded.
|
---|
2250 | $dbh->commit;
|
---|
2251 | }; # end eval
|
---|
2252 |
|
---|
2253 | if ($@) {
|
---|
2254 | my $msg = $@;
|
---|
2255 | eval { $dbh->rollback; };
|
---|
2256 | $self->_log(group_id => $group, entry => "Failed adding domain $domain ($msg)")
|
---|
2257 | if $self->{log_failures};
|
---|
2258 | $dbh->commit; # since we enabled transactions earlier
|
---|
2259 | return ('FAIL',$msg);
|
---|
2260 | } else {
|
---|
2261 | return ('OK',$dom_id);
|
---|
2262 | }
|
---|
2263 | } # end addDomain
|
---|
2264 |
|
---|
2265 |
|
---|
2266 | ## DNSDB::delZone()
|
---|
2267 | # Delete a forward or reverse zone.
|
---|
2268 | # Takes a database handle, zone ID, and forward/reverse flag.
|
---|
2269 | # for now, just delete the records, then the domain.
|
---|
2270 | # later we may want to archive it in some way instead (status code 2, for example?)
|
---|
2271 | sub delZone {
|
---|
2272 | my $self = shift;
|
---|
2273 | my $dbh = $self->{dbh};
|
---|
2274 | my $zoneid = shift;
|
---|
2275 | my $revrec = shift;
|
---|
2276 |
|
---|
2277 | # Allow transactions, and raise an exception on errors so we can catch it later.
|
---|
2278 | # Use local to make sure these get "reset" properly on exiting this block
|
---|
2279 | local $dbh->{AutoCommit} = 0;
|
---|
2280 | local $dbh->{RaiseError} = 1;
|
---|
2281 |
|
---|
2282 | my $msg = '';
|
---|
2283 | my $failmsg = '';
|
---|
2284 | my $zone = ($revrec eq 'n' ? $self->domainName($zoneid) : $self->revName($zoneid));
|
---|
2285 |
|
---|
2286 | return ('FAIL', ($revrec eq 'n' ? 'Domain' : 'Reverse zone')." ID $zoneid doesn't exist") if !$zone;
|
---|
2287 |
|
---|
2288 | # Set this up here since we may use if if $self->{log_failures} is enabled
|
---|
2289 | my %loghash;
|
---|
2290 | $loghash{domain_id} = $zoneid if $revrec eq 'n';
|
---|
2291 | $loghash{rdns_id} = $zoneid if $revrec eq 'y';
|
---|
2292 | $loghash{group_id} = $self->parentID(
|
---|
2293 | id => $zoneid, type => ($revrec eq 'n' ? 'domain' : 'revzone'), revrec => $revrec);
|
---|
2294 |
|
---|
2295 | # Wrap all the SQL in a transaction
|
---|
2296 | eval {
|
---|
2297 | # Disentangle custom record types before removing the
|
---|
2298 | # ones that are only in the zone to be deleted
|
---|
2299 | if ($revrec eq 'n') {
|
---|
2300 | my $sth = $dbh->prepare("UPDATE records SET type=?,domain_id=0 WHERE domain_id=? AND type=?");
|
---|
2301 | $failmsg = "Failure converting multizone types to single-zone";
|
---|
2302 | $sth->execute($reverse_typemap{PTR}, $zoneid, 65280);
|
---|
2303 | $sth->execute($reverse_typemap{PTR}, $zoneid, 65281);
|
---|
2304 | $sth->execute(65282, $zoneid, 65283);
|
---|
2305 | $sth->execute(65282, $zoneid, 65284);
|
---|
2306 | $failmsg = "Failure removing domain records";
|
---|
2307 | $dbh->do("DELETE FROM records WHERE domain_id=?", undef, ($zoneid));
|
---|
2308 | $failmsg = "Failure removing domain";
|
---|
2309 | $dbh->do("DELETE FROM domains WHERE domain_id=?", undef, ($zoneid));
|
---|
2310 | } else {
|
---|
2311 | my $sth = $dbh->prepare("UPDATE records SET type=?,rdns_id=0 WHERE rdns_id=? AND type=?");
|
---|
2312 | $failmsg = "Failure converting multizone types to single-zone";
|
---|
2313 | $sth->execute($reverse_typemap{A}, $zoneid, 65280);
|
---|
2314 | $sth->execute($reverse_typemap{AAAA}, $zoneid, 65281);
|
---|
2315 | # We don't have an "A template" or "AAAA template" type, although it might be useful for symmetry.
|
---|
2316 | # $sth->execute(65286?, $zoneid, 65283);
|
---|
2317 | # $sth->execute(65286?, $zoneid, 65284);
|
---|
2318 | $failmsg = "Failure removing reverse records";
|
---|
2319 | $dbh->do("DELETE FROM records WHERE rdns_id=?", undef, ($zoneid));
|
---|
2320 | $failmsg = "Failure removing reverse zone";
|
---|
2321 | $dbh->do("DELETE FROM revzones WHERE rdns_id=?", undef, ($zoneid));
|
---|
2322 | }
|
---|
2323 |
|
---|
2324 | $msg = "Deleted ".($revrec eq 'n' ? 'domain' : 'reverse zone')." $zone";
|
---|
2325 | $loghash{entry} = $msg;
|
---|
2326 | $self->_log(%loghash);
|
---|
2327 |
|
---|
2328 | # once we get here, we should have suceeded.
|
---|
2329 | $dbh->commit;
|
---|
2330 | }; # end eval
|
---|
2331 |
|
---|
2332 | if ($@) {
|
---|
2333 | $msg = $@;
|
---|
2334 | eval { $dbh->rollback; };
|
---|
2335 | $loghash{entry} = "Error deleting $zone: $msg ($failmsg)";
|
---|
2336 | if ($self->{log_failures}) {
|
---|
2337 | $self->_log(%loghash);
|
---|
2338 | $dbh->commit; # since we enabled transactions earlier
|
---|
2339 | }
|
---|
2340 | return ('FAIL', $loghash{entry});
|
---|
2341 | } else {
|
---|
2342 | return ('OK', $msg);
|
---|
2343 | }
|
---|
2344 |
|
---|
2345 | } # end delZone()
|
---|
2346 |
|
---|
2347 |
|
---|
2348 | ## DNSDB::domainName()
|
---|
2349 | # Return the domain name based on a domain ID
|
---|
2350 | # Takes a database handle and the domain ID
|
---|
2351 | # Returns the domain name or undef on failure
|
---|
2352 | sub domainName {
|
---|
2353 | $errstr = '';
|
---|
2354 | my $self = shift;
|
---|
2355 | my $dbh = $self->{dbh};
|
---|
2356 | my $domid = shift;
|
---|
2357 | my ($domname) = $dbh->selectrow_array("SELECT domain FROM domains WHERE domain_id=?", undef, ($domid) );
|
---|
2358 | $errstr = $DBI::errstr if !$domname;
|
---|
2359 | return $domname if $domname;
|
---|
2360 | } # end domainName()
|
---|
2361 |
|
---|
2362 |
|
---|
2363 | ## DNSDB::revName()
|
---|
2364 | # Return the reverse zone name based on an rDNS ID
|
---|
2365 | # Takes a database handle and the rDNS ID, and an optional flag to force return of the CIDR zone
|
---|
2366 | # instead of the formal .arpa zone name
|
---|
2367 | # Returns the reverse zone name or undef on failure
|
---|
2368 | sub revName {
|
---|
2369 | $errstr = '';
|
---|
2370 | my $self = shift;
|
---|
2371 | my $dbh = $self->{dbh};
|
---|
2372 | my $revid = shift;
|
---|
2373 | my $cidrflag = shift || 'n';
|
---|
2374 | my ($revname) = $dbh->selectrow_array("SELECT revnet FROM revzones WHERE rdns_id=?", undef, ($revid) );
|
---|
2375 | $errstr = $DBI::errstr if !$revname;
|
---|
2376 | my $tmp = new NetAddr::IP $revname;
|
---|
2377 | $revname = _ZONE($tmp, 'ZONE', 'r', '.').($tmp->{isv6} ? '.ip6.arpa' : '.in-addr.arpa')
|
---|
2378 | if ($self->{showrev_arpa} eq 'zone' || $self->{showrev_arpa} eq 'all') && $cidrflag eq 'n';
|
---|
2379 | return $revname if $revname;
|
---|
2380 | } # end revName()
|
---|
2381 |
|
---|
2382 |
|
---|
2383 | ## DNSDB::domainID()
|
---|
2384 | # Takes a database handle and domain name
|
---|
2385 | # Returns the domain ID number
|
---|
2386 | sub domainID {
|
---|
2387 | $errstr = '';
|
---|
2388 | my $self = shift;
|
---|
2389 | my $dbh = $self->{dbh};
|
---|
2390 | my $domain = shift;
|
---|
2391 | my ($domid) = $dbh->selectrow_array("SELECT domain_id FROM domains WHERE lower(domain) = lower(?)",
|
---|
2392 | undef, ($domain) );
|
---|
2393 | if (!$domid) {
|
---|
2394 | if ($dbh->err) {
|
---|
2395 | $errstr = $DBI::errstr;
|
---|
2396 | } else {
|
---|
2397 | $errstr = "Domain $domain not present";
|
---|
2398 | }
|
---|
2399 | }
|
---|
2400 | return $domid if $domid;
|
---|
2401 | } # end domainID()
|
---|
2402 |
|
---|
2403 |
|
---|
2404 | ## DNSDB::revID()
|
---|
2405 | # Takes a database handle and reverse zone name
|
---|
2406 | # Returns the rDNS ID number
|
---|
2407 | sub revID {
|
---|
2408 | $errstr = '';
|
---|
2409 | my $self = shift;
|
---|
2410 | my $dbh = $self->{dbh};
|
---|
2411 | my $revzone = shift;
|
---|
2412 | my ($revid) = $dbh->selectrow_array("SELECT rdns_id FROM revzones WHERE revnet=?", undef, ($revzone) );
|
---|
2413 | if (!$revid) {
|
---|
2414 | if ($dbh->err) {
|
---|
2415 | $errstr = $DBI::errstr;
|
---|
2416 | } else {
|
---|
2417 | $errstr = "Reverse zone $revzone not present";
|
---|
2418 | }
|
---|
2419 | }
|
---|
2420 | return $revid if $revid;
|
---|
2421 | } # end revID()
|
---|
2422 |
|
---|
2423 |
|
---|
2424 | ## DNSDB::addRDNS
|
---|
2425 | # Adds a reverse DNS zone
|
---|
2426 | # Takes a database handle, CIDR block, reverse DNS pattern, numeric group,
|
---|
2427 | # and boolean(ish) state (active/inactive)
|
---|
2428 | # Returns a status code and message
|
---|
2429 | sub addRDNS {
|
---|
2430 | my $self = shift;
|
---|
2431 | my $dbh = $self->{dbh};
|
---|
2432 | my $zone = shift;
|
---|
2433 |
|
---|
2434 | # Autodetect formal .arpa zones
|
---|
2435 | if ($zone =~ /\.arpa\.?$/) {
|
---|
2436 | my $code;
|
---|
2437 | ($code,$zone) = _zone2cidr($zone);
|
---|
2438 | return ('FAIL', $zone) if $code eq 'FAIL';
|
---|
2439 | }
|
---|
2440 | $zone = NetAddr::IP->new($zone);
|
---|
2441 |
|
---|
2442 | return ('FAIL',"Zone name must be a valid CIDR netblock") unless ($zone && $zone->addr !~ /^0/);
|
---|
2443 | my $revpatt = shift; # construct a custom (A/AAAA+)? PTR template record
|
---|
2444 | my $group = shift;
|
---|
2445 | my $state = shift;
|
---|
2446 | my $defloc = shift || '';
|
---|
2447 |
|
---|
2448 | $state = 1 if $state =~ /^active$/;
|
---|
2449 | $state = 1 if $state =~ /^on$/;
|
---|
2450 | $state = 0 if $state =~ /^inactive$/;
|
---|
2451 | $state = 0 if $state =~ /^off$/;
|
---|
2452 |
|
---|
2453 | return ('FAIL',"Invalid zone status") if $state !~ /^\d+$/;
|
---|
2454 |
|
---|
2455 | # quick check to start to see if we've already got one
|
---|
2456 | my ($rdns_id) = $dbh->selectrow_array("SELECT rdns_id FROM revzones WHERE revnet=?", undef, ("$zone"));
|
---|
2457 |
|
---|
2458 | return ('FAIL', "Zone already exists") if $rdns_id;
|
---|
2459 |
|
---|
2460 | # Allow transactions, and raise an exception on errors so we can catch it later.
|
---|
2461 | # Use local to make sure these get "reset" properly on exiting this block
|
---|
2462 | local $dbh->{AutoCommit} = 0;
|
---|
2463 | local $dbh->{RaiseError} = 1;
|
---|
2464 |
|
---|
2465 | my $warnstr = '';
|
---|
2466 | my $defttl = 3600; # 1 hour should be reasonable. And unless things have gone horribly
|
---|
2467 | # wrong, we should have a value to override this anyway.
|
---|
2468 |
|
---|
2469 | # Wrap all the SQL in a transaction
|
---|
2470 | eval {
|
---|
2471 | # insert the zone...
|
---|
2472 | $dbh->do("INSERT INTO revzones (revnet,group_id,status,default_location) VALUES (?,?,?,?)", undef,
|
---|
2473 | ($zone, $group, $state, $defloc) );
|
---|
2474 |
|
---|
2475 | # get the ID...
|
---|
2476 | ($rdns_id) = $dbh->selectrow_array("SELECT currval('revzones_rdns_id_seq')");
|
---|
2477 |
|
---|
2478 | $self->_log(rdns_id => $rdns_id, group_id => $group,
|
---|
2479 | entry => "Added ".($state ? 'active' : 'inactive')." reverse zone $zone");
|
---|
2480 |
|
---|
2481 | # ... and now we construct the standard records from the default set. NB: group should be variable.
|
---|
2482 | my $sth = $dbh->prepare("SELECT host,type,val,ttl FROM default_rev_records WHERE group_id=?");
|
---|
2483 | my $sth_in = $dbh->prepare("INSERT INTO records (rdns_id,domain_id,host,type,val,ttl,location)".
|
---|
2484 | " VALUES ($rdns_id,?,?,?,?,?,?)");
|
---|
2485 | $sth->execute($group);
|
---|
2486 | while (my ($host,$type,$val,$ttl) = $sth->fetchrow_array()) {
|
---|
2487 | # Silently skip v4/v6 mismatches. This is not an error, this is expected.
|
---|
2488 | if ($zone->{isv6}) {
|
---|
2489 | next if ($type == 65280 || $type == 65283);
|
---|
2490 | } else {
|
---|
2491 | next if ($type == 65281 || $type == 65284);
|
---|
2492 | }
|
---|
2493 |
|
---|
2494 | $host =~ s/ADMINDOMAIN/$self->{domain}/g;
|
---|
2495 |
|
---|
2496 | # Check to make sure the IP stubs will fit in the zone. Under most usage failures here should be rare.
|
---|
2497 | # On failure, tack a note on to a warning string and continue without adding this record.
|
---|
2498 | # While we're at it, we substitute $zone for ZONE in the value.
|
---|
2499 | if ($val eq 'ZONE') {
|
---|
2500 | # If we've got a pattern, we skip the default record version on (A+)PTR-template types
|
---|
2501 | next if $revpatt && ($type == 65282 || $type == 65283);
|
---|
2502 | ##fixme? do we care if we have multiple whole-zone templates?
|
---|
2503 | $val = $zone->network;
|
---|
2504 | } elsif ($val =~ /ZONE/) {
|
---|
2505 | my $tmpval = $val;
|
---|
2506 | $tmpval =~ s/ZONE//;
|
---|
2507 | # Bend the rules and allow single-trailing-number PTR or PTR template records to be inserted
|
---|
2508 | # as either v4 or v6. May make this an off-by-default config flag
|
---|
2509 | # Note that the origin records that may trigger this **SHOULD** already have ZONE,\d
|
---|
2510 | if ($type == 12 || $type == 65282) {
|
---|
2511 | $tmpval =~ s/[,.]/::/ if ($tmpval =~ /^[,.]\d+$/ && $zone->{isv6});
|
---|
2512 | $tmpval =~ s/[,:]+/./ if ($tmpval =~ /^(?:,|::)\d+$/ && !$zone->{isv6});
|
---|
2513 | }
|
---|
2514 | my $addr;
|
---|
2515 | if ($self->_ipparent('n', 'y', \$tmpval, $rdns_id, \$addr)) {
|
---|
2516 | $val = $addr->addr;
|
---|
2517 | } else {
|
---|
2518 | $warnstr .= "\nDefault record '$val $typemap{$type} $host' doesn't fit in $zone, skipping";
|
---|
2519 | next;
|
---|
2520 | }
|
---|
2521 | }
|
---|
2522 |
|
---|
2523 | # Substitute $zone for ZONE in the hostname, but only for non-NS records.
|
---|
2524 | # NS records get this substitution on the value instead.
|
---|
2525 | $host = _ZONE($zone, $host) if $type != 2;
|
---|
2526 |
|
---|
2527 | # Fill in the forward domain ID if we can find it, otherwise:
|
---|
2528 | # Coerce type down to PTR or PTR template if we can't
|
---|
2529 | my $domid = 0;
|
---|
2530 | if ($type >= 65280) {
|
---|
2531 | if (!($domid = $self->_hostparent($host))) {
|
---|
2532 | $warnstr .= "\nRecord added as PTR instead of $typemap{$type}; domain not found for $host";
|
---|
2533 | $type = $reverse_typemap{PTR};
|
---|
2534 | $domid = 0; # just to be explicit.
|
---|
2535 | }
|
---|
2536 | }
|
---|
2537 |
|
---|
2538 | _caseclean(\$type, \$host, \$val, 'n', 'y') if $self->{lowercase};
|
---|
2539 |
|
---|
2540 | $sth_in->execute($domid,$host,$type,$val,$ttl,$defloc);
|
---|
2541 |
|
---|
2542 | if ($typemap{$type} eq 'SOA') {
|
---|
2543 | my @tmp1 = split /:/, $host;
|
---|
2544 | my @tmp2 = split /:/, $val;
|
---|
2545 | $self->_log(rdns_id => $rdns_id, group_id => $group,
|
---|
2546 | entry => "[new $zone] Added SOA record [contact $tmp1[0]] [master $tmp1[1]] ".
|
---|
2547 | "[refresh $tmp2[0]] [retry $tmp2[1]] [expire $tmp2[2]] [minttl $tmp2[3]], TTL $ttl");
|
---|
2548 | $defttl = $tmp2[3];
|
---|
2549 | } else {
|
---|
2550 | my $logentry = "[new $zone] Added record '$host $typemap{$type} $val', TTL $ttl";
|
---|
2551 | $logentry .= ", default location ".$self->getLoc($defloc)->{description} if $defloc;
|
---|
2552 | $self->_log(rdns_id => $rdns_id, domain_id => $domid, group_id => $group, entry => $logentry);
|
---|
2553 | }
|
---|
2554 | }
|
---|
2555 |
|
---|
2556 | # Generate record based on provided pattern.
|
---|
2557 | if ($revpatt) {
|
---|
2558 | my $host;
|
---|
2559 | my $type = ($zone->{isv6} ? 65284 : 65283);
|
---|
2560 | my $val = $zone->network;
|
---|
2561 |
|
---|
2562 | # Substitute $zone for ZONE in the hostname.
|
---|
2563 | $host = _ZONE($zone, $revpatt);
|
---|
2564 |
|
---|
2565 | my $domid = 0;
|
---|
2566 | if (!($domid = $self->_hostparent($host))) {
|
---|
2567 | $warnstr .= "\nDefault pattern added as PTR template instead of $typemap{$type}; domain not found for $host";
|
---|
2568 | $type = 65282;
|
---|
2569 | $domid = 0; # just to be explicit.
|
---|
2570 | }
|
---|
2571 |
|
---|
2572 | $sth_in->execute($domid,$host,$type,$val,$defttl,$defloc);
|
---|
2573 | my $logentry = "[new $zone] Added record '$host $typemap{$type}";
|
---|
2574 | $self->_log(rdns_id => $rdns_id, domain_id => $domid, group_id => $group,
|
---|
2575 | entry => $logentry." $val', TTL $defttl from pattern");
|
---|
2576 | }
|
---|
2577 |
|
---|
2578 | # If there are warnings (presumably about default records skipped for cause) log them
|
---|
2579 | $self->_log(rdns_id => $rdns_id, group_id => $group, entry => "Warning(s) adding $zone:$warnstr")
|
---|
2580 | if $warnstr;
|
---|
2581 |
|
---|
2582 | # once we get here, we should have suceeded.
|
---|
2583 | $dbh->commit;
|
---|
2584 | }; # end eval
|
---|
2585 |
|
---|
2586 | if ($@) {
|
---|
2587 | my $msg = $@;
|
---|
2588 | eval { $dbh->rollback; };
|
---|
2589 | $self->_log(group_id => $group, entry => "Failed adding reverse zone $zone ($msg)")
|
---|
2590 | if $self->{log_failures};
|
---|
2591 | $dbh->commit; # since we enabled transactions earlier
|
---|
2592 | return ('FAIL',$msg);
|
---|
2593 | } else {
|
---|
2594 | my $retcode = 'OK';
|
---|
2595 | if ($warnstr) {
|
---|
2596 | $resultstr = $warnstr;
|
---|
2597 | $retcode = 'WARN';
|
---|
2598 | }
|
---|
2599 | return ($retcode, $rdns_id);
|
---|
2600 | }
|
---|
2601 |
|
---|
2602 | } # end addRDNS()
|
---|
2603 |
|
---|
2604 |
|
---|
2605 | ## DNSDB::getZoneCount
|
---|
2606 | # Get count of zones in group or groups
|
---|
2607 | # Takes a database handle and hash containing:
|
---|
2608 | # - the "current" group
|
---|
2609 | # - an array of "acceptable" groups
|
---|
2610 | # - a flag for forward/reverse zones
|
---|
2611 | # - Optionally accept a "starts with" and/or "contains" filter argument
|
---|
2612 | # Returns an integer count of the resulting zone list.
|
---|
2613 | sub getZoneCount {
|
---|
2614 | my $self = shift;
|
---|
2615 | my $dbh = $self->{dbh};
|
---|
2616 |
|
---|
2617 | my %args = @_;
|
---|
2618 |
|
---|
2619 | # Fail on bad curgroup argument. There's no sane fallback on this one.
|
---|
2620 | if (!$args{curgroup} || $args{curgroup} !~ /^\d+$/) {
|
---|
2621 | $errstr = "Bad or missing curgroup argument";
|
---|
2622 | return;
|
---|
2623 | }
|
---|
2624 | # Fail on bad childlist argument. This could be sanely ignored if bad, maybe.
|
---|
2625 | if ($args{childlist} && $args{childlist} !~ /^[\d,]+$/) {
|
---|
2626 | $errstr = "Bad childlist argument";
|
---|
2627 | return;
|
---|
2628 | }
|
---|
2629 |
|
---|
2630 | my @filterargs;
|
---|
2631 | $args{startwith} = undef if $args{startwith} && $args{startwith} !~ /^(?:[a-z]|0-9)$/;
|
---|
2632 | push @filterargs, "^$args{startwith}" if $args{startwith};
|
---|
2633 | $args{filter} =~ s/\./\[\.\]/g if $args{filter}; # only match literal dots, usually in reverse zones
|
---|
2634 | push @filterargs, $args{filter} if $args{filter};
|
---|
2635 |
|
---|
2636 | my $sql;
|
---|
2637 | # Not as compact, and fix-me-twice if the common bits get wrong, but much easier to read
|
---|
2638 | if ($args{revrec} eq 'n') {
|
---|
2639 | $sql = "SELECT count(*) FROM domains".
|
---|
2640 | " WHERE group_id IN ($args{curgroup}".($args{childlist} ? ",$args{childlist}" : '').")".
|
---|
2641 | ($args{startwith} ? " AND domain ~* ?" : '').
|
---|
2642 | ($args{filter} ? " AND domain ~* ?" : '');
|
---|
2643 | } else {
|
---|
2644 | $sql = "SELECT count(*) FROM revzones".
|
---|
2645 | " WHERE group_id IN ($args{curgroup}".($args{childlist} ? ",$args{childlist}" : '').")".
|
---|
2646 | ($args{startwith} ? " AND CAST(revnet AS VARCHAR) ~* ?" : '');
|
---|
2647 | # if ($self->{showrev_arpa} eq 'zone' || $self->{showrev_arpa} eq 'all') {
|
---|
2648 | # Just In Case the UI is using formal .arpa notation, and someone enters something reversed,
|
---|
2649 | # we want to match both the formal and natural zone name
|
---|
2650 | $sql .= ($args{filter} ? " AND (CAST(revnet AS VARCHAR) ~* ? OR CAST(revnet AS VARCHAR) ~* ?)" : '');
|
---|
2651 | push @filterargs, join('[.]',reverse(split(/\[\.\]/,$args{filter}))) if $args{filter};
|
---|
2652 | # } else {
|
---|
2653 | # $sql .= ($args{filter} ? " AND CAST(revnet AS VARCHAR) ~* ?" : '');
|
---|
2654 | # }
|
---|
2655 | }
|
---|
2656 | my ($count) = $dbh->selectrow_array($sql, undef, @filterargs);
|
---|
2657 | return $count;
|
---|
2658 | } # end getZoneCount()
|
---|
2659 |
|
---|
2660 |
|
---|
2661 | ## DNSDB::getZoneList()
|
---|
2662 | # Get a list of zones in the specified group(s)
|
---|
2663 | # Takes the same arguments as getZoneCount() above
|
---|
2664 | # Returns a reference to an array of hashrefs suitable for feeding to HTML::Template
|
---|
2665 | sub getZoneList {
|
---|
2666 | my $self = shift;
|
---|
2667 | my $dbh = $self->{dbh};
|
---|
2668 |
|
---|
2669 | my %args = @_;
|
---|
2670 |
|
---|
2671 | my @zonelist;
|
---|
2672 |
|
---|
2673 | $args{sortorder} = 'ASC' if !$args{sortorder} || !grep /^$args{sortorder}$/, ('ASC','DESC');
|
---|
2674 | $args{offset} = 0 if !$args{offset} || $args{offset} !~ /^(?:all|\d+)$/;
|
---|
2675 |
|
---|
2676 | # Fail on bad curgroup argument. There's no sane fallback on this one.
|
---|
2677 | if (!$args{curgroup} || $args{curgroup} !~ /^\d+$/) {
|
---|
2678 | $errstr = "Bad or missing curgroup argument";
|
---|
2679 | return;
|
---|
2680 | }
|
---|
2681 | # Fail on bad childlist argument. This could be sanely ignored if bad, maybe.
|
---|
2682 | if ($args{childlist} && $args{childlist} !~ /^[\d,]+$/) {
|
---|
2683 | $errstr = "Bad childlist argument";
|
---|
2684 | return;
|
---|
2685 | }
|
---|
2686 |
|
---|
2687 | my @filterargs;
|
---|
2688 | $args{startwith} = undef if $args{startwith} && $args{startwith} !~ /^(?:[a-z]|0-9)$/;
|
---|
2689 | push @filterargs, "^$args{startwith}" if $args{startwith};
|
---|
2690 | $args{filter} =~ s/\./\[\.\]/g if $args{filter}; # only match literal dots, usually in reverse zones
|
---|
2691 | push @filterargs, $args{filter} if $args{filter};
|
---|
2692 |
|
---|
2693 | my $sql;
|
---|
2694 | # Not as compact, and fix-me-twice if the common bits get wrong, but much easier to read
|
---|
2695 | if ($args{revrec} eq 'n') {
|
---|
2696 | $args{sortby} = 'domain' if !$args{sortby} || !grep /^$args{sortby}$/, ('domain','group','status');
|
---|
2697 | $sql = "SELECT domain_id AS zoneid,domain AS zone,status,groups.group_name AS group FROM domains".
|
---|
2698 | " INNER JOIN groups ON domains.group_id=groups.group_id".
|
---|
2699 | " WHERE domains.group_id IN ($args{curgroup}".($args{childlist} ? ",$args{childlist}" : '').")".
|
---|
2700 | ($args{startwith} ? " AND domain ~* ?" : '').
|
---|
2701 | ($args{filter} ? " AND domain ~* ?" : '');
|
---|
2702 | } else {
|
---|
2703 | ##fixme: arguably startwith here is irrelevant. depends on the UI though.
|
---|
2704 | $args{sortby} = 'revnet' if !$args{sortby} || !grep /^$args{sortby}$/, ('revnet','group','status');
|
---|
2705 | $sql = "SELECT rdns_id AS zoneid,revnet AS zone,status,groups.group_name AS group FROM revzones".
|
---|
2706 | " INNER JOIN groups ON revzones.group_id=groups.group_id".
|
---|
2707 | " WHERE revzones.group_id IN ($args{curgroup}".($args{childlist} ? ",$args{childlist}" : '').")".
|
---|
2708 | ($args{startwith} ? " AND CAST(revnet AS VARCHAR) ~* ?" : '');
|
---|
2709 | # if ($self->{showrev_arpa} eq 'zone' || $self->{showrev_arpa} eq 'all') {
|
---|
2710 | # Just In Case the UI is using formal .arpa notation, and someone enters something reversed,
|
---|
2711 | # we want to match both the formal and natural zone name
|
---|
2712 | $sql .= ($args{filter} ? " AND (CAST(revnet AS VARCHAR) ~* ? OR CAST(revnet AS VARCHAR) ~* ?)" : '');
|
---|
2713 | push @filterargs, join('[.]',reverse(split(/\[\.\]/,$args{filter}))) if $args{filter};
|
---|
2714 | # } else {
|
---|
2715 | # $sql .= ($args{filter} ? " AND CAST(revnet AS VARCHAR) ~* ?" : '');
|
---|
2716 | # }
|
---|
2717 | }
|
---|
2718 | # A common tail.
|
---|
2719 | $sql .= " ORDER BY ".($args{sortby} eq 'group' ? 'groups.group_name' : $args{sortby})." $args{sortorder} ".
|
---|
2720 | ($args{offset} eq 'all' ? '' : " LIMIT $self->{perpage}".
|
---|
2721 | " OFFSET ".$args{offset}*$self->{perpage});
|
---|
2722 |
|
---|
2723 | my @working;
|
---|
2724 | my $zsth = $dbh->prepare($sql);
|
---|
2725 | $zsth->execute(@filterargs);
|
---|
2726 | while (my $zone = $zsth->fetchrow_hashref) {
|
---|
2727 | if ($args{revrec} eq 'y' && ($self->{showrev_arpa} eq 'zone' || $self->{showrev_arpa} eq 'all')) {
|
---|
2728 | my $tmp = new NetAddr::IP $zone->{zone};
|
---|
2729 | $zone->{zone} = DNSDB::_ZONE($tmp, 'ZONE', 'r', '.').($tmp->{isv6} ? '.ip6.arpa' : '.in-addr.arpa');
|
---|
2730 | }
|
---|
2731 | push @working, $zone;
|
---|
2732 | }
|
---|
2733 | return \@working;
|
---|
2734 | } # end getZoneList()
|
---|
2735 |
|
---|
2736 |
|
---|
2737 | ## DNSDB::getZoneLocation()
|
---|
2738 | # Retrieve the default location for a zone.
|
---|
2739 | # Takes a database handle, forward/reverse flag, and zone ID
|
---|
2740 | sub getZoneLocation {
|
---|
2741 | my $self = shift;
|
---|
2742 | my $dbh = $self->{dbh};
|
---|
2743 | my $revrec = shift;
|
---|
2744 | my $zoneid = shift;
|
---|
2745 |
|
---|
2746 | my ($loc) = $dbh->selectrow_array("SELECT default_location FROM ".
|
---|
2747 | ($revrec eq 'n' ? 'domains WHERE domain_id = ?' : 'revzones WHERE rdns_id = ?'),
|
---|
2748 | undef, ($zoneid));
|
---|
2749 | return $loc;
|
---|
2750 | } # end getZoneLocation()
|
---|
2751 |
|
---|
2752 |
|
---|
2753 | ## DNSDB::addGroup()
|
---|
2754 | # Add a group
|
---|
2755 | # Takes a database handle, group name, parent group, hashref for permissions,
|
---|
2756 | # and optional template-vs-cloneme flag for the default records
|
---|
2757 | # Returns a status code and message
|
---|
2758 | sub addGroup {
|
---|
2759 | $errstr = '';
|
---|
2760 | my $self = shift;
|
---|
2761 | my $dbh = $self->{dbh};
|
---|
2762 | my $groupname = shift;
|
---|
2763 | my $pargroup = shift;
|
---|
2764 | my $permissions = shift;
|
---|
2765 |
|
---|
2766 | # 0 indicates "custom", hardcoded.
|
---|
2767 | # Any other value clones that group's default records, if it exists.
|
---|
2768 | my $inherit = shift || 0;
|
---|
2769 | ##fixme: need a flag to indicate clone records or <?> ?
|
---|
2770 |
|
---|
2771 | # Allow transactions, and raise an exception on errors so we can catch it later.
|
---|
2772 | # Use local to make sure these get "reset" properly on exiting this block
|
---|
2773 | local $dbh->{AutoCommit} = 0;
|
---|
2774 | local $dbh->{RaiseError} = 1;
|
---|
2775 |
|
---|
2776 | my ($group_id) = $dbh->selectrow_array("SELECT group_id FROM groups WHERE group_name=?", undef, ($groupname));
|
---|
2777 |
|
---|
2778 | return ('FAIL', "Group already exists") if $group_id;
|
---|
2779 |
|
---|
2780 | # Wrap all the SQL in a transaction
|
---|
2781 | eval {
|
---|
2782 | $dbh->do("INSERT INTO groups (parent_group_id,group_name) VALUES (?,?)", undef, ($pargroup, $groupname) );
|
---|
2783 |
|
---|
2784 | my ($groupid) = $dbh->selectrow_array("SELECT currval('groups_group_id_seq')");
|
---|
2785 |
|
---|
2786 | # We work through the whole set of permissions instead of specifying them so
|
---|
2787 | # that when we add a new permission, we don't have to change the code anywhere
|
---|
2788 | # that doesn't explicitly deal with that specific permission.
|
---|
2789 | my @permvals;
|
---|
2790 | foreach (@permtypes) {
|
---|
2791 | if (!defined ($permissions->{$_})) {
|
---|
2792 | push @permvals, 0;
|
---|
2793 | } else {
|
---|
2794 | push @permvals, $permissions->{$_};
|
---|
2795 | }
|
---|
2796 | }
|
---|
2797 | $dbh->do("INSERT INTO permissions (group_id,$permlist) values (?".',?'x($#permtypes+1).")",
|
---|
2798 | undef, ($groupid, @permvals) );
|
---|
2799 | my ($permid) = $dbh->selectrow_array("SELECT currval('permissions_permission_id_seq')");
|
---|
2800 | $dbh->do("UPDATE groups SET permission_id=$permid WHERE group_id=$groupid");
|
---|
2801 |
|
---|
2802 | # Default records
|
---|
2803 | my $sthf = $dbh->prepare("INSERT INTO default_records (group_id,host,type,val,distance,weight,port,ttl) ".
|
---|
2804 | "VALUES ($groupid,?,?,?,?,?,?,?)");
|
---|
2805 | my $sthr = $dbh->prepare("INSERT INTO default_rev_records (group_id,host,type,val,ttl) ".
|
---|
2806 | "VALUES ($groupid,?,?,?,?)");
|
---|
2807 | if ($inherit) {
|
---|
2808 | # Duplicate records from parent. Actually relying on inherited records feels
|
---|
2809 | # very fragile, and it would be problematic to roll over at a later time.
|
---|
2810 | my $sth2 = $dbh->prepare("SELECT host,type,val,distance,weight,port,ttl FROM default_records WHERE group_id=?");
|
---|
2811 | $sth2->execute($pargroup);
|
---|
2812 | while (my @clonedata = $sth2->fetchrow_array) {
|
---|
2813 | $sthf->execute(@clonedata);
|
---|
2814 | }
|
---|
2815 | # And now the reverse records
|
---|
2816 | $sth2 = $dbh->prepare("SELECT host,type,val,ttl FROM default_rev_records WHERE group_id=?");
|
---|
2817 | $sth2->execute($pargroup);
|
---|
2818 | while (my @clonedata = $sth2->fetchrow_array) {
|
---|
2819 | $sthr->execute(@clonedata);
|
---|
2820 | }
|
---|
2821 | } else {
|
---|
2822 | ##fixme: Hardcoding is Bad, mmmmkaaaay?
|
---|
2823 | # reasonable basic defaults for SOA, MX, NS, and minimal hosting
|
---|
2824 | # could load from a config file, but somewhere along the line we need hardcoded bits.
|
---|
2825 | $sthf->execute('ns1.example.com:hostmaster.example.com', 6, '10800:3600:604800:10800', 0, 0, 0, 86400);
|
---|
2826 | $sthf->execute('DOMAIN', 1, '192.168.4.2', 0, 0, 0, 7200);
|
---|
2827 | $sthf->execute('DOMAIN', 15, 'mx.example.com', 10, 0, 0, 7200);
|
---|
2828 | $sthf->execute('DOMAIN', 2, 'ns1.example.com', 0, 0, 0, 7200);
|
---|
2829 | $sthf->execute('DOMAIN', 2, 'ns2.example.com', 0, 0, 0, 7200);
|
---|
2830 | $sthf->execute('www.DOMAIN', 5, 'DOMAIN', 0, 0, 0, 7200);
|
---|
2831 | # reasonable basic defaults for generic reverse zone. Same as initial SQL tabledef.
|
---|
2832 | $sthr->execute('hostmaster.ADMINDOMAIN:ns1.ADMINDOMAIN', 6, '10800:3600:604800:10800', 86400);
|
---|
2833 | $sthr->execute('unused-%r.ADMINDOMAIN', 65283, 'ZONE', 3600);
|
---|
2834 | }
|
---|
2835 |
|
---|
2836 | $self->_log(group_id => $pargroup, entry => "Added group $groupname");
|
---|
2837 |
|
---|
2838 | # once we get here, we should have suceeded.
|
---|
2839 | $dbh->commit;
|
---|
2840 | }; # end eval
|
---|
2841 |
|
---|
2842 | if ($@) {
|
---|
2843 | my $msg = $@;
|
---|
2844 | eval { $dbh->rollback; };
|
---|
2845 | if ($self->{log_failures}) {
|
---|
2846 | $self->_log(group_id => $pargroup, entry => "Failed to add group $groupname: $msg");
|
---|
2847 | $dbh->commit;
|
---|
2848 | }
|
---|
2849 | return ('FAIL',$msg);
|
---|
2850 | }
|
---|
2851 |
|
---|
2852 | return ('OK','OK');
|
---|
2853 | } # end addGroup()
|
---|
2854 |
|
---|
2855 |
|
---|
2856 | ## DNSDB::delGroup()
|
---|
2857 | # Delete a group.
|
---|
2858 | # Takes a group ID
|
---|
2859 | # Returns a status code and message
|
---|
2860 | sub delGroup {
|
---|
2861 | my $self = shift;
|
---|
2862 | my $dbh = $self->{dbh};
|
---|
2863 | my $groupid = shift;
|
---|
2864 |
|
---|
2865 | # Allow transactions, and raise an exception on errors so we can catch it later.
|
---|
2866 | # Use local to make sure these get "reset" properly on exiting this block
|
---|
2867 | local $dbh->{AutoCommit} = 0;
|
---|
2868 | local $dbh->{RaiseError} = 1;
|
---|
2869 |
|
---|
2870 | ##fixme: locate "knowable" error conditions and deal with them before the eval
|
---|
2871 | # ... or inside, whatever.
|
---|
2872 | # -> domains still exist in group
|
---|
2873 | # -> ...
|
---|
2874 | my $failmsg = '';
|
---|
2875 | my $resultmsg = '';
|
---|
2876 |
|
---|
2877 | # collect some pieces for logging and error messages
|
---|
2878 | my $groupname = $self->groupName($groupid);
|
---|
2879 | my $parid = $self->parentID(id => $groupid, type => 'group');
|
---|
2880 |
|
---|
2881 | # Wrap all the SQL in a transaction
|
---|
2882 | eval {
|
---|
2883 | # Check for Things in the group
|
---|
2884 | $failmsg = "Can't remove group $groupname";
|
---|
2885 | my ($grpcnt) = $dbh->selectrow_array("SELECT count(*) FROM groups WHERE parent_group_id=?", undef, ($groupid));
|
---|
2886 | die "$grpcnt groups still in group\n" if $grpcnt;
|
---|
2887 | my ($domcnt) = $dbh->selectrow_array("SELECT count(*) FROM domains WHERE group_id=?", undef, ($groupid));
|
---|
2888 | die "$domcnt domains still in group\n" if $domcnt;
|
---|
2889 | my ($revcnt) = $dbh->selectrow_array("SELECT count(*) FROM revzones WHERE group_id=?", undef, ($groupid));
|
---|
2890 | die "$revcnt reverse zones still in group\n" if $revcnt;
|
---|
2891 | my ($usercnt) = $dbh->selectrow_array("SELECT count(*) FROM users WHERE group_id=?", undef, ($groupid));
|
---|
2892 | die "$usercnt users still in group\n" if $usercnt;
|
---|
2893 |
|
---|
2894 | $failmsg = "Failed to delete default records for $groupname";
|
---|
2895 | $dbh->do("DELETE from default_records WHERE group_id=?", undef, ($groupid));
|
---|
2896 | $failmsg = "Failed to delete default reverse records for $groupname";
|
---|
2897 | $dbh->do("DELETE from default_rev_records WHERE group_id=?", undef, ($groupid));
|
---|
2898 | $failmsg = "Failed to remove group $groupname";
|
---|
2899 | $dbh->do("DELETE from groups WHERE group_id=?", undef, ($groupid));
|
---|
2900 |
|
---|
2901 | $self->_log(group_id => $parid, entry => "Deleted group $groupname");
|
---|
2902 | $resultmsg = "Deleted group $groupname";
|
---|
2903 |
|
---|
2904 | # once we get here, we should have suceeded.
|
---|
2905 | $dbh->commit;
|
---|
2906 | }; # end eval
|
---|
2907 |
|
---|
2908 | if ($@) {
|
---|
2909 | my $msg = $@;
|
---|
2910 | eval { $dbh->rollback; };
|
---|
2911 | if ($self->{log_failures}) {
|
---|
2912 | $self->_log(group_id => $parid, entry => "$failmsg: $msg");
|
---|
2913 | $dbh->commit; # since we enabled transactions earlier
|
---|
2914 | }
|
---|
2915 | return ('FAIL',"$failmsg: $msg");
|
---|
2916 | }
|
---|
2917 |
|
---|
2918 | return ('OK',$resultmsg);
|
---|
2919 | } # end delGroup()
|
---|
2920 |
|
---|
2921 |
|
---|
2922 | ## DNSDB::getChildren()
|
---|
2923 | # Get a list of all groups whose parent^n is group <n>
|
---|
2924 | # Takes a database handle, group ID, reference to an array to put the group IDs in,
|
---|
2925 | # and an optional flag to return only immediate children or all children-of-children
|
---|
2926 | # default to returning all children
|
---|
2927 | # Calls itself
|
---|
2928 | sub getChildren {
|
---|
2929 | $errstr = '';
|
---|
2930 | my $self = shift;
|
---|
2931 | my $dbh = $self->{dbh};
|
---|
2932 | my $rootgroup = shift;
|
---|
2933 | my $groupdest = shift;
|
---|
2934 | my $immed = shift || 'all';
|
---|
2935 |
|
---|
2936 | # special break for default group; otherwise we get stuck.
|
---|
2937 | if ($rootgroup == 1) {
|
---|
2938 | # by definition, group 1 is the Root Of All Groups
|
---|
2939 | my $sth = $dbh->prepare("SELECT group_id FROM groups WHERE NOT (group_id=1)".
|
---|
2940 | ($immed ne 'all' ? " AND parent_group_id=1" : '')." ORDER BY group_name");
|
---|
2941 | $sth->execute;
|
---|
2942 | while (my @this = $sth->fetchrow_array) {
|
---|
2943 | push @$groupdest, @this;
|
---|
2944 | }
|
---|
2945 | } else {
|
---|
2946 | my $sth = $dbh->prepare("SELECT group_id FROM groups WHERE parent_group_id=? ORDER BY group_name");
|
---|
2947 | $sth->execute($rootgroup);
|
---|
2948 | return if $sth->rows == 0;
|
---|
2949 | my @grouplist;
|
---|
2950 | while (my ($group) = $sth->fetchrow_array) {
|
---|
2951 | push @$groupdest, $group;
|
---|
2952 | $self->getChildren($group, $groupdest) if $immed eq 'all';
|
---|
2953 | }
|
---|
2954 | }
|
---|
2955 | } # end getChildren()
|
---|
2956 |
|
---|
2957 |
|
---|
2958 | ## DNSDB::groupName()
|
---|
2959 | # Return the group name based on a group ID
|
---|
2960 | # Takes a database handle and the group ID
|
---|
2961 | # Returns the group name or undef on failure
|
---|
2962 | sub groupName {
|
---|
2963 | $errstr = '';
|
---|
2964 | my $self = shift;
|
---|
2965 | my $dbh = $self->{dbh};
|
---|
2966 | my $groupid = shift;
|
---|
2967 | my $sth = $dbh->prepare("SELECT group_name FROM groups WHERE group_id=?");
|
---|
2968 | $sth->execute($groupid);
|
---|
2969 | my ($groupname) = $sth->fetchrow_array();
|
---|
2970 | $errstr = $DBI::errstr if !$groupname;
|
---|
2971 | return $groupname if $groupname;
|
---|
2972 | } # end groupName
|
---|
2973 |
|
---|
2974 |
|
---|
2975 | ## DNSDB::getGroupCount()
|
---|
2976 | # Get count of subgroups in group or groups
|
---|
2977 | # Takes a database handle and hash containing:
|
---|
2978 | # - the "current" group
|
---|
2979 | # - an array of "acceptable" groups
|
---|
2980 | # - Optionally accept a "starts with" and/or "contains" filter argument
|
---|
2981 | # Returns an integer count of the resulting group list.
|
---|
2982 | sub getGroupCount {
|
---|
2983 | my $self = shift;
|
---|
2984 | my $dbh = $self->{dbh};
|
---|
2985 |
|
---|
2986 | my %args = @_;
|
---|
2987 |
|
---|
2988 | # Fail on bad curgroup argument. There's no sane fallback on this one.
|
---|
2989 | if (!$args{curgroup} || $args{curgroup} !~ /^\d+$/) {
|
---|
2990 | $errstr = "Bad or missing curgroup argument";
|
---|
2991 | return;
|
---|
2992 | }
|
---|
2993 | # Fail on bad childlist argument. This could be sanely ignored if bad, maybe.
|
---|
2994 | if ($args{childlist} && $args{childlist} !~ /^[\d,]+$/) {
|
---|
2995 | $errstr = "Bad childlist argument";
|
---|
2996 | return;
|
---|
2997 | }
|
---|
2998 |
|
---|
2999 | my @filterargs;
|
---|
3000 | $args{startwith} = undef if $args{startwith} && $args{startwith} !~ /^(?:[a-z]|0-9)$/;
|
---|
3001 | push @filterargs, "^$args{startwith}" if $args{startwith};
|
---|
3002 | push @filterargs, $args{filter} if $args{filter};
|
---|
3003 |
|
---|
3004 | my $sql = "SELECT count(*) FROM groups ".
|
---|
3005 | "WHERE parent_group_id IN ($args{curgroup}".($args{childlist} ? ",$args{childlist}" : '').")".
|
---|
3006 | ($args{startwith} ? " AND group_name ~* ?" : '').
|
---|
3007 | ($args{filter} ? " AND group_name ~* ?" : '');
|
---|
3008 | my ($count) = $dbh->selectrow_array($sql, undef, (@filterargs) );
|
---|
3009 | $errstr = $dbh->errstr if !$count;
|
---|
3010 | return $count;
|
---|
3011 | } # end getGroupCount
|
---|
3012 |
|
---|
3013 |
|
---|
3014 | ## DNSDB::getGroupList()
|
---|
3015 | # Get a list of sub^n-groups in the specified group(s)
|
---|
3016 | # Takes the same arguments as getGroupCount() above
|
---|
3017 | # Returns an arrayref containing hashrefs suitable for feeding straight to HTML::Template
|
---|
3018 | sub getGroupList {
|
---|
3019 | my $self = shift;
|
---|
3020 | my $dbh = $self->{dbh};
|
---|
3021 |
|
---|
3022 | my %args = @_;
|
---|
3023 |
|
---|
3024 | # Fail on bad curgroup argument. There's no sane fallback on this one.
|
---|
3025 | if (!$args{curgroup} || $args{curgroup} !~ /^\d+$/) {
|
---|
3026 | $errstr = "Bad or missing curgroup argument";
|
---|
3027 | return;
|
---|
3028 | }
|
---|
3029 | # Fail on bad childlist argument. This could be sanely ignored if bad, maybe.
|
---|
3030 | if ($args{childlist} && $args{childlist} !~ /^[\d,]+$/) {
|
---|
3031 | $errstr = "Bad childlist argument";
|
---|
3032 | return;
|
---|
3033 | }
|
---|
3034 |
|
---|
3035 | my @filterargs;
|
---|
3036 | $args{startwith} = undef if $args{startwith} && $args{startwith} !~ /^(?:[a-z]|0-9)$/;
|
---|
3037 | push @filterargs, "^$args{startwith}" if $args{startwith};
|
---|
3038 | push @filterargs, $args{filter} if $args{filter};
|
---|
3039 |
|
---|
3040 | # protection against bad or missing arguments
|
---|
3041 | $args{sortorder} = 'ASC' if !$args{sortorder} || !grep /^$args{sortorder}$/, ('ASC','DESC');
|
---|
3042 | $args{sortby} = 'group' if !$args{sortby} || $args{sortby} !~ /^[\w_.]+$/;
|
---|
3043 | $args{offset} = 0 if !$args{offset} || $args{offset} !~ /^(?:all|\d+)$/;
|
---|
3044 |
|
---|
3045 | # munge sortby for columns in database
|
---|
3046 | $args{sortby} = 'g.group_name' if $args{sortby} eq 'group';
|
---|
3047 | $args{sortby} = 'g2.group_name' if $args{sortby} eq 'parent';
|
---|
3048 |
|
---|
3049 | my $sql = q(SELECT g.group_id AS groupid, g.group_name AS groupname, g2.group_name AS pgroup
|
---|
3050 | FROM groups g
|
---|
3051 | INNER JOIN groups g2 ON g2.group_id=g.parent_group_id
|
---|
3052 | ).
|
---|
3053 | " WHERE g.parent_group_id IN ($args{curgroup}".($args{childlist} ? ",$args{childlist}" : '').")".
|
---|
3054 | ($args{startwith} ? " AND g.group_name ~* ?" : '').
|
---|
3055 | ($args{filter} ? " AND g.group_name ~* ?" : '').
|
---|
3056 | " GROUP BY g.group_id, g.group_name, g2.group_name ".
|
---|
3057 | " ORDER BY $args{sortby} $args{sortorder} ".
|
---|
3058 | ($args{offset} eq 'all' ? '' : " LIMIT $self->{perpage} OFFSET ".$args{offset}*$self->{perpage});
|
---|
3059 | my $glist = $dbh->selectall_arrayref($sql, { Slice => {} }, (@filterargs) );
|
---|
3060 | $errstr = $dbh->errstr if !$glist;
|
---|
3061 |
|
---|
3062 | # LEFT JOINs make the result set balloon beyond sanity just to include counts;
|
---|
3063 | # this means there's lots of crunching needed to trim the result set back down.
|
---|
3064 | # So instead we track the order of the groups, and push the counts into the
|
---|
3065 | # arrayref result separately.
|
---|
3066 | ##fixme: put this whole sub in a transaction? might be
|
---|
3067 | # needed for accurate results on very busy systems.
|
---|
3068 | ##fixme: large group lists need prepared statements?
|
---|
3069 | #my $ucsth = $dbh->prepare("SELECT count(*) FROM users WHERE group_id=?");
|
---|
3070 | #my $dcsth = $dbh->prepare("SELECT count(*) FROM domains WHERE group_id=?");
|
---|
3071 | #my $rcsth = $dbh->prepare("SELECT count(*) FROM revzones WHERE group_id=?");
|
---|
3072 | foreach (@{$glist}) {
|
---|
3073 | my ($ucnt) = $dbh->selectrow_array("SELECT count(*) FROM users WHERE group_id=?", undef, ($$_{groupid}));
|
---|
3074 | $$_{nusers} = $ucnt;
|
---|
3075 | my ($dcnt) = $dbh->selectrow_array("SELECT count(*) FROM domains WHERE group_id=?", undef, ($$_{groupid}));
|
---|
3076 | $$_{ndomains} = $dcnt;
|
---|
3077 | my ($rcnt) = $dbh->selectrow_array("SELECT count(*) FROM revzones WHERE group_id=?", undef, ($$_{groupid}));
|
---|
3078 | $$_{nrevzones} = $rcnt;
|
---|
3079 | }
|
---|
3080 |
|
---|
3081 | return $glist;
|
---|
3082 | } # end getGroupList
|
---|
3083 |
|
---|
3084 |
|
---|
3085 | ## DNSDB::groupID()
|
---|
3086 | # Return the group ID based on the group name
|
---|
3087 | # Takes a database handle and the group name
|
---|
3088 | # Returns the group ID or undef on failure
|
---|
3089 | sub groupID {
|
---|
3090 | $errstr = '';
|
---|
3091 | my $self = shift;
|
---|
3092 | my $dbh = $self->{dbh};
|
---|
3093 | my $group = shift;
|
---|
3094 | my ($grpid) = $dbh->selectrow_array("SELECT group_id FROM groups WHERE group_name=?", undef, ($group) );
|
---|
3095 | $errstr = $DBI::errstr if !$grpid;
|
---|
3096 | return $grpid if $grpid;
|
---|
3097 | } # end groupID()
|
---|
3098 |
|
---|
3099 |
|
---|
3100 | ## DNSDB::addUser()
|
---|
3101 | # Add a user.
|
---|
3102 | # Takes a DB handle, username, group ID, password, state (active/inactive).
|
---|
3103 | # Optionally accepts:
|
---|
3104 | # user type (user/admin) - defaults to user
|
---|
3105 | # permissions string - defaults to inherit from group
|
---|
3106 | # three valid forms:
|
---|
3107 | # i - Inherit permissions
|
---|
3108 | # c:<user_id> - Clone permissions from <user_id>
|
---|
3109 | # C:<permission list> - Set these specific permissions
|
---|
3110 | # first name - defaults to username
|
---|
3111 | # last name - defaults to blank
|
---|
3112 | # phone - defaults to blank (could put other data within column def)
|
---|
3113 | # Returns (OK,<uid>) on success, (FAIL,<message>) on failure
|
---|
3114 | sub addUser {
|
---|
3115 | $errstr = '';
|
---|
3116 | my $self = shift;
|
---|
3117 | my $dbh = $self->{dbh};
|
---|
3118 | my $username = shift;
|
---|
3119 | my $group = shift;
|
---|
3120 | my $pass = shift;
|
---|
3121 | my $state = shift;
|
---|
3122 |
|
---|
3123 | return ('FAIL', "Missing one or more required entries") if !defined($state);
|
---|
3124 | return ('FAIL', "Username must not be blank") if !$username;
|
---|
3125 |
|
---|
3126 | # Munge in some alternate state values
|
---|
3127 | $state = 1 if $state =~ /^active$/;
|
---|
3128 | $state = 1 if $state =~ /^on$/;
|
---|
3129 | $state = 0 if $state =~ /^inactive$/;
|
---|
3130 | $state = 0 if $state =~ /^off$/;
|
---|
3131 |
|
---|
3132 | my $type = shift || 'u'; # create limited users by default - fwiw, not sure yet how this will interact with ACLs
|
---|
3133 |
|
---|
3134 | my $permstring = shift || 'i'; # default is to inhert permissions from group
|
---|
3135 |
|
---|
3136 | my $fname = shift || $username;
|
---|
3137 | my $lname = shift || '';
|
---|
3138 | my $phone = shift || ''; # not going format-check
|
---|
3139 |
|
---|
3140 | my $sth = $dbh->prepare("SELECT user_id FROM users WHERE username=?");
|
---|
3141 | my $user_id;
|
---|
3142 |
|
---|
3143 | # quick check to start to see if we've already got one
|
---|
3144 | $sth->execute($username);
|
---|
3145 | ($user_id) = $sth->fetchrow_array;
|
---|
3146 |
|
---|
3147 | return ('FAIL', "User already exists") if $user_id;
|
---|
3148 |
|
---|
3149 | # Allow transactions, and raise an exception on errors so we can catch it later.
|
---|
3150 | # Use local to make sure these get "reset" properly on exiting this block
|
---|
3151 | local $dbh->{AutoCommit} = 0;
|
---|
3152 | local $dbh->{RaiseError} = 1;
|
---|
3153 |
|
---|
3154 | # Wrap all the SQL in a transaction
|
---|
3155 | eval {
|
---|
3156 | # insert the user... note we set inherited perms by default since
|
---|
3157 | # it's simple and cleans up some other bits of state
|
---|
3158 | ##fixme: need better handling of case of inherited or missing (!!) permissions entries
|
---|
3159 | my $sth = $dbh->prepare("INSERT INTO users ".
|
---|
3160 | "(group_id,username,password,firstname,lastname,phone,type,status,permission_id,inherit_perm) ".
|
---|
3161 | "VALUES (?,?,?,?,?,?,?,?,(SELECT permission_id FROM permissions WHERE group_id=?),'t')");
|
---|
3162 | $sth->execute($group,$username,unix_md5_crypt($pass),$fname,$lname,$phone,$type,$state,$group);
|
---|
3163 |
|
---|
3164 | # get the ID...
|
---|
3165 | ($user_id) = $dbh->selectrow_array("SELECT currval('users_user_id_seq')");
|
---|
3166 |
|
---|
3167 | # Permissions! Gotta set'em all!
|
---|
3168 | die "Invalid permission string $permstring\n"
|
---|
3169 | if $permstring !~ /^(?:
|
---|
3170 | i # inherit
|
---|
3171 | |c:\d+ # clone
|
---|
3172 | # custom. no, the leading , is not a typo
|
---|
3173 | |C:(?:,(?:group|user|domain|record|location|self)_(?:edit|create|delete|locchg|view))*
|
---|
3174 | )$/x;
|
---|
3175 | # bleh. I'd call another function to do my dirty work, but we're in the middle of a transaction already.
|
---|
3176 | if ($permstring ne 'i') {
|
---|
3177 | # for cloned or custom permissions, we have to create a new permissions entry.
|
---|
3178 | my $clonesrc = $group;
|
---|
3179 | if ($permstring =~ /^c:(\d+)/) { $clonesrc = $1; }
|
---|
3180 | $dbh->do("INSERT INTO permissions ($permlist,user_id) ".
|
---|
3181 | "SELECT $permlist,? FROM permissions WHERE permission_id=".
|
---|
3182 | "(SELECT permission_id FROM permissions WHERE ".($permstring =~ /^c:/ ? 'user' : 'group')."_id=?)",
|
---|
3183 | undef, ($user_id,$clonesrc) );
|
---|
3184 | $dbh->do("UPDATE users SET permission_id=".
|
---|
3185 | "(SELECT permission_id FROM permissions WHERE user_id=?) ".
|
---|
3186 | "WHERE user_id=?", undef, ($user_id, $user_id) );
|
---|
3187 | }
|
---|
3188 | if ($permstring =~ /^C:/) {
|
---|
3189 | # finally for custom permissions, we set the passed-in permissions (and unset
|
---|
3190 | # any that might have been brought in by the clone operation above)
|
---|
3191 | my ($permid) = $dbh->selectrow_array("SELECT permission_id FROM permissions WHERE user_id=?",
|
---|
3192 | undef, ($user_id) );
|
---|
3193 | foreach (@permtypes) {
|
---|
3194 | if ($permstring =~ /,$_/) {
|
---|
3195 | $dbh->do("UPDATE permissions SET $_='t' WHERE permission_id=?", undef, ($permid) );
|
---|
3196 | } else {
|
---|
3197 | $dbh->do("UPDATE permissions SET $_='f' WHERE permission_id=?", undef, ($permid) );
|
---|
3198 | }
|
---|
3199 | }
|
---|
3200 | }
|
---|
3201 |
|
---|
3202 | $dbh->do("UPDATE users SET inherit_perm='n' WHERE user_id=?", undef, ($user_id) );
|
---|
3203 |
|
---|
3204 | ##fixme: add another table to hold name/email for log table?
|
---|
3205 |
|
---|
3206 | $self->_log(group_id => $group, entry => "Added user $username ($fname $lname)");
|
---|
3207 | # once we get here, we should have suceeded.
|
---|
3208 | $dbh->commit;
|
---|
3209 | }; # end eval
|
---|
3210 |
|
---|
3211 | if ($@) {
|
---|
3212 | my $msg = $@;
|
---|
3213 | eval { $dbh->rollback; };
|
---|
3214 | if ($self->{log_failures}) {
|
---|
3215 | $self->_log(group_id => $group, entry => "Error adding user $username: $msg");
|
---|
3216 | $dbh->commit; # since we enabled transactions earlier
|
---|
3217 | }
|
---|
3218 | return ('FAIL',"Error adding user $username: $msg");
|
---|
3219 | }
|
---|
3220 |
|
---|
3221 | return ('OK',"User $username ($fname $lname) added");
|
---|
3222 | } # end addUser
|
---|
3223 |
|
---|
3224 |
|
---|
3225 | ## DNSDB::getUserCount()
|
---|
3226 | # Get count of users in group
|
---|
3227 | # Takes a database handle and hash containing at least the current group, and optionally:
|
---|
3228 | # - a reference list of secondary groups
|
---|
3229 | # - a filter string
|
---|
3230 | # - a "Starts with" string
|
---|
3231 | sub getUserCount {
|
---|
3232 | my $self = shift;
|
---|
3233 | my $dbh = $self->{dbh};
|
---|
3234 |
|
---|
3235 | my %args = @_;
|
---|
3236 |
|
---|
3237 | # Fail on bad curgroup argument. There's no sane fallback on this one.
|
---|
3238 | if (!$args{curgroup} || $args{curgroup} !~ /^\d+$/) {
|
---|
3239 | $errstr = "Bad or missing curgroup argument";
|
---|
3240 | return;
|
---|
3241 | }
|
---|
3242 | # Fail on bad childlist argument. This could be sanely ignored if bad, maybe.
|
---|
3243 | if ($args{childlist} && $args{childlist} !~ /^[\d,]+$/) {
|
---|
3244 | $errstr = "Bad childlist argument";
|
---|
3245 | return;
|
---|
3246 | }
|
---|
3247 |
|
---|
3248 | my @filterargs;
|
---|
3249 | $args{startwith} = undef if $args{startwith} && $args{startwith} !~ /^(?:[a-z]|0-9)$/;
|
---|
3250 | push @filterargs, "^$args{startwith}" if $args{startwith};
|
---|
3251 | push @filterargs, $args{filter} if $args{filter};
|
---|
3252 |
|
---|
3253 | my $sql = "SELECT count(*) FROM users ".
|
---|
3254 | "WHERE group_id IN ($args{curgroup}".($args{childlist} ? ",$args{childlist}" : '').")".
|
---|
3255 | ($args{startwith} ? " AND username ~* ?" : '').
|
---|
3256 | ($args{filter} ? " AND username ~* ?" : '');
|
---|
3257 | my ($count) = $dbh->selectrow_array($sql, undef, (@filterargs) );
|
---|
3258 | $errstr = $dbh->errstr if !$count;
|
---|
3259 | return $count;
|
---|
3260 | } # end getUserCount()
|
---|
3261 |
|
---|
3262 |
|
---|
3263 | ## DNSDB::getUserList()
|
---|
3264 | # Get list of users
|
---|
3265 | # Takes the same arguments as getUserCount() above, plus optional:
|
---|
3266 | # - sort field
|
---|
3267 | # - sort order
|
---|
3268 | # - offset/return-all-everything flag (defaults to $perpage records)
|
---|
3269 | sub getUserList {
|
---|
3270 | my $self = shift;
|
---|
3271 | my $dbh = $self->{dbh};
|
---|
3272 |
|
---|
3273 | my %args = @_;
|
---|
3274 |
|
---|
3275 | # Fail on bad curgroup argument. There's no sane fallback on this one.
|
---|
3276 | if (!$args{curgroup} || $args{curgroup} !~ /^\d+$/) {
|
---|
3277 | $errstr = "Bad or missing curgroup argument";
|
---|
3278 | return;
|
---|
3279 | }
|
---|
3280 | # Fail on bad childlist argument. This could be sanely ignored if bad, maybe.
|
---|
3281 | if ($args{childlist} && $args{childlist} !~ /^[\d,]+$/) {
|
---|
3282 | $errstr = "Bad childlist argument";
|
---|
3283 | return;
|
---|
3284 | }
|
---|
3285 |
|
---|
3286 | my @filterargs;
|
---|
3287 | $args{startwith} = undef if $args{startwith} && $args{startwith} !~ /^(?:[a-z]|0-9)$/;
|
---|
3288 | push @filterargs, "^$args{startwith}" if $args{startwith};
|
---|
3289 | push @filterargs, $args{filter} if $args{filter};
|
---|
3290 |
|
---|
3291 | # better to request sorts on "simple" names, but it means we need to map it to real columns
|
---|
3292 | my %sortmap = (user => 'u.username', type => 'u.type', group => 'g.group_name', status => 'u.status',
|
---|
3293 | fname => 'fname');
|
---|
3294 | $args{sortby} = $sortmap{$args{sortby}};
|
---|
3295 |
|
---|
3296 | # protection against bad or missing arguments
|
---|
3297 | $args{sortorder} = 'ASC' if !$args{sortorder} || !grep /^$args{sortorder}$/, ('ASC','DESC');
|
---|
3298 | $args{sortby} = 'u.username' if !$args{sortby} || $args{sortby} !~ /^[\w_.]+$/;
|
---|
3299 | $args{offset} = 0 if !$args{offset} || $args{offset} !~ /^(?:all|\d+)$/;
|
---|
3300 |
|
---|
3301 | my $sql = "SELECT u.user_id, u.username, u.firstname || ' ' || u.lastname AS fname, u.type, g.group_name, u.status ".
|
---|
3302 | "FROM users u ".
|
---|
3303 | "INNER JOIN groups g ON u.group_id=g.group_id ".
|
---|
3304 | "WHERE u.group_id IN ($args{curgroup}".($args{childlist} ? ",$args{childlist}" : '').")".
|
---|
3305 | ($args{startwith} ? " AND u.username ~* ?" : '').
|
---|
3306 | ($args{filter} ? " AND u.username ~* ?" : '').
|
---|
3307 | " AND NOT u.type = 'R' ".
|
---|
3308 | " ORDER BY $args{sortby} $args{sortorder} ".
|
---|
3309 | ($args{offset} eq 'all' ? '' : " LIMIT $self->{perpage} OFFSET ".$args{offset}*$self->{perpage});
|
---|
3310 | my $ulist = $dbh->selectall_arrayref($sql, { Slice => {} }, (@filterargs) );
|
---|
3311 | $errstr = $dbh->errstr if !$ulist;
|
---|
3312 | return $ulist;
|
---|
3313 | } # end getUserList()
|
---|
3314 |
|
---|
3315 |
|
---|
3316 | ## DNSDB::getUserDropdown()
|
---|
3317 | # Get a list of usernames for use in a dropdown menu.
|
---|
3318 | # Takes a database handle, current group, and optional "tag this as selected" flag.
|
---|
3319 | # Returns a reference to a list of hashrefs suitable to feeding to HTML::Template
|
---|
3320 | sub getUserDropdown {
|
---|
3321 | my $self = shift;
|
---|
3322 | my $dbh = $self->{dbh};
|
---|
3323 | my $grp = shift;
|
---|
3324 | my $sel = shift || 0;
|
---|
3325 |
|
---|
3326 | my $sth = $dbh->prepare("SELECT username,user_id FROM users WHERE group_id=?");
|
---|
3327 | $sth->execute($grp);
|
---|
3328 |
|
---|
3329 | my @userlist;
|
---|
3330 | while (my ($username,$uid) = $sth->fetchrow_array) {
|
---|
3331 | my %row = (
|
---|
3332 | username => $username,
|
---|
3333 | uid => $uid,
|
---|
3334 | selected => ($sel == $uid ? 1 : 0)
|
---|
3335 | );
|
---|
3336 | push @userlist, \%row;
|
---|
3337 | }
|
---|
3338 | return \@userlist;
|
---|
3339 | } # end getUserDropdown()
|
---|
3340 |
|
---|
3341 |
|
---|
3342 | ## DNSDB:: updateUser()
|
---|
3343 | # Update general data about user
|
---|
3344 | sub updateUser {
|
---|
3345 | my $self = shift;
|
---|
3346 | my $dbh = $self->{dbh};
|
---|
3347 |
|
---|
3348 | ##fixme: tweak calling convention so that we can update any given bit of data
|
---|
3349 | my $uid = shift;
|
---|
3350 | my $username = shift;
|
---|
3351 | my $group = shift;
|
---|
3352 | my $pass = shift;
|
---|
3353 | my $state = shift;
|
---|
3354 | my $type = shift || 'u';
|
---|
3355 | my $fname = shift || $username;
|
---|
3356 | my $lname = shift || '';
|
---|
3357 | my $phone = shift || ''; # not going format-check
|
---|
3358 |
|
---|
3359 | my $resultmsg = '';
|
---|
3360 |
|
---|
3361 | # Munge in some alternate state values
|
---|
3362 | $state = 1 if $state =~ /^active$/;
|
---|
3363 | $state = 1 if $state =~ /^on$/;
|
---|
3364 | $state = 0 if $state =~ /^inactive$/;
|
---|
3365 | $state = 0 if $state =~ /^off$/;
|
---|
3366 |
|
---|
3367 | # Allow transactions, and raise an exception on errors so we can catch it later.
|
---|
3368 | # Use local to make sure these get "reset" properly on exiting this block
|
---|
3369 | local $dbh->{AutoCommit} = 0;
|
---|
3370 | local $dbh->{RaiseError} = 1;
|
---|
3371 |
|
---|
3372 | my $sth;
|
---|
3373 |
|
---|
3374 | # Password can be left blank; if so we assume there's one on file.
|
---|
3375 | # Actual blank passwords are bad, mm'kay?
|
---|
3376 | if (!$pass) {
|
---|
3377 | ($pass) = $dbh->selectrow_array("SELECT password FROM users WHERE user_id=?", undef, ($uid));
|
---|
3378 | } else {
|
---|
3379 | $pass = unix_md5_crypt($pass);
|
---|
3380 | }
|
---|
3381 |
|
---|
3382 | eval {
|
---|
3383 | $dbh->do("UPDATE users SET username=?, password=?, firstname=?, lastname=?, phone=?, type=?, status=?".
|
---|
3384 | " WHERE user_id=?", undef, ($username, $pass, $fname, $lname, $phone, $type, $state, $uid));
|
---|
3385 | $resultmsg = "Updated user info for $username ($fname $lname)";
|
---|
3386 | $self->_log(group_id => $group, entry => $resultmsg);
|
---|
3387 | $dbh->commit;
|
---|
3388 | };
|
---|
3389 | if ($@) {
|
---|
3390 | my $msg = $@;
|
---|
3391 | eval { $dbh->rollback; };
|
---|
3392 | if ($self->{log_failures}) {
|
---|
3393 | $self->_log(group_id => $group, entry => "Error updating user $username: $msg");
|
---|
3394 | $dbh->commit; # since we enabled transactions earlier
|
---|
3395 | }
|
---|
3396 | return ('FAIL',"Error updating user $username: $msg");
|
---|
3397 | }
|
---|
3398 |
|
---|
3399 | return ('OK',$resultmsg);
|
---|
3400 | } # end updateUser()
|
---|
3401 |
|
---|
3402 |
|
---|
3403 | ## DNSDB::delUser()
|
---|
3404 | # Delete a user.
|
---|
3405 | # Takes a database handle and user ID
|
---|
3406 | # Returns a success/failure code and matching message
|
---|
3407 | sub delUser {
|
---|
3408 | my $self = shift;
|
---|
3409 | my $dbh = $self->{dbh};
|
---|
3410 | my $userid = shift;
|
---|
3411 |
|
---|
3412 | return ('FAIL',"Bad userid") if !defined($userid);
|
---|
3413 |
|
---|
3414 | my $userdata = $self->getUserData($userid);
|
---|
3415 |
|
---|
3416 | # Allow transactions, and raise an exception on errors so we can catch it later.
|
---|
3417 | # Use local to make sure these get "reset" properly on exiting this block
|
---|
3418 | local $dbh->{AutoCommit} = 0;
|
---|
3419 | local $dbh->{RaiseError} = 1;
|
---|
3420 |
|
---|
3421 | eval {
|
---|
3422 | $dbh->do("DELETE FROM users WHERE user_id=?", undef, ($userid));
|
---|
3423 | $self->_log(group_id => $userdata->{group_id},
|
---|
3424 | entry => "Deleted user ID $userid/".$userdata->{username}.
|
---|
3425 | " (".$userdata->{firstname}." ".$userdata->{lastname}.")");
|
---|
3426 | $dbh->commit;
|
---|
3427 | };
|
---|
3428 | if ($@) {
|
---|
3429 | my $msg = $@;
|
---|
3430 | eval { $dbh->rollback; };
|
---|
3431 | if ($self->{log_failures}) {
|
---|
3432 | $self->_log(group_id => $userdata->{group_id}, entry => "Error deleting user ID ".
|
---|
3433 | "$userid/".$userdata->{username}.": $msg");
|
---|
3434 | $dbh->commit;
|
---|
3435 | }
|
---|
3436 | return ('FAIL',"Error deleting user $userid/".$userdata->{username}.": $msg");
|
---|
3437 | }
|
---|
3438 |
|
---|
3439 | return ('OK',"Deleted user ".$userdata->{username}." (".$userdata->{firstname}." ".$userdata->{lastname}.")");
|
---|
3440 | } # end delUser
|
---|
3441 |
|
---|
3442 |
|
---|
3443 | ## DNSDB::userFullName()
|
---|
3444 | # Return a pretty string!
|
---|
3445 | # Takes a user_id and optional printf-ish string to indicate which pieces where:
|
---|
3446 | # %u for the username
|
---|
3447 | # %f for the first name
|
---|
3448 | # %l for the last name
|
---|
3449 | # All other text in the passed string will be left as-is.
|
---|
3450 | ##fixme: need a "smart" option too, so that missing/null/blank first/last names don't give funky output
|
---|
3451 | sub userFullName {
|
---|
3452 | $errstr = '';
|
---|
3453 | my $self = shift;
|
---|
3454 | my $dbh = $self->{dbh};
|
---|
3455 | my $userid = shift;
|
---|
3456 | my $fullformat = shift || '%f %l (%u)';
|
---|
3457 | my $sth = $dbh->prepare("select username,firstname,lastname from users where user_id=?");
|
---|
3458 | $sth->execute($userid);
|
---|
3459 | my ($uname,$fname,$lname) = $sth->fetchrow_array();
|
---|
3460 | $errstr = $DBI::errstr if !$uname;
|
---|
3461 |
|
---|
3462 | $fullformat =~ s/\%u/$uname/g;
|
---|
3463 | $fullformat =~ s/\%f/$fname/g;
|
---|
3464 | $fullformat =~ s/\%l/$lname/g;
|
---|
3465 |
|
---|
3466 | return $fullformat;
|
---|
3467 | } # end userFullName
|
---|
3468 |
|
---|
3469 |
|
---|
3470 | ## DNSDB::userStatus()
|
---|
3471 | # Sets and/or returns a user's status
|
---|
3472 | # Takes a database handle, user ID and optionally a status argument
|
---|
3473 | # Returns undef on errors.
|
---|
3474 | sub userStatus {
|
---|
3475 | my $self = shift;
|
---|
3476 | my $dbh = $self->{dbh};
|
---|
3477 | my $id = shift;
|
---|
3478 | my $newstatus = shift || 'mu';
|
---|
3479 |
|
---|
3480 | return undef if $id !~ /^\d+$/;
|
---|
3481 |
|
---|
3482 | my $userdata = $self->getUserData($id);
|
---|
3483 |
|
---|
3484 | # Allow transactions, and raise an exception on errors so we can catch it later.
|
---|
3485 | # Use local to make sure these get "reset" properly on exiting this block
|
---|
3486 | local $dbh->{AutoCommit} = 0;
|
---|
3487 | local $dbh->{RaiseError} = 1;
|
---|
3488 |
|
---|
3489 | if ($newstatus ne 'mu') {
|
---|
3490 | # ooo, fun! let's see what we were passed for status
|
---|
3491 | eval {
|
---|
3492 | $newstatus = 0 if $newstatus eq 'useroff';
|
---|
3493 | $newstatus = 1 if $newstatus eq 'useron';
|
---|
3494 | $dbh->do("UPDATE users SET status=? WHERE user_id=?", undef, ($newstatus, $id));
|
---|
3495 |
|
---|
3496 | $resultstr = ($newstatus ? 'Enabled' : 'Disabled')." user ".$userdata->{username}.
|
---|
3497 | " (".$userdata->{firstname}." ".$userdata->{lastname}.")";
|
---|
3498 |
|
---|
3499 | my %loghash;
|
---|
3500 | $loghash{group_id} = $self->parentID(id => $id, type => 'user');
|
---|
3501 | $loghash{entry} = $resultstr;
|
---|
3502 | $self->_log(%loghash);
|
---|
3503 |
|
---|
3504 | $dbh->commit;
|
---|
3505 | };
|
---|
3506 | if ($@) {
|
---|
3507 | my $msg = $@;
|
---|
3508 | eval { $dbh->rollback; };
|
---|
3509 | $resultstr = '';
|
---|
3510 | $errstr = $msg;
|
---|
3511 | ##fixme: failure logging?
|
---|
3512 | return;
|
---|
3513 | }
|
---|
3514 | }
|
---|
3515 |
|
---|
3516 | my ($status) = $dbh->selectrow_array("SELECT status FROM users WHERE user_id=?", undef, ($id));
|
---|
3517 | return $status;
|
---|
3518 | } # end userStatus()
|
---|
3519 |
|
---|
3520 |
|
---|
3521 | ## DNSDB::getUserData()
|
---|
3522 | # Get misc user data for display
|
---|
3523 | sub getUserData {
|
---|
3524 | my $self = shift;
|
---|
3525 | my $dbh = $self->{dbh};
|
---|
3526 | my $uid = shift;
|
---|
3527 |
|
---|
3528 | my $sth = $dbh->prepare("SELECT group_id,username,firstname,lastname,phone,type,status,inherit_perm ".
|
---|
3529 | "FROM users WHERE user_id=?");
|
---|
3530 | $sth->execute($uid);
|
---|
3531 | return $sth->fetchrow_hashref();
|
---|
3532 | } # end getUserData()
|
---|
3533 |
|
---|
3534 |
|
---|
3535 | ## DNSDB::addLoc()
|
---|
3536 | # Add a new location.
|
---|
3537 | # Takes a database handle, group ID, short and long description, and a comma-separated
|
---|
3538 | # list of IP addresses.
|
---|
3539 | # Returns ('OK',<location>) on success, ('FAIL',<failmsg>) on failure
|
---|
3540 | sub addLoc {
|
---|
3541 | my $self = shift;
|
---|
3542 | my $dbh = $self->{dbh};
|
---|
3543 | my $grp = shift;
|
---|
3544 | my $shdesc = shift;
|
---|
3545 | my $comments = shift;
|
---|
3546 | my $iplist = shift;
|
---|
3547 |
|
---|
3548 | # $shdesc gets set to the generated location ID if possible, but these can be de-undefined here.
|
---|
3549 | $comments = '' if !$comments;
|
---|
3550 | $iplist = '' if !$iplist;
|
---|
3551 |
|
---|
3552 | my $loc;
|
---|
3553 |
|
---|
3554 | # Generate a location ID. This is, by spec, a two-character widget. We'll use [a-z][a-z]
|
---|
3555 | # for now; 676 locations should satisfy all but the largest of the huge networks.
|
---|
3556 | # Not sure whether these are case-sensitive, or what other rules might apply - in any case
|
---|
3557 | # the absolute maximum is 16K (256*256) since it's parsed by tinydns as a two-character field.
|
---|
3558 |
|
---|
3559 | # add just after "my $origloc = $loc;":
|
---|
3560 | # # These expand the possible space from 26^2 to 52^2 [* note in testing only 2052 were achieved],
|
---|
3561 | # # and wrap it around.
|
---|
3562 | # # Yes, they skip a couple of possibles. No, I don't care.
|
---|
3563 | # $loc = 'aA' if $loc eq 'zz';
|
---|
3564 | # $loc = 'Aa' if $loc eq 'zZ';
|
---|
3565 | # $loc = 'ZA' if $loc eq 'Zz';
|
---|
3566 | # $loc = 'aa' if $loc eq 'ZZ';
|
---|
3567 |
|
---|
3568 | # Allow transactions, and raise an exception on errors so we can catch it later.
|
---|
3569 | # Use local to make sure these get "reset" properly on exiting this block
|
---|
3570 | local $dbh->{AutoCommit} = 0;
|
---|
3571 | local $dbh->{RaiseError} = 1;
|
---|
3572 |
|
---|
3573 | ##fixme: There is probably a far better way to do this. Sequential increments
|
---|
3574 | # are marginally less stupid that pure random generation though, and the existence
|
---|
3575 | # check makes sure we don't stomp on an imported one.
|
---|
3576 |
|
---|
3577 | eval {
|
---|
3578 | # Get the "last" location. Note this is the only use for loc_id, because selecting on location Does Funky Things
|
---|
3579 | ($loc) = $dbh->selectrow_array("SELECT location FROM locations ORDER BY loc_id DESC LIMIT 1");
|
---|
3580 | ($loc) = ($loc =~ /^(..)/) if $loc;
|
---|
3581 | my $origloc = $loc;
|
---|
3582 | $loc = 'aa' if !$loc;
|
---|
3583 | # Make a change...
|
---|
3584 | $loc++;
|
---|
3585 | # ... and keep changing if it exists
|
---|
3586 | while ($dbh->selectrow_array("SELECT count(*) FROM locations WHERE location LIKE ?", undef, ($loc.'%'))) {
|
---|
3587 | $loc++;
|
---|
3588 | ($loc) = ($loc =~ /^(..)/);
|
---|
3589 | die "too many locations in use, can't add another one\n" if $loc eq $origloc;
|
---|
3590 | ##fixme: really need to handle this case faster somehow
|
---|
3591 | #if $loc eq $origloc die "<thwap> bad admin: all locations used, your network is too fragmented";
|
---|
3592 | }
|
---|
3593 | # And now we should have a unique location. tinydns fundamentally limits the
|
---|
3594 | # number of these but there's no doc on what characters are valid.
|
---|
3595 | $shdesc = $loc if !$shdesc;
|
---|
3596 | $dbh->do("INSERT INTO locations (location, group_id, iplist, description, comments) VALUES (?,?,?,?,?)",
|
---|
3597 | undef, ($loc, $grp, $iplist, $shdesc, $comments) );
|
---|
3598 | $self->_log(entry => "Added location ($shdesc, '$iplist')");
|
---|
3599 | $dbh->commit;
|
---|
3600 | };
|
---|
3601 | if ($@) {
|
---|
3602 | my $msg = $@;
|
---|
3603 | eval { $dbh->rollback; };
|
---|
3604 | if ($self->{log_failures}) {
|
---|
3605 | $shdesc = $loc if !$shdesc;
|
---|
3606 | $self->_log(entry => "Failed adding location ($shdesc, '$iplist'): $msg");
|
---|
3607 | $dbh->commit;
|
---|
3608 | }
|
---|
3609 | return ('FAIL',$msg);
|
---|
3610 | }
|
---|
3611 |
|
---|
3612 | return ('OK',$loc);
|
---|
3613 | } # end addLoc()
|
---|
3614 |
|
---|
3615 |
|
---|
3616 | ## DNSDB::updateLoc()
|
---|
3617 | # Update details of a location.
|
---|
3618 | # Takes a database handle, location ID, group ID, short description,
|
---|
3619 | # long comments/notes, and comma/space-separated IP list
|
---|
3620 | # Returns a result code and message
|
---|
3621 | sub updateLoc {
|
---|
3622 | my $self = shift;
|
---|
3623 | my $dbh = $self->{dbh};
|
---|
3624 | my $loc = shift;
|
---|
3625 | my $grp = shift;
|
---|
3626 | my $shdesc = shift;
|
---|
3627 | my $comments = shift;
|
---|
3628 | my $iplist = shift;
|
---|
3629 |
|
---|
3630 | $shdesc = '' if !$shdesc;
|
---|
3631 | $comments = '' if !$comments;
|
---|
3632 | $iplist = '' if !$iplist;
|
---|
3633 |
|
---|
3634 | # Allow transactions, and raise an exception on errors so we can catch it later.
|
---|
3635 | # Use local to make sure these get "reset" properly on exiting this block
|
---|
3636 | local $dbh->{AutoCommit} = 0;
|
---|
3637 | local $dbh->{RaiseError} = 1;
|
---|
3638 |
|
---|
3639 | my $oldloc = $self->getLoc($loc);
|
---|
3640 | my $okmsg = "Updated location (".$oldloc->{description}.", '".$oldloc->{iplist}."') to ($shdesc, '$iplist')";
|
---|
3641 |
|
---|
3642 | eval {
|
---|
3643 | $dbh->do("UPDATE locations SET group_id=?,iplist=?,description=?,comments=? WHERE location=?",
|
---|
3644 | undef, ($grp, $iplist, $shdesc, $comments, $loc) );
|
---|
3645 | $self->_log(entry => $okmsg);
|
---|
3646 | $dbh->commit;
|
---|
3647 | };
|
---|
3648 | if ($@) {
|
---|
3649 | my $msg = $@;
|
---|
3650 | eval { $dbh->rollback; };
|
---|
3651 | if ($self->{log_failures}) {
|
---|
3652 | $shdesc = $loc if !$shdesc;
|
---|
3653 | $self->_log(entry => "Failed updating location ($shdesc, '$iplist'): $msg");
|
---|
3654 | $dbh->commit;
|
---|
3655 | }
|
---|
3656 | return ('FAIL',$msg);
|
---|
3657 | }
|
---|
3658 |
|
---|
3659 | return ('OK',$okmsg);
|
---|
3660 | } # end updateLoc()
|
---|
3661 |
|
---|
3662 |
|
---|
3663 | ## DNSDB::delLoc()
|
---|
3664 | sub delLoc {
|
---|
3665 | my $self = shift;
|
---|
3666 | my $dbh = $self->{dbh};
|
---|
3667 | my $loc = shift;
|
---|
3668 |
|
---|
3669 | # Allow transactions, and raise an exception on errors so we can catch it later.
|
---|
3670 | # Use local to make sure these get "reset" properly on exiting this block
|
---|
3671 | local $dbh->{AutoCommit} = 0;
|
---|
3672 | local $dbh->{RaiseError} = 1;
|
---|
3673 |
|
---|
3674 | my $oldloc = $self->getLoc($loc);
|
---|
3675 | my $olddesc = ($oldloc->{description} ? $oldloc->{description} : $loc);
|
---|
3676 | my $okmsg = "Deleted location ($olddesc, '".$oldloc->{iplist}."')";
|
---|
3677 |
|
---|
3678 | eval {
|
---|
3679 | # Check for records with this location first. Deleting a location without deleting records
|
---|
3680 | # tagged for that location will render them unpublished without other warning.
|
---|
3681 | my ($r) = $dbh->selectrow_array("SELECT record_id FROM records WHERE location=? LIMIT 1", undef, ($loc) );
|
---|
3682 | die "Records still exist in location $olddesc\n" if $r;
|
---|
3683 | $dbh->do("DELETE FROM locations WHERE location=?", undef, ($loc) );
|
---|
3684 | $self->_log(entry => $okmsg);
|
---|
3685 | $dbh->commit;
|
---|
3686 | };
|
---|
3687 | if ($@) {
|
---|
3688 | my $msg = $@;
|
---|
3689 | eval { $dbh->rollback; };
|
---|
3690 | if ($self->{log_failures}) {
|
---|
3691 | $self->_log(entry => "Failed to delete location ($olddesc, '$oldloc->{iplist}'): $msg");
|
---|
3692 | $dbh->commit;
|
---|
3693 | }
|
---|
3694 | return ('FAIL', "Failed to delete location ($olddesc, '$oldloc->{iplist}'): $msg");
|
---|
3695 | }
|
---|
3696 |
|
---|
3697 | return ('OK',$okmsg);
|
---|
3698 | } # end delLoc()
|
---|
3699 |
|
---|
3700 |
|
---|
3701 | ## DNSDB::getLoc()
|
---|
3702 | # Get details about a location/view
|
---|
3703 | # Takes a database handle and location ID.
|
---|
3704 | # Returns a reference to a hash containing the group ID, IP list, description, and comments/notes
|
---|
3705 | sub getLoc {
|
---|
3706 | my $self = shift;
|
---|
3707 | my $dbh = $self->{dbh};
|
---|
3708 | my $loc = shift;
|
---|
3709 |
|
---|
3710 | my $sth = $dbh->prepare("SELECT group_id,iplist,description,comments FROM locations WHERE location=?");
|
---|
3711 | $sth->execute($loc);
|
---|
3712 | return $sth->fetchrow_hashref();
|
---|
3713 | } # end getLoc()
|
---|
3714 |
|
---|
3715 |
|
---|
3716 | ## DNSDB::getLocCount()
|
---|
3717 | # Get count of locations/views
|
---|
3718 | # Takes a database handle and hash containing at least the current group, and optionally:
|
---|
3719 | # - a reference list of secondary groups
|
---|
3720 | # - a filter string
|
---|
3721 | # - a "Starts with" string
|
---|
3722 | sub getLocCount {
|
---|
3723 | my $self = shift;
|
---|
3724 | my $dbh = $self->{dbh};
|
---|
3725 |
|
---|
3726 | my %args = @_;
|
---|
3727 |
|
---|
3728 | # Fail on bad curgroup argument. There's no sane fallback on this one.
|
---|
3729 | if (!$args{curgroup} || $args{curgroup} !~ /^\d+$/) {
|
---|
3730 | $errstr = "Bad or missing curgroup argument";
|
---|
3731 | return;
|
---|
3732 | }
|
---|
3733 | # Fail on bad childlist argument. This could be sanely ignored if bad, maybe.
|
---|
3734 | if ($args{childlist} && $args{childlist} !~ /^[\d,]+$/) {
|
---|
3735 | $errstr = "Bad childlist argument";
|
---|
3736 | return;
|
---|
3737 | }
|
---|
3738 |
|
---|
3739 | my @filterargs;
|
---|
3740 | $args{startwith} = undef if $args{startwith} && $args{startwith} !~ /^(?:[a-z]|0-9)$/;
|
---|
3741 | push @filterargs, "^$args{startwith}" if $args{startwith};
|
---|
3742 | push @filterargs, $args{filter} if $args{filter};
|
---|
3743 |
|
---|
3744 | my $sql = "SELECT count(*) FROM locations ".
|
---|
3745 | "WHERE group_id IN ($args{curgroup}".($args{childlist} ? ",$args{childlist}" : '').")".
|
---|
3746 | ($args{startwith} ? " AND description ~* ?" : '').
|
---|
3747 | ($args{filter} ? " AND description ~* ?" : '');
|
---|
3748 | my ($count) = $dbh->selectrow_array($sql, undef, (@filterargs) );
|
---|
3749 | $errstr = $dbh->errstr if !$count;
|
---|
3750 | return $count;
|
---|
3751 | } # end getLocCount()
|
---|
3752 |
|
---|
3753 |
|
---|
3754 | ## DNSDB::getLocList()
|
---|
3755 | sub getLocList {
|
---|
3756 | my $self = shift;
|
---|
3757 | my $dbh = $self->{dbh};
|
---|
3758 |
|
---|
3759 | my %args = @_;
|
---|
3760 |
|
---|
3761 | # Fail on bad curgroup argument. There's no sane fallback on this one.
|
---|
3762 | if (!$args{curgroup} || $args{curgroup} !~ /^\d+$/) {
|
---|
3763 | $errstr = "Bad or missing curgroup argument";
|
---|
3764 | return;
|
---|
3765 | }
|
---|
3766 | # Fail on bad childlist argument. This could be sanely ignored if bad, maybe.
|
---|
3767 | if ($args{childlist} && $args{childlist} !~ /^[\d,]+$/) {
|
---|
3768 | $errstr = "Bad childlist argument";
|
---|
3769 | return;
|
---|
3770 | }
|
---|
3771 |
|
---|
3772 | my @filterargs;
|
---|
3773 | $args{startwith} = undef if $args{startwith} && $args{startwith} !~ /^(?:[a-z]|0-9)$/;
|
---|
3774 | push @filterargs, "^$args{startwith}" if $args{startwith};
|
---|
3775 | push @filterargs, $args{filter} if $args{filter};
|
---|
3776 |
|
---|
3777 | # better to request sorts on "simple" names, but it means we need to map it to real columns
|
---|
3778 | # my %sortmap = (user => 'u.username', type => 'u.type', group => 'g.group_name', status => 'u.status',
|
---|
3779 | # fname => 'fname');
|
---|
3780 | # $args{sortby} = $sortmap{$args{sortby}};
|
---|
3781 |
|
---|
3782 | # protection against bad or missing arguments
|
---|
3783 | $args{sortorder} = 'ASC' if !$args{sortorder} || !grep /^$args{sortorder}$/, ('ASC','DESC');
|
---|
3784 | $args{sortby} = 'l.description' if !$args{sortby} || $args{sortby} !~ /^[\w_.]+$/;
|
---|
3785 | $args{offset} = 0 if !$args{offset} || $args{offset} !~ /^(?:all|\d+)$/;
|
---|
3786 |
|
---|
3787 | my $sql = "SELECT l.location, l.description, l.iplist, g.group_name ".
|
---|
3788 | "FROM locations l ".
|
---|
3789 | "INNER JOIN groups g ON l.group_id=g.group_id ".
|
---|
3790 | "WHERE l.group_id IN ($args{curgroup}".($args{childlist} ? ",$args{childlist}" : '').")".
|
---|
3791 | ($args{startwith} ? " AND l.description ~* ?" : '').
|
---|
3792 | ($args{filter} ? " AND l.description ~* ?" : '').
|
---|
3793 | " ORDER BY $args{sortby} $args{sortorder} ".
|
---|
3794 | ($args{offset} eq 'all' ? '' : " LIMIT $self->{perpage} OFFSET ".$args{offset}*$self->{perpage});
|
---|
3795 | my $ulist = $dbh->selectall_arrayref($sql, { Slice => {} }, (@filterargs) );
|
---|
3796 | $errstr = $dbh->errstr if !$ulist;
|
---|
3797 | return $ulist;
|
---|
3798 | } # end getLocList()
|
---|
3799 |
|
---|
3800 |
|
---|
3801 | ## DNSDB::getLocDropdown()
|
---|
3802 | # Get a list of location names for use in a dropdown menu.
|
---|
3803 | # Takes a database handle, current group, and optional "tag this as selected" flag.
|
---|
3804 | # Returns a reference to a list of hashrefs suitable to feeding to HTML::Template
|
---|
3805 | sub getLocDropdown {
|
---|
3806 | my $self = shift;
|
---|
3807 | my $dbh = $self->{dbh};
|
---|
3808 | my $grp = shift;
|
---|
3809 | my $sel = shift || '';
|
---|
3810 |
|
---|
3811 | my $sth = $dbh->prepare(qq(
|
---|
3812 | SELECT description,location FROM locations
|
---|
3813 | WHERE group_id=?
|
---|
3814 | ORDER BY description
|
---|
3815 | ) );
|
---|
3816 | $sth->execute($grp);
|
---|
3817 |
|
---|
3818 | my @loclist;
|
---|
3819 | push @loclist, { locname => "(Default/All)", loc => '', selected => ($sel ? 0 : ($sel eq '' ? 1 : 0)) };
|
---|
3820 | while (my ($locname, $loc) = $sth->fetchrow_array) {
|
---|
3821 | my %row = (
|
---|
3822 | locname => $locname,
|
---|
3823 | loc => $loc,
|
---|
3824 | selected => ($sel eq $loc ? 1 : 0)
|
---|
3825 | );
|
---|
3826 | push @loclist, \%row;
|
---|
3827 | }
|
---|
3828 | return \@loclist;
|
---|
3829 | } # end getLocDropdown()
|
---|
3830 |
|
---|
3831 |
|
---|
3832 | ## DNSDB::getSOA()
|
---|
3833 | # Return all suitable fields from an SOA record in separate elements of a hash
|
---|
3834 | # Takes a database handle, default/live flag, domain/reverse flag, and parent ID
|
---|
3835 | sub getSOA {
|
---|
3836 | $errstr = '';
|
---|
3837 | my $self = shift;
|
---|
3838 | my $dbh = $self->{dbh};
|
---|
3839 | my $def = shift;
|
---|
3840 | my $rev = shift;
|
---|
3841 | my $id = shift;
|
---|
3842 |
|
---|
3843 | # (ab)use distance and weight columns to store SOA data? can't for default_rev_records...
|
---|
3844 | # - should really attach serial to the zone parent somewhere
|
---|
3845 |
|
---|
3846 | my $sql = "SELECT record_id,host,val,ttl from "._rectable($def,$rev).
|
---|
3847 | " WHERE "._recparent($def,$rev)." = ? AND type=$reverse_typemap{SOA}";
|
---|
3848 | my $ret = $dbh->selectrow_hashref($sql, undef, ($id) );
|
---|
3849 | return if !$ret;
|
---|
3850 | ##fixme: stick a flag somewhere if the record doesn't exist. by the API, this is an impossible case, but...
|
---|
3851 |
|
---|
3852 | ($ret->{contact},$ret->{prins}) = split /:/, $ret->{host};
|
---|
3853 | delete $ret->{host};
|
---|
3854 | ($ret->{refresh},$ret->{retry},$ret->{expire},$ret->{minttl}) = split /:/, $ret->{val};
|
---|
3855 | delete $ret->{val};
|
---|
3856 |
|
---|
3857 | return $ret;
|
---|
3858 | } # end getSOA()
|
---|
3859 |
|
---|
3860 |
|
---|
3861 | ## DNSDB::updateSOA()
|
---|
3862 | # Update the specified SOA record
|
---|
3863 | # Takes a database handle, default/live flag, forward/reverse flag, and SOA data hash
|
---|
3864 | # Returns a two-element list with a result code and message
|
---|
3865 | sub updateSOA {
|
---|
3866 | my $self = shift;
|
---|
3867 | my $dbh = $self->{dbh};
|
---|
3868 | my $defrec = shift;
|
---|
3869 | my $revrec = shift;
|
---|
3870 |
|
---|
3871 | my %soa = @_;
|
---|
3872 |
|
---|
3873 | my $oldsoa = $self->getSOA($defrec, $revrec, $soa{id});
|
---|
3874 |
|
---|
3875 | my $msg;
|
---|
3876 | my %logdata;
|
---|
3877 | if ($defrec eq 'n') {
|
---|
3878 | $logdata{domain_id} = $soa{id} if $revrec eq 'n';
|
---|
3879 | $logdata{rdns_id} = $soa{id} if $revrec eq 'y';
|
---|
3880 | $logdata{group_id} = $self->parentID(id => $soa{id}, revrec => $revrec,
|
---|
3881 | type => ($revrec eq 'n' ? 'domain' : 'revzone') );
|
---|
3882 | } else {
|
---|
3883 | $logdata{group_id} = $soa{id};
|
---|
3884 | }
|
---|
3885 | my $parname = ($defrec eq 'y' ? $self->groupName($soa{id}) :
|
---|
3886 | ($revrec eq 'n' ? $self->domainName($soa{id}) : $self->revName($soa{id})) );
|
---|
3887 |
|
---|
3888 | # Allow transactions, and raise an exception on errors so we can catch it later.
|
---|
3889 | # Use local to make sure these get "reset" properly on exiting this block
|
---|
3890 | local $dbh->{AutoCommit} = 0;
|
---|
3891 | local $dbh->{RaiseError} = 1;
|
---|
3892 |
|
---|
3893 | eval {
|
---|
3894 | if (!$oldsoa) {
|
---|
3895 | # old SOA record is missing for some reason. create a new one.
|
---|
3896 | my $sql = "INSERT INTO "._rectable($defrec, $revrec)." ("._recparent($defrec, $revrec).
|
---|
3897 | ", host, type, val, ttl) VALUES (?,?,6,?,?)";
|
---|
3898 | $dbh->do($sql, undef, ($soa{id}, "$soa{contact}:$soa{prins}",
|
---|
3899 | "$soa{refresh}:$soa{retry}:$soa{expire}:$soa{minttl}", $soa{ttl}) );
|
---|
3900 | $msg = ($defrec eq 'y' ? ($revrec eq 'y' ? 'Default reverse ' : 'Default ') : '').
|
---|
3901 | "SOA missing for $parname; added (ns $soa{prins}, contact $soa{contact}, refresh $soa{refresh},".
|
---|
3902 | " retry $soa{retry}, expire $soa{expire}, minTTL $soa{minttl}, TTL $soa{ttl})";
|
---|
3903 | } else {
|
---|
3904 | my $sql = "UPDATE "._rectable($defrec, $revrec)." SET host=?, val=?, ttl=? WHERE record_id=? AND type=6";
|
---|
3905 | $dbh->do($sql, undef, ("$soa{contact}:$soa{prins}", "$soa{refresh}:$soa{retry}:$soa{expire}:$soa{minttl}",
|
---|
3906 | $soa{ttl}, $oldsoa->{record_id}) );
|
---|
3907 | $msg = "Updated ".($defrec eq 'y' ? ($revrec eq 'y' ? 'default reverse ' : 'default ') : '').
|
---|
3908 | "SOA for $parname: ".
|
---|
3909 | "(ns $oldsoa->{prins}, contact $oldsoa->{contact}, refresh $oldsoa->{refresh},".
|
---|
3910 | " retry $oldsoa->{retry}, expire $oldsoa->{expire}, minTTL $oldsoa->{minttl}, TTL $oldsoa->{ttl}) to ".
|
---|
3911 | "(ns $soa{prins}, contact $soa{contact}, refresh $soa{refresh},".
|
---|
3912 | " retry $soa{retry}, expire $soa{expire}, minTTL $soa{minttl}, TTL $soa{ttl})";
|
---|
3913 | }
|
---|
3914 | $logdata{entry} = $msg;
|
---|
3915 | $self->_log(%logdata);
|
---|
3916 |
|
---|
3917 | $dbh->commit;
|
---|
3918 | };
|
---|
3919 | if ($@) {
|
---|
3920 | $msg = $@;
|
---|
3921 | eval { $dbh->rollback; };
|
---|
3922 | $logdata{entry} = "Error updating ".($defrec eq 'y' ? ($revrec eq 'y' ? 'default reverse zone ' : 'default ') : '').
|
---|
3923 | "SOA record for $parname: $msg";
|
---|
3924 | if ($self->{log_failures}) {
|
---|
3925 | $self->_log(%logdata);
|
---|
3926 | $dbh->commit;
|
---|
3927 | }
|
---|
3928 | return ('FAIL', $logdata{entry});
|
---|
3929 | } else {
|
---|
3930 | return ('OK', $msg);
|
---|
3931 | }
|
---|
3932 | } # end updateSOA()
|
---|
3933 |
|
---|
3934 |
|
---|
3935 | ## DNSDB::getRecLine()
|
---|
3936 | # Return all data fields for a zone record in separate elements of a hash
|
---|
3937 | # Takes a database handle, default/live flag, forward/reverse flag, and record ID
|
---|
3938 | sub getRecLine {
|
---|
3939 | $errstr = '';
|
---|
3940 | my $self = shift;
|
---|
3941 | my $dbh = $self->{dbh};
|
---|
3942 | my $defrec = shift;
|
---|
3943 | my $revrec = shift;
|
---|
3944 | my $id = shift;
|
---|
3945 |
|
---|
3946 | ##fixme: do we need a knob to twist to switch between unix epoch and postgres time string?
|
---|
3947 | my $sql = "SELECT record_id,host,type,val,ttl".
|
---|
3948 | ($defrec eq 'n' ? ',location' : '').
|
---|
3949 | ($revrec eq 'n' ? ',distance,weight,port' : '').
|
---|
3950 | (($defrec eq 'y') ? ',group_id FROM ' : ',domain_id,rdns_id,stamp,stamp < now() AS ispast,expires,stampactive FROM ').
|
---|
3951 | _rectable($defrec,$revrec)." WHERE record_id=?";
|
---|
3952 | my $ret = $dbh->selectrow_hashref($sql, undef, ($id) );
|
---|
3953 |
|
---|
3954 | if ($dbh->err) {
|
---|
3955 | $errstr = $DBI::errstr;
|
---|
3956 | return undef;
|
---|
3957 | }
|
---|
3958 |
|
---|
3959 | if (!$ret) {
|
---|
3960 | $errstr = "No such record";
|
---|
3961 | return undef;
|
---|
3962 | }
|
---|
3963 |
|
---|
3964 | # explicitly set a parent id
|
---|
3965 | if ($defrec eq 'y') {
|
---|
3966 | $ret->{parid} = $ret->{group_id};
|
---|
3967 | } else {
|
---|
3968 | $ret->{parid} = (($revrec eq 'n') ? $ret->{domain_id} : $ret->{rdns_id});
|
---|
3969 | # and a secondary if we have a custom type that lives in both a forward and reverse zone
|
---|
3970 | $ret->{secid} = (($revrec eq 'y') ? $ret->{domain_id} : $ret->{rdns_id}) if $ret->{type} > 65279;
|
---|
3971 | }
|
---|
3972 | $ret->{address} = $ret->{val}; # because.
|
---|
3973 |
|
---|
3974 | return $ret;
|
---|
3975 | }
|
---|
3976 |
|
---|
3977 |
|
---|
3978 | ##fixme: should use above (getRecLine()) to get lines for below?
|
---|
3979 | ## DNSDB::getRecList()
|
---|
3980 | # Return records for a group or zone
|
---|
3981 | # Takes a default/live flag, group or zone ID, start,
|
---|
3982 | # number of records, sort field, and sort order
|
---|
3983 | # Returns a reference to an array of hashes
|
---|
3984 | sub getRecList {
|
---|
3985 | $errstr = '';
|
---|
3986 | my $self = shift;
|
---|
3987 | my $dbh = $self->{dbh};
|
---|
3988 |
|
---|
3989 | my %args = @_;
|
---|
3990 |
|
---|
3991 | # protection against bad or missing arguments
|
---|
3992 | $args{sortorder} = 'ASC' if !$args{sortorder} || !grep /^$args{sortorder}$/, ('ASC','DESC');
|
---|
3993 | my $defsort;
|
---|
3994 | $defsort = 'host' if $args{revrec} eq 'n'; # default sort by host on domain record list
|
---|
3995 | $defsort = 'val' if $args{revrec} eq 'y'; # default sort by IP on revzone record list
|
---|
3996 | $args{sortby} = '' if !$args{sortby};
|
---|
3997 | $args{sortby} = $defsort if !$args{revrec};
|
---|
3998 | $args{sortby} = $defsort if $args{sortby} !~ /^[\w_,.]+$/;
|
---|
3999 | $args{offset} = 0 if !$args{offset} || $args{offset} !~ /^(?:all|\d+)$/;
|
---|
4000 | my $perpage = ($args{nrecs} ? $args{nrecs} : $self->{perpage});
|
---|
4001 |
|
---|
4002 | # sort reverse zones on IP, correctly
|
---|
4003 | # do other fiddling with $args{sortby} while we're at it.
|
---|
4004 | # whee! multisort means just passing comma-separated fields in sortby!
|
---|
4005 | my $newsort = '';
|
---|
4006 | foreach my $sf (split /,/, $args{sortby}) {
|
---|
4007 | $sf = "r.$sf";
|
---|
4008 | $sf =~ s/r\.val/inetlazy(r.val)/
|
---|
4009 | if $args{revrec} eq 'y' && $args{defrec} eq 'n';
|
---|
4010 | $sf =~ s/r\.type/t.alphaorder/;
|
---|
4011 | $newsort .= ",$sf";
|
---|
4012 | }
|
---|
4013 | $newsort =~ s/^,//;
|
---|
4014 |
|
---|
4015 | my @bindvars = ($args{id});
|
---|
4016 | push @bindvars, ($args{filter},$args{filter}) if $args{filter};
|
---|
4017 |
|
---|
4018 | ##fixme: do we need a knob to twist to switch from unix epoch to postgres time string?
|
---|
4019 | my $sql = "SELECT r.record_id,r.host,r.type,r.val,r.ttl";
|
---|
4020 | $sql .= ",l.description AS locname,stamp,r.stamp < now() AS ispast,r.expires,r.stampactive"
|
---|
4021 | if $args{defrec} eq 'n';
|
---|
4022 | $sql .= ",r.distance,r.weight,r.port" if $args{revrec} eq 'n';
|
---|
4023 | $sql .= " FROM "._rectable($args{defrec},$args{revrec})." r ";
|
---|
4024 | $sql .= "INNER JOIN rectypes t ON r.type=t.val "; # for sorting by type alphabetically
|
---|
4025 | $sql .= "LEFT JOIN locations l ON r.location=l.location " if $args{defrec} eq 'n';
|
---|
4026 | $sql .= "WHERE "._recparent($args{defrec},$args{revrec})." = ?";
|
---|
4027 | $sql .= " AND NOT r.type=$reverse_typemap{SOA}";
|
---|
4028 | if ($args{filter}) {
|
---|
4029 | $sql .= " AND (r.host ~* ? OR r.val ~* ? OR r.host ~* ? OR r.val ~* ?)";
|
---|
4030 | my $tmp = join('.',reverse(split(/\./,$args{filter})));
|
---|
4031 | push @bindvars, ($tmp, $tmp);
|
---|
4032 | }
|
---|
4033 | $sql .= " ORDER BY $newsort $args{sortorder}";
|
---|
4034 | # ensure consistent ordering by sorting on record_id too
|
---|
4035 | $sql .= ", record_id $args{sortorder}";
|
---|
4036 | $sql .= ($args{offset} eq 'all' ? '' : " LIMIT $perpage OFFSET ".$args{offset}*$perpage);
|
---|
4037 |
|
---|
4038 | my @working;
|
---|
4039 | my $recsth = $dbh->prepare($sql);
|
---|
4040 | $recsth->execute(@bindvars);
|
---|
4041 | while (my $rec = $recsth->fetchrow_hashref) {
|
---|
4042 | if ($args{revrec} eq 'y' && $args{defrec} eq 'n' &&
|
---|
4043 | ($self->{showrev_arpa} eq 'record' || $self->{showrev_arpa} eq 'all') &&
|
---|
4044 | $rec->{val} !~ /\.arpa$/ ) {
|
---|
4045 | # skip all reverse zone .arpa "hostnames" since they're already .arpa names.
|
---|
4046 | ##enhance: extend {showrev_arpa} eq 'record' to specify record types
|
---|
4047 | my $tmpip = new NetAddr::IP $rec->{val} if $rec->{val} =~ /^(?:[\d.\/]+|[a-fA-F0-9:\/]+)$/;
|
---|
4048 | $rec->{val} = DNSDB::_ZONE($tmpip, 'ZONE', 'r', '.').($tmpip->{isv6} ? '.ip6.arpa' : '.in-addr.arpa') if $tmpip;
|
---|
4049 | }
|
---|
4050 | push @working, $rec;
|
---|
4051 | }
|
---|
4052 | return \@working;
|
---|
4053 | } # end getRecList()
|
---|
4054 |
|
---|
4055 |
|
---|
4056 | ## DNSDB::getRecCount()
|
---|
4057 | # Return count of non-SOA records in zone (or default records in a group)
|
---|
4058 | # Takes a database handle, default/live flag, reverse/forward flag, group/domain ID,
|
---|
4059 | # and optional filtering modifier
|
---|
4060 | # Returns the count
|
---|
4061 | sub getRecCount {
|
---|
4062 | my $self = shift;
|
---|
4063 | my $dbh = $self->{dbh};
|
---|
4064 | my $defrec = shift;
|
---|
4065 | my $revrec = shift;
|
---|
4066 | my $id = shift;
|
---|
4067 | my $filter = shift || '';
|
---|
4068 |
|
---|
4069 | # keep the nasties down, since we can't ?-sub this bit. :/
|
---|
4070 | # note this is chars allowed in DNS hostnames
|
---|
4071 | $filter =~ s/[^a-zA-Z0-9_.:-]//g;
|
---|
4072 |
|
---|
4073 | my @bindvars = ($id);
|
---|
4074 | push @bindvars, ($filter,$filter) if $filter;
|
---|
4075 | my $sql = "SELECT count(*) FROM ".
|
---|
4076 | _rectable($defrec,$revrec).
|
---|
4077 | " WHERE "._recparent($defrec,$revrec)."=? ".
|
---|
4078 | "AND NOT type=$reverse_typemap{SOA}";
|
---|
4079 | if ($filter) {
|
---|
4080 | $sql .= " AND (r.host ~* ? OR r.val ~* ? OR r.host ~* ? OR r.val ~* ?)";
|
---|
4081 | my $tmp = join('.',reverse(split(/\./,$filter)));
|
---|
4082 | push @bindvars, ($tmp, $tmp);
|
---|
4083 | }
|
---|
4084 | $sql .= " AND (host ~* ? OR val ~* ? OR host ~* ? OR val ~* ?)" if $filter;
|
---|
4085 | my $tmp = join('.',reverse(split(/\./,$filter)));
|
---|
4086 | push @bindvars, ($tmp, $tmp) if $filter;
|
---|
4087 |
|
---|
4088 | my ($count) = $dbh->selectrow_array($sql, undef, (@bindvars) );
|
---|
4089 |
|
---|
4090 | return $count;
|
---|
4091 |
|
---|
4092 | } # end getRecCount()
|
---|
4093 |
|
---|
4094 |
|
---|
4095 | ## DNSDB::addRec()
|
---|
4096 | # Add a new record to a domain or a group's default records
|
---|
4097 | # Takes a database handle, default/live flag, group/domain ID,
|
---|
4098 | # host, type, value, and TTL
|
---|
4099 | # Some types require additional detail: "distance" for MX and SRV,
|
---|
4100 | # and weight/port for SRV
|
---|
4101 | # Returns a status code and detail message in case of error
|
---|
4102 | ##fixme: pass a hash with the record data, not a series of separate values
|
---|
4103 | sub addRec {
|
---|
4104 | $errstr = '';
|
---|
4105 | my $self = shift;
|
---|
4106 | my $dbh = $self->{dbh};
|
---|
4107 | my $defrec = shift;
|
---|
4108 | my $revrec = shift;
|
---|
4109 | my $id = shift; # parent (group_id for defrecs, rdns_id for reverse records,
|
---|
4110 | # domain_id for domain records)
|
---|
4111 |
|
---|
4112 | my $host = shift;
|
---|
4113 | my $rectype = shift; # reference so we can coerce it if "+"-types can't find both zones
|
---|
4114 | my $val = shift;
|
---|
4115 | my $ttl = shift;
|
---|
4116 | my $location = shift;
|
---|
4117 | $location = '' if !$location;
|
---|
4118 |
|
---|
4119 | my $expires = shift;
|
---|
4120 | $expires = 1 if $expires eq 'until'; # Turn some special values into the appropriate booleans.
|
---|
4121 | $expires = 0 if $expires eq 'after';
|
---|
4122 | my $stamp = shift;
|
---|
4123 | $stamp = '' if !$stamp; # Timestamp should be a string at this point.
|
---|
4124 |
|
---|
4125 | # Spaces are evil.
|
---|
4126 | $$host =~ s/^\s+//;
|
---|
4127 | $$host =~ s/\s+$//;
|
---|
4128 | if ($typemap{$$rectype} ne 'TXT') {
|
---|
4129 | # Leading or trailng spaces could be legit in TXT records.
|
---|
4130 | $$val =~ s/^\s+//;
|
---|
4131 | $$val =~ s/\s+$//;
|
---|
4132 | }
|
---|
4133 |
|
---|
4134 | _caseclean($rectype, $host, $val, $defrec, $revrec) if $self->{lowercase};
|
---|
4135 |
|
---|
4136 | # prep for validation
|
---|
4137 | my $addr = NetAddr::IP->new($$val) if _maybeip($val);
|
---|
4138 | $$host =~ s/\.+$//; # FQDNs ending in . are an internal detail, and really shouldn't be exposed in the UI.
|
---|
4139 |
|
---|
4140 | my $domid = 0;
|
---|
4141 | my $revid = 0;
|
---|
4142 |
|
---|
4143 | my $retcode = 'OK'; # assume everything will go OK
|
---|
4144 | my $retmsg = '';
|
---|
4145 |
|
---|
4146 | # do simple validation first
|
---|
4147 | return ('FAIL', "TTL must be numeric") unless $ttl =~ /^-?\d+$/;
|
---|
4148 |
|
---|
4149 | # Collect these even if we're only doing a simple A record so we can call *any* validation sub
|
---|
4150 | my $dist = shift;
|
---|
4151 | my $weight = shift;
|
---|
4152 | my $port = shift;
|
---|
4153 |
|
---|
4154 | my $fields;
|
---|
4155 | my @vallist;
|
---|
4156 |
|
---|
4157 | # Call the validation sub for the type requested.
|
---|
4158 | ($retcode,$retmsg) = $validators{$$rectype}($self, defrec => $defrec, revrec => $revrec, id => $id,
|
---|
4159 | host => $host, rectype => $rectype, val => $val, addr => $addr,
|
---|
4160 | dist => \$dist, port => \$port, weight => \$weight,
|
---|
4161 | fields => \$fields, vallist => \@vallist);
|
---|
4162 |
|
---|
4163 | return ($retcode,$retmsg) if $retcode eq 'FAIL';
|
---|
4164 |
|
---|
4165 | # Set up database fields and bind parameters
|
---|
4166 | $fields .= "host,type,val,ttl,"._recparent($defrec,$revrec);
|
---|
4167 | push @vallist, ($$host,$$rectype,$$val,$ttl,$id);
|
---|
4168 |
|
---|
4169 | if ($defrec eq 'n') {
|
---|
4170 | # locations are not for default records, silly coder!
|
---|
4171 | $fields .= ",location";
|
---|
4172 | push @vallist, $location;
|
---|
4173 | # timestamps are rare.
|
---|
4174 | if ($stamp) {
|
---|
4175 | $fields .= ",stamp,expires,stampactive";
|
---|
4176 | push @vallist, $stamp, $expires, 'y';
|
---|
4177 | } else {
|
---|
4178 | $fields .= ",stampactive";
|
---|
4179 | push @vallist, 'n';
|
---|
4180 | }
|
---|
4181 | }
|
---|
4182 |
|
---|
4183 | # a little magic to get the right number of ? placeholders based on how many values we're providing
|
---|
4184 | my $vallen = '?'.(',?'x$#vallist);
|
---|
4185 |
|
---|
4186 | # Put together the success log entry. We have to use this horrible kludge
|
---|
4187 | # because domain_id and rdns_id may or may not be present, and if they are,
|
---|
4188 | # they're not at a guaranteed consistent index in the array. wheee!
|
---|
4189 | my %logdata;
|
---|
4190 | my @ftmp = split /,/, $fields;
|
---|
4191 | for (my $i=0; $i <= $#vallist; $i++) {
|
---|
4192 | $logdata{domain_id} = $vallist[$i] if $ftmp[$i] eq 'domain_id';
|
---|
4193 | $logdata{rdns_id} = $vallist[$i] if $ftmp[$i] eq 'rdns_id';
|
---|
4194 | }
|
---|
4195 | $logdata{group_id} = $id if $defrec eq 'y';
|
---|
4196 | $logdata{group_id} = $self->parentID(id => $id, type => ($revrec eq 'n' ? 'domain' : 'revzone'), revrec => $revrec)
|
---|
4197 | if $defrec eq 'n';
|
---|
4198 | $logdata{entry} = "Added ".($defrec eq 'y' ? 'default record' : 'record');
|
---|
4199 | # Log reverse records to match the formal .arpa tree
|
---|
4200 | if ($revrec eq 'y') {
|
---|
4201 | $logdata{entry} .= " '$$val $typemap{$$rectype} $$host";
|
---|
4202 | } else {
|
---|
4203 | $logdata{entry} .= " '$$host $typemap{$$rectype} $$val";
|
---|
4204 | }
|
---|
4205 |
|
---|
4206 | $logdata{entry} .= " [distance $dist]" if $typemap{$$rectype} eq 'MX';
|
---|
4207 | $logdata{entry} .= " [priority $dist] [weight $weight] [port $port]"
|
---|
4208 | if $typemap{$$rectype} eq 'SRV';
|
---|
4209 | $logdata{entry} .= "', TTL $ttl";
|
---|
4210 | $logdata{entry} .= ", location ".$self->getLoc($location)->{description} if $location;
|
---|
4211 | $logdata{entry} .= ($expires ? ', expires at ' : ', valid after ').$stamp if $stamp;
|
---|
4212 |
|
---|
4213 | # Allow transactions, and raise an exception on errors so we can catch it later.
|
---|
4214 | # Use local to make sure these get "reset" properly on exiting this block
|
---|
4215 | local $dbh->{AutoCommit} = 0;
|
---|
4216 | local $dbh->{RaiseError} = 1;
|
---|
4217 |
|
---|
4218 | eval {
|
---|
4219 | $dbh->do("INSERT INTO "._rectable($defrec, $revrec)." ($fields) VALUES ($vallen)",
|
---|
4220 | undef, @vallist);
|
---|
4221 | $self->_log(%logdata);
|
---|
4222 | $dbh->commit;
|
---|
4223 | };
|
---|
4224 | if ($@) {
|
---|
4225 | my $msg = $@;
|
---|
4226 | eval { $dbh->rollback; };
|
---|
4227 | if ($self->{log_failures}) {
|
---|
4228 | $logdata{entry} = "Failed adding ".($defrec eq 'y' ? 'default ' : '').
|
---|
4229 | "record '$$host $typemap{$$rectype} $$val', TTL $ttl ($msg)";
|
---|
4230 | $self->_log(%logdata);
|
---|
4231 | $dbh->commit;
|
---|
4232 | }
|
---|
4233 | return ('FAIL',$msg);
|
---|
4234 | }
|
---|
4235 |
|
---|
4236 | $resultstr = $logdata{entry};
|
---|
4237 | return ($retcode, $retmsg);
|
---|
4238 |
|
---|
4239 | } # end addRec()
|
---|
4240 |
|
---|
4241 |
|
---|
4242 | ## DNSDB::updateRec()
|
---|
4243 | # Update a record
|
---|
4244 | # Takes a database handle, default and reverse flags, record ID, immediate parent ID, and new record data.
|
---|
4245 | # Returns a status code and message
|
---|
4246 | sub updateRec {
|
---|
4247 | $errstr = '';
|
---|
4248 |
|
---|
4249 | my $self = shift;
|
---|
4250 | my $dbh = $self->{dbh};
|
---|
4251 | my $defrec = shift;
|
---|
4252 | my $revrec = shift;
|
---|
4253 | my $id = shift;
|
---|
4254 | my $parid = shift; # immediate parent entity that we're descending from to update the record
|
---|
4255 |
|
---|
4256 | # all records have these
|
---|
4257 | my $host = shift;
|
---|
4258 | my $hostbk = $$host; # Keep a backup copy of the original, so we can WARN if the update mangles the domain
|
---|
4259 | my $rectype = shift;
|
---|
4260 | my $val = shift;
|
---|
4261 | my $ttl = shift;
|
---|
4262 | my $location = shift; # may be empty/null/undef depending on caller
|
---|
4263 | $location = '' if !$location;
|
---|
4264 |
|
---|
4265 | my $expires = shift;
|
---|
4266 | $expires = 1 if $expires eq 'until'; # Turn some special values into the appropriate booleans.
|
---|
4267 | $expires = 0 if $expires eq 'after';
|
---|
4268 | my $stamp = shift;
|
---|
4269 | $stamp = '' if !$stamp; # Timestamp should be a string at this point.
|
---|
4270 |
|
---|
4271 | # just set it to an empty string; failures will be caught later.
|
---|
4272 | $$host = '' if !$$host;
|
---|
4273 |
|
---|
4274 | # Spaces are evil.
|
---|
4275 | $$host =~ s/^\s+//;
|
---|
4276 | $$host =~ s/\s+$//;
|
---|
4277 | if ($typemap{$$rectype} ne 'TXT') {
|
---|
4278 | # Leading or trailng spaces could be legit in TXT records.
|
---|
4279 | $$val =~ s/^\s+//;
|
---|
4280 | $$val =~ s/\s+$//;
|
---|
4281 | }
|
---|
4282 |
|
---|
4283 | _caseclean($rectype, $host, $val, $defrec, $revrec) if $self->{lowercase};
|
---|
4284 |
|
---|
4285 | # prep for validation
|
---|
4286 | my $addr = NetAddr::IP->new($$val) if _maybeip($val);
|
---|
4287 | $$host =~ s/\.+$//; # FQDNs ending in . are an internal detail, and really shouldn't be exposed in the UI.
|
---|
4288 |
|
---|
4289 | my $domid = 0;
|
---|
4290 | my $revid = 0;
|
---|
4291 |
|
---|
4292 | my $retcode = 'OK'; # assume everything will go OK
|
---|
4293 | my $retmsg = '';
|
---|
4294 |
|
---|
4295 | # do simple validation first
|
---|
4296 | return ('FAIL', "TTL must be numeric") unless $ttl =~ /^-?\d+$/;
|
---|
4297 |
|
---|
4298 | # only MX and SRV will use these
|
---|
4299 | my $dist = shift || 0;
|
---|
4300 | my $weight = shift || 0;
|
---|
4301 | my $port = shift || 0;
|
---|
4302 |
|
---|
4303 | my $fields;
|
---|
4304 | my @vallist;
|
---|
4305 |
|
---|
4306 | # get old record data so we have the right parent ID
|
---|
4307 | # and for logging (eventually)
|
---|
4308 | my $oldrec = $self->getRecLine($defrec, $revrec, $id);
|
---|
4309 |
|
---|
4310 | # Call the validation sub for the type requested.
|
---|
4311 | # Note the ID to pass here is the *parent*, not the record
|
---|
4312 | ($retcode,$retmsg) = $validators{$$rectype}($self, defrec => $defrec, revrec => $revrec,
|
---|
4313 | id => ($defrec eq 'y' ? $oldrec->{group_id} : ($revrec eq 'n' ? $oldrec->{domain_id} : $oldrec->{rdns_id})),
|
---|
4314 | host => $host, rectype => $rectype, val => $val, addr => $addr,
|
---|
4315 | dist => \$dist, port => \$port, weight => \$weight,
|
---|
4316 | fields => \$fields, vallist => \@vallist,
|
---|
4317 | update => $id);
|
---|
4318 |
|
---|
4319 | return ($retcode,$retmsg) if $retcode eq 'FAIL';
|
---|
4320 |
|
---|
4321 | # Set up database fields and bind parameters. Note only the optional fields
|
---|
4322 | # (distance, weight, port, secondary parent ID) are added in the validation call above
|
---|
4323 | $fields .= "host,type,val,ttl,"._recparent($defrec,$revrec);
|
---|
4324 | push @vallist, ($$host,$$rectype,$$val,$ttl,
|
---|
4325 | ($defrec eq 'y' ? $oldrec->{group_id} : ($revrec eq 'n' ? $oldrec->{domain_id} : $oldrec->{rdns_id})) );
|
---|
4326 |
|
---|
4327 | if ($defrec eq 'n') {
|
---|
4328 | # locations are not for default records, silly coder!
|
---|
4329 | $fields .= ",location";
|
---|
4330 | push @vallist, $location;
|
---|
4331 | # timestamps are rare.
|
---|
4332 | if ($stamp) {
|
---|
4333 | $fields .= ",stamp,expires,stampactive";
|
---|
4334 | push @vallist, $stamp, $expires, 'y';
|
---|
4335 | } else {
|
---|
4336 | $fields .= ",stampactive";
|
---|
4337 | push @vallist, 'n';
|
---|
4338 | }
|
---|
4339 | }
|
---|
4340 |
|
---|
4341 | # hack hack PTHUI
|
---|
4342 | # need to forcibly make sure we disassociate a record with a parent it's no longer related to.
|
---|
4343 | # eg, PTR records may not have a domain parent, or A/AAAA records may not have a revzone parent.
|
---|
4344 | # needed for crossover types that got coerced down to "standard" types due to data changes
|
---|
4345 | # need to *avoid* funky records being updated like A/AAAA records in revzones, or PTRs in forward zones.
|
---|
4346 | if ($defrec eq 'n' && $oldrec->{type} > 65000) {
|
---|
4347 | if ($$rectype == $reverse_typemap{PTR}) {
|
---|
4348 | $fields .= ",domain_id";
|
---|
4349 | push @vallist, 0;
|
---|
4350 | }
|
---|
4351 | if ($$rectype == $reverse_typemap{A} || $$rectype == $reverse_typemap{AAAA}) {
|
---|
4352 | $fields .= ",rdns_id";
|
---|
4353 | push @vallist, 0;
|
---|
4354 | }
|
---|
4355 | }
|
---|
4356 | # fix fat-finger-originated record type changes
|
---|
4357 | if ($$rectype == 65285) { # delegation
|
---|
4358 | $fields .= ",rdns_id" if $revrec eq 'n';
|
---|
4359 | $fields .= ",domain_id" if $revrec eq 'y';
|
---|
4360 | push @vallist, 0;
|
---|
4361 | }
|
---|
4362 | # ... and now make sure we *do* associate a record with the "calling" parent
|
---|
4363 | if ($defrec eq 'n') {
|
---|
4364 | $domid = $parid if $revrec eq 'n';
|
---|
4365 | $revid = $parid if $revrec eq 'y';
|
---|
4366 | }
|
---|
4367 |
|
---|
4368 | # Put together the success log entry. Horrible kludge from addRec() copied as-is since
|
---|
4369 | # we don't know whether the passed arguments or retrieved values for domain_id and rdns_id
|
---|
4370 | # will be maintained (due to "not-in-zone" validation changes)
|
---|
4371 | my %logdata;
|
---|
4372 | $logdata{domain_id} = $domid;
|
---|
4373 | $logdata{rdns_id} = $revid;
|
---|
4374 | my @ftmp = split /,/, $fields;
|
---|
4375 | for (my $i=0; $i <= $#vallist; $i++) {
|
---|
4376 | $logdata{domain_id} = $vallist[$i] if $ftmp[$i] eq 'domain_id';
|
---|
4377 | $logdata{rdns_id} = $vallist[$i] if $ftmp[$i] eq 'rdns_id';
|
---|
4378 | }
|
---|
4379 | $logdata{group_id} = $parid if $defrec eq 'y';
|
---|
4380 | $logdata{group_id} = $self->parentID(id => $parid, type => ($revrec eq 'n' ? 'domain' : 'revzone'), revrec => $revrec)
|
---|
4381 | if $defrec eq 'n';
|
---|
4382 | $logdata{entry} = "Updated ".($defrec eq 'y' ? 'default record' : 'record')." from\n";
|
---|
4383 | # Log reverse records "naturally", since they're stored, um, unnaturally.
|
---|
4384 | if ($revrec eq 'y') {
|
---|
4385 | $logdata{entry} .= " '$oldrec->{val} $typemap{$oldrec->{type}} $oldrec->{host}";
|
---|
4386 | } else {
|
---|
4387 | $logdata{entry} .= " '$oldrec->{host} $typemap{$oldrec->{type}} $oldrec->{val}";
|
---|
4388 | }
|
---|
4389 | $logdata{entry} .= " [distance $oldrec->{distance}]" if $typemap{$oldrec->{type}} eq 'MX';
|
---|
4390 | $logdata{entry} .= " [priority $oldrec->{distance}] [weight $oldrec->{weight}] [port $oldrec->{port}]"
|
---|
4391 | if $typemap{$oldrec->{type}} eq 'SRV';
|
---|
4392 | $logdata{entry} .= "', TTL $oldrec->{ttl}";
|
---|
4393 | $logdata{entry} .= ", location ".$self->getLoc($oldrec->{location})->{description} if $oldrec->{location};
|
---|
4394 | $logdata{entry} .= ($oldrec->{expires} ? ', expires at ' : ', valid after ').$oldrec->{stamp}
|
---|
4395 | if $oldrec->{stampactive};
|
---|
4396 | $logdata{entry} .= "\nto\n";
|
---|
4397 | # Log reverse records "naturally", since they're stored, um, unnaturally.
|
---|
4398 | if ($revrec eq 'y') {
|
---|
4399 | $logdata{entry} .= "'$$val $typemap{$$rectype} $$host";
|
---|
4400 | } else {
|
---|
4401 | $logdata{entry} .= "'$$host $typemap{$$rectype} $$val";
|
---|
4402 | }
|
---|
4403 | $logdata{entry} .= " [distance $dist]" if $typemap{$$rectype} eq 'MX';
|
---|
4404 | $logdata{entry} .= " [priority $dist] [weight $weight] [port $port]" if $typemap{$$rectype} eq 'SRV';
|
---|
4405 | $logdata{entry} .= "', TTL $ttl";
|
---|
4406 | $logdata{entry} .= ", location ".$self->getLoc($location)->{description} if $location;
|
---|
4407 | $logdata{entry} .= ($expires ? ', expires at ' : ', valid after ').$stamp if $stamp;
|
---|
4408 |
|
---|
4409 | local $dbh->{AutoCommit} = 0;
|
---|
4410 | local $dbh->{RaiseError} = 1;
|
---|
4411 |
|
---|
4412 | # Fiddle the field list into something suitable for updates
|
---|
4413 | $fields =~ s/,/=?,/g;
|
---|
4414 | $fields .= "=?";
|
---|
4415 |
|
---|
4416 | eval {
|
---|
4417 | $dbh->do("UPDATE "._rectable($defrec,$revrec)." SET $fields WHERE record_id=?", undef, (@vallist, $id) );
|
---|
4418 | $self->_log(%logdata);
|
---|
4419 | $dbh->commit;
|
---|
4420 | };
|
---|
4421 | if ($@) {
|
---|
4422 | my $msg = $@;
|
---|
4423 | eval { $dbh->rollback; };
|
---|
4424 | if ($self->{log_failures}) {
|
---|
4425 | $logdata{entry} = "Failed updating ".($defrec eq 'y' ? 'default ' : '').
|
---|
4426 | "record '$oldrec->{host} $typemap{$oldrec->{type}} $oldrec->{val}', TTL $oldrec->{ttl} ($msg)";
|
---|
4427 | $self->_log(%logdata);
|
---|
4428 | $dbh->commit;
|
---|
4429 | }
|
---|
4430 | return ('FAIL', $msg);
|
---|
4431 | }
|
---|
4432 |
|
---|
4433 | $resultstr = $logdata{entry};
|
---|
4434 | return ($retcode, $retmsg);
|
---|
4435 | } # end updateRec()
|
---|
4436 |
|
---|
4437 |
|
---|
4438 | ## DNSDB::downconvert()
|
---|
4439 | # A mostly internal (not exported) semiutilty sub to downconvert from pseudotype <x>
|
---|
4440 | # to a compatible component type. Only a handful of operations are valid, anything
|
---|
4441 | # else is a null-op.
|
---|
4442 | # Takes the record ID and the new type. Returns boolean.
|
---|
4443 | sub downconvert {
|
---|
4444 | my $self = shift;
|
---|
4445 | my $dbh = $self->{dbh};
|
---|
4446 | my $recid = shift;
|
---|
4447 | my $newtype = shift;
|
---|
4448 |
|
---|
4449 | # also, only work on live records; little to no value trying to do this on default records.
|
---|
4450 | my $rec = $self->getRecLine('n', 'y', $recid);
|
---|
4451 |
|
---|
4452 | # hm?
|
---|
4453 | #return 1 if !$rec;
|
---|
4454 |
|
---|
4455 | return 1 if $rec->{type} < 65000; # Only the reverse-record pseudotypes can be downconverted
|
---|
4456 | return 1 if $rec->{type} == 65282; # Nowhere to go
|
---|
4457 |
|
---|
4458 | my $delpar;
|
---|
4459 | my @sqlargs;
|
---|
4460 | if ($rec->{type} == 65280) {
|
---|
4461 | return 1 if $newtype != 1 && $newtype != 12;
|
---|
4462 | $delpar = ($newtype == 1 ? 'rdns_id' : 'domain_id');
|
---|
4463 | push @sqlargs, 0, $newtype, $recid;
|
---|
4464 | } elsif ($rec->{type} == 65281) {
|
---|
4465 | return 1 if $newtype != 28 && $newtype != 12;
|
---|
4466 | $delpar = ($newtype == 28 ? 'rdns_id' : 'domain_id');
|
---|
4467 | push @sqlargs, 0, $newtype, $recid;
|
---|
4468 | } elsif ($rec->{type} == 65283) {
|
---|
4469 | return 1 if $newtype != 65282;
|
---|
4470 | $delpar = 'rdns_id';
|
---|
4471 | } elsif ($rec->{type} == 65284) {
|
---|
4472 | return 1 if $newtype != 65282;
|
---|
4473 | $delpar = 'rdns_id';
|
---|
4474 | } else {
|
---|
4475 | # Your llama is on fire.
|
---|
4476 | }
|
---|
4477 |
|
---|
4478 | local $dbh->{AutoCommit} = 0;
|
---|
4479 | local $dbh->{RaiseError} = 1;
|
---|
4480 |
|
---|
4481 | eval {
|
---|
4482 | $dbh->do("UPDATE records SET $delpar = ?, type = ? WHERE record_id = ?", undef, @sqlargs);
|
---|
4483 | $dbh->commit;
|
---|
4484 | };
|
---|
4485 | if ($@) {
|
---|
4486 | $errstr = $@;
|
---|
4487 | eval { $dbh->rollback; };
|
---|
4488 | return 0;
|
---|
4489 | }
|
---|
4490 | return 1;
|
---|
4491 | } # end downconvert()
|
---|
4492 |
|
---|
4493 |
|
---|
4494 | ## DNSDB::delRec()
|
---|
4495 | # Delete a record.
|
---|
4496 | sub delRec {
|
---|
4497 | $errstr = '';
|
---|
4498 | my $self = shift;
|
---|
4499 | my $dbh = $self->{dbh};
|
---|
4500 | my $defrec = shift;
|
---|
4501 | my $revrec = shift;
|
---|
4502 | my $id = shift;
|
---|
4503 |
|
---|
4504 | my $oldrec = $self->getRecLine($defrec, $revrec, $id);
|
---|
4505 |
|
---|
4506 | # Allow transactions, and raise an exception on errors so we can catch it later.
|
---|
4507 | # Use local to make sure these get "reset" properly on exiting this block
|
---|
4508 | local $dbh->{AutoCommit} = 0;
|
---|
4509 | local $dbh->{RaiseError} = 1;
|
---|
4510 |
|
---|
4511 | # Put together the log entry
|
---|
4512 | my %logdata;
|
---|
4513 | $logdata{domain_id} = $oldrec->{domain_id};
|
---|
4514 | $logdata{rdns_id} = $oldrec->{rdns_id};
|
---|
4515 | $logdata{group_id} = $oldrec->{group_id} if $defrec eq 'y';
|
---|
4516 | $logdata{group_id} = $self->parentID(id => $oldrec->{domain_id}, type => ($revrec eq 'n' ? 'domain' : 'revzone'),
|
---|
4517 | revrec => $revrec)
|
---|
4518 | if $defrec eq 'n';
|
---|
4519 | $logdata{entry} = "Deleted ".($defrec eq 'y' ? 'default record ' : 'record ').
|
---|
4520 | "'$oldrec->{host} $typemap{$oldrec->{type}} $oldrec->{val}";
|
---|
4521 | $logdata{entry} .= " [distance $oldrec->{distance}]" if $typemap{$oldrec->{type}} eq 'MX';
|
---|
4522 | $logdata{entry} .= " [priority $oldrec->{distance}] [weight $oldrec->{weight}] [port $oldrec->{port}]"
|
---|
4523 | if $typemap{$oldrec->{type}} eq 'SRV';
|
---|
4524 | $logdata{entry} .= "', TTL $oldrec->{ttl}";
|
---|
4525 | $logdata{entry} .= ", location ".$self->getLoc($oldrec->{location})->{description} if $oldrec->{location};
|
---|
4526 |
|
---|
4527 | eval {
|
---|
4528 | my $sth = $dbh->do("DELETE FROM "._rectable($defrec,$revrec)." WHERE record_id=?", undef, ($id));
|
---|
4529 | $self->_log(%logdata);
|
---|
4530 | $dbh->commit;
|
---|
4531 | };
|
---|
4532 | if ($@) {
|
---|
4533 | my $msg = $@;
|
---|
4534 | eval { $dbh->rollback; };
|
---|
4535 | if ($self->{log_failures}) {
|
---|
4536 | $logdata{entry} = "Error deleting ".($defrec eq 'y' ? 'default record' : 'record').
|
---|
4537 | " '$oldrec->{host} $typemap{$oldrec->{type}} $oldrec->{val}', TTL $oldrec->{ttl} ($msg)";
|
---|
4538 | $self->_log(%logdata);
|
---|
4539 | $dbh->commit;
|
---|
4540 | }
|
---|
4541 | return ('FAIL', $msg);
|
---|
4542 | }
|
---|
4543 |
|
---|
4544 | return ('OK',$logdata{entry});
|
---|
4545 | } # end delRec()
|
---|
4546 |
|
---|
4547 |
|
---|
4548 | ## DNSDB::getLogCount()
|
---|
4549 | # Get a count of log entries
|
---|
4550 | # Takes a database handle and a hash containing at least:
|
---|
4551 | # - Entity ID and entity type as the primary log "slice"
|
---|
4552 | sub getLogCount {
|
---|
4553 | my $self = shift;
|
---|
4554 | my $dbh = $self->{dbh};
|
---|
4555 |
|
---|
4556 | my %args = @_;
|
---|
4557 |
|
---|
4558 | my @filterargs;
|
---|
4559 | ##fixme: which fields do we want to filter on?
|
---|
4560 | # push @filterargs,
|
---|
4561 |
|
---|
4562 | $errstr = 'Missing primary parent ID and/or type';
|
---|
4563 | # fail early if we don't have a "prime" ID to look for log entries for
|
---|
4564 | return if !$args{id};
|
---|
4565 |
|
---|
4566 | # or if the prime id type is missing or invalid
|
---|
4567 | return if !$args{logtype};
|
---|
4568 | $args{logtype} = 'revzone' if $args{logtype} eq 'rdns'; # hack pthui
|
---|
4569 | $args{logtype} = 'domain' if $args{logtype} eq 'dom'; # hack pthui
|
---|
4570 | return if !grep /^$args{logtype}$/, ('group', 'domain', 'revzone', 'user');
|
---|
4571 |
|
---|
4572 | my $sql = "SELECT count(*) FROM log ".
|
---|
4573 | "WHERE $id_col{$args{logtype}}=?".
|
---|
4574 | ($args{filter} ? " AND entry ~* ?" : '');
|
---|
4575 | my ($count) = $dbh->selectrow_array($sql, undef, ($args{id}, @filterargs) );
|
---|
4576 | $errstr = $dbh->errstr if !$count;
|
---|
4577 | return $count;
|
---|
4578 | } # end getLogCount()
|
---|
4579 |
|
---|
4580 |
|
---|
4581 | ## DNSDB::getLogEntries()
|
---|
4582 | # Get a list of log entries
|
---|
4583 | # Takes arguments as with getLogCount() above, plus optional:
|
---|
4584 | # - sort field
|
---|
4585 | # - sort order
|
---|
4586 | # - offset for pagination
|
---|
4587 | sub getLogEntries {
|
---|
4588 | my $self = shift;
|
---|
4589 | my $dbh = $self->{dbh};
|
---|
4590 |
|
---|
4591 | my %args = @_;
|
---|
4592 |
|
---|
4593 | my @filterargs;
|
---|
4594 |
|
---|
4595 | # fail early if we don't have a "prime" ID to look for log entries for
|
---|
4596 | return if !$args{id};
|
---|
4597 |
|
---|
4598 | # or if the prime id type is missing or invalid
|
---|
4599 | return if !$args{logtype};
|
---|
4600 | $args{logtype} = 'revzone' if $args{logtype} eq 'rdns'; # hack pthui
|
---|
4601 | $args{logtype} = 'domain' if $args{logtype} eq 'dom'; # hack pthui
|
---|
4602 | return if !grep /^$args{logtype}$/, ('group', 'domain', 'revzone', 'user');
|
---|
4603 |
|
---|
4604 | # Sorting defaults
|
---|
4605 | $args{sortorder} = 'DESC' if !$args{sortorder} || !grep /^$args{sortorder}$/, ('ASC','DESC');
|
---|
4606 | $args{sortby} = 'stamp' if !$args{sortby} || $args{sortby} !~ /^[\w_.]+$/;
|
---|
4607 | $args{offset} = 0 if !$args{offset} || $args{offset} !~ /^(?:all|\d+)$/;
|
---|
4608 |
|
---|
4609 | my %sortmap = (fname => 'name', username => 'email', entry => 'entry', stamp => 'stamp');
|
---|
4610 | $args{sortby} = $sortmap{$args{sortby}};
|
---|
4611 |
|
---|
4612 | my $sql = "SELECT user_id AS userid, email AS useremail, name AS userfname, entry AS logentry, ".
|
---|
4613 | "date_trunc('second',stamp) AS logtime ".
|
---|
4614 | "FROM log ".
|
---|
4615 | "WHERE $id_col{$args{logtype}}=?".
|
---|
4616 | ($args{filter} ? " AND entry ~* ?" : '').
|
---|
4617 | " ORDER BY $args{sortby} $args{sortorder}, log_id $args{sortorder}".
|
---|
4618 | ($args{offset} eq 'all' ? '' : " LIMIT $self->{perpage} OFFSET ".$args{offset}*$self->{perpage});
|
---|
4619 | my $loglist = $dbh->selectall_arrayref($sql, { Slice => {} }, ($args{id}, @filterargs) );
|
---|
4620 | $errstr = $dbh->errstr if !$loglist;
|
---|
4621 | return $loglist;
|
---|
4622 | } # end getLogEntries()
|
---|
4623 |
|
---|
4624 |
|
---|
4625 | ## IPDB::getRevPattern()
|
---|
4626 | # Get the narrowest template pattern applicable to a passed CIDR address (may be a netblock or an IP)
|
---|
4627 | sub getRevPattern {
|
---|
4628 | my $self = shift;
|
---|
4629 | my $dbh = $self->{dbh};
|
---|
4630 | my $cidr = shift;
|
---|
4631 | my $group = shift || 1; # just in case
|
---|
4632 |
|
---|
4633 | # for speed! Casting and comparing even ~7K records takes ~2.5s, so narrow it down to one revzone first.
|
---|
4634 | my ($revid) = $dbh->selectrow_array("SELECT rdns_id FROM revzones WHERE revnet >>= ? AND group_id = ?",
|
---|
4635 | undef, ($cidr, $group) );
|
---|
4636 |
|
---|
4637 | ##fixme? may need to narrow things down more by octet-chopping and doing text comparisons before casting.
|
---|
4638 | my ($revpatt) = $dbh->selectrow_array("SELECT host FROM records ".
|
---|
4639 | "WHERE (type in (12,65280,65281,65282,65283,65284)) AND rdns_id = ? AND inetlazy(val) >>= ? ".
|
---|
4640 | "ORDER BY inetlazy(val) DESC LIMIT 1", undef, ($revid, $cidr) );
|
---|
4641 | return $revpatt;
|
---|
4642 | } # end getRevPattern()
|
---|
4643 |
|
---|
4644 |
|
---|
4645 | ## DNSDB::getTypelist()
|
---|
4646 | # Get a list of record types for various UI dropdowns
|
---|
4647 | # Takes database handle, forward/reverse/lookup flag, and optional "tag as selected" indicator (defaults to A)
|
---|
4648 | # Returns an arrayref to list of hashrefs perfect for HTML::Template
|
---|
4649 | sub getTypelist {
|
---|
4650 | my $self = shift;
|
---|
4651 | my $dbh = $self->{dbh};
|
---|
4652 | my $recgroup = shift;
|
---|
4653 | my $type = shift || $reverse_typemap{A};
|
---|
4654 |
|
---|
4655 | # also accepting $webvar{revrec}!
|
---|
4656 | $recgroup = 'f' if $recgroup eq 'n';
|
---|
4657 | $recgroup = 'r' if $recgroup eq 'y';
|
---|
4658 |
|
---|
4659 | my $sql = "SELECT val,name FROM rectypes WHERE ";
|
---|
4660 | if ($recgroup eq 'r') {
|
---|
4661 | # reverse zone types
|
---|
4662 | $sql .= "stdflag=2 OR stdflag=3";
|
---|
4663 | } elsif ($recgroup eq 'l') {
|
---|
4664 | # DNS lookup types. Note we avoid our custom types >= 65280, since those are entirely internal.
|
---|
4665 | $sql .= "(stdflag=1 OR stdflag=2 OR stdflag=3) AND val < 65280";
|
---|
4666 | } else {
|
---|
4667 | # default; forward zone types. technically $type eq 'f' but not worth the error message.
|
---|
4668 | $sql .= "stdflag=1 OR stdflag=2";
|
---|
4669 | $sql .= " AND val < 65280" if $recgroup eq 'fo'; # An extra flag to trim off the pseudotypes as well.
|
---|
4670 | }
|
---|
4671 | $sql .= " ORDER BY listorder";
|
---|
4672 |
|
---|
4673 | my $sth = $dbh->prepare($sql);
|
---|
4674 | $sth->execute;
|
---|
4675 | my @typelist;
|
---|
4676 | # track whether the passed type is in the list at all. allows you to edit a record
|
---|
4677 | # that wouldn't otherwise be generally available in that zone (typically, reverse zones)
|
---|
4678 | # without changing its type (accidentally or otherwise)
|
---|
4679 | my $selflag = 0;
|
---|
4680 | while (my ($rval,$rname) = $sth->fetchrow_array()) {
|
---|
4681 | my %row = ( recval => $rval, recname => $rname );
|
---|
4682 | if ($rval == $type) {
|
---|
4683 | $row{tselect} = 1;
|
---|
4684 | $selflag = 1;
|
---|
4685 | }
|
---|
4686 | push @typelist, \%row;
|
---|
4687 | }
|
---|
4688 |
|
---|
4689 | # add the passed type if it wasn't in the list
|
---|
4690 | if (!$selflag) {
|
---|
4691 | my %row = ( recval => $type, recname => $typemap{$type}, tselect => 1 );
|
---|
4692 | push @typelist, \%row;
|
---|
4693 | }
|
---|
4694 |
|
---|
4695 | # Add SOA on lookups since it's not listed in other dropdowns.
|
---|
4696 | if ($recgroup eq 'l') {
|
---|
4697 | my %row = ( recval => $reverse_typemap{SOA}, recname => 'SOA' );
|
---|
4698 | $row{tselect} = 1 if $reverse_typemap{SOA} == $type;
|
---|
4699 | push @typelist, \%row;
|
---|
4700 | }
|
---|
4701 |
|
---|
4702 | return \@typelist;
|
---|
4703 | } # end getTypelist()
|
---|
4704 |
|
---|
4705 |
|
---|
4706 | ## DNSDB::parentID()
|
---|
4707 | # Get ID of entity that is nearest parent to requested id
|
---|
4708 | # Takes a database handle and a hash of entity ID, entity type, optional parent type flag
|
---|
4709 | # (domain/reverse zone or group), and optional default/live and forward/reverse flags
|
---|
4710 | # Returns the ID or undef on failure
|
---|
4711 | sub parentID {
|
---|
4712 | my $self = shift;
|
---|
4713 | my $dbh = $self->{dbh};
|
---|
4714 |
|
---|
4715 | my %args = @_;
|
---|
4716 |
|
---|
4717 | # clean up the parent-type. Set it to group if not set; coerce revzone to domain for simpler logic
|
---|
4718 | $args{partype} = 'group' if !$args{partype};
|
---|
4719 | $args{partype} = 'domain' if $args{partype} eq 'revzone';
|
---|
4720 |
|
---|
4721 | # clean up defrec and revrec. default to live record, forward zone
|
---|
4722 | $args{defrec} = 'n' if !$args{defrec};
|
---|
4723 | $args{revrec} = 'n' if !$args{revrec};
|
---|
4724 |
|
---|
4725 | if ($par_type{$args{partype}} eq 'domain') {
|
---|
4726 | # only live records can have a domain/zone parent
|
---|
4727 | return unless ($args{type} eq 'record' && $args{defrec} eq 'n');
|
---|
4728 | my $result = $dbh->selectrow_hashref("SELECT ".($args{revrec} eq 'n' ? 'domain_id' : 'rdns_id').
|
---|
4729 | " FROM records WHERE record_id = ?",
|
---|
4730 | undef, ($args{id}) ) or return;
|
---|
4731 | return $result;
|
---|
4732 | } else {
|
---|
4733 | # snag some arguments that will either fall through or be overwritten to save some code duplication
|
---|
4734 | my $tmpid = $args{id};
|
---|
4735 | my $type = $args{type};
|
---|
4736 | if ($type eq 'record' && $args{defrec} eq 'n') {
|
---|
4737 | # Live records go through the records table first.
|
---|
4738 | ($tmpid) = $dbh->selectrow_array("SELECT ".($args{revrec} eq 'n' ? 'domain_id' : 'rdns_id').
|
---|
4739 | " FROM records WHERE record_id = ?",
|
---|
4740 | undef, ($args{id}) ) or return;
|
---|
4741 | $type = ($args{revrec} eq 'n' ? 'domain' : 'revzone');
|
---|
4742 | }
|
---|
4743 | my ($result) = $dbh->selectrow_array("SELECT $par_col{$type} FROM $par_tbl{$type} WHERE $id_col{$type} = ?",
|
---|
4744 | undef, ($tmpid) );
|
---|
4745 | return $result;
|
---|
4746 | }
|
---|
4747 | # should be impossible to get here with even remotely sane arguments
|
---|
4748 | return;
|
---|
4749 | } # end parentID()
|
---|
4750 |
|
---|
4751 |
|
---|
4752 | ## DNSDB::isParent()
|
---|
4753 | # Returns true if $id1 is a parent of $id2, false otherwise
|
---|
4754 | sub isParent {
|
---|
4755 | my $self = shift;
|
---|
4756 | my $dbh = $self->{dbh};
|
---|
4757 | my $id1 = shift;
|
---|
4758 | my $type1 = shift;
|
---|
4759 | my $id2 = shift;
|
---|
4760 | my $type2 = shift;
|
---|
4761 | ##todo: immediate, secondary, full (default)
|
---|
4762 |
|
---|
4763 | # Return false on invalid types
|
---|
4764 | return 0 if !grep /^$type1$/, ('record','defrec','defrevrec','user','domain','revzone','group');
|
---|
4765 | return 0 if !grep /^$type2$/, ('record','defrec','defrevrec','user','domain','revzone','group');
|
---|
4766 |
|
---|
4767 | # Return false on impossible relations
|
---|
4768 | return 0 if $type1 eq 'record'; # nothing may be a child of a record
|
---|
4769 | return 0 if $type1 eq 'defrec'; # nothing may be a child of a record
|
---|
4770 | return 0 if $type1 eq 'defrevrec'; # nothing may be a child of a record
|
---|
4771 | return 0 if $type1 eq 'user'; # nothing may be child of a user
|
---|
4772 | return 0 if $type1 eq 'domain' && $type2 ne 'record'; # domain may not be a parent of anything other than a record
|
---|
4773 | return 0 if $type1 eq 'revzone' && $type2 ne 'record';# reverse zone may not be a parent of anything other than a record
|
---|
4774 |
|
---|
4775 | # ennnhhhh.... if we're passed an id of 0, it will never be found. usual
|
---|
4776 | # case would be the UI creating a new <thing>, and so we don't have an ID for
|
---|
4777 | # <thing> to look up yet. in that case the UI should check the parent as well.
|
---|
4778 | return 0 if $id1 == 0; # nothing can have a parent id of 0
|
---|
4779 | return 1 if $id2 == 0; # anything could have a child id of 0 (or "unknown")
|
---|
4780 |
|
---|
4781 | # group 1 is the ultimate root parent
|
---|
4782 | return 1 if $type1 eq 'group' && $id1 == 1;
|
---|
4783 |
|
---|
4784 | # groups are always (a) parent of themselves
|
---|
4785 | return 1 if $type1 eq 'group' && $type2 eq 'group' && $id1 == $id2;
|
---|
4786 |
|
---|
4787 | my $id = $id2;
|
---|
4788 | my $type = $type2;
|
---|
4789 | my $foundparent = 0;
|
---|
4790 |
|
---|
4791 | # Records are the only entity with two possible parents. We need to split the parent checks on
|
---|
4792 | # domain/rdns.
|
---|
4793 | if ($type eq 'record') {
|
---|
4794 | my ($dom,$rdns) = $dbh->selectrow_array("SELECT domain_id,rdns_id FROM records WHERE record_id=?",
|
---|
4795 | undef, ($id));
|
---|
4796 | # check immediate parent against request
|
---|
4797 | return 1 if $type1 eq 'domain' && $id1 == $dom;
|
---|
4798 | return 1 if $type1 eq 'revzone' && $id1 == $rdns;
|
---|
4799 | # if request is group, check *both* parents. Only check if the parent is nonzero though.
|
---|
4800 | return 1 if $dom && $self->isParent($id1, $type1, $dom, 'domain');
|
---|
4801 | return 1 if $rdns && $self->isParent($id1, $type1, $rdns, 'revzone');
|
---|
4802 | # exit here since we've executed the loop below by proxy in the above recursive calls.
|
---|
4803 | return 0;
|
---|
4804 | }
|
---|
4805 |
|
---|
4806 | # almost the same loop as getParents() above
|
---|
4807 | my $limiter = 0;
|
---|
4808 | while (1) {
|
---|
4809 | my $sql = "SELECT $par_col{$type} FROM $par_tbl{$type} WHERE $id_col{$type} = ?";
|
---|
4810 | my $result = $dbh->selectrow_hashref($sql,
|
---|
4811 | undef, ($id) );
|
---|
4812 | if (!$result) {
|
---|
4813 | $limiter++;
|
---|
4814 | ##fixme: how often will this happen on a live site? fail at max limiter <n>?
|
---|
4815 | # 2013/10/22 only seems to happen when you request an entity that doesn't exist.
|
---|
4816 | warn "no results looking for $sql with id $id (depth $limiter)\n";
|
---|
4817 | last;
|
---|
4818 | }
|
---|
4819 | if ($result && $result->{$par_col{$type}} == $id1) {
|
---|
4820 | $foundparent = 1;
|
---|
4821 | last;
|
---|
4822 | } else {
|
---|
4823 | ##fixme: do we care about trying to return a "no such record/domain/user/group" error?
|
---|
4824 | # should be impossible to create an inconsistent DB just with API calls.
|
---|
4825 | warn $dbh->errstr." $sql, $id" if $dbh->errstr;
|
---|
4826 | }
|
---|
4827 | # group 1 is its own parent. need this here more to break strange loops than for detecting a parent
|
---|
4828 | last if $result->{$par_col{$type}} == 1;
|
---|
4829 | $id = $result->{$par_col{$type}};
|
---|
4830 | $type = $par_type{$type};
|
---|
4831 | }
|
---|
4832 |
|
---|
4833 | return $foundparent;
|
---|
4834 | } # end isParent()
|
---|
4835 |
|
---|
4836 |
|
---|
4837 | ## DNSDB::zoneStatus()
|
---|
4838 | # Returns and optionally sets a zone's status
|
---|
4839 | # Takes a database handle, domain/revzone ID, forward/reverse flag, and optionally a status argument
|
---|
4840 | # Returns status, or undef on errors.
|
---|
4841 | sub zoneStatus {
|
---|
4842 | my $self = shift;
|
---|
4843 | my $dbh = $self->{dbh};
|
---|
4844 | my $id = shift;
|
---|
4845 | my $revrec = shift;
|
---|
4846 | my $newstatus = shift || 'mu';
|
---|
4847 |
|
---|
4848 | return undef if $id !~ /^\d+$/;
|
---|
4849 |
|
---|
4850 | # Allow transactions, and raise an exception on errors so we can catch it later.
|
---|
4851 | # Use local to make sure these get "reset" properly on exiting this block
|
---|
4852 | local $dbh->{AutoCommit} = 0;
|
---|
4853 | local $dbh->{RaiseError} = 1;
|
---|
4854 |
|
---|
4855 | if ($newstatus ne 'mu') {
|
---|
4856 | # ooo, fun! let's see what we were passed for status
|
---|
4857 | eval {
|
---|
4858 | $newstatus = 0 if $newstatus eq 'domoff';
|
---|
4859 | $newstatus = 1 if $newstatus eq 'domon';
|
---|
4860 | $dbh->do("UPDATE ".($revrec eq 'n' ? 'domains' : 'revzones')." SET status=? WHERE ".
|
---|
4861 | ($revrec eq 'n' ? 'domain_id' : 'rdns_id')."=?", undef, ($newstatus,$id) );
|
---|
4862 |
|
---|
4863 | ##fixme switch to more consise "Enabled <domain"/"Disabled <domain>" as with users?
|
---|
4864 | $resultstr = "Changed ".($revrec eq 'n' ? $self->domainName($id) : $self->revName($id)).
|
---|
4865 | " state to ".($newstatus ? 'active' : 'inactive');
|
---|
4866 |
|
---|
4867 | my %loghash;
|
---|
4868 | $loghash{domain_id} = $id if $revrec eq 'n';
|
---|
4869 | $loghash{rdns_id} = $id if $revrec eq 'y';
|
---|
4870 | $loghash{group_id} = $self->parentID(id => $id, type => ($revrec eq 'n' ? 'domain' : 'revzone'), revrec => $revrec);
|
---|
4871 | $loghash{entry} = $resultstr;
|
---|
4872 | $self->_log(%loghash);
|
---|
4873 |
|
---|
4874 | $dbh->commit;
|
---|
4875 | };
|
---|
4876 | if ($@) {
|
---|
4877 | my $msg = $@;
|
---|
4878 | eval { $dbh->rollback; };
|
---|
4879 | $resultstr = '';
|
---|
4880 | $errstr = $msg;
|
---|
4881 | return;
|
---|
4882 | }
|
---|
4883 | }
|
---|
4884 |
|
---|
4885 | my ($status) = $dbh->selectrow_array("SELECT status FROM ".
|
---|
4886 | ($revrec eq 'n' ? "domains WHERE domain_id=?" : "revzones WHERE rdns_id=?"),
|
---|
4887 | undef, ($id) );
|
---|
4888 | return $status;
|
---|
4889 | } # end zoneStatus()
|
---|
4890 |
|
---|
4891 |
|
---|
4892 | ## DNSDB::getZonesByCIDR()
|
---|
4893 | # Get a list of zone names and IDs that records for a passed CIDR block are within.
|
---|
4894 | sub getZonesByCIDR {
|
---|
4895 | my $self = shift;
|
---|
4896 | my $dbh = $self->{dbh};
|
---|
4897 | my %args = @_;
|
---|
4898 |
|
---|
4899 | my $result = $dbh->selectall_arrayref("SELECT rdns_id,revnet FROM revzones WHERE revnet >>= ? OR revnet <<= ?",
|
---|
4900 | { Slice => {} }, ($args{cidr}, $args{cidr}) );
|
---|
4901 | return $result;
|
---|
4902 | } # end getZonesByCIDR()
|
---|
4903 |
|
---|
4904 |
|
---|
4905 | ## DNSDB::importAXFR
|
---|
4906 | # Import a domain via AXFR
|
---|
4907 | # Takes AXFR host, domain to transfer, group to put the domain in,
|
---|
4908 | # and an optional hash containing:
|
---|
4909 | # status - active/inactive state flag (defaults to active)
|
---|
4910 | # rwsoa - overwrite-SOA flag (defaults to off)
|
---|
4911 | # rwns - overwrite-NS flag (defaults to off, doesn't affect subdomain NS records)
|
---|
4912 | # merge - flag to automerge A or AAAA records with matching PTR records
|
---|
4913 | # Returns a status code (OK, WARN, or FAIL) and message - message should be blank
|
---|
4914 | # if status is OK, but WARN includes conditions that are not fatal but should
|
---|
4915 | # really be reported.
|
---|
4916 | sub importAXFR {
|
---|
4917 | my $self = shift;
|
---|
4918 | my $dbh = $self->{dbh};
|
---|
4919 | my $ifrom_in = shift;
|
---|
4920 | my $zone = shift;
|
---|
4921 | my $group = shift;
|
---|
4922 |
|
---|
4923 | my %args = @_;
|
---|
4924 |
|
---|
4925 | ##fixme: add mode to delete&replace, merge+overwrite, merge new?
|
---|
4926 |
|
---|
4927 | $args{status} = (defined($args{status}) ? $args{status} : 0);
|
---|
4928 | $args{status} = 1 if $args{status} eq 'on';
|
---|
4929 |
|
---|
4930 | my $nrecs = 0;
|
---|
4931 | my $soaflag = 0;
|
---|
4932 | my $nsflag = 0;
|
---|
4933 | my $warnmsg = '';
|
---|
4934 | my $ifrom;
|
---|
4935 |
|
---|
4936 | my $rev = 'n';
|
---|
4937 | my $code = 'OK';
|
---|
4938 | my $msg = 'foobar?';
|
---|
4939 |
|
---|
4940 | # choke on possible bad setting in ifrom
|
---|
4941 | # IPv4 and v6, and valid hostnames!
|
---|
4942 | ($ifrom) = ($ifrom_in =~ /^([0-9a-f\:.]+|[0-9a-z_.-]+)$/i);
|
---|
4943 | return ('FAIL', "Bad AXFR source host $ifrom")
|
---|
4944 | unless ($ifrom) = ($ifrom_in =~ /^([0-9a-f\:.]+|[0-9a-z_.-]+)$/i);
|
---|
4945 |
|
---|
4946 | my $errmsg;
|
---|
4947 |
|
---|
4948 | my $zone_id;
|
---|
4949 | my $domain_id = 0;
|
---|
4950 | my $rdns_id = 0;
|
---|
4951 | my $cidr;
|
---|
4952 |
|
---|
4953 | # magic happens! detect if we're importing a domain or a reverse zone
|
---|
4954 | # while we're at it, figure out what the CIDR netblock is (if we got a .arpa)
|
---|
4955 | # or what the formal .arpa zone is (if we got a CIDR netblock)
|
---|
4956 | # Handles sub-octet v4 zones in the format specified in the Cricket Book, 2nd Ed, p217-218
|
---|
4957 |
|
---|
4958 | if ($zone =~ m{(?:\.arpa\.?|/\d+|^[\d.]+|^[a-fA-F0-9:]+)$}) {
|
---|
4959 | # we seem to have a reverse zone
|
---|
4960 | $rev = 'y';
|
---|
4961 |
|
---|
4962 | if ($zone =~ /\.arpa\.?$/) {
|
---|
4963 | # we have a formal reverse zone. call _zone2cidr and get the CIDR block.
|
---|
4964 | ($code,$msg) = _zone2cidr($zone);
|
---|
4965 | return ($code, $msg) if $code eq 'FAIL';
|
---|
4966 | $cidr = $msg;
|
---|
4967 | } elsif ($zone =~ m|^[\d.]+/\d+$|) {
|
---|
4968 | # v4 revzone, CIDR netblock
|
---|
4969 | $cidr = NetAddr::IP->new($zone) or return ('FAIL',"$zone is not a valid CIDR block");
|
---|
4970 | $zone = _ZONE($cidr, 'ZONE.in-addr.arpa', 'r', '.');
|
---|
4971 | } elsif ($zone =~ /^[\d.]+$/) {
|
---|
4972 | # v4 revzone, leading-octet format
|
---|
4973 | my $mask = 32;
|
---|
4974 | while ($zone !~ /^\d+\.\d+\.\d+\.\d+$/) {
|
---|
4975 | $zone .= '.0';
|
---|
4976 | $mask -= 8;
|
---|
4977 | }
|
---|
4978 | $zone .= "/$mask";
|
---|
4979 | $cidr = NetAddr::IP->new($zone) or return ('FAIL',"$zone is not a valid CIDR block");
|
---|
4980 | $zone = _ZONE($cidr, 'ZONE.in-addr.arpa', 'r', '.');
|
---|
4981 | } elsif ($zone =~ m|^[a-fA-F\d:]+/\d+$|) {
|
---|
4982 | # v6 revzone, CIDR netblock
|
---|
4983 | $cidr = NetAddr::IP->new($zone) or return ('FAIL',"$zone is not a valid CIDR block");
|
---|
4984 | return ('FAIL', "$zone is not a nibble-aligned block") if $cidr->masklen % 4 != 0;
|
---|
4985 | $zone = _ZONE($cidr, 'ZONE.ip6.arpa', 'r', '.');
|
---|
4986 | } elsif ($zone =~ /^[a-fA-F\d:]+$/) {
|
---|
4987 | # v6 revzone, leading-group format
|
---|
4988 | $zone =~ s/::$//;
|
---|
4989 | my $mask = 128;
|
---|
4990 | while ($zone !~ /^(?:[a-fA-F\d]{1,4}:){7}[a-fA-F\d]$/) {
|
---|
4991 | $zone .= ":0";
|
---|
4992 | $mask -= 16;
|
---|
4993 | }
|
---|
4994 | $zone .= "/$mask";
|
---|
4995 | $cidr = NetAddr::IP->new($zone) or return ('FAIL',"$zone is not a valid CIDR block");
|
---|
4996 | $zone = _ZONE($cidr, 'ZONE.ip6.arpa', 'r', '.');
|
---|
4997 | } else {
|
---|
4998 | # there is. no. else!
|
---|
4999 | return ('FAIL', "Unknown zone name format '$zone'");
|
---|
5000 | }
|
---|
5001 |
|
---|
5002 | # several places this can be triggered from; better to do it once.
|
---|
5003 | $warnmsg .= "Apparent sub-/64 IPv6 reverse zone\n" if $cidr->masklen > 64;
|
---|
5004 |
|
---|
5005 | # quick check to start to see if we've already got one
|
---|
5006 |
|
---|
5007 | ($zone_id) = $dbh->selectrow_array("SELECT rdns_id FROM revzones WHERE revnet=?",
|
---|
5008 | undef, ("$cidr"));
|
---|
5009 | $rdns_id = $zone_id;
|
---|
5010 | } else {
|
---|
5011 | # default to domain
|
---|
5012 | ($zone_id) = $dbh->selectrow_array("SELECT domain_id FROM domains WHERE lower(domain) = lower(?)",
|
---|
5013 | undef, ($zone));
|
---|
5014 | $domain_id = $zone_id;
|
---|
5015 | }
|
---|
5016 |
|
---|
5017 | return ('FAIL', ($rev eq 'n' ? 'Domain' : 'Reverse zone')." already exists") if $zone_id;
|
---|
5018 |
|
---|
5019 | # little local utility sub to swap $val and $host for revzone records.
|
---|
5020 | sub _revswap {
|
---|
5021 | my $rechost = shift;
|
---|
5022 | my $recdata = shift;
|
---|
5023 |
|
---|
5024 | if ($rechost =~ /\.in-addr\.arpa\.?$/) {
|
---|
5025 | $rechost =~ s/\.in-addr\.arpa\.?$//;
|
---|
5026 | $rechost = join '.', reverse split /\./, $rechost;
|
---|
5027 | } else {
|
---|
5028 | $rechost =~ s/\.ip6\.arpa\.?$//;
|
---|
5029 | my @nibs = reverse split /\./, $rechost;
|
---|
5030 | $rechost = '';
|
---|
5031 | my $nc;
|
---|
5032 | foreach (@nibs) {
|
---|
5033 | # # fail on multicharacter nibbles; it's syntactically valid but no standard lookup
|
---|
5034 | # # will ever reach it, because it doesn't directly represent a real IP address.
|
---|
5035 | # return ('FAIL', "Invalid reverse v6 entry") if $_ !~ /^.$/;
|
---|
5036 | $rechost.= $_;
|
---|
5037 | $rechost .= ":" if ++$nc % 4 == 0 && $nc < 32;
|
---|
5038 | }
|
---|
5039 | $rechost .= ":" if $nc < 32 && $rechost !~ /\*$/; # close netblock records?
|
---|
5040 | ##fixme: there's a case that ends up with a partial entry here:
|
---|
5041 | # ip:add:re:ss::
|
---|
5042 | # can't reproduce after letting it sit overnight after discovery. :(
|
---|
5043 | #print "$rechost\n";
|
---|
5044 | # canonicalize with NetAddr::IP
|
---|
5045 | $rechost = NetAddr::IP->new($rechost)->addr unless $rechost =~ /\*$/;
|
---|
5046 | }
|
---|
5047 | return ($recdata,$rechost)
|
---|
5048 | }
|
---|
5049 |
|
---|
5050 |
|
---|
5051 | # Allow transactions, and raise an exception on errors so we can catch it later.
|
---|
5052 | # Use local to make sure these get "reset" properly on exiting this block
|
---|
5053 | local $dbh->{AutoCommit} = 0;
|
---|
5054 | local $dbh->{RaiseError} = 1;
|
---|
5055 |
|
---|
5056 | my $sth;
|
---|
5057 | eval {
|
---|
5058 |
|
---|
5059 | if ($rev eq 'n') {
|
---|
5060 | ##fixme: serial
|
---|
5061 | $dbh->do("INSERT INTO domains (domain,group_id,status) VALUES (?,?,?)", undef,
|
---|
5062 | ($zone, $group, $args{status}) );
|
---|
5063 | # get domain id so we can do the records
|
---|
5064 | ($zone_id) = $dbh->selectrow_array("SELECT currval('domains_domain_id_seq')");
|
---|
5065 | $domain_id = $zone_id;
|
---|
5066 | $self->_log(group_id => $group, domain_id => $domain_id,
|
---|
5067 | entry => "[Added ".($args{status} ? 'active' : 'inactive')." domain $zone via AXFR]");
|
---|
5068 | } else {
|
---|
5069 | ##fixme: serial
|
---|
5070 | $dbh->do("INSERT INTO revzones (revnet,group_id,status) VALUES (?,?,?)", undef,
|
---|
5071 | ($cidr,$group,$args{status}) );
|
---|
5072 | # get revzone id so we can do the records
|
---|
5073 | ($zone_id) = $dbh->selectrow_array("SELECT currval('revzones_rdns_id_seq')");
|
---|
5074 | $rdns_id = $zone_id;
|
---|
5075 | $self->_log(group_id => $group, rdns_id => $rdns_id,
|
---|
5076 | entry => "[Added ".($args{status} ? 'active' : 'inactive')." reverse zone $cidr via AXFR]");
|
---|
5077 | }
|
---|
5078 |
|
---|
5079 | ## bizarre DBI<->Net::DNS interaction bug:
|
---|
5080 | ## sometimes a zone will cause an immediate commit-and-exit (sort of) of the while()
|
---|
5081 | ## fixed, apparently I was doing *something* odd, but not certain what it was that
|
---|
5082 | ## caused a commit instead of barfing
|
---|
5083 |
|
---|
5084 | my $res = Net::DNS::Resolver->new;
|
---|
5085 | $res->nameservers($ifrom);
|
---|
5086 | $res->axfr_start($zone)
|
---|
5087 | or die "Couldn't begin AXFR\n";
|
---|
5088 |
|
---|
5089 | $sth = $dbh->prepare("INSERT INTO records (domain_id,rdns_id,host,type,val,distance,weight,port,ttl)".
|
---|
5090 | " VALUES (?,?,?,?,?,?,?,?,?)");
|
---|
5091 |
|
---|
5092 | # Stash info about sub-octet v4 revzones here so we don't have
|
---|
5093 | # to store the CNAMEs used to delegate a suboctet zone
|
---|
5094 | # $suboct{zone}{ns}[] -> array of nameservers
|
---|
5095 | # $suboct{zone}{cname}[] -> array of extant CNAMEs (Just In Case someone did something bizarre)
|
---|
5096 | ## commented pending actual use of this data. for now, we'll just
|
---|
5097 | ## auto-(re)create the CNAMEs in revzones on export
|
---|
5098 | # my %suboct;
|
---|
5099 |
|
---|
5100 | while (my $rr = $res->axfr_next()) {
|
---|
5101 |
|
---|
5102 | # Discard out-of-zone records. After trying for a while to replicate this with
|
---|
5103 | # *nix-based DNS servers, it appears that only MS DNS is prone to including these
|
---|
5104 | # in the AXFR data in the first place, and possibly only older versions at that...
|
---|
5105 | # so it can't be reasonably tested. Yay Microsoft.
|
---|
5106 | if ($rr->name !~ /$zone$/i) {
|
---|
5107 | $warnmsg .= "Discarding out-of-zone record ".$rr->string."\n";
|
---|
5108 | }
|
---|
5109 |
|
---|
5110 | my $val;
|
---|
5111 | my $distance = 0;
|
---|
5112 | my $weight = 0;
|
---|
5113 | my $port = 0;
|
---|
5114 | my $logfrag = '';
|
---|
5115 |
|
---|
5116 | # Collect some record parts
|
---|
5117 | my $type = $rr->type;
|
---|
5118 | my $host = $rr->name;
|
---|
5119 | my $ttl = ($args{newttl} ? $args{newttl} : $rr->ttl); # allow force-override TTLs
|
---|
5120 |
|
---|
5121 | # Info flags for SOA and NS records
|
---|
5122 | $soaflag = 1 if $type eq 'SOA';
|
---|
5123 | $nsflag = 1 if $type eq 'NS';
|
---|
5124 |
|
---|
5125 | # "Primary" types:
|
---|
5126 | # A, NS, CNAME, SOA, PTR(warn in forward), MX, TXT, AAAA, SRV, A6(ob), SPF
|
---|
5127 | # maybe KEY
|
---|
5128 |
|
---|
5129 | # BIND supports:
|
---|
5130 | # [standard]
|
---|
5131 | # A AAAA CNAME MX NS PTR SOA TXT
|
---|
5132 | # [variously experimental, obsolete, or obscure]
|
---|
5133 | # 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
|
---|
5134 | # ... if one can ever find the right magic to format them correctly
|
---|
5135 |
|
---|
5136 | # Net::DNS supports:
|
---|
5137 | # RRSIG SIG NSAP NS NIMLOC NAPTR MX MR MINFO MG MB LOC ISDN IPSECKEY HINFO
|
---|
5138 | # EID DNAME CNAME CERT APL AFSDB AAAA A DS NXT NSEC3PARAM NSEC3 NSEC KEY
|
---|
5139 | # DNSKEY DLV X25 TXT TSIG TKEY SSHFP SRV SPF SOA RT RP PX PTR NULL APL::AplItem
|
---|
5140 |
|
---|
5141 | # nasty big ugly case-like thing here, since we have to do *some* different
|
---|
5142 | # processing depending on the record. le sigh.
|
---|
5143 |
|
---|
5144 | # do the initial processing as if the record was in a forward zone. If we're
|
---|
5145 | # doing a revzone, we can flip $host and $val as needed, once, after this
|
---|
5146 | # monster if-elsif-...-elsif-else. This actually simplifies things a lot.
|
---|
5147 |
|
---|
5148 | ##fixme: what record types other than TXT can/will have >255-byte payloads?
|
---|
5149 |
|
---|
5150 | if ($type eq 'A') {
|
---|
5151 | $val = $rr->address;
|
---|
5152 | } elsif ($type eq 'NS') {
|
---|
5153 | # hmm. should we warn here if subdomain NS'es are left alone? OTOH, those should rarely be rewritten anyway.
|
---|
5154 | next if ($args{rwns} && ($host eq $zone));
|
---|
5155 | $val = $rr->nsdname;
|
---|
5156 | $warnmsg .= "Suspect record '".$rr->string."' may not be imported correctly: NS records may not be bare IP addresses\n"
|
---|
5157 | if $val =~ /^(?:(?:\d+\.){3}\d+|[a-fA-F0-9:]+)$/;
|
---|
5158 | $nsflag = 1;
|
---|
5159 | } elsif ($type eq 'CNAME') {
|
---|
5160 | $val = $rr->cname;
|
---|
5161 | $warnmsg .= "Suspect record '".$rr->string."' may not be imported correctly: CNAME records may not be bare IP addresses\n"
|
---|
5162 | if $val =~ /^(?:(?:\d+\.){3}\d+|[a-fA-F0-9:]+)$/;
|
---|
5163 | } elsif ($type eq 'SOA') {
|
---|
5164 | next if $args{rwsoa};
|
---|
5165 | $host = $rr->rname.":".$rr->mname;
|
---|
5166 | $val = $rr->refresh.":".$rr->retry.":".$rr->expire.":".$rr->minimum;
|
---|
5167 | $soaflag = 1;
|
---|
5168 | } elsif ($type eq 'PTR') {
|
---|
5169 | $val = $rr->ptrdname;
|
---|
5170 | } elsif ($type eq 'MX') {
|
---|
5171 | $val = $rr->exchange;
|
---|
5172 | $distance = $rr->preference;
|
---|
5173 | } elsif ($type eq 'TXT') {
|
---|
5174 | ##fixme: Net::DNS docs say this should be deprecated for rdatastr() or char_str_list(),
|
---|
5175 | ## but don't really seem enthusiastic about it.
|
---|
5176 | #print "should use rdatastr:\n\t".$rr->rdatastr."\n or char_str_list:\n\t".join(' ',$rr->char_str_list())."\n";
|
---|
5177 | # rdatastr returns a BIND-targetted logical string, including opening and closing quotes
|
---|
5178 | # char_str_list returns a list of the individual string fragments in the record
|
---|
5179 | # txtdata returns the more useful all-in-one form (since we want to push such protocol
|
---|
5180 | # details as far down the stack as we can)
|
---|
5181 | # NB: this may turn out to be more troublesome if we ever have need of >512-byte TXT records.
|
---|
5182 | $val = $rr->txtdata;
|
---|
5183 | } elsif ($type eq 'SPF') {
|
---|
5184 | ##fixme: and the same caveat here, since it is apparently a clone of ::TXT
|
---|
5185 | $val = $rr->txtdata;
|
---|
5186 | } elsif ($type eq 'AAAA') {
|
---|
5187 | $val = $rr->address;
|
---|
5188 | } elsif ($type eq 'SRV') {
|
---|
5189 | $val = $rr->target;
|
---|
5190 | $distance = $rr->priority;
|
---|
5191 | $weight = $rr->weight;
|
---|
5192 | $port = $rr->port;
|
---|
5193 | $warnmsg .= "Suspect record '".$rr->string."' may not be imported correctly: SRV records may not be bare IP addresses\n"
|
---|
5194 | if $val =~ /^(?:(?:\d+\.){3}\d+|[a-fA-F0-9:]+)$/;
|
---|
5195 | } elsif ($type eq 'KEY') {
|
---|
5196 | # we don't actually know what to do with these...
|
---|
5197 | $val = $rr->flags.":".$rr->protocol.":".$rr->algorithm.":".$rr->key.":".$rr->keytag.":".$rr->privatekeyname;
|
---|
5198 | } else {
|
---|
5199 | $val = $rr->rdatastr;
|
---|
5200 | # Finding a different record type is not fatal.... just problematic.
|
---|
5201 | # We may not be able to export it correctly.
|
---|
5202 | $warnmsg .= "Unusual record ".$rr->name." ($type) found\n";
|
---|
5203 | }
|
---|
5204 |
|
---|
5205 | if ($rev eq 'y' && $type ne 'SOA') {
|
---|
5206 | # up to this point we haven't meddled with the record's hostname part or rdata part.
|
---|
5207 | # for reverse records, (except SOA) we must swap the two.
|
---|
5208 | $host = $val;
|
---|
5209 | $val = $rr->name;
|
---|
5210 | my ($tmpcode,$tmpmsg) = _zone2cidr($val);
|
---|
5211 | if ($tmpcode eq 'FAIL') {
|
---|
5212 | # $val did not have a valid IP value. It's syntactically valid but WTF?
|
---|
5213 | $warnmsg .= "Suspect record '".$rr->string."' may not be imported correctly: $tmpmsg\n";
|
---|
5214 | } else {
|
---|
5215 | # $val has a valid IP value. See if we can store it as that IP value.
|
---|
5216 | # Note we're enumerating do-nothing cases for clarity.
|
---|
5217 | ##enhance: this is where we will implement the more subtle variations on #53
|
---|
5218 | if ($type ne 'PTR' && $type ne 'NS' && $type ne 'CNAME' && $type ne 'TXT') {
|
---|
5219 | # case: the record is "weird" - ie, not a PTR, NS, CNAME, or TXT
|
---|
5220 | # $warnmsg .= "Discarding suspect record '".$rr->string."'\n" if $self->{strict} eq 'full';
|
---|
5221 | } elsif ($type eq 'PTR' && $tmpmsg->masklen != 32 && $tmpmsg->masklen != 128) {
|
---|
5222 | # case: PTR with netblock value, not IP value
|
---|
5223 | # eg, "@ PTR foo" in zone f.e.e.b.d.a.e.d.ip6.arpa should not be
|
---|
5224 | # stored/displayed as dead:beef::/32 PTR foo
|
---|
5225 |
|
---|
5226 | ## hrm. WTF is this case for, anyway? Needs testing to check the logic.
|
---|
5227 | # } elsif ( ($type eq 'PTR' || $type eq 'NS' || $type eq 'CNAME' || $type eq 'TXT') &&
|
---|
5228 | # ($tmpmsg->masklen != $cidr->masklen)
|
---|
5229 | # ) {
|
---|
5230 | # # leave $val as-is if the record is "normal" (a PTR, NS, CNAME, or TXT),
|
---|
5231 | # # and the mask does not match the zone
|
---|
5232 | #$warnmsg .= "WTF case: $host $type $val\n";
|
---|
5233 | # # $warnmsg .= "Discarding suspect record '".$rr->string."'\n" if $self->{strict} eq 'full';
|
---|
5234 |
|
---|
5235 | } else {
|
---|
5236 | $val = $tmpmsg;
|
---|
5237 | $val =~ s/\/(?:32|128)$//; # automagically converts $val back to a string before s///
|
---|
5238 | #$val =~ s/:0$//g;
|
---|
5239 | }
|
---|
5240 | }
|
---|
5241 | # magic? convert * records to PTR template (not sure this actually makes sense)
|
---|
5242 | #if ($val =~ /^\*/) {
|
---|
5243 | # $val =~ s/\*\.//;
|
---|
5244 | # ($tmpcode,$tmpmsg) = _zone2cidr($val);
|
---|
5245 | # if ($tmpcode eq 'FAIL') {
|
---|
5246 | # $val = "*.$val";
|
---|
5247 | # $warnmsg .= "Suspect record '".$rr->string."' may not be converted to PTR template correctly: $tmpmsg\n";
|
---|
5248 | # } else {
|
---|
5249 | # $type = 'PTR template';
|
---|
5250 | # $val = $tmpmsg; if $tmp
|
---|
5251 | # $val =~ s/\/(?:32|128)$//; # automagically converts $val back to a string before s///
|
---|
5252 | # }
|
---|
5253 | #}
|
---|
5254 | } # non-SOA revrec $host/$val inversion and munging
|
---|
5255 |
|
---|
5256 | my $logentry = "[AXFR ".($rev eq 'n' ? $zone : $cidr)."] ";
|
---|
5257 |
|
---|
5258 | if ($args{merge}) {
|
---|
5259 | if ($rev eq 'n') {
|
---|
5260 | # importing a domain; we have A and AAAA records that could be merged with matching PTR records
|
---|
5261 | my $etype;
|
---|
5262 | my ($erdns,$erid,$ettl) = $dbh->selectrow_array("SELECT rdns_id,record_id,ttl FROM records ".
|
---|
5263 | "WHERE host=? AND val=? AND type=12",
|
---|
5264 | undef, ($host, $val) );
|
---|
5265 | if ($erid) {
|
---|
5266 | if ($type eq 'A') { # PTR -> A+PTR
|
---|
5267 | $etype = 65280;
|
---|
5268 | $logentry .= "Merged A record with existing PTR record '$host A+PTR $val', TTL $ettl";
|
---|
5269 | }
|
---|
5270 | if ($type eq 'AAAA') { # PTR -> AAAA+PTR
|
---|
5271 | $etype = 65281;
|
---|
5272 | $logentry .= "Merged AAAA record with existing PTR record '$host AAAA+PTR $val', TTL $ettl";
|
---|
5273 | }
|
---|
5274 | $ettl = ($ettl < $ttl ? $ettl : $ttl); # use lower TTL
|
---|
5275 | $dbh->do("UPDATE records SET domain_id=?,ttl=?,type=? WHERE record_id=?", undef,
|
---|
5276 | ($domain_id, $ettl, $etype, $erid));
|
---|
5277 | $nrecs++;
|
---|
5278 | $self->_log(group_id => $group, domain_id => $domain_id, rdns_id => $erdns, entry => $logentry);
|
---|
5279 | next; # while axfr_next
|
---|
5280 | }
|
---|
5281 | } # $rev eq 'n'
|
---|
5282 | else {
|
---|
5283 | # importing a revzone, we have PTR records that could be merged with matching A/AAAA records
|
---|
5284 | my ($domid,$erid,$ettl,$etype) = $dbh->selectrow_array("SELECT domain_id,record_id,ttl,type FROM records ".
|
---|
5285 | "WHERE host=? AND val=? AND (type=1 OR type=28)",
|
---|
5286 | undef, ($host, $val) );
|
---|
5287 | if ($erid) {
|
---|
5288 | if ($etype == 1) { # A -> A+PTR
|
---|
5289 | $etype = 65280;
|
---|
5290 | $logentry .= "Merged PTR record with existing matching A record '$host A+PTR $val', TTL $ettl";
|
---|
5291 | }
|
---|
5292 | if ($etype == 28) { # AAAA -> AAAA+PTR
|
---|
5293 | $etype = 65281;
|
---|
5294 | $logentry .= "Merged PTR record with existing matching AAAA record '$host AAAA+PTR $val', TTL $ettl";
|
---|
5295 | }
|
---|
5296 | $ettl = ($ettl < $ttl ? $ettl : $ttl); # use lower TTL
|
---|
5297 | $dbh->do("UPDATE records SET rdns_id=?,ttl=?,type=? WHERE record_id=?", undef,
|
---|
5298 | ($rdns_id, $ettl, $etype, $erid));
|
---|
5299 | $nrecs++;
|
---|
5300 | $self->_log(group_id => $group, domain_id => $domid, rdns_id => $rdns_id, entry => $logentry);
|
---|
5301 | next; # while axfr_next
|
---|
5302 | }
|
---|
5303 | } # $rev eq 'y'
|
---|
5304 | } # if $args{merge}
|
---|
5305 |
|
---|
5306 | # Insert the new record
|
---|
5307 | $sth->execute($domain_id, $rdns_id, $host, $reverse_typemap{$type}, $val,
|
---|
5308 | $distance, $weight, $port, $ttl);
|
---|
5309 |
|
---|
5310 | $nrecs++;
|
---|
5311 |
|
---|
5312 | if ($type eq 'SOA') {
|
---|
5313 | # also !$args{rwsoa}, but if that's set, it should be impossible to get here.
|
---|
5314 | my @tmp1 = split /:/, $host;
|
---|
5315 | my @tmp2 = split /:/, $val;
|
---|
5316 | $logentry .= "Added SOA record [contact $tmp1[0]] [master $tmp1[1]] ".
|
---|
5317 | "[refresh $tmp2[0]] [retry $tmp2[1]] [expire $tmp2[2]] [minttl $tmp2[3]], TTL $ttl";
|
---|
5318 | } elsif ($logfrag) {
|
---|
5319 | # special case for log entries we need to meddle with a little.
|
---|
5320 | $logentry .= $logfrag;
|
---|
5321 | } else {
|
---|
5322 | $logentry .= "Added record '".($rev eq 'y' ? $val : $host)." $type";
|
---|
5323 | $logentry .= " [distance $distance]" if $type eq 'MX';
|
---|
5324 | $logentry .= " [priority $distance] [weight $weight] [port $port]" if $type eq 'SRV';
|
---|
5325 | $logentry .= " ".($rev eq 'y' ? $host : $val)."', TTL $ttl";
|
---|
5326 | }
|
---|
5327 | $self->_log(group_id => $group, domain_id => $domain_id, rdns_id => $rdns_id, entry => $logentry);
|
---|
5328 |
|
---|
5329 | } # while axfr_next
|
---|
5330 |
|
---|
5331 | # Detect and handle delegated subzones
|
---|
5332 | # Placeholder for when we decide what to actually do with this, see previous comments in NS and CNAME handling.
|
---|
5333 | #foreach (keys %suboct) {
|
---|
5334 | # print "found ".($suboct{$_}{ns} ? @{$suboct{$_}{ns}} : '0')." NS records and ".
|
---|
5335 | # ($suboct{$_}{cname} ? @{$suboct{$_}{cname}} : '0')." CNAMEs for $_\n";
|
---|
5336 | #}
|
---|
5337 |
|
---|
5338 | # Overwrite SOA record
|
---|
5339 | if ($args{rwsoa}) {
|
---|
5340 | $soaflag = 1;
|
---|
5341 | my $sthgetsoa = $dbh->prepare("SELECT host,val,ttl FROM "._rectable('y', $rev)." WHERE group_id=? AND type=?");
|
---|
5342 | my $sthputsoa = $dbh->prepare("INSERT INTO records (".
|
---|
5343 | ($rev eq 'n' ? 'domain_id' : 'rdns_id').",host,type,val,ttl) VALUES (?,?,?,?,?)");
|
---|
5344 | $sthgetsoa->execute($group,$reverse_typemap{SOA});
|
---|
5345 | while (my ($host,$val,$ttl) = $sthgetsoa->fetchrow_array()) {
|
---|
5346 | if ($rev eq 'n') {
|
---|
5347 | $host =~ s/DOMAIN/$zone/g;
|
---|
5348 | $val =~ s/DOMAIN/$zone/g; # arguably useless
|
---|
5349 | } else {
|
---|
5350 | $host =~ s/ADMINDOMAIN/$self->{domain}/g;
|
---|
5351 | }
|
---|
5352 | $sthputsoa->execute($zone_id,$host,$reverse_typemap{SOA},$val,$ttl);
|
---|
5353 | }
|
---|
5354 | }
|
---|
5355 |
|
---|
5356 | # Add standard NS records. The old one(s) should have been skipped by this point.
|
---|
5357 | if ($args{rwns}) {
|
---|
5358 | $nsflag = 1;
|
---|
5359 | my $sthgetns = $dbh->prepare("SELECT host,val,ttl FROM "._rectable('y',$rev)." WHERE group_id=? AND type=?");
|
---|
5360 | my $sthputns = $dbh->prepare("INSERT INTO records (".
|
---|
5361 | ($rev eq 'n' ? 'domain_id' : 'rdns_id').",host,type,val,ttl) VALUES (?,?,?,?,?)");
|
---|
5362 | $sthgetns->execute($group,$reverse_typemap{NS});
|
---|
5363 | while (my ($host,$val,$ttl) = $sthgetns->fetchrow_array()) {
|
---|
5364 | if ($rev eq 'n') {
|
---|
5365 | $host =~ s/DOMAIN/$zone/g;
|
---|
5366 | $val =~ s/DOMAIN/$zone/g; #hmm.
|
---|
5367 | } else {
|
---|
5368 | $host =~ s/ADMINDOMAIN/$self->{domain}/g; #hmm.
|
---|
5369 | $val =~ s/ZONE/$cidr/g;
|
---|
5370 | }
|
---|
5371 | $sthputns->execute($zone_id,$host,$reverse_typemap{NS},$val,$ttl);
|
---|
5372 | }
|
---|
5373 | }
|
---|
5374 |
|
---|
5375 | die "No records found; either $ifrom is not authoritative or doesn't allow transfers\n" if !$nrecs;
|
---|
5376 | die "Bad zone: No SOA record!\n" if !$soaflag;
|
---|
5377 | die "Bad zone: No NS records!\n" if !$nsflag;
|
---|
5378 |
|
---|
5379 | $dbh->commit;
|
---|
5380 |
|
---|
5381 | };
|
---|
5382 |
|
---|
5383 | if ($@) {
|
---|
5384 | my $msg = $@;
|
---|
5385 | eval { $dbh->rollback; };
|
---|
5386 | return ('FAIL',$msg." $warnmsg");
|
---|
5387 | } else {
|
---|
5388 | return ('WARN', $warnmsg) if $warnmsg;
|
---|
5389 | return ('OK',"Imported OK");
|
---|
5390 | }
|
---|
5391 |
|
---|
5392 | # it should be impossible to get here.
|
---|
5393 | return ('WARN',"OOOK!");
|
---|
5394 | } # end importAXFR()
|
---|
5395 |
|
---|
5396 |
|
---|
5397 | ## DNSDB::importBIND()
|
---|
5398 | sub importBIND {
|
---|
5399 | } # end importBIND()
|
---|
5400 |
|
---|
5401 |
|
---|
5402 | ## DNSDB::import_tinydns()
|
---|
5403 | sub import_tinydns {
|
---|
5404 | } # end import_tinydns()
|
---|
5405 |
|
---|
5406 |
|
---|
5407 | ## DNSDB::export()
|
---|
5408 | # Export the DNS database, or a part of it
|
---|
5409 | # Takes a string indicating the export type, plus optional arguments depending on type
|
---|
5410 | # Writes zone data to targets as appropriate for type
|
---|
5411 | sub export {
|
---|
5412 | my $self = shift;
|
---|
5413 | my $target = shift;
|
---|
5414 |
|
---|
5415 | if ($target eq 'tiny') {
|
---|
5416 | eval {
|
---|
5417 | $self->__export_tiny(@_);
|
---|
5418 | };
|
---|
5419 | if ($@) {
|
---|
5420 | $errstr = $@;
|
---|
5421 | return undef;
|
---|
5422 | }
|
---|
5423 | }
|
---|
5424 | # elsif ($target eq 'foo') {
|
---|
5425 | # __export_foo(@_);
|
---|
5426 | #}
|
---|
5427 | # etc
|
---|
5428 |
|
---|
5429 | return 1;
|
---|
5430 | } # end export()
|
---|
5431 |
|
---|
5432 |
|
---|
5433 | ## DNSDB::__export_tiny
|
---|
5434 | # Internal sub to implement tinyDNS (compatible) export
|
---|
5435 | # Takes filehandle to write export to, optional argument(s)
|
---|
5436 | # to determine which data gets exported
|
---|
5437 | sub __export_tiny {
|
---|
5438 | my $self = shift;
|
---|
5439 | my $dbh = $self->{dbh};
|
---|
5440 | my $datafile = shift;
|
---|
5441 | my $zonefilehandle = $datafile; # makes cache/no-cache a little simpler
|
---|
5442 |
|
---|
5443 | ##fixme: slurp up further options to specify particular zone(s) to export
|
---|
5444 |
|
---|
5445 | ##fixme: fail if $datafile isn't an open, writable file
|
---|
5446 |
|
---|
5447 | # Error check - does the cache dir exist, if we're using one?
|
---|
5448 | if ($self->{usecache}) {
|
---|
5449 | die "Cache directory does not exist\n" if !-e $self->{exportcache};
|
---|
5450 | die "$self->{exportcache} is not a directory\n" if !-d $self->{exportcache};
|
---|
5451 | die "$self->{exportcache} must be both readable and writable\n"
|
---|
5452 | if !-r $self->{exportcache} || !-w $self->{exportcache};
|
---|
5453 | }
|
---|
5454 |
|
---|
5455 | # easy case - export all evarything
|
---|
5456 | # not-so-easy case - export item(s) specified
|
---|
5457 | # todo: figure out what kind of list we use to export items
|
---|
5458 |
|
---|
5459 | # raw packet in unknown format: first byte indicates length
|
---|
5460 | # of remaining data, allows up to 255 raw bytes
|
---|
5461 |
|
---|
5462 | # note: the only I/O failures we seem to be able to actually catch
|
---|
5463 | # here are "closed filehandle" errors. we're probably not writing
|
---|
5464 | # enough data at this point to properly trigger an "out of space"
|
---|
5465 | # error. :/
|
---|
5466 | eval {
|
---|
5467 | use warnings FATAL => ('io');
|
---|
5468 | # Locations/views - worth including in the caching setup?
|
---|
5469 | my $lochash = $dbh->selectall_hashref("SELECT location,iplist FROM locations", 'location');
|
---|
5470 | foreach my $location (keys %$lochash) {
|
---|
5471 | foreach my $ipprefix (split /[,\s]+/, $lochash->{$location}{iplist}) {
|
---|
5472 | $ipprefix =~ s/\s+//g;
|
---|
5473 | $ipprefix = new NetAddr::IP $ipprefix;
|
---|
5474 | ##fixme: how to handle IPv6?
|
---|
5475 | next if $ipprefix->{isv6};
|
---|
5476 | # have to account for /nn CIDR entries. tinydns only speaks octet-sliced prefix.
|
---|
5477 | if ($ipprefix->masklen <= 8) {
|
---|
5478 | foreach ($ipprefix->split(8)) {
|
---|
5479 | my $tmp = $_->addr;
|
---|
5480 | $tmp =~ s/\.\d+\.\d+\.\d+$//;
|
---|
5481 | print $datafile "%$location:$tmp\n";
|
---|
5482 | }
|
---|
5483 | } elsif ($ipprefix->masklen <= 16) {
|
---|
5484 | foreach ($ipprefix->split(16)) {
|
---|
5485 | my $tmp = $_->addr;
|
---|
5486 | $tmp =~ s/\.\d+\.\d+$//;
|
---|
5487 | print $datafile "%$location:$tmp\n";
|
---|
5488 | }
|
---|
5489 | } elsif ($ipprefix->masklen <= 24) {
|
---|
5490 | foreach ($ipprefix->split(24)) {
|
---|
5491 | my $tmp = $_->addr;
|
---|
5492 | $tmp =~ s/\.\d+$//;
|
---|
5493 | print $datafile "%$location:$tmp\n";
|
---|
5494 | }
|
---|
5495 | } else {
|
---|
5496 | foreach ($ipprefix->split(32)) {
|
---|
5497 | print $datafile "%$location:".$_->addr."\n";
|
---|
5498 | }
|
---|
5499 | }
|
---|
5500 | }
|
---|
5501 | print $datafile "%$location\n" if !$lochash->{$location}{iplist};
|
---|
5502 | }
|
---|
5503 | };
|
---|
5504 | if ($@) {
|
---|
5505 | die "Error writing locations to master file: $@, $!\n";
|
---|
5506 | }
|
---|
5507 |
|
---|
5508 | # tracking hash so we don't double-export A+PTR or AAAA+PTR records.
|
---|
5509 | my %recflags;
|
---|
5510 |
|
---|
5511 | # For reasons unknown, we can't sanely UNION these statements. Feh.
|
---|
5512 | # Supposedly it should work though (note last 3 lines):
|
---|
5513 | ## PG manual
|
---|
5514 | #UNION Clause
|
---|
5515 | #
|
---|
5516 | #The UNION clause has this general form:
|
---|
5517 | #
|
---|
5518 | # select_statement UNION [ ALL ] select_statement
|
---|
5519 | #
|
---|
5520 | #select_statement is any SELECT statement without an ORDER BY, LIMIT, FOR UPDATE, or FOR SHARE clause. (ORDER BY
|
---|
5521 | #and LIMIT can be attached to a subexpression if it is enclosed in parentheses. Without parentheses, these
|
---|
5522 | #clauses will be taken to apply to the result of the UNION, not to its right-hand input expression.)
|
---|
5523 | my $soasth = $dbh->prepare("SELECT host,type,val,distance,weight,port,ttl,record_id,location ".
|
---|
5524 | "FROM records WHERE rdns_id=? AND type=6");
|
---|
5525 | my $recsth = $dbh->prepare("SELECT host,type,val,distance,weight,port,ttl,record_id,location,extract(epoch from stamp),expires,stampactive ".
|
---|
5526 | "FROM records WHERE rdns_id=? AND NOT type=6 ".
|
---|
5527 | "ORDER BY masklen(inetlazy(val)) DESC, inetlazy(val)");
|
---|
5528 | my $revsth = $dbh->prepare("SELECT rdns_id,revnet,status,changed FROM revzones WHERE status=1 ".
|
---|
5529 | "ORDER BY masklen(revnet) DESC, rdns_id");
|
---|
5530 | my $zonesth = $dbh->prepare("UPDATE revzones SET changed='n' WHERE rdns_id=?");
|
---|
5531 | $revsth->execute();
|
---|
5532 | while (my ($revid,$revzone,$revstat,$changed) = $revsth->fetchrow_array) {
|
---|
5533 | ##fixme: need to find a way to block opening symlinked files without introducing a race.
|
---|
5534 | # O_NOFOLLOW
|
---|
5535 | # If pathname is a symbolic link, then the open fails. This is a FreeBSD extension, which was
|
---|
5536 | # added to Linux in version 2.1.126. Symbolic links in earlier components of the pathname will
|
---|
5537 | # still be followed.
|
---|
5538 | # but that doesn't help other platforms. :/
|
---|
5539 | my $tmpzone = NetAddr::IP->new($revzone);
|
---|
5540 | ##fixme: locations/views? subnet mask? need to avoid possible collisions with zone/superzone
|
---|
5541 | ## (eg /20 vs /24, starting on .0.0)
|
---|
5542 | my $cz = $tmpzone->network->addr."-".$tmpzone->masklen;
|
---|
5543 | my $cachefile = "$self->{exportcache}/$cz";
|
---|
5544 | my $tmpcache = "$self->{exportcache}/tmp.$cz.$$";
|
---|
5545 | eval {
|
---|
5546 |
|
---|
5547 | # write fresh records if:
|
---|
5548 | # - we are not using the cache
|
---|
5549 | # - force_refresh is set
|
---|
5550 | # - the zone has changed
|
---|
5551 | # - the cache file does not exist
|
---|
5552 | # - the cache file is empty
|
---|
5553 | if (!$self->{usecache} || $self->{force_refresh} || $changed || !-e $cachefile || -z $cachefile) {
|
---|
5554 | if ($self->{usecache}) {
|
---|
5555 | open ZONECACHE, ">$tmpcache" or die "Error creating temporary file $tmpcache: $!\n";
|
---|
5556 | $zonefilehandle = *ZONECACHE;
|
---|
5557 | }
|
---|
5558 |
|
---|
5559 | # need to fetch this separately since the rest of the records all (should) have real IPs in val
|
---|
5560 | $soasth->execute($revid);
|
---|
5561 | my (@zsoa) = $soasth->fetchrow_array();
|
---|
5562 | $self->_printrec_tiny($zonefilehandle, $zsoa[7], 'y',\%recflags,$revzone,
|
---|
5563 | $zsoa[0],$zsoa[1],$zsoa[2],$zsoa[3],$zsoa[4],$zsoa[5],$zsoa[6],$zsoa[8],'');
|
---|
5564 |
|
---|
5565 | $recsth->execute($revid);
|
---|
5566 | my $fullzone = _ZONE($tmpzone, 'ZONE', 'r', '.').($tmpzone->{isv6} ? '.ip6.arpa' : '.in-addr.arpa');
|
---|
5567 |
|
---|
5568 | while (my ($host, $type, $val, $dist, $weight, $port, $ttl, $recid, $loc, $stamp, $expires, $stampactive)
|
---|
5569 | = $recsth->fetchrow_array) {
|
---|
5570 | next if $recflags{$recid};
|
---|
5571 |
|
---|
5572 | # Check for out-of-zone data
|
---|
5573 | if ($val =~ /\.arpa$/) {
|
---|
5574 | # val is non-IP
|
---|
5575 | if ($val !~ /$fullzone$/) {
|
---|
5576 | warn "Not exporting out-of-zone record $val $typemap{$type} $host, $ttl (zone $tmpzone)\n";
|
---|
5577 | next;
|
---|
5578 | }
|
---|
5579 | } else {
|
---|
5580 | my $ipval = new NetAddr::IP $val;
|
---|
5581 | if (!$tmpzone->contains($ipval)) {
|
---|
5582 | warn "Not exporting out-of-zone record $val $typemap{$type} $host, $ttl (zone $tmpzone)\n";
|
---|
5583 | next;
|
---|
5584 | }
|
---|
5585 | } # is $val a raw .arpa name?
|
---|
5586 |
|
---|
5587 | # Spaces are evil.
|
---|
5588 | $val =~ s/^\s+//;
|
---|
5589 | $val =~ s/\s+$//;
|
---|
5590 | if ($typemap{$type} ne 'TXT') {
|
---|
5591 | # Leading or trailng spaces could be legit in TXT records.
|
---|
5592 | $host =~ s/^\s+//;
|
---|
5593 | $host =~ s/\s+$//;
|
---|
5594 | }
|
---|
5595 |
|
---|
5596 | $self->_printrec_tiny($zonefilehandle, $recid, 'y', \%recflags, $revzone,
|
---|
5597 | $host, $type, $val, $dist, $weight, $port, $ttl, $loc, $stamp, $expires, $stampactive);
|
---|
5598 |
|
---|
5599 | $recflags{$recid} = 1;
|
---|
5600 |
|
---|
5601 | } # while ($recsth)
|
---|
5602 |
|
---|
5603 | if ($self->{usecache}) {
|
---|
5604 | close ZONECACHE; # force the file to be written
|
---|
5605 | # catch obvious write errors that leave an empty temp file
|
---|
5606 | if (-s $tmpcache) {
|
---|
5607 | rename $tmpcache, $cachefile
|
---|
5608 | or die "Error overwriting cache file $cachefile with temporary file: $!\n";
|
---|
5609 | }
|
---|
5610 | }
|
---|
5611 |
|
---|
5612 | } # if $changed or cache filesize is 0
|
---|
5613 |
|
---|
5614 | };
|
---|
5615 | if ($@) {
|
---|
5616 | die "error writing ".($self->{usecache} ? 'new data for ' : '')."$revzone: $@\n";
|
---|
5617 | # error! something borked, and we should be able to fall back on the old cache file
|
---|
5618 | # report the error, somehow.
|
---|
5619 | } else {
|
---|
5620 | # mark zone as unmodified. Only do this if no errors, that way
|
---|
5621 | # export failures should recover a little more automatically.
|
---|
5622 | $zonesth->execute($revid);
|
---|
5623 | }
|
---|
5624 |
|
---|
5625 | if ($self->{usecache}) {
|
---|
5626 | # We've already made as sure as we can that a cached zone file is "good",
|
---|
5627 | # although possibly stale/obsolete due to errors creating a new one.
|
---|
5628 | eval {
|
---|
5629 | open CACHE, "<$cachefile" or die $!;
|
---|
5630 | print $datafile $_ or die "error copying cached $revzone to master file: $!" while <CACHE>;
|
---|
5631 | close CACHE;
|
---|
5632 | };
|
---|
5633 | die $@ if $@;
|
---|
5634 | }
|
---|
5635 |
|
---|
5636 | } # while ($revsth)
|
---|
5637 |
|
---|
5638 | $soasth = $dbh->prepare("SELECT host,type,val,distance,weight,port,ttl,record_id,location ".
|
---|
5639 | "FROM records WHERE domain_id=? AND type=6");
|
---|
5640 | $recsth = $dbh->prepare("SELECT host,type,val,distance,weight,port,ttl,record_id,location,extract(epoch from stamp),expires,stampactive ".
|
---|
5641 | "FROM records WHERE domain_id=? AND NOT type=6"); # Just exclude all types relating to rDNS
|
---|
5642 | # "FROM records WHERE domain_id=? AND type < 65280"); # Just exclude all types relating to rDNS
|
---|
5643 | my $domsth = $dbh->prepare("SELECT domain_id,domain,status,changed FROM domains WHERE status=1 ORDER BY domain_id");
|
---|
5644 | $zonesth = $dbh->prepare("UPDATE domains SET changed='n' WHERE domain_id=?");
|
---|
5645 | $domsth->execute();
|
---|
5646 | while (my ($domid,$dom,$domstat,$changed) = $domsth->fetchrow_array) {
|
---|
5647 | ##fixme: need to find a way to block opening symlinked files without introducing a race.
|
---|
5648 | # O_NOFOLLOW
|
---|
5649 | # If pathname is a symbolic link, then the open fails. This is a FreeBSD extension, which was
|
---|
5650 | # added to Linux in version 2.1.126. Symbolic links in earlier components of the pathname will
|
---|
5651 | # still be followed.
|
---|
5652 | # but that doesn't help other platforms. :/
|
---|
5653 | my $cachefile = "$self->{exportcache}/$dom";
|
---|
5654 | my $tmpcache = "$self->{exportcache}/tmp.$dom.$$";
|
---|
5655 | eval {
|
---|
5656 |
|
---|
5657 | # write fresh records if:
|
---|
5658 | # - we are not using the cache
|
---|
5659 | # - force_refresh is set
|
---|
5660 | # - the zone has changed
|
---|
5661 | # - the cache file does not exist
|
---|
5662 | # - the cache file is empty
|
---|
5663 | if (!$self->{usecache} || $self->{force_refresh} || $changed || !-e $cachefile || -z $cachefile) {
|
---|
5664 | if ($self->{usecache}) {
|
---|
5665 | open ZONECACHE, ">$tmpcache" or die "Error creating temporary file $tmpcache: $!\n";
|
---|
5666 | $zonefilehandle = *ZONECACHE;
|
---|
5667 | }
|
---|
5668 |
|
---|
5669 | # need to fetch this separately so the SOA comes first in the flatfile....
|
---|
5670 | # Just In Case we need/want to reimport from the flatfile later on.
|
---|
5671 | $soasth->execute($domid);
|
---|
5672 | my (@zsoa) = $soasth->fetchrow_array();
|
---|
5673 | $self->_printrec_tiny($zonefilehandle, $zsoa[7], 'n',\%recflags,$dom,
|
---|
5674 | $zsoa[0],$zsoa[1],$zsoa[2],$zsoa[3],$zsoa[4],$zsoa[5],$zsoa[6],$zsoa[8],'');
|
---|
5675 |
|
---|
5676 | $recsth->execute($domid);
|
---|
5677 | while (my ($host,$type,$val,$dist,$weight,$port,$ttl,$recid,$loc,$stamp,$expires,$stampactive) = $recsth->fetchrow_array) {
|
---|
5678 | next if $recflags{$recid};
|
---|
5679 |
|
---|
5680 | # Check for out-of-zone data
|
---|
5681 | if ($host !~ /$dom$/) {
|
---|
5682 | warn "Not exporting out-of-zone record $host $type $val, $ttl (zone $dom)\n";
|
---|
5683 | next;
|
---|
5684 | }
|
---|
5685 |
|
---|
5686 | # Spaces are evil.
|
---|
5687 | $host =~ s/^\s+//;
|
---|
5688 | $host =~ s/\s+$//;
|
---|
5689 | if ($typemap{$type} ne 'TXT') {
|
---|
5690 | # Leading or trailng spaces could be legit in TXT records.
|
---|
5691 | $val =~ s/^\s+//;
|
---|
5692 | $val =~ s/\s+$//;
|
---|
5693 | }
|
---|
5694 |
|
---|
5695 | $self->_printrec_tiny($zonefilehandle, $recid, 'n', \%recflags,
|
---|
5696 | $dom, $host, $type, $val, $dist, $weight, $port, $ttl, $loc, $stamp, $expires, $stampactive);
|
---|
5697 |
|
---|
5698 | $recflags{$recid} = 1;
|
---|
5699 |
|
---|
5700 | } # while ($recsth)
|
---|
5701 |
|
---|
5702 |
|
---|
5703 | if ($self->{usecache}) {
|
---|
5704 | close ZONECACHE; # force the file to be written
|
---|
5705 | # catch obvious write errors that leave an empty temp file
|
---|
5706 | if (-s $tmpcache) {
|
---|
5707 | rename $tmpcache, $cachefile
|
---|
5708 | or die "Error overwriting cache file $cachefile with temporary file: $!\n";
|
---|
5709 | }
|
---|
5710 | }
|
---|
5711 |
|
---|
5712 | } # if $changed or cache filesize is 0
|
---|
5713 |
|
---|
5714 | };
|
---|
5715 | if ($@) {
|
---|
5716 | die "error writing ".($self->{usecache} ? 'new data for ' : '')."$dom: $@\n";
|
---|
5717 | # error! something borked, and we should be able to fall back on the old cache file
|
---|
5718 | # report the error, somehow.
|
---|
5719 | } else {
|
---|
5720 | # mark domain as unmodified. Only do this if no errors, that way
|
---|
5721 | # export failures should recover a little more automatically.
|
---|
5722 | $zonesth->execute($domid);
|
---|
5723 | }
|
---|
5724 |
|
---|
5725 | if ($self->{usecache}) {
|
---|
5726 | # We've already made as sure as we can that a cached zone file is "good",
|
---|
5727 | # although possibly stale/obsolete due to errors creating a new one.
|
---|
5728 | eval {
|
---|
5729 | open CACHE, "<$cachefile" or die $!;
|
---|
5730 | print $datafile $_ or die "error copying cached $dom to master file: $!" while <CACHE>;
|
---|
5731 | close CACHE;
|
---|
5732 | };
|
---|
5733 | die $@ if $@;
|
---|
5734 | }
|
---|
5735 |
|
---|
5736 | } # while ($domsth)
|
---|
5737 |
|
---|
5738 | return 1;
|
---|
5739 | } # end __export_tiny()
|
---|
5740 |
|
---|
5741 |
|
---|
5742 | # Utility sub for __export_tiny above
|
---|
5743 | sub _printrec_tiny {
|
---|
5744 | my $self = shift;
|
---|
5745 | my ($datafile, $recid, $revrec, $recflags, $zone, $host, $type, $val, $dist, $weight, $port, $ttl,
|
---|
5746 | $loc, $stamp, $expires, $stampactive) = @_;
|
---|
5747 |
|
---|
5748 | $loc = '' if !$loc; # de-nullify - just in case
|
---|
5749 | ##fixme: handle case of record-with-location-that-doesn't-exist better.
|
---|
5750 | # note this currently fails safe (tested) - records with a location that
|
---|
5751 | # doesn't exist will not be sent to any client
|
---|
5752 | # $loc = '' if !$lochash->{$loc};
|
---|
5753 |
|
---|
5754 |
|
---|
5755 | ## Records that are valid only before or after a set time
|
---|
5756 |
|
---|
5757 | # record due to expire sometime is the complex case. we don't want to just
|
---|
5758 | # rely on tinydns' auto-adjusting TTLs, because the default TTL in that case
|
---|
5759 | # is one day instead of the SOA minttl as BIND might do.
|
---|
5760 |
|
---|
5761 | # consider the case where a record is set to expire a week ahead, but the next
|
---|
5762 | # day later you want to change it NOW (or as NOWish as you get with your DNS
|
---|
5763 | # management practice). but now you're stuck, because someone, somewhere,
|
---|
5764 | # has just done a lookup before your latest change was published, and they'll
|
---|
5765 | # be caching that old, broken record for 1 day instead of your zone default
|
---|
5766 | # TTL.
|
---|
5767 |
|
---|
5768 | # $stamp-$ttl is the *latest* we can publish the record with the defined TTL
|
---|
5769 | # to still have the expiry happen as scheduled, but we need to find some
|
---|
5770 | # *earlier* point. We can maybe guess, and 2x TTL is probably reasonable,
|
---|
5771 | # but we need info on the export frequency.
|
---|
5772 |
|
---|
5773 | # export the normal, non-expiring record up until $stamp-<guesstimate>, then
|
---|
5774 | # switch to exporting a record with the TAI64 stamp and a 0 TTL so tinydns
|
---|
5775 | # takes over TTL management.
|
---|
5776 |
|
---|
5777 | if ($stampactive) {
|
---|
5778 | if ($expires) {
|
---|
5779 | # record expires at $stamp; decide if we need to keep the TTL and ignore
|
---|
5780 | # the stamp for a time or if we need to change the TTL to 0 and convert
|
---|
5781 | # $stamp to TAI64 so tinydns can use $stamp to autoadjust the TTL on the fly.
|
---|
5782 | # extra hack, optimally needs more knowledge of data export frequency
|
---|
5783 | # smack the idiot customer who insists on 0 TTLs; they can suck up and
|
---|
5784 | # deal with a 10-minute TTL. especially on scheduled changes. note this
|
---|
5785 | # should be (export freq * 2), but we don't know the actual export frequency.
|
---|
5786 | $ttl = 300 if $ttl == 0; #hack phtui
|
---|
5787 | my $ahead = (86400 < $ttl*2 ? 86400 : $ttl*2);
|
---|
5788 | if ((time() + $ahead) < $stamp) {
|
---|
5789 | # more than 2x TTL OR more than one day (whichever is less) from expiry time; publish normal record
|
---|
5790 | $stamp = '';
|
---|
5791 | } else {
|
---|
5792 | # less than 2x TTL from expiry time, let tinydns take over TTL management and publish the TAI64 stamp.
|
---|
5793 | $ttl = 0;
|
---|
5794 | $stamp = unixtai64($stamp);
|
---|
5795 | $stamp =~ s/\@//;
|
---|
5796 | }
|
---|
5797 | } else {
|
---|
5798 | # record is "active after"; convert epoch from database to TAI64, publish, and collect $200.
|
---|
5799 | $stamp = unixtai64($stamp);
|
---|
5800 | $stamp =~ s/\@//;
|
---|
5801 | }
|
---|
5802 | } else {
|
---|
5803 | # flag for active timestamp is false; don't actually put a timestamp in the output
|
---|
5804 | $stamp = '';
|
---|
5805 | }
|
---|
5806 |
|
---|
5807 | # support tinydns' auto-TTL
|
---|
5808 | $ttl = '' if $ttl == -1;
|
---|
5809 | # these are WAY FREAKING HIGH - higher even than most TLD registry TTLs!
|
---|
5810 | # NS 259200 => 3d
|
---|
5811 | # all others 86400 => 1d
|
---|
5812 |
|
---|
5813 | if ($revrec eq 'y') {
|
---|
5814 | $val = $zone if $val eq '@';
|
---|
5815 | } else {
|
---|
5816 | $host = $zone if $host eq '@';
|
---|
5817 | }
|
---|
5818 |
|
---|
5819 | ## Convert a bare number into an octal-coded pair of octets.
|
---|
5820 | # Take optional arg to indicate a decimal or hex input. Defaults to hex.
|
---|
5821 | sub octalize {
|
---|
5822 | my $tmp = shift;
|
---|
5823 | my $srctype = shift || 'h'; # default assumes hex string
|
---|
5824 | $tmp = sprintf "%0.4x", hex($tmp) if $srctype eq 'h'; # 0-pad hex to 4 digits
|
---|
5825 | $tmp = sprintf "%0.4x", $tmp if $srctype eq 'd'; # 0-pad decimal to 4 hex digits
|
---|
5826 | my @o = ($tmp =~ /^(..)(..)$/); # split into octets
|
---|
5827 | return sprintf "\\%0.3o\\%0.3o", hex($o[0]), hex($o[1]);;
|
---|
5828 | }
|
---|
5829 |
|
---|
5830 | # Utility sub-sub for reverse records; with "any-record-in-any-zone"
|
---|
5831 | # we may need to do extra processing on $val to make it publishable.
|
---|
5832 | sub __revswap {
|
---|
5833 | my $host = shift;
|
---|
5834 | my $val = shift;
|
---|
5835 | return ($val, $host) if $val =~ /\.arpa/;
|
---|
5836 | $val = new NetAddr::IP $val;
|
---|
5837 | my $newval = _ZONE($val, 'ZONE', 'r', '.').($val->{isv6} ? '.ip6.arpa' : '.in-addr.arpa');
|
---|
5838 | return ($newval, $host);
|
---|
5839 | }
|
---|
5840 |
|
---|
5841 | ## WARNING: This works to export even the whole Internet's worth of IP space...
|
---|
5842 | ## if you have the disk/RAM to handle the dataset, and you call this sub based on /16-sized chunks
|
---|
5843 | ## A /16 took ~3 seconds with a handful of separate records; adding a /8 pushed export time out to ~13m:40s
|
---|
5844 | ## 0/0 is estimated to take ~54 hours and ~256G of disk
|
---|
5845 | ## RAM usage depends on how many non-template entries you have in the set.
|
---|
5846 | ## This should probably be done on record addition rather than export; large blocks may need to be done in a
|
---|
5847 | ## forked process
|
---|
5848 | sub __publish_subnet {
|
---|
5849 | my $obj = shift; # *sigh* need to pass in the DNSDB object so we can read a couple of options
|
---|
5850 | my $sub = shift;
|
---|
5851 | my $recflags = shift;
|
---|
5852 | my $hpat = shift;
|
---|
5853 | my $fh = shift;
|
---|
5854 | my $ttl = shift;
|
---|
5855 | my $stamp = shift;
|
---|
5856 | my $loc = shift;
|
---|
5857 | my $zone = new NetAddr::IP shift;
|
---|
5858 | my $ptronly = shift || 0;
|
---|
5859 |
|
---|
5860 | # do this conversion once, not (number-of-ips-in-subnet) times
|
---|
5861 | my $arpabase = _ZONE($zone, 'ZONE.in-addr.arpa', 'r', '.');
|
---|
5862 |
|
---|
5863 | my $iplist = $sub->splitref(32);
|
---|
5864 | foreach (@$iplist) {
|
---|
5865 | my $ip = $_->addr;
|
---|
5866 | # make as if we split the non-octet-aligned block into octet-aligned blocks as with SOA
|
---|
5867 | my $lastoct = (split /\./, $ip)[3];
|
---|
5868 | next if $ip =~ /\.0$/ && $obj->{template_skip_0};
|
---|
5869 | next if $ip =~ /\.255$/ && $obj->{template_skip_255};
|
---|
5870 | next if $$recflags{$ip}; # && $self->{skip_bcast_255}
|
---|
5871 | $$recflags{$ip}++;
|
---|
5872 | next if $hpat eq '%blank%'; # Allows blanking a subnet so no records are published.
|
---|
5873 | my $rec = $hpat; # start fresh with the template for each IP
|
---|
5874 | ##fixme: there really isn't a good way to handle sub-/24 zones here. This way at least
|
---|
5875 | # seems less bad than some alternatives.
|
---|
5876 | _template4_expand(\$rec, $ip);
|
---|
5877 | if ($ptronly || $zone->masklen > 24) {
|
---|
5878 | print $fh "^$lastoct.$arpabase:$rec:$ttl:$stamp:$loc\n" or die $!;
|
---|
5879 | if (!$ptronly) {
|
---|
5880 | # print a separate A record. Arguably we could use an = record here instead.
|
---|
5881 | print $fh "+$rec:$ip:$ttl:$stamp:$loc\n" or die $!;
|
---|
5882 | }
|
---|
5883 | } else {
|
---|
5884 | print $fh "=$rec:$ip:$ttl:$stamp:$loc\n" or die $!;
|
---|
5885 | }
|
---|
5886 | }
|
---|
5887 | }
|
---|
5888 |
|
---|
5889 | ## And now the meat.
|
---|
5890 |
|
---|
5891 | ##fixme? append . to all host/val hostnames
|
---|
5892 | #print "debug: rawdata: $host $typemap{$type} $val\n";
|
---|
5893 |
|
---|
5894 | if ($typemap{$type} eq 'SOA') {
|
---|
5895 | # host contains pri-ns:responsible
|
---|
5896 | # val is abused to contain refresh:retry:expire:minttl
|
---|
5897 | ##fixme: "manual" serial vs tinydns-autoserial
|
---|
5898 | # let's be explicit about abusing $host and $val
|
---|
5899 | my ($email, $primary) = (split /:/, $host)[0,1];
|
---|
5900 | my ($refresh, $retry, $expire, $min_ttl) = (split /:/, $val)[0,1,2,3];
|
---|
5901 | if ($revrec eq 'y') {
|
---|
5902 | ##fixme: have to publish SOA records for each v4 /24 in sub-/16, and each /16 in sub-/8
|
---|
5903 | # what about v6?
|
---|
5904 | # -> only need SOA for local chunks offset from reverse delegation boundaries, so v6 is fine
|
---|
5905 | # anyone who says they need sub-nibble v6 delegations, at this time, needs their head examined.
|
---|
5906 | $zone = NetAddr::IP->new($zone);
|
---|
5907 | # handle split-n-multiply SOA for off-octet (8 < mask < 16) or (16 < mask < 24) v4 zones
|
---|
5908 | if (!$zone->{isv6} && ($zone->masklen < 24) && ($zone->masklen % 8 != 0)) {
|
---|
5909 | foreach my $szone ($zone->split($zone->masklen + (8 - $zone->masklen % 8))) {
|
---|
5910 | $szone = _ZONE($szone, 'ZONE.in-addr.arpa', 'r', '.');
|
---|
5911 | print $datafile "Z$szone:$primary:$email"."::$refresh:$retry:$expire:$min_ttl:$ttl:$stamp:$loc\n"
|
---|
5912 | or die $!;
|
---|
5913 | }
|
---|
5914 | return; # skips "default" bits just below
|
---|
5915 | }
|
---|
5916 | $zone = _ZONE($zone, 'ZONE', 'r', '.').($zone->{isv6} ? '.ip6.arpa' : '.in-addr.arpa');
|
---|
5917 | }
|
---|
5918 | print $datafile "Z$zone:$primary:$email"."::$refresh:$retry:$expire:$min_ttl:$ttl:$stamp:$loc\n"
|
---|
5919 | or die $!;
|
---|
5920 |
|
---|
5921 | } elsif ($typemap{$type} eq 'A') {
|
---|
5922 |
|
---|
5923 | ($host,$val) = __revswap($host,$val) if $revrec eq 'y';
|
---|
5924 | print $datafile "+$host:$val:$ttl:$stamp:$loc\n" or die $!;
|
---|
5925 |
|
---|
5926 | } elsif ($typemap{$type} eq 'NS') {
|
---|
5927 |
|
---|
5928 | if ($revrec eq 'y') {
|
---|
5929 | $val = NetAddr::IP->new($val);
|
---|
5930 | # handle split-n-multiply SOA for off-octet (8 < mask < 16) or (16 < mask < 24) v4 zones
|
---|
5931 | if (!$val->{isv6} && ($val->masklen < 24) && ($val->masklen % 8 != 0)) {
|
---|
5932 | foreach my $szone ($val->split($val->masklen + (8 - $val->masklen % 8))) {
|
---|
5933 | my $szone2 = _ZONE($szone, 'ZONE.in-addr.arpa', 'r', '.');
|
---|
5934 | next if $$recflags{$szone2} && $$recflags{$szone2} > $val->masklen;
|
---|
5935 | print $datafile "\&$szone2"."::$host:$ttl:$stamp:$loc\n" or die $!;
|
---|
5936 | $$recflags{$szone2} = $val->masklen;
|
---|
5937 | }
|
---|
5938 | } elsif ($val->{isv6} && ($val->masklen < 64) && ($val->masklen % 4 !=0)) {
|
---|
5939 | foreach my $szone ($val->split($val->masklen + (4 - $val->masklen % 4))) {
|
---|
5940 | my $szone2 = _ZONE($szone, 'ZONE.ip6.arpa', 'r', '.');
|
---|
5941 | next if $$recflags{$szone2} && $$recflags{$szone2} > $val->masklen;
|
---|
5942 | print $datafile "\&$szone2"."::$host:$ttl:$stamp:$loc\n" or die $!;
|
---|
5943 | $$recflags{$szone2} = $val->masklen;
|
---|
5944 | }
|
---|
5945 | } else {
|
---|
5946 | my $val2 = _ZONE($val, 'ZONE', 'r', '.').($val->{isv6} ? '.ip6.arpa' : '.in-addr.arpa');
|
---|
5947 | print $datafile "\&$val2"."::$host:$ttl:$stamp:$loc\n" or die $!;
|
---|
5948 | $$recflags{$val2} = $val->masklen;
|
---|
5949 | }
|
---|
5950 | } else {
|
---|
5951 | print $datafile "\&$host"."::$val:$ttl:$stamp:$loc\n" or die $!;
|
---|
5952 | }
|
---|
5953 |
|
---|
5954 | } elsif ($typemap{$type} eq 'AAAA') {
|
---|
5955 |
|
---|
5956 | ($host,$val) = __revswap($host,$val) if $revrec eq 'y';
|
---|
5957 | my $altgrp = 0;
|
---|
5958 | my @altconv;
|
---|
5959 | # Split in to up to 8 groups of hex digits (allows for IPv6 :: 0-collapsing)
|
---|
5960 | foreach (split /:/, $val) {
|
---|
5961 | if (/^$/) {
|
---|
5962 | # flag blank entry; this is a series of 0's of (currently) unknown length
|
---|
5963 | $altconv[$altgrp++] = 's';
|
---|
5964 | } else {
|
---|
5965 | # call sub to convert 1-4 hex digits to 2 string-rep octal bytes
|
---|
5966 | $altconv[$altgrp++] = octalize($_)
|
---|
5967 | }
|
---|
5968 | }
|
---|
5969 | my $prefix = ":$host:28:";
|
---|
5970 | foreach my $octet (@altconv) {
|
---|
5971 | # if not 's', output
|
---|
5972 | $prefix .= $octet unless $octet =~ /^s$/;
|
---|
5973 | # if 's', output (9-array length)x literal '\000\000'
|
---|
5974 | $prefix .= '\000\000'x(9-$altgrp) if $octet =~ /^s$/;
|
---|
5975 | }
|
---|
5976 | print $datafile "$prefix:$ttl:$stamp:$loc\n" or die $!;
|
---|
5977 |
|
---|
5978 | } elsif ($typemap{$type} eq 'MX') {
|
---|
5979 |
|
---|
5980 | ($host,$val) = __revswap($host,$val) if $revrec eq 'y';
|
---|
5981 | print $datafile "\@$host"."::$val:$dist:$ttl:$stamp:$loc\n" or die $!;
|
---|
5982 |
|
---|
5983 | } elsif ($typemap{$type} eq 'TXT') {
|
---|
5984 |
|
---|
5985 | ($host,$val) = __revswap($host,$val) if $revrec eq 'y';
|
---|
5986 | ##fixme: split v-e-r-y long TXT strings? will need to do so for BIND export, at least
|
---|
5987 | $val =~ s/:/\\072/g; # may need to replace other symbols
|
---|
5988 | print $datafile "'$host:$val:$ttl:$stamp:$loc\n" or die $!;
|
---|
5989 |
|
---|
5990 | # by-hand TXT
|
---|
5991 | #:deepnet.cx:16:2v\075spf1\040a\040a\072bacon.deepnet.cx\040a\072home.deepnet.cx\040-all:3600
|
---|
5992 | #@ IN TXT "v=spf1 a a:bacon.deepnet.cx a:home.deepnet.cx -all"
|
---|
5993 | #'deepnet.cx:v=spf1 a a\072bacon.deepnet.cx a\072home.deepnet.cx -all:3600
|
---|
5994 |
|
---|
5995 | #txttest IN TXT "v=foo bar:bob kn;ob' \" !@#$%^&*()-=_+[]{}<>?"
|
---|
5996 | #: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
|
---|
5997 |
|
---|
5998 | # very long TXT record as brought in by axfr-get
|
---|
5999 | # note tinydns does not support >512-byte RR data, need axfr-dns (for TCP support) for that
|
---|
6000 | # also note, tinydns does not seem to support <512, >256-byte RRdata from axfr-get either. :/
|
---|
6001 | #:longtxt.deepnet.cx:16:
|
---|
6002 | #\170this is a very long txt record. it is really long. long. very long. really very long. this is a very long txt record.
|
---|
6003 | #\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.
|
---|
6004 | #\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.
|
---|
6005 | #:3600
|
---|
6006 |
|
---|
6007 | } elsif ($typemap{$type} eq 'CNAME') {
|
---|
6008 |
|
---|
6009 | ($host,$val) = __revswap($host,$val) if $revrec eq 'y';
|
---|
6010 | print $datafile "C$host:$val:$ttl:$stamp:$loc\n" or die $!;
|
---|
6011 |
|
---|
6012 | } elsif ($typemap{$type} eq 'SRV') {
|
---|
6013 |
|
---|
6014 | ($host,$val) = __revswap($host,$val) if $revrec eq 'y';
|
---|
6015 |
|
---|
6016 | # data is two-byte values for priority, weight, port, in that order,
|
---|
6017 | # followed by length/string data
|
---|
6018 |
|
---|
6019 | my $prefix = ":$host:33:".octalize($dist,'d').octalize($weight,'d').octalize($port,'d');
|
---|
6020 |
|
---|
6021 | $val .= '.' if $val !~ /\.$/;
|
---|
6022 | foreach (split /\./, $val) {
|
---|
6023 | $prefix .= sprintf "\\%0.3o%s", length($_), $_ or die $!;
|
---|
6024 | }
|
---|
6025 | print $datafile "$prefix\\000:$ttl:$stamp:$loc\n" or die $!;
|
---|
6026 |
|
---|
6027 | } elsif ($typemap{$type} eq 'RP') {
|
---|
6028 |
|
---|
6029 | ($host,$val) = __revswap($host,$val) if $revrec eq 'y';
|
---|
6030 | # RP consists of two mostly free-form strings.
|
---|
6031 | # The first is supposed to be an email address with @ replaced by . (as with the SOA contact)
|
---|
6032 | # The second is the "hostname" of a TXT record with more info.
|
---|
6033 | my $prefix = ":$host:17:";
|
---|
6034 | my ($who,$what) = split /\s/, $val;
|
---|
6035 | foreach (split /\./, $who) {
|
---|
6036 | $prefix .= sprintf "\\%0.3o%s", length($_), $_;
|
---|
6037 | }
|
---|
6038 | $prefix .= '\000';
|
---|
6039 | foreach (split /\./, $what) {
|
---|
6040 | $prefix .= sprintf "\\%0.3o%s", length($_), $_;
|
---|
6041 | }
|
---|
6042 | print $datafile "$prefix\\000:$ttl:$stamp:$loc\n" or die $!;
|
---|
6043 |
|
---|
6044 | } elsif ($typemap{$type} eq 'PTR') {
|
---|
6045 |
|
---|
6046 | $$recflags{$val}++;
|
---|
6047 | if ($revrec eq 'y') {
|
---|
6048 |
|
---|
6049 | if ($val =~ /\.arpa$/) {
|
---|
6050 | # someone put in the formal .arpa name. humor them.
|
---|
6051 | print $datafile "^$val:$host:$ttl:$stamp:$loc\n" or die $!;
|
---|
6052 | } else {
|
---|
6053 | $zone = NetAddr::IP->new($zone);
|
---|
6054 | if (!$zone->{isv6} && $zone->masklen > 24) {
|
---|
6055 | # sub-octet v4 zone
|
---|
6056 | ($val) = ($val =~ /\.(\d+)$/);
|
---|
6057 | print $datafile "^$val."._ZONE($zone, 'ZONE', 'r', '.').'.in-addr.arpa'.
|
---|
6058 | ":$host:$ttl:$stamp:$loc\n" or die $!;
|
---|
6059 | } else {
|
---|
6060 | # not going to care about strange results if $val is not an IP value and is resolveable in DNS
|
---|
6061 | $val = NetAddr::IP->new($val);
|
---|
6062 | print $datafile "^".
|
---|
6063 | _ZONE($val, 'ZONE', 'r', '.').($val->{isv6} ? '.ip6.arpa' : '.in-addr.arpa').
|
---|
6064 | ":$host:$ttl:$stamp:$loc\n" or die $!;
|
---|
6065 | }
|
---|
6066 | } # non-".arpa" $val
|
---|
6067 |
|
---|
6068 | } else {
|
---|
6069 | # PTRs in forward zones are less bizarre and insane than some other record types
|
---|
6070 | # in reverse zones... OTOH we can't validate them any which way, so we cross our
|
---|
6071 | # fingers and close our eyes and make it Someone Else's Problem.
|
---|
6072 | print $datafile "^$host:$val:$ttl:$stamp:$loc\n" or die $!;
|
---|
6073 | }
|
---|
6074 |
|
---|
6075 | } elsif ($type == 65280) { # A+PTR
|
---|
6076 |
|
---|
6077 | $$recflags{$val}++;
|
---|
6078 | print $datafile "=$host:$val:$ttl:$stamp:$loc\n" or die $!;
|
---|
6079 |
|
---|
6080 | } elsif ($type == 65281) { # AAAA+PTR
|
---|
6081 |
|
---|
6082 | $$recflags{$val}++;
|
---|
6083 | # treat these as two separate records. since tinydns doesn't have
|
---|
6084 | # a native combined type, we have to create them separately anyway.
|
---|
6085 | # print both; a dangling record is harmless, and impossible via web
|
---|
6086 | # UI anyway
|
---|
6087 | $self->_printrec_tiny($datafile,$revrec,$recflags,$zone,$host,28,$val,$dist,$weight,$port,$ttl,$loc,$stamp);
|
---|
6088 | $self->_printrec_tiny($datafile,$revrec,$recflags,$zone,$host,12,$val,$dist,$weight,$port,$ttl,$loc,$stamp);
|
---|
6089 | ##fixme: add a config flag to indicate use of the patch from http://www.fefe.de/dns/
|
---|
6090 | # type 6 is for AAAA+PTR, type 3 is for AAAA
|
---|
6091 |
|
---|
6092 | } elsif ($type == 65282) { # PTR template
|
---|
6093 |
|
---|
6094 | # only useful for v4 with standard DNS software, since this expands all
|
---|
6095 | # IPs in $zone (or possibly $val?) with autogenerated records
|
---|
6096 | $val = NetAddr::IP->new($val);
|
---|
6097 | return if $val->{isv6};
|
---|
6098 |
|
---|
6099 | if ($val->masklen <= 16) {
|
---|
6100 | foreach my $sub ($val->split(16)) {
|
---|
6101 | $self->__publish_subnet($sub, $recflags, $host, $datafile, $ttl, $stamp, $loc, $zone, 1);
|
---|
6102 | }
|
---|
6103 | } else {
|
---|
6104 | $self->__publish_subnet($val, $recflags, $host, $datafile, $ttl, $stamp, $loc, $zone, 1);
|
---|
6105 | }
|
---|
6106 |
|
---|
6107 | } elsif ($type == 65283) { # A+PTR template
|
---|
6108 |
|
---|
6109 | $val = NetAddr::IP->new($val);
|
---|
6110 | # Just In Case. An A+PTR should be impossible to add to a v6 revzone via API.
|
---|
6111 | return if $val->{isv6};
|
---|
6112 |
|
---|
6113 | if ($val->masklen <= 16) {
|
---|
6114 | foreach my $sub ($val->split(16)) {
|
---|
6115 | $self->__publish_subnet($sub, $recflags, $host, $datafile, $ttl, $stamp, $loc, $zone, 0);
|
---|
6116 | }
|
---|
6117 | } else {
|
---|
6118 | $self->__publish_subnet($val, $recflags, $host, $datafile, $ttl, $stamp, $loc, $zone, 0);
|
---|
6119 | }
|
---|
6120 |
|
---|
6121 | } elsif ($type == 65284) { # AAAA+PTR template
|
---|
6122 | # Stub for completeness. Could be exported to DNS software that supports
|
---|
6123 | # some degree of internal automagic in generic-record-creation
|
---|
6124 | # (eg http://search.cpan.org/dist/AllKnowingDNS/ )
|
---|
6125 |
|
---|
6126 | } elsif ($type == 65285) { # Delegation
|
---|
6127 | # This is intended for reverse zones, but may prove useful in forward zones.
|
---|
6128 |
|
---|
6129 | # All delegations need to create one or more NS records. The NS record handler knows what to do.
|
---|
6130 | $self->_printrec_tiny($datafile,$recid,$revrec,$recflags,$zone,$host,$reverse_typemap{'NS'},
|
---|
6131 | $val,$dist,$weight,$port,$ttl,$loc,$stamp);
|
---|
6132 | if ($revrec eq 'y') {
|
---|
6133 | # In the case of a sub-/24 v4 reverse delegation, we need to generate CNAMEs
|
---|
6134 | # to redirect all of the individual IP lookups as well.
|
---|
6135 | # OR
|
---|
6136 | # create NS records for each IP
|
---|
6137 | # Not sure how this would actually resolve if a /24 or larger was delegated
|
---|
6138 | # one way, and a sub-/24 in that >=/24 was delegated elsewhere...
|
---|
6139 | my $dblock = NetAddr::IP->new($val);
|
---|
6140 | if (!$dblock->{isv6} && $dblock->masklen > 24) {
|
---|
6141 | my @subs = $dblock->split;
|
---|
6142 | foreach (@subs) {
|
---|
6143 | next if $$recflags{"$_"};
|
---|
6144 | my ($oct) = ($_->addr =~ /(\d+)$/);
|
---|
6145 | print $datafile "C"._ZONE($_, 'ZONE.in-addr.arpa', 'r', '.').":$oct.".
|
---|
6146 | _ZONE($dblock, 'ZONE.in-addr.arpa', 'r', '.').":$ttl:$stamp:$loc\n" or die $!;
|
---|
6147 | $$recflags{"$_"}++;
|
---|
6148 | }
|
---|
6149 | }
|
---|
6150 | }
|
---|
6151 |
|
---|
6152 | ##
|
---|
6153 | ## Uncommon types. These will need better UI support Any Day Sometime Maybe(TM).
|
---|
6154 | ##
|
---|
6155 |
|
---|
6156 | } elsif ($type == 44) { # SSHFP
|
---|
6157 |
|
---|
6158 | ($host,$val) = __revswap($host,$val) if $revrec eq 'y';
|
---|
6159 |
|
---|
6160 | my ($algo,$fpt,$fp) = split /\s+/, $val;
|
---|
6161 |
|
---|
6162 | my $rec = sprintf ":$host:44:\\%0.3o\\%0.3o", $algo, $fpt;
|
---|
6163 | while (my ($byte) = ($fp =~ /^(..)/) ) {
|
---|
6164 | $rec .= sprintf "\\%0.3o", hex($byte);
|
---|
6165 | $fp =~ s/^..//;
|
---|
6166 | }
|
---|
6167 | print $datafile "$rec:$ttl:$stamp:$loc\n" or die $!;
|
---|
6168 |
|
---|
6169 | } else {
|
---|
6170 | # raw record. we don't know what's in here, so we ASS-U-ME the user has
|
---|
6171 | # put it in correctly, since either the user is messing directly with the
|
---|
6172 | # database, or the record was imported via AXFR
|
---|
6173 | # <split by char>
|
---|
6174 | # convert anything not a-zA-Z0-9.- to octal coding
|
---|
6175 |
|
---|
6176 | ##fixme: add flag to export "unknown" record types - note we'll probably end up
|
---|
6177 | # mangling them since they were written to the DB from Net::DNS::RR::<type>->rdatastr.
|
---|
6178 | #print $datafile ":$host:$type:$val:$ttl:$stamp:$loc\n";
|
---|
6179 |
|
---|
6180 | } # record type if-else
|
---|
6181 |
|
---|
6182 | } # end _printrec_tiny()
|
---|
6183 |
|
---|
6184 |
|
---|
6185 | ## DNSDB::mailNotify()
|
---|
6186 | # Sends notification mail to recipients regarding a DNSDB operation
|
---|
6187 | sub mailNotify {
|
---|
6188 | my $self = shift;
|
---|
6189 | my $dbh = $self->{dbh};
|
---|
6190 | my ($subj,$message) = @_;
|
---|
6191 |
|
---|
6192 | return if $self->{mailhost} eq 'smtp.example.com'; # do nothing if still using default SMTP host.
|
---|
6193 |
|
---|
6194 | my $mailer = Net::SMTP->new($self->{mailhost}, Hello => "dnsadmin.$self->{domain}");
|
---|
6195 |
|
---|
6196 | my $mailsender = ($self->{mailsender} ? $self->{mailsender} : $self->{mailnotify});
|
---|
6197 |
|
---|
6198 | $mailer->mail($mailsender);
|
---|
6199 | $mailer->to($self->{mailnotify});
|
---|
6200 | $mailer->data("From: \"$self->{mailname}\" <$mailsender>\n",
|
---|
6201 | "To: <$self->{mailnotify}>\n",
|
---|
6202 | "Date: ".strftime("%a, %d %b %Y %H:%M:%S %z",localtime)."\n",
|
---|
6203 | "Subject: $subj\n",
|
---|
6204 | "X-Mailer: DNSAdmin v".$DNSDB::VERSION." Notify\n",
|
---|
6205 | "Organization: $self->{orgname}\n",
|
---|
6206 | "\n$message\n");
|
---|
6207 | $mailer->quit;
|
---|
6208 | }
|
---|
6209 |
|
---|
6210 | # shut Perl up
|
---|
6211 | 1;
|
---|